mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-05 12:16:55 -06:00
Compare commits
133
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
241bf8c94d | ||
|
|
824d3c431e | ||
|
|
789cabd832 | ||
|
|
6545c44f0a | ||
|
|
b22e901c45 | ||
|
|
c60c82d960 | ||
|
|
67bfa46a3d | ||
|
|
513ff0541f | ||
|
|
6f7b8156dc | ||
|
|
a21324bf78 | ||
|
|
a39f6adf9f | ||
|
|
b2dd74729f | ||
|
|
5ea160c706 | ||
|
|
8a7fef3ec6 | ||
|
|
84118adcf9 | ||
|
|
0ec775a9b9 | ||
|
|
caf9c8de8b | ||
|
|
c07b649e7b | ||
|
|
135c1f72b1 | ||
|
|
c70ad1bab2 | ||
|
|
4358f546d8 | ||
|
|
6b79b722d3 | ||
|
|
eba89475f6 | ||
|
|
64ef08c60a | ||
|
|
bc71452511 | ||
|
|
fb9276c4a6 | ||
|
|
1129aa51f2 | ||
|
|
4ad6272409 | ||
|
|
70e181a966 | ||
|
|
496d276873 | ||
|
|
32ad05fe64 | ||
|
|
b2dd18c916 | ||
|
|
dc9327501c | ||
|
|
b2021313ab | ||
|
|
41b351d770 | ||
|
|
3fbc536eba | ||
|
|
7342c32b1e | ||
|
|
0f0551351a | ||
|
|
c99d119543 | ||
|
|
a60bd414ed | ||
|
|
53d83510d7 | ||
|
|
58b595835f | ||
|
|
438c12d54a | ||
|
|
fb813b7988 | ||
|
|
67aa8ca4b7 | ||
|
|
b8ac6de3d0 | ||
|
|
db92b5cf2e | ||
|
|
18a8326ff0 | ||
|
|
b1de6f8556 | ||
|
|
d2ed8a334b | ||
|
|
c583679407 | ||
|
|
e6ff55e758 | ||
|
|
7d45de75f6 | ||
|
|
84e7aee82f | ||
|
|
dfb7e2647e | ||
|
|
c070c2a258 | ||
|
|
ba7318322a | ||
|
|
b7f52b6c78 | ||
|
|
4d7be007da | ||
|
|
14280d1c03 | ||
|
|
2bf03bcfc6 | ||
|
|
ea2e2f2970 | ||
|
|
f5892400de | ||
|
|
501dddf7b5 | ||
|
|
1f6eb8eceb | ||
|
|
087bf2535b | ||
|
|
7a408c7eb3 | ||
|
|
7b213b331b | ||
|
|
d62508ca40 | ||
|
|
a1ad0f4cbc | ||
|
|
9c54fc1446 | ||
|
|
fbde8c47a3 | ||
|
|
481207f29d | ||
|
|
4add275c07 | ||
|
|
5f39de62f8 | ||
|
|
830065bd62 | ||
|
|
31b2be75f4 | ||
|
|
195f103ceb | ||
|
|
96b8c1c58b | ||
|
|
de30199f1f | ||
|
|
14ed0bfa28 | ||
|
|
bf54864f37 | ||
|
|
61893e1950 | ||
|
|
b6777d494c | ||
|
|
434d9b223e | ||
|
|
802a2e2120 | ||
|
|
83f437ec89 | ||
|
|
3bae0c1cdb | ||
|
|
aa2c33e5a9 | ||
|
|
c26f801e20 | ||
|
|
7b1d234029 | ||
|
|
7361228721 | ||
|
|
05dda70d5c | ||
|
|
0d8409ea36 | ||
|
|
4281ebbcb1 | ||
|
|
3843ada39b | ||
|
|
ed17e883e5 | ||
|
|
a0ca3766b3 | ||
|
|
3ebe82eb5e | ||
|
|
e9708b91ae | ||
|
|
9f28b67cbc | ||
|
|
2ddf619270 | ||
|
|
27da3abc76 | ||
|
|
ecd8b5db7b | ||
|
|
ffadc1d8de | ||
|
|
e4e2c2d9d7 | ||
|
|
dba4269b25 | ||
|
|
7888d77bbd | ||
|
|
94aa34729c | ||
|
|
d0dbc425ee | ||
|
|
6e67012f78 | ||
|
|
11323ff0dd | ||
|
|
b3302eeef3 | ||
|
|
1342420920 | ||
|
|
b917ca74c1 | ||
|
|
03070810eb | ||
|
|
4b772c030c | ||
|
|
3794d9718e | ||
|
|
97daa4b3ed | ||
|
|
7b03696d8c | ||
|
|
bbad606bc3 | ||
|
|
49f89569d0 | ||
|
|
408dcc0367 | ||
|
|
aaecdd6313 | ||
|
|
0ee236e6a4 | ||
|
|
1131c3120d | ||
|
|
f94aecace7 | ||
|
|
366b89341d | ||
|
|
0c7f425e91 | ||
|
|
9cdc60b2c1 | ||
|
|
8e90f8f336 | ||
|
|
59e818424c | ||
|
|
02e7bbc640 |
@@ -38,11 +38,19 @@ fn run_saves_the_document_opened_last() {
|
||||
assert_eq!(stdout.matches("\"id\"").count(), 1, "{stdout}");
|
||||
}
|
||||
|
||||
struct TempFile(std::path::PathBuf);
|
||||
|
||||
impl Drop for TempFile {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_run_commands_still_exit_with_an_error() {
|
||||
let script = std::env::temp_dir().join(format!("wordcraft-cli-run-error-{}.json", std::process::id()));
|
||||
std::fs::write(&script, r#"{"commands":["no.such.command"]}"#).unwrap();
|
||||
let script_path = script.to_string_lossy();
|
||||
let script = TempFile(std::env::temp_dir().join(format!("wordcraft-cli-run-error-{}.json", std::process::id())));
|
||||
std::fs::write(&script.0, r#"{"commands":["no.such.command"]}"#).unwrap();
|
||||
let script_path = script.0.to_string_lossy();
|
||||
let cases = [(["run", "--cmd", "no.such.command"], "no.such.command:"), (["run", "--script", &script_path], "command 1 (no.such.command):")];
|
||||
for (args, expected) in cases {
|
||||
let out = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).args(args).output().unwrap();
|
||||
@@ -52,5 +60,4 @@ fn failed_run_commands_still_exit_with_an_error() {
|
||||
assert!(stderr.starts_with("wordcraft-cli: ") && stderr.contains(expected), "{stderr}");
|
||||
assert!(!stderr.contains("wordcraft-cli: warning:"), "{stderr}");
|
||||
}
|
||||
std::fs::remove_file(script).unwrap();
|
||||
}
|
||||
|
||||
@@ -9,5 +9,6 @@ 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,6 +519,7 @@ 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);
|
||||
@@ -842,6 +843,43 @@ 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,7 +122,6 @@ 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)),
|
||||
@@ -130,21 +129,33 @@ 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(EmphasisMark::Dot),
|
||||
Some(EmphasisMark::Comma),
|
||||
Some(EmphasisMark::Circle),
|
||||
Some(EmphasisMark::UnderDot),
|
||||
Some(EmphasisMark::None),
|
||||
None,
|
||||
(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),
|
||||
];
|
||||
for (run, mark) in p.runs.iter().skip(6).zip(expected_runs) {
|
||||
assert_eq!(run.props.emphasis, mark);
|
||||
}
|
||||
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 pass in 0..2 {
|
||||
let out = wordcraft_docx::write(&doc).unwrap();
|
||||
@@ -156,17 +167,7 @@ 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();
|
||||
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}");
|
||||
}
|
||||
assert_state(&doc, &format!("pass {pass}"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -513,6 +513,7 @@ 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);
|
||||
|
||||
+148
-19
@@ -2,7 +2,8 @@
|
||||
|
||||
use serde_json::Value;
|
||||
use wordcraft_doc::math_edit::MathPos;
|
||||
use wordcraft_doc::para::OBJ;
|
||||
use wordcraft_doc::para::{NBSP, OBJ};
|
||||
use wordcraft_doc::props::TextDirection;
|
||||
use wordcraft_doc::{InlineObject, Paragraph, Path, Pos, StoryRef};
|
||||
use wordcraft_layout::ViewMode;
|
||||
|
||||
@@ -113,6 +114,47 @@ fn bidi_para(s: &Session) -> bool {
|
||||
|
||||
/// Left/Right: with a selection and no Shift, collapse to its edge.
|
||||
fn lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
|
||||
if let Some(t) = turn(s) {
|
||||
// Vertical text (#8986): Left/Right change line; top-to-bottom lines stack leftwards.
|
||||
return line_step(s, v, (t == TextDirection::Down) == is_left, is_left);
|
||||
}
|
||||
lr_along(s, v, is_left)
|
||||
}
|
||||
|
||||
/// The text direction at the caret when it is in turned (vertical) text.
|
||||
fn turn(s: &mut Session) -> Option<TextDirection> {
|
||||
let l = s.layout();
|
||||
l.turn_at(&s.sel.focus, s.page_hint)
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// 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);
|
||||
if !ext && !s.sel.is_collapsed() {
|
||||
let (a, b) = s.sel.ordered();
|
||||
s.sel = Selection::caret(if next { b } else { a });
|
||||
s.goal_x = None;
|
||||
return sel_result(s);
|
||||
}
|
||||
let l = s.layout();
|
||||
let from = s.sel.focus.clone();
|
||||
let to = match l.turned_line(&from, s.goal_x, next, s.page_hint) {
|
||||
Some((p, g)) => {
|
||||
s.goal_x = Some(g);
|
||||
p
|
||||
}
|
||||
None => return lr_along(s, v, is_left),
|
||||
};
|
||||
let gx = s.goal_x;
|
||||
apply(s, to, ext);
|
||||
s.goal_x = gx;
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Left/Right as a step along the text (`is_left`: backwards).
|
||||
fn lr_along(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
|
||||
let ext = extend(v);
|
||||
if !ext && !s.sel.is_collapsed() {
|
||||
let (a, b) = s.sel.ordered();
|
||||
@@ -184,23 +226,30 @@ fn visual_lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// The two ends of a hidden deletion share a caret position. Cross the hidden
|
||||
/// span before taking the normal grapheme step, including adjacent deletions.
|
||||
fn hidden_deletion_edge(para: &Paragraph, off: usize, is_left: bool, hides: impl Fn(Option<u32>) -> bool) -> usize {
|
||||
// At a run boundary, inspect the byte on the side the caret is moving toward.
|
||||
let Some(byte) = off.checked_sub(usize::from(is_left)).filter(|&byte| byte < para.len()) else { return off };
|
||||
// Runs store lengths, so find the containing run from the nearer end of the paragraph.
|
||||
let found = if byte < para.len() / 2 {
|
||||
/// Find the run containing `byte` from the nearer end of `para`.
|
||||
fn run_at_byte(para: &Paragraph, byte: usize) -> Option<(usize, std::ops::Range<usize>)> {
|
||||
if byte >= para.len() {
|
||||
return None;
|
||||
}
|
||||
if byte < para.len() / 2 {
|
||||
para.run_ranges().enumerate().find_map(|(i, (range, _))| range.contains(&byte).then_some((i, range)))
|
||||
} else {
|
||||
let mut end = para.len();
|
||||
para.runs.iter().enumerate().rev().find_map(|(i, run)| {
|
||||
let range = end - run.len..end;
|
||||
end = range.start;
|
||||
let start = end.saturating_sub(run.len);
|
||||
let range = start..end;
|
||||
end = start;
|
||||
range.contains(&byte).then_some((i, range))
|
||||
})
|
||||
};
|
||||
let Some((i, range)) = found else { return off };
|
||||
}
|
||||
}
|
||||
|
||||
/// The two ends of a hidden deletion share a caret position. Cross the hidden
|
||||
/// span before taking the normal grapheme step, including adjacent deletions.
|
||||
fn hidden_deletion_edge(para: &Paragraph, off: usize, is_left: bool, hides: impl Fn(Option<u32>) -> bool) -> usize {
|
||||
// At a run boundary, inspect the byte on the side the caret is moving toward.
|
||||
let Some(byte) = off.checked_sub(usize::from(is_left)) else { return off };
|
||||
let Some((i, range)) = run_at_byte(para, byte) else { return off };
|
||||
if !hides(para.runs[i].props.del) {
|
||||
return off;
|
||||
}
|
||||
@@ -256,18 +305,94 @@ fn step_to_neighbor(s: &Session, from: &Pos, is_left: bool, skip_deleted: bool)
|
||||
Pos { story, path, off }
|
||||
}
|
||||
|
||||
fn word_left(s: &mut Session, p: &Pos) -> Pos {
|
||||
match s.doc.para_at(p) {
|
||||
Some(para) if p.off > 0 => Pos { off: para.word_start(p.off), ..p.clone() },
|
||||
_ => step_to_neighbor(s, p, true, false),
|
||||
fn visible_word_start(para: &Paragraph, off: usize) -> Option<usize> {
|
||||
let off = para.clamp(off);
|
||||
let byte = off.checked_sub(1)?;
|
||||
let (i, range) = run_at_byte(para, byte)?;
|
||||
let mut idx = off;
|
||||
let mut seen_word = false;
|
||||
let mut seen_visible = false;
|
||||
let mut end = range.end;
|
||||
for run in para.runs[..=i].iter().rev() {
|
||||
let start = end.saturating_sub(run.len);
|
||||
let range_end = end.min(off);
|
||||
end = start;
|
||||
if run.props.del.is_some() {
|
||||
continue;
|
||||
}
|
||||
let Some(slice) = para.text.get(start..range_end) else { continue };
|
||||
for (rel, c) in slice.char_indices().rev() {
|
||||
seen_visible = true;
|
||||
if wordcraft_doc::bidi::is_word_char(c) {
|
||||
seen_word = true;
|
||||
idx = start + rel;
|
||||
} else if seen_word {
|
||||
return Some(idx);
|
||||
} else {
|
||||
idx = start + rel;
|
||||
}
|
||||
}
|
||||
}
|
||||
seen_visible.then_some(idx)
|
||||
}
|
||||
|
||||
fn visible_word_end(para: &Paragraph, off: usize) -> Option<usize> {
|
||||
let off = para.clamp(off);
|
||||
let (i, range) = run_at_byte(para, off)?;
|
||||
let mut first_word = None;
|
||||
let mut in_space = false;
|
||||
let mut last_end = None;
|
||||
let mut run_start = range.start;
|
||||
for run in ¶.runs[i..] {
|
||||
let run_end = run_start.saturating_add(run.len);
|
||||
let start = run_start.max(off);
|
||||
run_start = run_end;
|
||||
if run.props.del.is_some() {
|
||||
continue;
|
||||
}
|
||||
let Some(slice) = para.text.get(start..run_end) else { continue };
|
||||
for (rel, c) in slice.char_indices() {
|
||||
let abs = start + rel;
|
||||
last_end = Some(abs + c.len_utf8());
|
||||
let is_first = first_word.is_none();
|
||||
let fw = *first_word.get_or_insert_with(|| wordcraft_doc::bidi::is_word_char(c) && c != '\'');
|
||||
let w = wordcraft_doc::bidi::is_word_char(c);
|
||||
if c == ' ' || c == NBSP {
|
||||
in_space = true;
|
||||
continue;
|
||||
}
|
||||
if in_space || (fw && !w) || (!fw && !is_first) {
|
||||
return Some(abs);
|
||||
}
|
||||
}
|
||||
}
|
||||
last_end
|
||||
}
|
||||
|
||||
fn word_left(s: &mut Session, p: &Pos) -> Pos {
|
||||
if let Some(para) = s.doc.para_at(p) {
|
||||
if !s.view.show_markup {
|
||||
if let Some(off) = visible_word_start(para, p.off) {
|
||||
return Pos { off, ..p.clone() };
|
||||
}
|
||||
} else if p.off > 0 {
|
||||
return Pos { off: para.word_start(p.off), ..p.clone() };
|
||||
}
|
||||
}
|
||||
step_to_neighbor(s, p, true, false)
|
||||
}
|
||||
|
||||
fn word_right(s: &mut Session, p: &Pos) -> Pos {
|
||||
match s.doc.para_at(p) {
|
||||
Some(para) if p.off < para.len() => Pos { off: para.word_end(p.off), ..p.clone() },
|
||||
_ => step_to_neighbor(s, p, false, false),
|
||||
if let Some(para) = s.doc.para_at(p) {
|
||||
if !s.view.show_markup {
|
||||
if let Some(off) = visible_word_end(para, p.off) {
|
||||
return Pos { off, ..p.clone() };
|
||||
}
|
||||
} else if p.off < para.len() {
|
||||
return Pos { off: para.word_end(p.off), ..p.clone() };
|
||||
}
|
||||
}
|
||||
step_to_neighbor(s, p, false, false)
|
||||
}
|
||||
|
||||
fn para_up(s: &mut Session, p: &Pos) -> Pos {
|
||||
@@ -291,6 +416,10 @@ fn para_down(s: &mut Session, p: &Pos) -> Pos {
|
||||
}
|
||||
|
||||
fn vert(s: &mut Session, v: &Value, dir: i32) -> CmdResult {
|
||||
if let Some(t) = turn(s) {
|
||||
// Vertical text (#8986): Up/Down step along the line (top-to-bottom text runs down).
|
||||
return lr_along(s, v, (dir < 0) == (t == TextDirection::Down));
|
||||
}
|
||||
let ext = extend(v);
|
||||
let l = s.layout();
|
||||
let from = s.sel.focus.clone();
|
||||
|
||||
@@ -335,43 +335,66 @@ 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};
|
||||
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();
|
||||
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 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));
|
||||
}
|
||||
s.touch();
|
||||
assert!(!reroute(&mut s), "rerouting must settle after refreshing the layout");
|
||||
big.touch();
|
||||
assert!(!reroute(&mut big), "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)"#),
|
||||
.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"#),
|
||||
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,16 +827,46 @@ fn replace(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(json!({"replaced": replaced, "remaining": search(s, story)?.len(), "selected": selected}))
|
||||
}
|
||||
|
||||
/// Every match replaced, last first so earlier positions stay valid (one undo step). A `\r` in
|
||||
/// the replacement (`^p`) splits the paragraph.
|
||||
/// 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.
|
||||
fn replace_all(s: &mut Session, v: &Value) -> CmdResult {
|
||||
need_query(s, v)?;
|
||||
read_opts(s, v);
|
||||
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)))?;
|
||||
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> {
|
||||
for Found { a, b, rep, .. } in results.into_iter().rev() {
|
||||
let with = rep.unwrap_or_default();
|
||||
if s.doc.settings.track_changes {
|
||||
@@ -857,8 +887,7 @@ fn replace_all(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
}
|
||||
}
|
||||
s.status = format!("All done. We made {n} replacements.");
|
||||
Ok(json!({"replaced": n}))
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn goto(s: &mut Session, v: &Value) -> CmdResult {
|
||||
|
||||
@@ -668,6 +668,18 @@ 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, selected, target_objects, with_obj};
|
||||
use super::select::{edit_obj, is_shape_or_canvas, obj_size, select_object, selected, target_objects, with_obj};
|
||||
use super::{CmdError, CmdResult, InlineObject, Pos, Rgb, Session, Value, Wrap, json, p};
|
||||
use wordcraft_doc::picfx::PicFx;
|
||||
|
||||
@@ -186,6 +186,30 @@ 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,6 +1,8 @@
|
||||
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, original_media, recolor, relook, remove_background, reset, shape_size, size};
|
||||
use super::picture::{
|
||||
adjust, adjust_media, clear_lum, crop, each_picture, original_media, recolor, relook, remove_background, reset, shape_size, size,
|
||||
};
|
||||
use super::select::{
|
||||
all_objects, alt_text, can_group, edit_obj, has_any_movable, has_any_shape, has_floating, has_group, has_movable, has_object, has_picture,
|
||||
has_placeable, has_shape, has_shape_or_canvas, has_sizable, is_shape_or_canvas, obj_size, objects_list, selected_or_text_box, target_objects,
|
||||
@@ -58,98 +60,112 @@ 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| {
|
||||
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)
|
||||
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)
|
||||
})
|
||||
})
|
||||
})
|
||||
.params(r#"{"brightness"?: -100..100, "contrast"?: -100..100, "sharpen"?: -100..100}"#)
|
||||
.when(has_picture),
|
||||
CommandSpec::new("picture.color", "Color", "Picture Format › Adjust", |s, v| {
|
||||
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)))
|
||||
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)))
|
||||
})
|
||||
})
|
||||
.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| {
|
||||
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))
|
||||
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))
|
||||
})
|
||||
})
|
||||
})
|
||||
.params(r#"{"color": "RRGGBB"}"#)
|
||||
.when(has_picture),
|
||||
CommandSpec::new("picture.effects", "Artistic Effects", "Picture Format › Adjust", |s, v| {
|
||||
// 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))
|
||||
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))
|
||||
})
|
||||
})
|
||||
.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| {
|
||||
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))
|
||||
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))
|
||||
})
|
||||
})
|
||||
})
|
||||
.params(r#"{"percent": 0..100}"#)
|
||||
.when(has_picture),
|
||||
CommandSpec::new("picture.removeBackground", "Remove Background", "Picture Format › Adjust", |s, v| {
|
||||
let tol = p::f32(v, "tolerance").unwrap_or(30.0).clamp(0.0, 255.0);
|
||||
adjust(s, move |img| Ok(remove_background(img, tol)))
|
||||
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)))
|
||||
})
|
||||
})
|
||||
.params(r#"{"tolerance"?: 0..255}"#)
|
||||
.when(has_picture),
|
||||
CommandSpec::new("picture.compress", "Compress Pictures", "Picture Format › Adjust", |s, v| {
|
||||
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 }))
|
||||
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 }))
|
||||
})
|
||||
})
|
||||
.params(r#"{"maxPixels"?: n}"#)
|
||||
.when(has_picture),
|
||||
CommandSpec::new("picture.reset", "Reset Picture", "Picture Format › Adjust", reset).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.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()))?
|
||||
@@ -184,20 +200,24 @@ 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| {
|
||||
// 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;
|
||||
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;
|
||||
})
|
||||
})
|
||||
})
|
||||
.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| {
|
||||
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)))
|
||||
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)))
|
||||
})
|
||||
})
|
||||
.params(r#"{"color"?: "RRGGBB", "width"?: px} (replaces the picture's border)"#)
|
||||
.when(has_picture),
|
||||
|
||||
@@ -432,6 +432,28 @@ 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 take turns.
|
||||
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
/// Tests that set the process-wide backend or packs directory share the dictionary test lock.
|
||||
use crate::custom_dict::DICT_TEST_LOCK as LOCK;
|
||||
|
||||
/// Puts the process back to no backend and no background thread when dropped, even when
|
||||
/// the test panicked.
|
||||
|
||||
@@ -167,7 +167,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("para.heading3", "Heading 3", "Home › Styles", |s, _| apply_style(s, &json!({"style": "Heading3"}))).key("Mod+Alt+3"),
|
||||
CommandSpec::new("para.bullets", "Bullets", "Home › Paragraph", |s, v| list(s, v, ListKind::Bullet)).params(r#"{"kind"?: "bullet" | single char, "off"?: bool}"#).key("Mod+Shift+L"),
|
||||
CommandSpec::new("para.numbering", "Numbering", "Home › Paragraph", |s, v| list(s, v, ListKind::Numbered))
|
||||
.params(r#"{"kind"?: "numbered|numberedParen|upperLetter|lowerLetter|lowerRoman|outline", "off"?: bool}"#),
|
||||
.params(r#"{"kind"?: "numbered|numberedParen|outline|upperLetter|lowerLetter|lowerLetterDot|lowerRoman", "off"?: bool}"#),
|
||||
CommandSpec::new("para.multilevel", "Multilevel List", "Home › Paragraph", |s, v| list(s, v, ListKind::Legal)).params(r#"{"kind"?: "legal|outline"}"#),
|
||||
CommandSpec::new("para.listLevel", "Change List Level", "Home › Paragraph › Bullets", |s, v| {
|
||||
let lvl = p::u64(v, "level").unwrap_or(0).min(8) as u8;
|
||||
|
||||
@@ -13,13 +13,24 @@ pub(super) fn list(s: &mut Session, v: &Value, default: ListKind) -> CmdResult {
|
||||
.map(|p| s.doc.para(a.story, p).and_then(|x| s.doc.styles.resolve_para(&x.props).numbering).filter(|n| n.num != 0))
|
||||
.collect();
|
||||
let same_kind = |n: &NumRef| {
|
||||
s.doc.numbering.level(n.num, n.level).is_some_and(|l| {
|
||||
let want = wordcraft_doc::numbering::levels_for(kind);
|
||||
want.get(usize::from(n.level)).is_some_and(|w| {
|
||||
let want = wordcraft_doc::numbering::levels_for(kind);
|
||||
// Is the list's level `i` (with this list's own overrides) the preset's level `i`?
|
||||
let level_is = |i: u8, with_text: bool| match (s.doc.numbering.level(n.num, i), want.get(usize::from(i))) {
|
||||
(Some(l), Some(w)) => {
|
||||
(w.format == wordcraft_doc::section::NumFormat::Bullet) == (l.format == wordcraft_doc::section::NumFormat::Bullet)
|
||||
&& (p::str(v, "kind").is_none() || w.text == l.text)
|
||||
})
|
||||
})
|
||||
// A named preset is the same one only in its number style and text: "1." and "A." are
|
||||
// both `%1.`, so picking one over the other changes the list, not switches it off (#4281).
|
||||
&& (!with_text || (w.text == l.text && w.format == l.format))
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
let named = p::str(v, "kind").is_some();
|
||||
// A named preset is told by its first level as well as the paragraph's own, as deeper levels of
|
||||
// two presets can look alike; unless the list starts with the other kind of marker (a bullet
|
||||
// above numbers, or the reverse), where the paragraph's own level decides.
|
||||
let is_bullet = |i: u8| s.doc.numbering.level(n.num, i).map(|l| l.format == wordcraft_doc::section::NumFormat::Bullet);
|
||||
let one_kind_throughout = is_bullet(0) == is_bullet(n.level);
|
||||
level_is(n.level, named) && (!named || !one_kind_throughout || level_is(0, true))
|
||||
};
|
||||
let remove = off || (!current.is_empty() && current.iter().all(|n| n.as_ref().is_some_and(same_kind)));
|
||||
if remove {
|
||||
|
||||
@@ -695,6 +695,27 @@ 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,6 +32,30 @@ 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};
|
||||
pub(crate) use tests::{DICT_TEST_LOCK, TestDir, dict_test_lock};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -282,6 +282,11 @@ 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,6 +300,7 @@ 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,6 +465,16 @@ 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"
|
||||
|
||||
+248
-33
@@ -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!({}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
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}));
|
||||
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!({}));
|
||||
run(&mut s, "select.all", json!({"whole": false}));
|
||||
assert!(s.column.is_none());
|
||||
assert_eq!(s.sel.ordered(), whole);
|
||||
}
|
||||
@@ -5233,6 +5233,132 @@ fn horizontal_caret_skips_hidden_tracked_deletions() {
|
||||
assert_eq!(s.sel.focus, Pos::body(0, "Aé🧪ZU".len()), "Left also skips the later deletion");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn word_caret_skips_hidden_tracked_deletions() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "one two three"}));
|
||||
let two_start = Pos::body(0, "one ".len());
|
||||
let two_mid = Pos::body(0, "one tw".len());
|
||||
let three_start = Pos::body(0, "one two ".len());
|
||||
let end = Pos::body(0, "one two three".len());
|
||||
// Keep the deleted word split across two formatting runs.
|
||||
s.doc.format_range(&two_start, &two_mid, &|c| c.bold = Some(true)).unwrap();
|
||||
run(&mut s, "review.trackChanges", json!({"value": true}));
|
||||
run(&mut s, "select.text", json!({"text": "two "}));
|
||||
run(&mut s, "text.delete", json!({}));
|
||||
|
||||
s.sel = crate::Selection::caret(Pos::body(0, 0));
|
||||
run(&mut s, "caret.wordRight", json!({}));
|
||||
assert_eq!(s.sel.focus, two_start, "visible markup still stops at the deleted word");
|
||||
|
||||
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
|
||||
s.sel = crate::Selection::caret(Pos::body(0, 0));
|
||||
run(&mut s, "caret.wordRight", json!({"extend": true}));
|
||||
assert_eq!(s.sel.anchor, Pos::body(0, 0));
|
||||
assert_eq!(s.sel.focus, three_start, "Ctrl+Right skips the hidden deleted word in one press");
|
||||
|
||||
s.sel = crate::Selection::caret(two_start.clone());
|
||||
run(&mut s, "caret.wordRight", json!({}));
|
||||
assert_eq!(s.sel.focus, end, "Ctrl+Right from the hidden start moves across the next visible word");
|
||||
|
||||
s.sel = crate::Selection::caret(end.clone());
|
||||
run(&mut s, "caret.wordLeft", json!({}));
|
||||
assert_eq!(s.sel.focus, three_start);
|
||||
run(&mut s, "caret.wordLeft", json!({}));
|
||||
assert_eq!(s.sel.focus, Pos::body(0, 0), "Ctrl+Left skips the hidden deleted word in one press");
|
||||
|
||||
s.sel = crate::Selection::caret(two_start);
|
||||
run(&mut s, "caret.wordLeft", json!({}));
|
||||
assert_eq!(s.sel.focus, Pos::body(0, 0));
|
||||
|
||||
// A deleted space between two visible word fragments joins them into one visible word.
|
||||
let mut s = self::s();
|
||||
run(&mut s, "document.setText", json!({"text": "foot ball next"}));
|
||||
run(&mut s, "review.trackChanges", json!({"value": true}));
|
||||
run(&mut s, "select.text", json!({"text": " "}));
|
||||
run(&mut s, "text.delete", json!({}));
|
||||
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
|
||||
let next_start = Pos::body(0, "foot ball ".len());
|
||||
s.sel = crate::Selection::caret(Pos::body(0, 0));
|
||||
run(&mut s, "caret.wordRight", json!({}));
|
||||
assert_eq!(s.sel.focus, next_start, "Ctrl+Right crosses a hidden deleted space inside a word");
|
||||
run(&mut s, "caret.wordLeft", json!({}));
|
||||
assert_eq!(s.sel.focus, Pos::body(0, 0), "Ctrl+Left crosses back over the joined word");
|
||||
|
||||
// Trailing and leading hidden deletions step to the neighbouring paragraph once no visible text remains.
|
||||
let mut s = self::s();
|
||||
run(&mut s, "document.setText", json!({"text": "alpha beta\ngamma delta"}));
|
||||
run(&mut s, "review.trackChanges", json!({"value": true}));
|
||||
run(&mut s, "select.text", json!({"text": "beta"}));
|
||||
run(&mut s, "text.delete", json!({}));
|
||||
run(&mut s, "select.text", json!({"text": "gamma "}));
|
||||
run(&mut s, "text.delete", json!({}));
|
||||
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
|
||||
|
||||
s.sel = crate::Selection::caret(Pos::body(0, 0));
|
||||
run(&mut s, "caret.wordRight", json!({}));
|
||||
assert_eq!(s.sel.focus, Pos::body(0, "alpha ".len()));
|
||||
run(&mut s, "caret.wordRight", json!({}));
|
||||
assert_eq!(s.sel.focus, Pos::body(1, 0), "Ctrl+Right before a trailing deletion crosses to the next paragraph");
|
||||
|
||||
s.sel = crate::Selection::caret(Pos::body(1, "gamma delta".len()));
|
||||
run(&mut s, "caret.wordLeft", json!({}));
|
||||
assert_eq!(s.sel.focus, Pos::body(1, "gamma ".len()));
|
||||
run(&mut s, "caret.wordLeft", json!({}));
|
||||
assert_eq!(s.sel.focus, Pos::body(0, "alpha beta".len()), "Ctrl+Left after a leading deletion crosses to the previous paragraph");
|
||||
|
||||
// Multi-run paragraph with separately formatted words, a far-away deletion, and adjacent deleted runs.
|
||||
let mut s = self::s();
|
||||
run(&mut s, "document.setText", json!({"text": "alpha beta gamma delta epsilon zeta"}));
|
||||
for word in ["alpha", "gamma", "epsilon"] {
|
||||
run(&mut s, "select.text", json!({"text": word}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
}
|
||||
let beta_mid = Pos::body(0, "alpha be".len());
|
||||
let gamma_start = Pos::body(0, "alpha beta ".len());
|
||||
s.doc.format_range(&Pos::body(0, "alpha ".len()), &beta_mid, &|c| c.italic = Some(true)).unwrap();
|
||||
run(&mut s, "review.trackChanges", json!({"value": true}));
|
||||
run(&mut s, "select.text", json!({"text": "beta "}));
|
||||
run(&mut s, "text.delete", json!({}));
|
||||
run(&mut s, "select.text", json!({"text": "epsilon "}));
|
||||
run(&mut s, "text.delete", json!({}));
|
||||
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
|
||||
|
||||
let expected_right = [
|
||||
Pos::body(0, "alpha beta ".len()),
|
||||
Pos::body(0, "alpha beta gamma ".len()),
|
||||
Pos::body(0, "alpha beta gamma delta epsilon ".len()),
|
||||
Pos::body(0, "alpha beta gamma delta epsilon zeta".len()),
|
||||
];
|
||||
s.sel = crate::Selection::caret(Pos::body(0, 0));
|
||||
for expected in &expected_right {
|
||||
run(&mut s, "caret.wordRight", json!({}));
|
||||
assert_eq!(s.sel.focus, *expected, "Ctrl+Right keeps the same visible word stops across formatted runs and far-away/adjacent deletions");
|
||||
}
|
||||
|
||||
let expected_left =
|
||||
[Pos::body(0, "alpha beta gamma delta epsilon ".len()), Pos::body(0, "alpha beta gamma ".len()), gamma_start, Pos::body(0, 0)];
|
||||
for expected in &expected_left {
|
||||
run(&mut s, "caret.wordLeft", json!({}));
|
||||
assert_eq!(s.sel.focus, *expected, "Ctrl+Left keeps the same visible word stops across formatted runs and far-away/adjacent deletions");
|
||||
}
|
||||
|
||||
// Word boundaries at paragraph edges preserve step_to_neighbor (do not skip a wholly deleted neighbor paragraph).
|
||||
let mut s = self::s();
|
||||
run(&mut s, "document.setText", json!({"text": "AB\nCD\nEF"}));
|
||||
run(&mut s, "review.trackChanges", json!({"value": true}));
|
||||
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 1), "focus": Pos::body(2, 1)}));
|
||||
run(&mut s, "text.delete", json!({}));
|
||||
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
|
||||
|
||||
s.sel = crate::Selection::caret(Pos::body(0, 1));
|
||||
run(&mut s, "caret.wordRight", json!({}));
|
||||
assert_eq!(s.sel.focus, Pos::body(1, 0), "Ctrl+Right at paragraph edge uses step_to_neighbor(skip_deleted=false)");
|
||||
s.sel = crate::Selection::caret(Pos::body(2, 1));
|
||||
run(&mut s, "caret.wordLeft", json!({}));
|
||||
assert_eq!(s.sel.focus, Pos::body(1, "CD".len()), "Ctrl+Left at paragraph edge uses step_to_neighbor(skip_deleted=false)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_all_is_tracked() {
|
||||
let mut s = s();
|
||||
@@ -11764,19 +11890,17 @@ fn next_footnote_skips_endnotes() {
|
||||
assert_eq!(s.sel.focus.off, 9);
|
||||
}
|
||||
|
||||
/// 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(());
|
||||
|
||||
/// Tests that read or mutate process-wide proofing dictionaries take turns through `DICT_TEST_LOCK`.
|
||||
fn dictionaries_turn() -> std::sync::MutexGuard<'static, ()> {
|
||||
DICTIONARIES.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
crate::custom_dict::dict_test_lock()
|
||||
}
|
||||
|
||||
/// 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() {
|
||||
let _turn = dictionaries_turn();
|
||||
fn polish_test_dictionary() -> std::sync::MutexGuard<'static, ()> {
|
||||
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";
|
||||
@@ -11784,9 +11908,10 @@ 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() {
|
||||
let _turn = dictionaries_turn();
|
||||
fn portuguese_test_dictionary() -> std::sync::MutexGuard<'static, ()> {
|
||||
let turn = dictionaries_turn();
|
||||
wordcraft_proof::pt::install_dictionary(PORTUGUESE_TEST_AFF, PORTUGUESE_TEST_DIC).unwrap();
|
||||
turn
|
||||
}
|
||||
|
||||
const PORTUGUESE_TEST_AFF: &str =
|
||||
@@ -11861,7 +11986,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() {
|
||||
portuguese_test_dictionary();
|
||||
let _turn = 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.
|
||||
@@ -11892,9 +12017,10 @@ fn portuguese_proofing_through_the_review_commands() {
|
||||
assert_eq!(left.as_array().unwrap().len(), 1, "{left}");
|
||||
}
|
||||
|
||||
fn indonesian_test_dictionary() {
|
||||
let _turn = dictionaries_turn();
|
||||
fn indonesian_test_dictionary() -> std::sync::MutexGuard<'static, ()> {
|
||||
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).
|
||||
@@ -11905,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() {
|
||||
indonesian_test_dictionary();
|
||||
let _turn = 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!({}));
|
||||
@@ -11960,6 +12086,7 @@ 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.
|
||||
@@ -12067,19 +12194,20 @@ 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() {
|
||||
fn spanish_test_dictionaries() -> std::sync::MutexGuard<'static, ()> {
|
||||
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() {
|
||||
spanish_test_dictionaries();
|
||||
let _turn = 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!({}));
|
||||
@@ -12110,7 +12238,7 @@ fn spanish_proofing_through_the_review_commands() {
|
||||
/// bytes.
|
||||
#[test]
|
||||
fn add_and_ignore_all_accept_both_normalization_forms() {
|
||||
spanish_test_dictionaries();
|
||||
let _turn = 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}));
|
||||
@@ -12139,7 +12267,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() {
|
||||
spanish_test_dictionaries();
|
||||
let _turn = 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!({}));
|
||||
@@ -12158,7 +12286,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() {
|
||||
czech_test_dict::install();
|
||||
let _turn = 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);
|
||||
@@ -12197,9 +12325,10 @@ 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() {
|
||||
let _turn = dictionaries_turn();
|
||||
fn italian_test_dictionary() -> std::sync::MutexGuard<'static, ()> {
|
||||
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
|
||||
@@ -12207,7 +12336,7 @@ fn italian_test_dictionary() {
|
||||
/// suggestions come from it, and a suggestion fixes the text.
|
||||
#[test]
|
||||
fn italian_proofing_through_the_review_commands() {
|
||||
italian_test_dictionary();
|
||||
let _turn = 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.
|
||||
@@ -12240,7 +12369,7 @@ fn italian_proofing_through_the_review_commands() {
|
||||
|
||||
#[test]
|
||||
fn polish_proofing_through_the_review_commands() {
|
||||
polish_test_dictionary();
|
||||
let _turn = 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.
|
||||
@@ -12280,6 +12409,7 @@ 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!({}));
|
||||
@@ -12307,7 +12437,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() {
|
||||
polish_test_dictionary();
|
||||
let _turn = polish_test_dictionary();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Hello wrold"}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
@@ -12335,7 +12465,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() {
|
||||
polish_test_dictionary();
|
||||
let _turn = 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()
|
||||
@@ -12379,7 +12509,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() {
|
||||
polish_test_dictionary();
|
||||
let _turn = 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");
|
||||
@@ -12485,7 +12615,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() {
|
||||
polish_test_dictionary();
|
||||
let _turn = 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!({}));
|
||||
@@ -15730,7 +15860,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(4);
|
||||
let long = "Lorem ipsum dolor sit amet ".repeat(2);
|
||||
run(&mut s, "text.insert", json!({"text": long}));
|
||||
run(&mut s, "text.newParagraph", json!({}));
|
||||
run(&mut s, "para.indents", json!({"right": 700}));
|
||||
@@ -15790,6 +15920,91 @@ 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();
|
||||
|
||||
@@ -274,6 +274,22 @@ fn word_moves_follow_reading_order() {
|
||||
assert_eq!(s.sel.focus.off, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn word_moves_skip_hidden_deletions_in_rtl_text() {
|
||||
let mut s = session("אב גדה וז", true);
|
||||
run(&mut s, "review.trackChanges", json!({"value": true}));
|
||||
run(&mut s, "select.text", json!({"text": "גדה "}));
|
||||
run(&mut s, "text.delete", json!({}));
|
||||
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
|
||||
|
||||
let third_word = "אב גדה ".len();
|
||||
s.sel = crate::Selection::caret(Pos::body(0, 0));
|
||||
run(&mut s, "caret.wordLeft", json!({}));
|
||||
assert_eq!(s.sel.focus.off, third_word, "Ctrl+Left skips the hidden deleted word in RTL text");
|
||||
run(&mut s, "caret.wordRight", json!({}));
|
||||
assert_eq!(s.sel.focus.off, 0, "Ctrl+Right skips back across the hidden deleted word in RTL text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_persian_keeps_logical_order() {
|
||||
let mut s = session("", true);
|
||||
|
||||
@@ -54,6 +54,8 @@ to
|
||||
zqzakázané/F
|
||||
";
|
||||
|
||||
pub fn install() {
|
||||
pub fn install() -> std::sync::MutexGuard<'static, ()> {
|
||||
let turn = super::dictionaries_turn();
|
||||
super::install_dictionary(AFF, DIC).unwrap();
|
||||
turn
|
||||
}
|
||||
|
||||
@@ -195,6 +195,68 @@ 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.
|
||||
@@ -2834,23 +2896,12 @@ 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);
|
||||
select_whole_document(&mut s);
|
||||
run(&mut s, "select.all", json!({}));
|
||||
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}");
|
||||
@@ -2859,7 +2910,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);
|
||||
select_whole_document(&mut s);
|
||||
run(&mut s, "select.all", json!({}));
|
||||
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}");
|
||||
@@ -3598,6 +3649,7 @@ 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"}));
|
||||
@@ -3617,6 +3669,18 @@ 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
|
||||
@@ -4648,6 +4712,60 @@ fn issues_1281_1045_english_dialects_proof_typed_text() {
|
||||
assert_eq!(words, ["21th"]);
|
||||
}
|
||||
|
||||
/// #4281: Home › Numbering offers every preset, "a. b. c." among them, and picking another preset
|
||||
/// for a list that is already numbered changes its style (only picking the same one again turns it off).
|
||||
#[test]
|
||||
fn the_numbering_gallery_presets_each_apply_and_switch_between_each_other() {
|
||||
let labels = |s: &mut Session| numbers(s).into_iter().map(|(l, _)| l.unwrap_or_default()).collect::<Vec<_>>();
|
||||
for (kind, want) in [
|
||||
("numbered", ["1.", "2.", "3."]),
|
||||
("numberedParen", ["1)", "2)", "3)"]),
|
||||
("outline", ["I.", "II.", "III."]),
|
||||
("upperLetter", ["A.", "B.", "C."]),
|
||||
("lowerLetter", ["a)", "b)", "c)"]),
|
||||
("lowerLetterDot", ["a.", "b.", "c."]),
|
||||
("lowerRoman", ["i.", "ii.", "iii."]),
|
||||
] {
|
||||
let mut s = s();
|
||||
typ(&mut s, "One\nTwo\nThree");
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "para.numbering", json!({"kind": kind}));
|
||||
assert_eq!(labels(&mut s), want, "{kind}");
|
||||
// Picking the same preset again turns the list off.
|
||||
run(&mut s, "para.numbering", json!({"kind": kind}));
|
||||
assert_eq!(labels(&mut s), ["", "", ""], "{kind} again");
|
||||
}
|
||||
// From one preset to another: the list changes style, it doesn't go off.
|
||||
let mut s = s();
|
||||
typ(&mut s, "One\nTwo\nThree");
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "para.numbering", json!({"kind": "numbered"}));
|
||||
for (kind, want) in [("upperLetter", "A."), ("lowerLetterDot", "a."), ("lowerRoman", "i."), ("outline", "I."), ("numbered", "1.")] {
|
||||
run(&mut s, "para.numbering", json!({"kind": kind}));
|
||||
assert_eq!(labels(&mut s)[0], want, "to {kind}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #4281: whatever level a list item is on, picking a different Numbering preset changes the list
|
||||
/// and never turns it off; deeper levels of two presets can look alike.
|
||||
#[test]
|
||||
fn another_numbering_preset_never_switches_a_list_off_at_any_level() {
|
||||
let kinds = ["numbered", "numberedParen", "outline", "upperLetter", "lowerLetter", "lowerLetterDot", "lowerRoman"];
|
||||
for a in kinds {
|
||||
for b in kinds.into_iter().filter(|b| *b != a) {
|
||||
for level in 0..9 {
|
||||
let mut s = s();
|
||||
typ(&mut s, "One");
|
||||
run(&mut s, "para.numbering", json!({"kind": a}));
|
||||
run(&mut s, "para.listLevel", json!({"level": level}));
|
||||
run(&mut s, "para.numbering", json!({"kind": b}));
|
||||
let label = numbers(&mut s).into_iter().next().and_then(|(l, _)| l);
|
||||
assert!(label.is_some(), "{a} -> {b} at level {level} turned the list off");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the first paragraph's list label starts (points from the page's text edge), and where its text starts.
|
||||
fn label_and_text_x(s: &mut Session) -> (f32, f32) {
|
||||
let l = s.layout();
|
||||
|
||||
+135
-12
@@ -13,14 +13,56 @@ 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::{decode, is_text, legacy};
|
||||
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))
|
||||
}
|
||||
|
||||
/// 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 enc = encoding_rs::Encoding::for_label(label.trim().as_bytes())?;
|
||||
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())?;
|
||||
Some(enc.decode(b).0.into_owned())
|
||||
}
|
||||
|
||||
@@ -28,7 +70,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{000C}')).collect();
|
||||
let clean: String = text.chars().filter(|c| !c.is_control() || matches!(c, '\n' | '\t' | '\u{000B}' | '\u{000C}' | '\u{000E}')).collect();
|
||||
Document::from_text(&clean)
|
||||
}
|
||||
|
||||
@@ -57,18 +99,23 @@ 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 cells: Vec<String> = row
|
||||
.iter()
|
||||
.map(|c| {
|
||||
if depth > 8 {
|
||||
return String::new();
|
||||
}
|
||||
let mut cells: Vec<String> = Vec::new();
|
||||
for c in row {
|
||||
if c.covered || depth > 8 {
|
||||
cells.push(String::new());
|
||||
} else {
|
||||
let mut v = Vec::new();
|
||||
blocks_text(&c.blocks, &mut v, &mut ListCounter::default(), depth + 1);
|
||||
v.join(" ")
|
||||
})
|
||||
.collect();
|
||||
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());
|
||||
out.push(cells.join("\t"));
|
||||
}
|
||||
}
|
||||
@@ -86,3 +133,79 @@ 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,6 +1,7 @@
|
||||
use super::ctx::{Ctx, Joining, page_anchored};
|
||||
use super::floats::{
|
||||
AnchoredFloat, ObjFrame, ObjectPlacement, WrapArea, align_in, float_rect, floating, left_out_objects, place_objects, rel_exclusions, wrap_area,
|
||||
AnchoredFloat, AreaKind, 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;
|
||||
@@ -162,11 +163,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, true));
|
||||
exclusions.push((area, false, None, WrapText::BothSides, AreaKind::Table));
|
||||
float_tables.push(area);
|
||||
table_areas.push(area);
|
||||
if float.v_rel == Anchor::Page {
|
||||
page_table_wraps.push((area, false, None, WrapText::BothSides, true));
|
||||
page_table_wraps.push((area, false, None, WrapText::BothSides, AreaKind::Table));
|
||||
}
|
||||
(rect.x, rect.y)
|
||||
}
|
||||
@@ -812,7 +813,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, false)];
|
||||
let mut areas = vec![(rect, false, None, WrapText::Right, AreaKind::Object)];
|
||||
// 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
|
||||
@@ -820,7 +821,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, false));
|
||||
areas.push((Rect::new(self.left, below, width.max(0.01), self.bottom() - below), true, None, WrapText::BothSides, AreaKind::Object));
|
||||
}
|
||||
(gap, areas)
|
||||
}
|
||||
|
||||
@@ -117,8 +117,20 @@ 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 whether it comes from a floating table (inclusive line-bottom contact, #3977).
|
||||
pub(crate) type WrapArea = (Rect, bool, Option<Arc<contour::Contour>>, WrapText, bool);
|
||||
/// 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,
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -210,13 +222,14 @@ 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, false));
|
||||
return Some((area, false, Some(Arc::new(c)), float.wrap_text, AreaKind::Tight));
|
||||
}
|
||||
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);
|
||||
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))
|
||||
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))
|
||||
}
|
||||
|
||||
/// Wrap areas relative to a paragraph whose column starts at `x0` and whose top is `y0`, with
|
||||
@@ -224,7 +237,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, table)| para::Exclusion {
|
||||
.map(|(r, tb, c, side, kind)| para::Exclusion {
|
||||
top: r.y - y0,
|
||||
bottom: r.bottom() - y0,
|
||||
left: r.x - x0,
|
||||
@@ -232,7 +245,8 @@ pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32, space_before:
|
||||
top_bottom: *tb,
|
||||
contour: c.clone(),
|
||||
side: *side,
|
||||
table: *table,
|
||||
table: *kind == AreaKind::Table,
|
||||
tight: *kind == AreaKind::Tight,
|
||||
})
|
||||
// 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, false));
|
||||
pb.excl.push((Rect::new(pb.col_x(), top, pb.col_w() - 26.0, 100.0), false, None, WrapText::BothSides, crate::floats::AreaKind::Object));
|
||||
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");
|
||||
|
||||
@@ -786,6 +786,42 @@ impl DocLayout {
|
||||
None
|
||||
}
|
||||
|
||||
/// The text direction of the lines holding `pos`; `None` for upright (horizontal) text.
|
||||
pub fn turn_at(&self, pos: &Pos, page_hint: usize) -> Option<TextDirection> {
|
||||
self.pieces(pos.story, &pos.path, page_hint).into_iter().find_map(|(_, it)| match it {
|
||||
Placed::Lines { para, l0, l1, turn, .. } if turn.is_turned() && (*l0..*l1).contains(¶.line_of(pos.off)) => Some(*turn),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// In turned text, the position on the next (`next`) or previous line in reading order, at
|
||||
/// `goal` along the line (its own frame; `None` keeps the caret's). Returns it with that
|
||||
/// along-line coordinate. Only lines of the same flow count (the paragraphs of one story
|
||||
/// level or of one table cell, not another cell's), so `None` at the first/last line of the
|
||||
/// caret's flow on the page.
|
||||
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 here = lines.iter().position(|(path, para, li)| *path == &pos.path && *li == para.line_of(pos.off))?;
|
||||
let (path, para, li) = lines.get(if next { here + 1 } else { here.checked_sub(1)? })?;
|
||||
let gx = match goal {
|
||||
Some(g) => g,
|
||||
None => lines[here].1.x_of(lines[here].2, pos.off)?,
|
||||
};
|
||||
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).
|
||||
pub fn vertical(&self, pos: &Pos, goal_x: Option<f32>, dir: i32, page_hint: usize) -> Option<(Pos, f32)> {
|
||||
let c = self.caret_on(pos, page_hint)?;
|
||||
|
||||
@@ -173,6 +173,9 @@ 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 {
|
||||
|
||||
+118
-18
@@ -30,6 +30,9 @@ 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,
|
||||
@@ -208,6 +211,7 @@ 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()
|
||||
@@ -295,7 +299,9 @@ 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).map(|mut spans| (spans.pop_front(), spans)) {
|
||||
match row_spans(self.exclusions, row, (lo, self.base_right), self.tight_indent, self.layout_2013)
|
||||
.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 };
|
||||
@@ -1190,10 +1196,28 @@ fn line_end_kern(pl: &ParaLayout, j: usize) -> f32 {
|
||||
}
|
||||
}
|
||||
|
||||
/// Narrowest span text flows into beside a floating object, points. Word puts an empty
|
||||
/// Narrowest span text flows into beside a floating table, 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
|
||||
@@ -1224,16 +1248,18 @@ 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). `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); 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").
|
||||
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();
|
||||
@@ -1241,13 +1267,14 @@ 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).
|
||||
let mut taken: Vec<(f32, f32, f32)> = Vec::new();
|
||||
// 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();
|
||||
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)),
|
||||
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))),
|
||||
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))),
|
||||
}
|
||||
// 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 };
|
||||
@@ -1260,23 +1287,96 @@ fn row_spans(
|
||||
_ => left - lo >= hi - right,
|
||||
};
|
||||
taken.truncate(first);
|
||||
taken.push(if text_left { (left, hi.max(right), e.bottom) } else { (lo.min(left), right, e.bottom) });
|
||||
taken.push(if text_left { (left, hi.max(right), e.bottom, min) } else { (lo.min(left), right, e.bottom, min) });
|
||||
}
|
||||
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)]));
|
||||
}
|
||||
let mut spans = vec![(lo, hi)];
|
||||
for &(left, right, _) in &taken {
|
||||
// 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 {
|
||||
spans = spans
|
||||
.into_iter()
|
||||
.flat_map(|(a, b)| if right <= a || left >= b { vec![(a, b)] } else { vec![(a, left.min(b)), (right.max(a), b)] })
|
||||
.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)]
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
spans.retain(|(a, b)| b - a >= MIN_SPAN);
|
||||
let spans: VecDeque<(f32, f32)> = spans.into_iter().filter(|(a, b, ml, mr)| b - a >= ml.max(*mr)).map(|(a, b, ..)| (a, b)).collect();
|
||||
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.into())
|
||||
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:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1775,7 +1775,10 @@ 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.
|
||||
/// 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.
|
||||
fn stale_grid_widths(t: &Table, grid: &[f32]) -> Option<Vec<f32>> {
|
||||
const WIDTH_EPSILON: f32 = 0.5;
|
||||
const EDGE_EPSILON: f32 = 0.01;
|
||||
@@ -2035,6 +2038,57 @@ 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::{WrapArea, align_in, body_wraps};
|
||||
use super::floats::{AreaKind, 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, true));
|
||||
pb.excl.push((area, false, None, WrapText::BothSides, AreaKind::Table));
|
||||
pb.float_tables.push(area);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -12574,6 +12574,68 @@ 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();
|
||||
|
||||
@@ -1167,3 +1167,46 @@ fn a_page_reference_into_nested_text_boxes_stops_where_layout_does() {
|
||||
let output = layout(&d, &mut LayoutCache::new(), &LayoutOptions { output_page_refs: true, ..Default::default() });
|
||||
assert_eq!(shown_in(&output, 0, StoryRef::Body), ["2", "2", "9"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_keeps_a_multiple_spaced_picture_line_while_the_picture_fits() {
|
||||
// A paragraph holding only a picture, at 1.15 spacing, as the page's last line stays on the
|
||||
// page while the picture itself ends above the bottom margin; the font's descent and the
|
||||
// spacing's leading below it may run into the margin. Only the picture's own extent counts:
|
||||
// ending 1 pt above the margin it stays, reaching past the margin it moves on.
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
let make = |h: f32| {
|
||||
let mut d = Document::from_text("A line of text\n");
|
||||
for b in &mut d.body {
|
||||
if let wordcraft_doc::Block::Para(p) = Arc::make_mut(b) {
|
||||
p.props.line_spacing = Some(LineSpacing::Multiple(1.15));
|
||||
p.props.space_after = Some(0.0);
|
||||
p.props.space_before = Some(0.0);
|
||||
}
|
||||
}
|
||||
d.insert_object(&Pos::body(1, 0), super::rect_shape(200.0, h, Default::default()), &Default::default()).unwrap();
|
||||
lay(&d)
|
||||
};
|
||||
let bottom = {
|
||||
let s = &Document::from_text("").last_section;
|
||||
s.page_h - s.margin_bottom
|
||||
};
|
||||
// Where the picture's line starts: below the text line, whatever the test font's height.
|
||||
let control = make(10.0);
|
||||
assert_eq!(control.pages.len(), 1);
|
||||
let pic_top = control.pages[0]
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|it| match it {
|
||||
Placed::Lines { story: StoryRef::Body, y, para, l0, .. } if para.lines.get(*l0).is_some() => Some(*y),
|
||||
_ => None,
|
||||
})
|
||||
.fold(f32::MIN, f32::max);
|
||||
let room = bottom - pic_top;
|
||||
assert!(room > 500.0, "{room}");
|
||||
let fits = make(room - 1.0);
|
||||
assert_eq!(fits.pages.len(), 1, "a picture ending 1 pt above the margin stays on the page ({room})");
|
||||
let too_tall = make(room + 0.5);
|
||||
assert_eq!(too_tall.pages.len(), 2, "a picture reaching past the margin moves on ({room})");
|
||||
}
|
||||
|
||||
@@ -171,3 +171,46 @@ fn a_click_outside_a_floating_table_in_a_vertical_section_skips_its_cells() {
|
||||
// Inside the table a click still lands in a cell.
|
||||
assert!(l.hit(0, cx, cy, StoryRef::Body).unwrap().path.0.len() > 1);
|
||||
}
|
||||
|
||||
/// #8986: in vertical text the next line is the next paragraph's, left of this one, at the same
|
||||
/// distance along it; the first and last lines have no previous/next.
|
||||
#[test]
|
||||
fn turned_line_steps_to_the_adjacent_column() {
|
||||
crate::test_fonts();
|
||||
let mut d = Document::from_text("abc\ndef\nghi");
|
||||
d.last_section.text_direction = TextDirection::Down;
|
||||
let l = lay(&d);
|
||||
let p = Pos::body(1, 1);
|
||||
assert_eq!(l.turn_at(&p, 0), Some(TextDirection::Down));
|
||||
let (next, g) = l.turned_line(&p, None, true, 0).unwrap();
|
||||
assert_eq!((next.path, next.off), (Path::top(2), 1));
|
||||
let (prev, _) = l.turned_line(&p, Some(g), false, 0).unwrap();
|
||||
assert_eq!((prev.path, prev.off), (Path::top(0), 1));
|
||||
assert!(l.turned_line(&Pos::body(2, 0), None, true, 0).is_none());
|
||||
assert_eq!(lay(&Document::from_text("abc")).turn_at(&Pos::body(0, 0), 0), None);
|
||||
}
|
||||
|
||||
/// #8986: in a table whose cells run vertical text, the next line is one of the same cell, never
|
||||
/// another cell's (a cell's only line has no previous/next).
|
||||
#[test]
|
||||
fn turned_line_stays_in_its_table_cell() {
|
||||
crate::test_fonts();
|
||||
let mut d = Document::from_text("before");
|
||||
let mut t = wordcraft_doc::Table::new(1, 3, 468.0);
|
||||
for (i, c) in t.rows[0].cells.iter_mut().enumerate() {
|
||||
c.props.text_direction = TextDirection::Down;
|
||||
let paras = if i == 1 { ["abc", "def"].as_slice() } else { ["xyz"].as_slice() };
|
||||
c.blocks = paras.iter().map(|s| wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(s, Default::default()))).collect();
|
||||
}
|
||||
d.insert_block(StoryRef::Body, &Path::top(1), Block::Table(t)).unwrap();
|
||||
let l = lay(&d);
|
||||
let at = |cell: u32, para: u32, off: usize| Pos { story: StoryRef::Body, path: Path(vec![1, 0, cell, para]), off };
|
||||
let (next, _) = l.turned_line(&at(1, 0, 1), None, true, 0).unwrap();
|
||||
assert_eq!((next.path, next.off), (Path(vec![1, 0, 1, 1]), 1));
|
||||
assert!(l.turned_line(&at(1, 1, 1), None, true, 0).is_none());
|
||||
assert!(l.turned_line(&at(1, 0, 1), None, false, 0).is_none());
|
||||
for cell in [0, 2] {
|
||||
assert!(l.turned_line(&at(cell, 0, 1), None, true, 0).is_none());
|
||||
assert!(l.turned_line(&at(cell, 0, 1), None, false, 0).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,6 +126,7 @@ impl WordApp {
|
||||
applied_editing: None,
|
||||
frame_ms: 0.0,
|
||||
quit_requested: false,
|
||||
quit_recheck: false,
|
||||
autosave: true,
|
||||
zotero: zotero::ZoteroLink::default(),
|
||||
ctx: None,
|
||||
@@ -264,8 +265,12 @@ impl WordApp {
|
||||
if let Some(ctx) = self.ctx.clone() {
|
||||
self.run_fired(&ctx, &out);
|
||||
self.canvas.take_focus_after_pass(&ctx);
|
||||
self.native_scale = theme::usable_scale(ctx.native_pixels_per_point().unwrap_or(1.0));
|
||||
if let Some(native) = ctx.native_pixels_per_point()
|
||||
// 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
|
||||
&& let Some(old) = self.legacy_interface_size.take()
|
||||
{
|
||||
self.ui.interface_size = theme::migrate_legacy_interface_size(old, native);
|
||||
|
||||
@@ -519,7 +519,12 @@ impl WordApp {
|
||||
return false;
|
||||
}
|
||||
if self.quit_requested {
|
||||
return true;
|
||||
// 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;
|
||||
}
|
||||
// Nothing to save, also with no document open in this window (#1129) and none elsewhere.
|
||||
if !self.has_unsaved_documents() {
|
||||
|
||||
@@ -653,13 +653,17 @@ fn mark_areas(app: &mut WordApp, layout: &DocLayout, selected: &[(usize, wordcra
|
||||
areas
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
/// 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 {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -862,11 +866,12 @@ 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())
|
||||
.navigation(navigation_options(animations))
|
||||
.editor(craft::ui::primitives::EditorPurpose::Text)
|
||||
.inactive_edits(inactive_edits)
|
||||
.rulers(show_rulers)
|
||||
@@ -1054,7 +1059,12 @@ 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);
|
||||
rulers::page_rulers(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;
|
||||
}
|
||||
// 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));
|
||||
|
||||
@@ -104,6 +104,27 @@ pub(crate) fn show(app: &mut WordApp, ui: &mut Ui, opener: &Response, ask: Optio
|
||||
}
|
||||
}
|
||||
|
||||
/// A menu row for `edit.paste` that runs `WordApp::run("edit.paste", ...)` directly instead of
|
||||
/// `MenuItem::command`: `edit.paste` is linked to the framework's `EditCommands::Paste`, which
|
||||
/// routes through `ViewportCommand::RequestPaste` when the page canvas has focus and silently does
|
||||
/// nothing if the platform paste event never arrives or carries no text (#8849).
|
||||
pub(crate) fn paste_menu_item(app: &mut WordApp, ui: &mut Ui) {
|
||||
let resolved = craft::ui::runtime::commands::resolve(ui.ctx(), CommandRef::new("edit.paste"));
|
||||
let mut row = MenuItem::new(tl!("Paste").to_string()).enabled(resolved.enabled);
|
||||
if let Some(chord) = &resolved.chord {
|
||||
row = row.shortcut(chord.display(craft::ui::runtime::windows::os_of(ui.ctx())));
|
||||
}
|
||||
if !resolved.enabled
|
||||
&& let Some(hint) = &resolved.hint
|
||||
{
|
||||
row = row.tooltip(craft::ui::contract::TooltipSpec::new(hint.clone()).disabled_text(hint.clone()));
|
||||
}
|
||||
if row.show(ui).ran {
|
||||
let _ = app.run("edit.paste", json!({}));
|
||||
app.canvas.focus_page(ui.ctx());
|
||||
}
|
||||
}
|
||||
|
||||
/// A row labelled `label` that runs command `id` with `params`; its chord, enabled state and
|
||||
/// action come from the command, its wording from the menu (one command id serves several rows).
|
||||
fn item(ui: &mut Ui, label: &str, id: &str, params: Value) {
|
||||
@@ -142,7 +163,7 @@ fn rows(app: &mut WordApp, ui: &mut Ui) {
|
||||
item(ui, "Copy", "edit.copy", json!({}));
|
||||
// How to paste, chosen before pasting (#2583): the ribbon's Paste menu, item for item. Paste
|
||||
// keeps the clipboard's formatting (Word's Keep Source Formatting).
|
||||
item(ui, "Paste", "edit.paste", json!({}));
|
||||
paste_menu_item(app, ui);
|
||||
item(ui, "Keep Text Only", "edit.pasteText", json!({}));
|
||||
item(ui, "Merge Formatting", "edit.pasteMerge", json!({}));
|
||||
item(ui, "Paste Special…", "edit.pasteSpecial", json!({}));
|
||||
|
||||
@@ -66,6 +66,8 @@ 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,
|
||||
}
|
||||
@@ -121,6 +123,7 @@ impl Component for EquationFrameControl<'_> {
|
||||
line: cx.color(t.color.overlay.line),
|
||||
accent: cx.color(t.color.accent.solid),
|
||||
soft: cx.color(t.color.accent.soft),
|
||||
shade: cx.color(t.color.accent.solid.with_alpha(40)),
|
||||
handle_fill: cx.color(t.color.overlay.handle_fill),
|
||||
handle_stroke: cx.color(t.color.overlay.handle_stroke),
|
||||
}
|
||||
@@ -160,7 +163,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.soft);
|
||||
draw.fill(&PaintShape::Rect(arg, CornerRadius::ZERO), style.shade);
|
||||
}
|
||||
draw.fill(&PaintShape::Rect(strip, CornerRadius::ZERO), style.soft);
|
||||
let (c, w) = (strip.center(), style.chevron / 2.0);
|
||||
|
||||
@@ -300,6 +300,10 @@ 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,9 +8,11 @@ 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 default step of a quarter second.
|
||||
/// (`tooltip::DELAY`, the framework's look), at the harness's configured step time (`predicted_dt`).
|
||||
fn rest_for_tip(h: &mut H) {
|
||||
let frames = (craft::ui::contract::tooltip::DELAY / 0.25).ceil() as usize + 3;
|
||||
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;
|
||||
steps(h, frames);
|
||||
}
|
||||
|
||||
@@ -2899,3 +2901,67 @@ 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,7 +14,14 @@ 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 {
|
||||
let mut b = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0));
|
||||
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);
|
||||
if let Some(dt) = dt {
|
||||
b = b.with_step_dt(dt);
|
||||
}
|
||||
@@ -26,9 +33,7 @@ fn window_dt(a: WordApp, dt: Option<f32>) -> H {
|
||||
},
|
||||
a,
|
||||
);
|
||||
for _ in 0..6 {
|
||||
h.app_frame();
|
||||
}
|
||||
steps(&mut h, settle);
|
||||
h
|
||||
}
|
||||
|
||||
@@ -262,12 +267,17 @@ 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();
|
||||
(window_dt(a, Some(1.0 / 60.0)), id)
|
||||
(sized_window(a, size, Some(1.0 / 60.0), settle), id)
|
||||
}
|
||||
|
||||
/// Click comment `id`'s balloon (from no selected balloon): the card is selected with no edit open (as in Word), then
|
||||
@@ -408,6 +418,24 @@ 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]
|
||||
@@ -977,3 +1005,29 @@ fn a_footnote_link_shows_its_tip_with_the_caret_in_the_body() {
|
||||
assert!(h.query_all_by_label_contains("https://example.com/note").count() > 0, "the footnote's link shows its tip (pointer at {at:?})");
|
||||
assert_eq!(h.query_all_by_label_contains("Inserted ").count(), 0, "not the tracked insertion's tip");
|
||||
}
|
||||
|
||||
/// #8849: choosing Paste in the right-click context menu pastes from the system clipboard
|
||||
/// directly without relying on a platform `RequestPaste` round-trip.
|
||||
#[test]
|
||||
fn context_menu_paste_inserts_system_clipboard_text() {
|
||||
use craft::platform::clipboard::{Clipboard, Flavor, MemoryClipboard};
|
||||
let mut clipboard = Clipboard::new(MemoryClipboard::default());
|
||||
let _ = clipboard.write(&[Flavor::text("pasted text")]).unwrap();
|
||||
let mut h = crate::test_harness::builder_with(move || crate::test_harness::install_spec().clipboard(clipboard))
|
||||
.with_size(egui::vec2(1440.0, 900.0))
|
||||
.build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Hello ")), Default::default()),
|
||||
);
|
||||
steps(&mut h, 6);
|
||||
let at = caret_point(&mut h, &Pos::body(0, 6));
|
||||
right_click(&mut h, at);
|
||||
assert!(h.state().canvas.context_menu_open, "menu open");
|
||||
pick(&mut h, &["Paste"]);
|
||||
steps(&mut h, 3);
|
||||
assert_eq!(h.state().session.doc.body[0].as_para().unwrap().plain_text(), "Hello pasted text");
|
||||
}
|
||||
|
||||
@@ -252,10 +252,14 @@ 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), 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).
|
||||
/// 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).
|
||||
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,3 +425,61 @@ 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.
|
||||
/// `\@` picture for date fields. Empty uses the field language's default.
|
||||
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: DATE_FORMATS.first().copied().unwrap_or("M/d/yyyy").to_string(),
|
||||
date_format: String::new(),
|
||||
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 = if name == "TIME" { "h:mm am/pm" } else { "M/d/yyyy" }.into();
|
||||
self.date_format.clear();
|
||||
}
|
||||
self.code = self.instruction();
|
||||
}
|
||||
@@ -377,10 +377,14 @@ impl FieldForm {
|
||||
match field_kind(&self.name) {
|
||||
FieldKind::Date => {
|
||||
text_field(ui, "field_date", &word("Date formats:"), &mut self.date_format);
|
||||
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);
|
||||
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());
|
||||
if let Some(at) = list_index(ui, &word("Date formats:"), &samples, current).selected
|
||||
&& let Some(p) = DATE_FORMATS.get(at)
|
||||
&& let Some(p) = 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 \@ "M/d/yyyy" \* MERGEFORMAT"#);
|
||||
assert_eq!(f.instruction(), r"DATE \* MERGEFORMAT");
|
||||
f.date_format = "yyyy-MM-dd".into();
|
||||
f.preserve = false;
|
||||
assert_eq!(f.instruction(), r#"DATE \@ "yyyy-MM-dd""#);
|
||||
@@ -275,6 +275,73 @@ 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,6 +481,9 @@ 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,6 +50,39 @@ 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());
|
||||
@@ -59,7 +92,8 @@ fn bar_over(pick: &str) -> H {
|
||||
}
|
||||
|
||||
/// `bar_over` for an app whose document and selection are already set up.
|
||||
fn bar_over_app(a: WordApp) -> H {
|
||||
fn bar_over_app(mut a: WordApp) -> H {
|
||||
a.font_catalog.get_or_insert_with(crate::test_harness::fixed_catalog);
|
||||
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();
|
||||
@@ -352,16 +386,6 @@ 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.
|
||||
|
||||
@@ -220,6 +220,7 @@ 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 = [
|
||||
@@ -228,7 +229,10 @@ 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">"#)),
|
||||
(comma_srcset_url, format!(r#"<img src="{url}" srcset="{comma_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">"#)),
|
||||
];
|
||||
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)]);
|
||||
@@ -239,12 +243,17 @@ mod tests {
|
||||
assert_eq!(pictures(&mut app), 0);
|
||||
}
|
||||
|
||||
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);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -170,8 +170,8 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
};
|
||||
let face = Button::new(tl!("Paste").to_string()).icon(IconId::new("paste")).tooltip(paste_tip).arrangement(Arrangement::Stacked);
|
||||
menu_button(ui, face, tl!("Paste").to_string(), Some("edit.paste"), |ui, _| {
|
||||
crate::canvas::context_menu::paste_menu_item(app, ui);
|
||||
for (label, id) in [
|
||||
("Paste", "edit.paste"),
|
||||
("Keep Text Only", "edit.pasteText"),
|
||||
("Merge Formatting", "edit.pasteMerge"),
|
||||
("Paste as Nested Table", "edit.pasteNestedTable"),
|
||||
@@ -204,8 +204,9 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
if let Some(f) = out.picked {
|
||||
let _ = app.run("format.font", json!({"name": f}));
|
||||
}
|
||||
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())
|
||||
// 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())
|
||||
.tooltip(tl!("Font Size").to_string())
|
||||
.show(ui);
|
||||
painted_ibeam_over(ui, &out.edit.response);
|
||||
@@ -312,6 +313,7 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
("I. II. III.", "outline"),
|
||||
("A. B. C.", "upperLetter"),
|
||||
("a) b) c)", "lowerLetter"),
|
||||
("a. b. c.", "lowerLetterDot"),
|
||||
("i. ii. iii.", "lowerRoman"),
|
||||
] {
|
||||
MenuItem::command(CommandRef::with_params("para.numbering", json!({"kind": k}))).label(tl!(l).to_string()).show(ui);
|
||||
@@ -553,7 +555,9 @@ mod tests {
|
||||
h.app_frame();
|
||||
assert!(!tooltip_visible(&h), "just focused: hint should not show before tooltip delay");
|
||||
|
||||
let delay_frames = (craft::ui::contract::tooltip::DELAY / 0.25).ceil() as usize + 3;
|
||||
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;
|
||||
for _ in 0..delay_frames {
|
||||
h.step();
|
||||
}
|
||||
|
||||
@@ -413,6 +413,11 @@ 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
|
||||
@@ -471,6 +476,11 @@ 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");
|
||||
@@ -1593,3 +1603,54 @@ fn picture_and_shape_size_fields_show_unit_hints() {
|
||||
assert!(h.query_by_label_contains(expected).is_some(), "{tab} W: hover tooltip shows unit hint");
|
||||
}
|
||||
}
|
||||
|
||||
/// #4281: the Numbering drop-down lists "a. b. c." and applies it, then switching to another
|
||||
/// preset changes the list instead of turning it off.
|
||||
#[test]
|
||||
fn the_numbering_menu_offers_a_dot_b_dot_c_dot() {
|
||||
use egui_kittest::kittest::{By, Queryable};
|
||||
let item = |label: &'static str| By::new().label_contains(label);
|
||||
let mut a = crate::WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
a.run("text.insert", json!({"text": "One"})).unwrap();
|
||||
let mut h = app_harness(a, vec2(2560.0, 900.0));
|
||||
let label = |h: &mut egui_kittest::Harness<'_, crate::WordApp>| {
|
||||
let l = h.state_mut().session.layout();
|
||||
l.pages.iter().flat_map(|p| &p.items).find_map(|i| match i {
|
||||
wordcraft_layout::Placed::Lines { para, l0: 0, .. } => para.label.as_ref().map(|lb| lb.text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
h.query_all(By::new().role(egui::accesskit::Role::Button).label("Numbering options")).last().expect("the Numbering arrow").click();
|
||||
crate::test_harness::frames(&mut h, 3);
|
||||
for want in ["1. 2. 3.", "a) b) c)", "a. b. c.", "i. ii. iii."] {
|
||||
assert!(h.query(item(want)).is_some(), "the menu lists {want}");
|
||||
}
|
||||
h.get(item("a. b. c.")).click();
|
||||
crate::test_harness::frames(&mut h, 3);
|
||||
assert_eq!(label(&mut h).as_deref(), Some("a."));
|
||||
h.query_all(By::new().role(egui::accesskit::Role::Button).label("Numbering options")).last().expect("the Numbering arrow").click();
|
||||
crate::test_harness::frames(&mut h, 3);
|
||||
h.get(item("A. B. C.")).click();
|
||||
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,5 +1,9 @@
|
||||
//! 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 and its multipliers.
|
||||
//! 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;
|
||||
|
||||
/// 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,6 +50,11 @@ 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,3 +169,60 @@ 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}");
|
||||
}
|
||||
}
|
||||
|
||||
+29
-22
@@ -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 (a wheel line scrolls less under the framework's page view).
|
||||
for _ in 0..240 {
|
||||
// Away from the caret, several pages down.
|
||||
for _ in 0..40 {
|
||||
frame(&mut a, vec![wheel(-1.0, egui::Modifiers::NONE)]);
|
||||
}
|
||||
for _ in 0..60 {
|
||||
@@ -2463,29 +2463,36 @@ fn clicks_on_ribbon_and_status_bar_chrome_keep_typing_in_the_document() {
|
||||
/// I-beam on a native Windows shell; other shells keep the system text cursor.
|
||||
#[test]
|
||||
fn the_ribbon_font_size_box_shows_a_painted_ibeam_on_windows() {
|
||||
use craft::host::target::{Os, Runtime};
|
||||
use craft::host::target::{Caps, Os, Runtime, ShellInfo};
|
||||
use craft::ui::InstallSpec;
|
||||
use egui::accesskit::Role;
|
||||
|
||||
let mut h = harness(app());
|
||||
h.run_steps(4);
|
||||
let size =
|
||||
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").rect();
|
||||
h.hover_at(size.center());
|
||||
h.step();
|
||||
h.step();
|
||||
let hover_font_size = |os: Os| {
|
||||
let shell = ShellInfo::current().os(os).runtime(Runtime::Native).caps(Caps::native(os));
|
||||
let spec = move || InstallSpec::new(shell, std::sync::Arc::new(craft::ui::testing::windows::NoWindows));
|
||||
let mut h = crate::test_harness::builder_with(spec).with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| app());
|
||||
h.run_steps(4);
|
||||
let size = 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")
|
||||
.rect();
|
||||
h.hover_at(size.center());
|
||||
h.step();
|
||||
h.step();
|
||||
h
|
||||
};
|
||||
|
||||
let env = craft::ui::runtime::env::Env::of_root(&h.ctx);
|
||||
let shell = env.view().shell();
|
||||
if shell.os == Os::Windows && shell.runtime == Runtime::Native {
|
||||
assert!(h.output().platform_output.cursor_image.is_some(), "the font size box asks for the painted I-beam on Windows native");
|
||||
assert_eq!(
|
||||
craft::ui::runtime::cursor::current(&h.ctx),
|
||||
Some(craft::behavior::cursor::Cursor::Painted(craft::behavior::cursor::PaintedCursor::IBeam)),
|
||||
"the font size box asks for the painted I-beam"
|
||||
);
|
||||
} else {
|
||||
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Text, "other shells keep the text cursor");
|
||||
}
|
||||
let win = hover_font_size(Os::Windows);
|
||||
assert!(win.output().platform_output.cursor_image.is_some(), "the font size box asks for the painted I-beam on Windows native");
|
||||
assert_eq!(
|
||||
craft::ui::runtime::cursor::current(&win.ctx),
|
||||
Some(craft::behavior::cursor::Cursor::Painted(craft::behavior::cursor::PaintedCursor::IBeam)),
|
||||
"the font size box asks for the painted I-beam"
|
||||
);
|
||||
|
||||
let linux = hover_font_size(Os::Linux);
|
||||
assert_eq!(linux.output().platform_output.cursor_icon, egui::CursorIcon::Text, "other shells keep the text cursor");
|
||||
}
|
||||
|
||||
/// #1538: inserting WordArt leaves its text selected, so Delete erased only the text and the
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
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;
|
||||
@@ -13,18 +10,9 @@ 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);
|
||||
@@ -263,7 +251,9 @@ fn the_typed_list_shows_on_the_frame_of_the_keystroke() {
|
||||
"missing-font advice should wait until the pointer rests on the warning mark"
|
||||
);
|
||||
h.event(egui::Event::PointerMoved(warning_pos));
|
||||
let delay_frames = (tooltip::DELAY / 0.25).ceil() as usize + 3;
|
||||
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 = (tooltip::DELAY / step_dt).ceil() as usize + 3;
|
||||
h.run_steps(delay_frames);
|
||||
assert!(
|
||||
h.query_by_label(expected_note.as_str()).is_some(),
|
||||
|
||||
@@ -176,6 +176,7 @@ impl WordApp {
|
||||
applied_editing: _,
|
||||
frame_ms: _,
|
||||
quit_requested: _,
|
||||
quit_recheck: _,
|
||||
autosave: _,
|
||||
zotero: _,
|
||||
ctx: _,
|
||||
|
||||
@@ -254,11 +254,18 @@ 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.
|
||||
/// 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.
|
||||
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.frame_after_root_report(a, root, child);
|
||||
self.kit.child_info(self.info(true));
|
||||
self.frame_with_reported_info(a, root, child);
|
||||
}
|
||||
|
||||
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));
|
||||
fn frame_with_reported_info(&mut self, a: &mut WordApp, root: Vec<egui::Event>, child: Vec<egui::Event>) {
|
||||
if let Some(focused) = self.focused {
|
||||
self.kit.focus(focused);
|
||||
}
|
||||
@@ -1035,14 +1035,15 @@ 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_after_root_report(&mut a, Vec::new(), Vec::new());
|
||||
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);
|
||||
let title = a.window_title();
|
||||
rig.frame_after_root_report(&mut a, Vec::new(), Vec::new());
|
||||
rig.frame_with_reported_info(&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)
|
||||
}
|
||||
@@ -1063,9 +1064,68 @@ 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));
|
||||
for (inner, outer) in [(Some(rect), None), (None, Some(rect))] {
|
||||
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)),
|
||||
] {
|
||||
let (builder, _) = new_document_builder(inner, outer);
|
||||
assert_eq!(builder.position, None, "the platform picks the initial position without a usable predecessor");
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
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; 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 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 (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 | `shift_tab_and_tab_change_list_levels` |
|
||||
| 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 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` |
|
||||
@@ -169,6 +169,7 @@ including in headers and notes when the body uses balloons. Shift extends across
|
||||
| Backspace, then type | the typed text takes the formatting of the character Backspace deleted, not of the one now left of the caret: in `Abc abc` with `Abc` bold, Backspace after the space then `X` gives a plain X; Backspace after a bold letter that follows a plain space gives a bold X. The Bold button shows it before typing, also with the caret inside a word (where it otherwise shows the word). Several Backspaces: the last deleted character's formatting. A Backspace that changes nothing (at the start of the document) keeps it, and keeps formatting set at the caret too. Typing goes on with it (in `ab Cd` with `C` bold, Backspace after the C then `YX` gives a bold YX), and undoing that typing brings it back. Moving the caret any way drops it, not only with the caret keys: a click elsewhere (also one that comes back to the same place), Go To, Find (typing over the found word takes that word's formatting; a Find with no match keeps it) and a paste, whose text never takes it (formatted or plain; a paste with nothing on the clipboard keeps it); typing then takes the formatting where the caret is. A command that is refused (a Backspace into a content control locked against editing) keeps it, and formatting set at the caret too. Forward Delete, a deleted selection, a paragraph join, an object or a break carry nothing. With Track Changes on Backspace carries it too: the character stays, marked deleted (or goes, when it is the author's own tracked insertion), and the typed text is a tracked insertion with that formatting, never marked deleted; moving the caret away and back drops it. Ctrl+Backspace that deletes a word or joins paragraphs drops formatting carried by an earlier Backspace (one that deletes nothing, at the start of the document, keeps it, like Backspace). Undo takes the carried formatting back with the Backspace. Observed in Word for Windows (#6518) | `typing_after_backspace_takes_the_deleted_characters_formatting`, `backspace_formatting_is_dropped_by_a_caret_move_and_delete_does_not_carry`, `backspace_at_the_document_start_keeps_waiting_formatting`, `ctrl_backspace_at_the_document_start_keeps_waiting_formatting`, `backspace_formatting_is_not_kept_past_a_paste`, `backspace_formatting_is_not_kept_past_find_or_go_to`, `backspace_formatting_survives_a_paste_of_an_empty_clipboard`, `backspace_formatting_is_not_kept_past_a_direct_caret_move_and_back`, `a_refused_backspace_keeps_the_formatting_waiting_at_the_caret`, `backspace_formatting_follows_typing_and_comes_back_with_undo`, `tracked_backspace_carries_the_deleted_characters_formatting` |
|
||||
| select text right to left (from its end), type | the new text takes the first selected character's formatting (font, size…), as with a selection made left to right; not the text's before it (#2879) | `typing_over_backward_selection_keeps_its_font` |
|
||||
| Down / Up (↓ / ↑) from a line beside a table | into the table's nearest row: the cell under the caret, or the nearest one when the caret is left or right of the cells' text (the start of the line above a table is left of the first cell's text); never past the table to the paragraph beyond it | `down_and_up_from_a_line_start_beside_a_table_go_into_it` |
|
||||
| Arrows in vertical text (top-to-bottom, lines stacking leftwards, #8986) | Up / Down step to the previous / next character along the line; Left / Right go to the next / previous line (the column to the left / right), keeping the distance along the line. In bottom-to-top text Up steps forward and Left goes to the previous line. Left / Right stay within the text flow of the caret (a vertical section's paragraphs, or one table cell's): at its first or last line (a table cell's only line, say) they step along the text, as in horizontal text | `turned_line_steps_to_the_adjacent_column`, `turned_line_stays_in_its_table_cell` (layout) |
|
||||
| Alt+Shift+Up / Down (⌃⇧↑ / ⌃⇧↓) | the paragraphs the selection touches swap with the paragraph above / below, keeping style and list membership; the selection moves with them; one undo step. A selection ending at the start of a paragraph doesn't take it along. Refused at the top or bottom of the story or cell, next to a table and across a section break | `alt_shift_down_then_up_moves_a_paragraph_and_back_and_undoes` |
|
||||
| Alt+Shift+Left / Right (⌃⇧← / ⌃⇧→) | Promote / Demote: a heading goes up or down one level (Heading 1 and Heading 9 are the ends); promoted body text becomes a heading at the level of the heading before it; a list item changes level like Shift+Tab / Tab | `alt_shift_left_and_right_promote_and_demote_headings_and_list_items` |
|
||||
| Outline view: Alt+Shift+Up / Down, Left / Right | as above, but a collapsed heading takes what is hidden under it along: moving passes whole shown paragraphs with their hidden content; promote/demote shifts the hidden subheadings too | `outline_collapse_hides_descendants_and_expand_restores` |
|
||||
@@ -181,7 +182,7 @@ including in headers and notes when the body uses balloons. Shift extends across
|
||||
| AltGr (Right Alt on Polish, German, Czech… layouts) | AltGr+letter types the layout's character (AltGr+S → ś, AltGr+L → ł) and a bare AltGr tap does nothing; neither opens KeyTips. On Linux AltGr is the Right Alt key with Level 3 Shift, not Alt, so its modifiers event no longer reads as Alt let go (#2388); on Windows it is Ctrl+Alt. Right Alt on a layout without AltGr (US) is Alt and opens KeyTips like Left Alt | ui-egui `altgr_types_its_characters_without_keytips` |
|
||||
| Shift+Right (⇧→) at the end of a cell's text | the whole cell is selected first (its end-of-cell mark); the next Shift+Right selects the next cell with it. In an empty cell the first press selects the cell | `shift_right_at_the_end_of_a_cell_selects_the_cell_first` |
|
||||
| Left / Right (← / →) next to an equation | the arrow steps into the equation instead of over it: Right from just before it opens it at its start, Left from just after it opens it at its end. The arrows then move inside it; past its far end the caret leaves on that side, so the same arrow goes on to the text (or, with two equations side by side, steps into the next one: not yet compared with Word). With text selected, the arrow only collapses the selection, as elsewhere; Shift+Left / Right still selects over the equation as one character. **Differs:** not in right-to-left or mixed-direction paragraphs yet (see Known gaps) (#4138) | `left_and_right_keys_step_into_and_out_of_an_equation`, `right_out_of_an_equation_steps_into_the_one_beside_it`; `cmd::equation::tests::left_and_right_step_into_an_equation_next_to_the_caret` |
|
||||
| Left / Right across a tracked deletion (#8268) | WordCraft skips hidden deleted text and equations within a paragraph in No Markup. In a paragraph that supports entering equations with the arrow keys, the same press can enter a visible equation immediately beyond the deletion. Shift+Left / Right extends the selection across it. When deleted text is visible inline, it keeps its ordinary caret stops. | `tests::horizontal_caret_skips_hidden_tracked_deletions`, `tests::bidi::arrow_keys_skip_hidden_deletions_in_rtl_text`, `arrow_keys_skip_a_deleted_equation_in_no_markup`, `arrow_keys_enter_a_visible_equation_across_a_hidden_deletion` |
|
||||
| Left / Right and Ctrl+Left / Right across a tracked deletion (#8268, #8772) | WordCraft skips hidden deleted text and equations within a paragraph in No Markup, for both character and word movement. In a paragraph that supports entering equations with the arrow keys, Left / Right can enter a visible equation immediately beyond the deletion. Shift+Left / Right and Shift+Ctrl+Left / Right extend the selection across it. When deleted text is visible inline, it keeps its ordinary caret stops. | `tests::horizontal_caret_skips_hidden_tracked_deletions`, `tests::word_caret_skips_hidden_tracked_deletions`, `tests::bidi::arrow_keys_skip_hidden_deletions_in_rtl_text`, `tests::bidi::word_moves_skip_hidden_deletions_in_rtl_text`, `arrow_keys_skip_a_deleted_equation_in_no_markup`, `arrow_keys_enter_a_visible_equation_across_a_hidden_deletion` |
|
||||
| Left / Right across a wholly deleted paragraph (#8743) | In No Markup, Left and Right skip paragraphs whose text and paragraph mark are both deleted. Shift+Left / Right crosses the same gap without moving the selection anchor. A visible empty paragraph and deletions shown inline still have caret stops. | `arrow_keys_skip_wholly_deleted_paragraphs_in_no_markup`, `arrow_keys_stop_in_a_visible_empty_paragraph_in_no_markup` |
|
||||
|
||||
## AutoCorrect and AutoFormat as you type
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
+32
-1
@@ -163,6 +163,10 @@ fn wasm_test_set(set: &[String]) -> Vec<String> {
|
||||
set.iter().filter(|pkg| !WASM_TEST_EXCLUDED.contains(&layers::short_name(pkg))).cloned().collect()
|
||||
}
|
||||
|
||||
fn wasm_summary(set: &[String], test_set: &[String]) -> String {
|
||||
format!("wasm32-unknown-unknown check: ok ({} crates, {} test crates: {})", set.len(), test_set.len(), test_set.join(", "))
|
||||
}
|
||||
|
||||
/// Checks the wasm-safe crates for `wasm32-unknown-unknown` (first all library
|
||||
/// targets together so features unify across the set, then `--tests` for the
|
||||
/// subset whose test targets compile on wasm32). `--keep-going` still reports
|
||||
@@ -187,7 +191,7 @@ fn cmd_wasm() -> Result<(), String> {
|
||||
}
|
||||
run(t, &format!("cargo check --target wasm32-unknown-unknown --tests --keep-going -p {}", test_set.join(" -p ")))?;
|
||||
}
|
||||
println!("\nwasm32-unknown-unknown check: ok ({} crates, {} test crates: {})", set.len(), test_set.len(), test_set.join(", "));
|
||||
println!("\n{}", wasm_summary(&set, &test_set));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -326,3 +330,30 @@ Tests that use a corpus skip cleanly when it is absent.
|
||||
println!("PngSuite: {n} PNG files in {}", dest.display());
|
||||
if n == 0 { Err("no PNG files extracted".into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[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 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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn wasm_summary_lists_only_crates_with_checked_test_targets() {
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_xtask")).arg("wasm").output().expect("run xtask wasm");
|
||||
|
||||
assert!(output.status.success(), "xtask wasm failed:\n{}", String::from_utf8_lossy(&output.stderr));
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let summary = stdout.lines().find(|line| line.starts_with("wasm32-unknown-unknown check: ok")).expect("wasm summary");
|
||||
assert_eq!(
|
||||
summary,
|
||||
"wasm32-unknown-unknown check: ok (15 crates, 8 test crates: wordcraft-control-key, wordcraft-docbin, wordcraft-engine, wordcraft-geom, wordcraft-layout, wordcraft-mcp, wordcraft-pdf, wordcraft-render)"
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user