mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-17 11:22:56 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4279c1059d | ||
|
|
266407e840 | ||
|
|
c817cc95c6 | ||
|
|
ff0823f40d | ||
|
|
211f62231d | ||
|
|
9144b9bfda | ||
|
|
a61cef5d45 | ||
|
|
739491f5c7 | ||
|
|
8377ea8e8f | ||
|
|
4357166531 | ||
|
|
5d871d0519 | ||
|
|
ae2d2b43d6 | ||
|
|
cd23034f65 | ||
|
|
b2306fe5ef | ||
|
|
646fbc7cd5 | ||
|
|
4a347e070a | ||
|
|
3bf4c05461 | ||
|
|
7b26a94193 | ||
|
|
ace000b4a4 | ||
|
|
7adbdc574c | ||
|
|
f77eef9cb6 | ||
|
|
a2f41d728e | ||
|
|
9fe9bd5042 | ||
|
|
83c3b5890b | ||
|
|
f472620ac0 | ||
|
|
5467f998a0 | ||
|
|
78dfa8f648 | ||
|
|
82f0c467be | ||
|
|
837a610133 | ||
|
|
de977bcde6 | ||
|
|
4ba0595760 | ||
|
|
6854bd1fb3 | ||
|
|
4356771236 | ||
|
|
cdf146cabd | ||
|
|
54e3e1cf34 | ||
|
|
97c13a2990 | ||
|
|
fe8a8a838c | ||
|
|
2bd6f372c5 | ||
|
|
8a1f101c46 | ||
|
|
42f8559b97 | ||
|
|
bf8b37759c | ||
|
|
1ed889c24c | ||
|
|
6a7af0d679 | ||
|
|
ce6e4094d5 | ||
|
|
9088ed777d | ||
|
|
cc90520b9d | ||
|
|
a95b065c2b | ||
|
|
84026f98b2 | ||
|
|
5f228a0e24 | ||
|
|
b354e0f870 | ||
|
|
86352d5cf3 | ||
|
|
3e776e4c7d | ||
|
|
a9a1aa36a2 | ||
|
|
bc0e51ee4d | ||
|
|
ed66198574 | ||
|
|
d53a740be1 | ||
|
|
e9750c5cb7 | ||
|
|
3d5a153e3d | ||
|
|
7bff3b53e9 | ||
|
|
0909b15eae | ||
|
|
52d17a91df | ||
|
|
e6e8c61dbf | ||
|
|
1d150004f7 | ||
|
|
0aefd4d025 | ||
|
|
235a38c665 | ||
|
|
3bf7a5dbbe | ||
|
|
e40199bf6f | ||
|
|
e2f94ecef9 | ||
|
|
7ccfd4caef | ||
|
|
7b3b6f8041 | ||
|
|
fecb717f99 | ||
|
|
bd188c19d8 | ||
|
|
56a28f33b7 | ||
|
|
cd4ab71552 |
+5
-1
@@ -1 +1,5 @@
|
||||
craft-i18n.rev text eol=lf
|
||||
# Text lives in the repository with LF. A Windows checkout once committed 50 files with CRLF
|
||||
# (#6537) and `cargo fmt --check` still passed, so the gate could not see it. Normalise on add.
|
||||
* text=auto
|
||||
|
||||
craft-i18n.rev text eol=lf
|
||||
@@ -18,4 +18,7 @@ jobs:
|
||||
sonarcloud:
|
||||
# Tracked at @main so org-wide CI improvements propagate without PR churn.
|
||||
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
|
||||
with:
|
||||
# Same craft-fonts commit as ci.yml: the UI glyph tests need its CJK and Arabic fonts.
|
||||
fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
secrets: inherit
|
||||
|
||||
Generated
+12
-1
@@ -1248,7 +1248,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.1",
|
||||
"chrono",
|
||||
"craft-tiff",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c)",
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
]
|
||||
@@ -1401,6 +1401,15 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1#6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
@@ -7331,6 +7340,7 @@ dependencies = [
|
||||
"chrono",
|
||||
"craft-font-catalog",
|
||||
"craft-font-store",
|
||||
"craft-mime",
|
||||
"craft-proof",
|
||||
"craft-zip",
|
||||
"encoding_rs",
|
||||
@@ -7406,6 +7416,7 @@ name = "wordcraft-geom"
|
||||
version = "0.18.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1)",
|
||||
"image",
|
||||
"serde",
|
||||
]
|
||||
|
||||
@@ -68,6 +68,7 @@ brotli-decompressor = "5"
|
||||
vello_cpu = "0.2"
|
||||
image = { version = "0.25", default-features = false }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
|
||||
@@ -122,6 +123,8 @@ arboard = { version = "3.7", default-features = false, features = ["wayland-data
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
# cargo llvm-cov sets `--cfg coverage`; timing tests skip themselves under its instrumentation.
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ["cfg(coverage)"] }
|
||||
|
||||
[workspace.lints.clippy]
|
||||
cognitive_complexity = "deny"
|
||||
|
||||
@@ -124,7 +124,7 @@ Every screenshot below is WordCraft itself, rendered offscreen by its own UI tes
|
||||
| **References** | Table of contents, footnotes and endnotes, citations and bibliography (APA, MLA, Chicago, IEEE), captions, table of figures, cross-references, index, table of authorities |
|
||||
| **Review** | Spelling and grammar with suggestions (English and Polish, by each run's language), thesaurus, word count, comments in margin balloons or a pane, track changes, accept/reject, compare documents, restrict editing, accessibility checker, document inspector |
|
||||
| **Mailings** | Mail merge from CSV, merge fields, address block, greeting line, rules, preview, finish to a document; envelopes and labels |
|
||||
| **View** | Print layout, web layout, draft, read mode, focus, zoom, one/multiple pages, page width, Navigation pane, rulers, gridlines, dark mode; interface in English, 简体中文, 繁體中文, 日本語, Português (Brasil), Español, Українська, Српски / Srpski, Eesti, Türkçe, Русский, Italiano, Deutsch, Polski, Čeština, Magyar, Français, Български, Tiếng Việt, 한국어, Svenska, Hrvatski, Nederlands, Dansk, Română, العربية (mirrored) or Slovenščina (follows the system language by default) |
|
||||
| **View** | Print layout, web layout, draft, read mode, focus, zoom, one/multiple pages, page width, Navigation pane, rulers, gridlines, dark mode; interface in English, 简体中文, 繁體中文, 日本語, Português (Brasil), Español, Українська, Српски / Srpski, Eesti, Türkçe, Русский, Italiano, Deutsch, Polski, Čeština, Magyar, Français, Български, Tiếng Việt, 한국어, Svenska, Hrvatski, Nederlands, Dansk, Română, العربية (mirrored) Slovenščina or Bosanski (follows the system language by default) |
|
||||
| **Files** | .docx read/write, legacy 97-2003 .doc import, PDF export, .odt, .rtf, .html, .md, .tex, .txt import/export, page images |
|
||||
|
||||
The honest picture, area by area, is in [ROADMAP.md](ROADMAP.md), the
|
||||
|
||||
+9
-1
File diff suppressed because one or more lines are too long
@@ -369,8 +369,11 @@ mod tests {
|
||||
|
||||
impl Conn {
|
||||
fn open(port: u16) -> Self {
|
||||
Self::open_within(port, Duration::from_secs(5))
|
||||
}
|
||||
fn open_within(port: u16, read_timeout: Duration) -> Self {
|
||||
let s = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
s.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
s.set_read_timeout(Some(read_timeout)).unwrap();
|
||||
Self(BufReader::new(s.try_clone().unwrap()), s)
|
||||
}
|
||||
fn send(&mut self, line: &str) {
|
||||
@@ -388,7 +391,24 @@ mod tests {
|
||||
/// The server closed the connection.
|
||||
fn closed(&mut self) -> bool {
|
||||
let mut r = String::new();
|
||||
matches!(self.0.read_line(&mut r), Ok(0))
|
||||
closed_by_peer(self.0.read_line(&mut r))
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a read means the peer closed the connection. End of stream does; so does a reset,
|
||||
/// which is how Windows can deliver a close when the writer had nothing to read back (the
|
||||
/// Windows Print job failed here). Any other error, such as `InvalidData` for bytes that are
|
||||
/// not UTF-8, leaves the connection open.
|
||||
fn closed_by_peer(read: std::io::Result<usize>) -> bool {
|
||||
match read {
|
||||
Ok(n) => n == 0,
|
||||
Err(e) => matches!(
|
||||
e.kind(),
|
||||
std::io::ErrorKind::ConnectionReset
|
||||
| std::io::ErrorKind::ConnectionAborted
|
||||
| std::io::ErrorKind::NotConnected
|
||||
| std::io::ErrorKind::BrokenPipe
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -473,13 +493,29 @@ mod tests {
|
||||
assert!(rx.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_closure_errors_mean_the_peer_closed() {
|
||||
use std::io::{Error, ErrorKind};
|
||||
assert!(closed_by_peer(Ok(0)), "end of stream");
|
||||
for kind in [ErrorKind::ConnectionReset, ErrorKind::ConnectionAborted, ErrorKind::NotConnected, ErrorKind::BrokenPipe] {
|
||||
assert!(closed_by_peer(Err(Error::new(kind, "closed"))), "{kind:?}");
|
||||
}
|
||||
assert!(!closed_by_peer(Ok(1)), "a reply arrived");
|
||||
// Not UTF-8, a timeout or a would-block leave the socket open.
|
||||
for kind in [ErrorKind::InvalidData, ErrorKind::TimedOut, ErrorKind::WouldBlock] {
|
||||
assert!(!closed_by_peer(Err(Error::new(kind, "still open"))), "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_silent_connection_is_closed() {
|
||||
let (port, rx) = boot_with(Duration::from_millis(300));
|
||||
let mut quiet = Conn::open(port);
|
||||
// A loaded Windows CI runner can take seconds to schedule the connection thread. The
|
||||
// production deadline is 30 s, so 10 s still proves the server's own budget fired.
|
||||
let mut quiet = Conn::open_within(port, Duration::from_secs(20));
|
||||
let t0 = Instant::now();
|
||||
assert!(quiet.closed());
|
||||
assert!(t0.elapsed() < Duration::from_secs(3));
|
||||
assert!(t0.elapsed() < Duration::from_secs(10), "{:?}", t0.elapsed());
|
||||
// After an authorised request the connection may stay idle.
|
||||
let mut busy = Conn::open(port);
|
||||
assert_eq!(busy.call(&format!(r#"{{"id":1,"method":"auth","key":"{KEY}"}}"#))["ok"], true);
|
||||
|
||||
@@ -94,8 +94,8 @@ pub use settings::{
|
||||
COMPAT_MODE_CURRENT, CoreProps, CustomProp, DEFAULT_GRID, DEFAULT_HYPHENATION_ZONE, LEGACY_COMPAT_MODE, OdfLayout, PagePicture, Settings, Source,
|
||||
THEME_COLORS, Watermark, Zoom, ZoomFit,
|
||||
};
|
||||
pub(crate) use text_walk::{PARA_WALK_DEPTH, walk_between};
|
||||
pub use text_walk::{count_chars, count_chars_no_spaces, count_words};
|
||||
pub(crate) use text_walk::walk_between;
|
||||
pub use text_walk::{PARA_WALK_DEPTH, count_chars, count_chars_no_spaces, count_words};
|
||||
|
||||
/// A document.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
|
||||
@@ -137,6 +137,12 @@ pub struct Settings {
|
||||
/// Keep contextual paragraph spacing inside legacy table cells (`allowSpaceOfSameStyleInTable`).
|
||||
/// Word ignores the layout override in compatibility mode 15, but the flag still round-trips.
|
||||
pub allow_space_of_same_style_in_table: bool,
|
||||
/// `w:doNotSuppressIndentation` (a `.doc`'s `Copts.fWW11IndentRules`): Word 2003's indent
|
||||
/// rules beside floating objects. An unnumbered paragraph's line starts right after a floating
|
||||
/// object before it on the line, its own indent ignored (ECMA-376 Part 4 §14.8.3.12). Word 2013's
|
||||
/// layout (compatibility mode 15) does not use it.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub do_not_suppress_indentation: bool,
|
||||
/// Drawing grid spacing in points, across and down (View › Gridlines); ECMA-376's default is 1/8 inch.
|
||||
pub grid_h: f32,
|
||||
pub grid_v: f32,
|
||||
@@ -319,6 +325,7 @@ impl Default for Settings {
|
||||
sum_paragraph_spacing: false,
|
||||
do_not_expand_shift_return: false,
|
||||
allow_space_of_same_style_in_table: false,
|
||||
do_not_suppress_indentation: false,
|
||||
grid_h: DEFAULT_GRID,
|
||||
grid_v: DEFAULT_GRID,
|
||||
math: None,
|
||||
|
||||
@@ -48,7 +48,7 @@ pub fn count_chars_no_spaces(s: &str) -> usize {
|
||||
}
|
||||
|
||||
/// How deep in nested tables [`Document::para_paths`] goes: cells below this are skipped.
|
||||
pub(crate) const PARA_WALK_DEPTH: usize = 16;
|
||||
pub const PARA_WALK_DEPTH: usize = 16;
|
||||
|
||||
/// The note and text box stories an object shows, for `Document::reachable`.
|
||||
pub(crate) fn notes_and_boxes(o: &InlineObject) -> Vec<(u32, &'static [PartKind])> {
|
||||
|
||||
@@ -15,6 +15,7 @@ workspace = true
|
||||
test-support = []
|
||||
|
||||
[dependencies]
|
||||
craft-mime.workspace = true
|
||||
wordcraft-geom = { workspace = true, features = ["image"] }
|
||||
wordcraft-doc = { workspace = true }
|
||||
wordcraft-fonts = { workspace = true }
|
||||
|
||||
@@ -79,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.when(has_canvas)
|
||||
.pure(),
|
||||
CommandSpec::new("canvas.member", "Canvas Member", "Shape Format › Drawing Canvas", member)
|
||||
.params(r#"{"index": n, "x"?: pt, "y"?: pt, "width"?: pt, "height"?: pt, "delete"?: bool} (moves, resizes or removes member `index` of the selected canvas; x/y from the canvas's top-left; with no change, returns the members)"#)
|
||||
.params(r#"{"index"?: n, "x"?: pt, "y"?: pt, "width"?: pt, "height"?: pt, "delete"?: bool} (moves, resizes or removes member `index` of the selected canvas; x/y from the canvas's top-left; without index, returns the members)"#)
|
||||
.when(has_canvas),
|
||||
]
|
||||
}
|
||||
@@ -211,7 +211,7 @@ fn scale(s: &mut Session, v: &Value) -> CmdResult {
|
||||
result(&o)
|
||||
}
|
||||
|
||||
/// `canvas.member`: move, resize or remove one member; with no change, list the members.
|
||||
/// `canvas.member`: move, resize or remove one member; without index, list the members.
|
||||
fn member(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let pos = canvas_pos(s)?;
|
||||
let Some(i) = p::u64(v, "index").and_then(|i| usize::try_from(i).ok()) else {
|
||||
|
||||
@@ -68,6 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
sel_result(s)
|
||||
})
|
||||
.key("Escape")
|
||||
.params(r#"{"end"?: bool (default false: collapse to the start; true: to the end)}"#)
|
||||
.pure(),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -63,7 +63,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let t = THEMES.iter().find(|t| t.0.eq_ignore_ascii_case(name)).ok_or_else(|| CmdError::Params(format!("unknown colours `{name}`")))?;
|
||||
set_accent(s, t.3[0]);
|
||||
sel_result(s)
|
||||
}),
|
||||
})
|
||||
.params(r#"{"name": string (see design.themes)}"#),
|
||||
CommandSpec::new("design.styleSet", "Style Set", "Design › Document Formatting", style_set)
|
||||
.params(r#"{"name": "default|basic|lines|shaded|casual|centered|minimalist|title"}"#),
|
||||
CommandSpec::new("design.paragraphSpacing", "Paragraph Spacing", "Design › Document Formatting", para_spacing)
|
||||
|
||||
@@ -141,7 +141,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.key(super::mac_or("Mod+Shift+G / Mod+PageUp", "Mod+PageUp"))
|
||||
.params(r#"{"text"?: string, "matchCase"?: bool, "wholeWord"?: bool, "regex"?: bool}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("edit.replace", "Replace", "Home › Editing", replace).params(r#"{"text": string, "with": string, …options of edit.replaceAll}"#),
|
||||
CommandSpec::new("edit.replace", "Replace", "Home › Editing", replace).params(
|
||||
r#"{"text": string, "with": string, …options of edit.replaceAll} — Word's Replace button: replaces the match only when it is already selected, then selects the next one. The first call on a caret replaces nothing; call again to replace the selected match, or use edit.replaceAll for every match. Returns {"replaced": 0 | 1, "remaining": n, "selected": {start, end} | null}"#,
|
||||
),
|
||||
// Ctrl+H, Home › Replace: the Find and Replace dialog on its Replace tab (#712). Opening
|
||||
// it changes nothing, so it is its own command and never marks the document edited.
|
||||
CommandSpec::new("edit.findReplace", "Find and Replace", "Home › Editing", |s, v| {
|
||||
@@ -172,7 +174,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.pure(),
|
||||
CommandSpec::new("edit.formatPainter", "Format Painter", "Home › Clipboard", painter).params(r#"{"sticky"?: bool}"#).pure(),
|
||||
CommandSpec::new("edit.copyFormat", "Copy Formatting", "Home › Clipboard", |s, _| {
|
||||
painter_pick(s);
|
||||
// One format buffer, as in Word: Copy Formatting replaces an armed Format Painter.
|
||||
s.painter = None;
|
||||
s.copied_format = Some(picked_format(s));
|
||||
sel_result(s)
|
||||
})
|
||||
.key(copy_format_shortcut(cfg!(target_arch = "wasm32")))
|
||||
@@ -744,12 +748,21 @@ fn replace(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let story = s.sel.focus.story;
|
||||
let results = search_full(s, story, true)?;
|
||||
let (a, b) = s.sel.ordered();
|
||||
// Replace the current match if selected, then move to the next.
|
||||
// Replace the current match if selected, then move to the next. The result says which
|
||||
// happened (#6877): a first call that only selects a match reads as `replaced: 0`.
|
||||
let mut replaced = 0;
|
||||
if let Some(f) = results.into_iter().find(|f| f.a == a && f.b == b) {
|
||||
super::paste_text(s, &f.rep.unwrap_or_default())?;
|
||||
replaced = 1;
|
||||
}
|
||||
let _ = step(s, 1);
|
||||
Ok(json!({"remaining": search(s, story)?.len()}))
|
||||
let selected = match step(s, 1) {
|
||||
Ok(_) => {
|
||||
let (start, end) = s.sel.ordered();
|
||||
json!({"start": pos_json(&start), "end": pos_json(&end)})
|
||||
}
|
||||
Err(_) => Value::Null,
|
||||
};
|
||||
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
|
||||
@@ -832,11 +845,21 @@ fn goto(s: &mut Session, v: &Value) -> CmdResult {
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
fn painter_pick(s: &mut Session) {
|
||||
/// The character and paragraph formatting at the start of the selection.
|
||||
fn picked_format(s: &Session) -> (wordcraft_doc::props::CharProps, wordcraft_doc::props::ParaProps) {
|
||||
let f = s.sel.ordered().0;
|
||||
// A symbol's own font isn't formatting to paint onto text.
|
||||
let chr = s.doc.para_at(&f).map(|p| p.props_of_char(f.off).clone().without_symbol()).unwrap_or_default();
|
||||
let para = s.doc.para_at(&f).map(|p| p.props.clone()).unwrap_or_default();
|
||||
// Formatting only: not the source's hyperlink or revision marks (#5616).
|
||||
let chr = s.doc.para_at(&f).map(|p| p.props_of_char(f.off).clone().without_symbol().formatting()).unwrap_or_default();
|
||||
let para = s.doc.para_at(&f).map(|p| p.props.clone().formatting()).unwrap_or_default();
|
||||
(chr, para)
|
||||
}
|
||||
|
||||
fn painter_pick(s: &mut Session) {
|
||||
let (chr, para) = picked_format(s);
|
||||
// One format buffer, as in Word: the pick is also what the next Paste Formatting applies,
|
||||
// and stays after the brush is used up or cancelled.
|
||||
s.copied_format = Some((chr.clone(), para.clone()));
|
||||
s.painter = Some((chr, para, false));
|
||||
}
|
||||
|
||||
@@ -852,9 +875,14 @@ fn painter(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(json!({"active": true}))
|
||||
}
|
||||
|
||||
/// Apply the format painter's formatting to the selection.
|
||||
/// Apply the format painter's formatting to the selection, or else what Copy Formatting picked
|
||||
/// up (which stays for the next Paste Formatting).
|
||||
fn paste_format(s: &mut Session, _: &Value) -> CmdResult {
|
||||
let Some((chr, para, sticky)) = s.painter.clone() else { return Err(CmdError::Failed("no formatting copied".into())) };
|
||||
let (chr, para, sticky) = match (s.painter.clone(), s.copied_format.clone()) {
|
||||
(Some(brush), _) => brush,
|
||||
(None, Some((chr, para))) => (chr, para, true),
|
||||
(None, None) => return Err(CmdError::Failed("no formatting copied".into())),
|
||||
};
|
||||
let (a, b) = s.sel.ordered();
|
||||
if a == b {
|
||||
// No selection: apply paragraph formatting (and word formatting like Word).
|
||||
@@ -864,15 +892,11 @@ fn paste_format(s: &mut Session, _: &Value) -> CmdResult {
|
||||
// Word selection includes trailing spaces; a painter click formats just the word,
|
||||
// matching the ordinary collapsed-caret formatting target.
|
||||
let word_end = pp.text.get(x..y).map(|word| x + word.trim_end().len()).unwrap_or(y);
|
||||
s.doc.format_range(&Pos { off: x, ..f.clone() }, &Pos { off: word_end, ..f.clone() }, &|c| *c = chr.cleared().overlaid(&chr))?;
|
||||
s.doc.format_range(&Pos { off: x, ..f.clone() }, &Pos { off: word_end, ..f.clone() }, &|c| *c = c.cleared().overlaid(&chr))?;
|
||||
}
|
||||
s.doc.format_paragraphs(&a, &b, &|p| *p = para.clone())?;
|
||||
} else {
|
||||
s.doc.format_range(&a, &b, &|c| {
|
||||
let link = c.link.clone();
|
||||
*c = c.cleared().overlaid(&chr);
|
||||
c.link = link;
|
||||
})?;
|
||||
s.doc.format_range(&a, &b, &|c| *c = c.cleared().overlaid(&chr))?;
|
||||
if a.path != b.path || a.off == 0 {
|
||||
s.doc.format_paragraphs(&a, &b, &|p| *p = para.clone())?;
|
||||
}
|
||||
|
||||
@@ -154,7 +154,7 @@ pub fn show_results(s: &mut Session) -> Result<(), CmdError> {
|
||||
fn set_code(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let code = p::req_str(v, "code")?.trim().to_string();
|
||||
if code.is_empty() || code.len() > MAX_CODE || code.contains(OBJ) {
|
||||
return Err(CmdError::Params("bad field code".into()));
|
||||
return Err(CmdError::Params("`code` must be non-empty, at most 4096 UTF-8 bytes, and contain no U+FFFC object markers".into()));
|
||||
}
|
||||
let Some(f) = selected(s).into_iter().next() else { return Err(none_selected()) };
|
||||
with_field(s, &f.at, |o| match o {
|
||||
@@ -441,7 +441,10 @@ mod tests {
|
||||
s.run("fields.setCode", &json!({"code": "TITLE"})).unwrap();
|
||||
let objs = |s: &Session| s.doc.body.first().and_then(|b| b.as_para()).map(|p| p.objects.clone()).unwrap_or_default();
|
||||
assert!(matches!(objs(&s).first(), Some(InlineObject::Field { instr, result, .. }) if instr == "TITLE" && result == "Report"));
|
||||
assert!(s.run("fields.setCode", &json!({"code": ""})).is_err());
|
||||
assert!(matches!(
|
||||
s.run("fields.setCode", &json!({"code": ""})),
|
||||
Err(crate::CmdError::Params(message)) if message == "`code` must be non-empty, at most 4096 UTF-8 bytes, and contain no U+FFFC object markers"
|
||||
));
|
||||
|
||||
// A locked field keeps its result.
|
||||
s.run("fields.lock", &json!({})).unwrap();
|
||||
|
||||
@@ -90,7 +90,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("file.new", "New", "File", new).key("Mod+N").params(r#"{"template"?: "blank|sample|letter|resume|report"}"#).pure(),
|
||||
CommandSpec::new("file.open", "Open", "File", open)
|
||||
.key("Mod+O / Mod+F12 / Mod+Alt+F2")
|
||||
.params(r#"{"path": string, "data"?: base64 (the file's bytes; `path` then only names it), "password"?: string (for a password-protected Word document)}"#)
|
||||
.params(r#"{"path": string, "data"?: base64 (the file's bytes; `path` then only names it), "password"?: string (for a password-protected Word or OpenDocument text file)}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("file.save", "Save", "File", save)
|
||||
.key("Mod+S / Shift+F12 / Alt+Shift+F2")
|
||||
@@ -100,7 +100,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
// Pure: the password must not land in Repeat or a recorded macro, and it isn't an edit
|
||||
// to undo; it marks the document as changed itself.
|
||||
CommandSpec::new("file.encrypt", "Encrypt with Password", "File › Info › Protect Document", encrypt)
|
||||
.params(r#"{"password": string (Word documents are saved encrypted with it) | null or "" (saved unencrypted)}"#)
|
||||
.params(r#"{"password": string (Word packages and OpenDocument text files (.odt, .ott) are saved encrypted with it) | null or "" (saved unencrypted)}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("file.exportPdf", "Export PDF", "File › Export", |s, v| {
|
||||
// No path (the command search, say): the app asks where to save, as File › Export
|
||||
@@ -368,8 +368,8 @@ fn close_document(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(json!({"closed": id, "active": s.document_id(), "documents": s.documents()}))
|
||||
}
|
||||
|
||||
/// File › Info › Protect Document › Encrypt with Password: the password Word documents are saved
|
||||
/// with from now on, or none.
|
||||
/// File › Info › Protect Document › Encrypt with Password: the password Word packages and
|
||||
/// OpenDocument text files (.odt, .ott) are saved with from now on, or none.
|
||||
fn encrypt(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let password = match v.get("password") {
|
||||
Some(Value::Null) => None,
|
||||
|
||||
@@ -336,7 +336,7 @@ fn font(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let Some(n) = v.get(k) else { return Ok(None) };
|
||||
let n = n.as_str().map(str::trim).unwrap_or("");
|
||||
if n.is_empty() || n.len() > 128 {
|
||||
return Err(CmdError::Params(format!("bad font name `{k}`")));
|
||||
return Err(CmdError::Params(format!("`{k}` must be a non-empty font name of at most 128 bytes")));
|
||||
}
|
||||
Ok(Some(n.to_string()))
|
||||
};
|
||||
|
||||
@@ -51,7 +51,7 @@ pub(super) fn link(s: &mut Session, v: &Value) -> CmdResult {
|
||||
},
|
||||
};
|
||||
if url.is_empty() || url.len() > 4096 {
|
||||
return Err(CmdError::Params("bad url".into()));
|
||||
return Err(CmdError::Params("`url` must be non-empty and at most 4096 UTF-8 bytes".into()));
|
||||
}
|
||||
let style = Some("Hyperlink".to_string());
|
||||
if s.sel.is_collapsed() {
|
||||
@@ -188,7 +188,9 @@ pub(super) fn delete_bookmark(s: &mut Session, v: &Value) -> CmdResult {
|
||||
pub(super) fn bookmark(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let name = p::req_str(v, "name")?.trim().to_string();
|
||||
if !bookmark_name_ok(&name) {
|
||||
return Err(CmdError::Params("bookmark names start with a letter, have no spaces and at most 40 characters".into()));
|
||||
return Err(CmdError::Params(
|
||||
"bookmark names start with a letter or underscore, contain only letters, numbers or underscores, and have at most 40 characters".into(),
|
||||
));
|
||||
}
|
||||
// Replace an existing bookmark of the same name.
|
||||
remove_bookmark(s, &name)?;
|
||||
|
||||
@@ -71,22 +71,7 @@ pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
|
||||
Some(out)
|
||||
}
|
||||
|
||||
pub fn base64_encode(b: &[u8]) -> String {
|
||||
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut out = String::with_capacity(b.len().div_ceil(3) * 4);
|
||||
for ch in b.chunks(3) {
|
||||
let n =
|
||||
(ch.first().copied().unwrap_or(0) as u32) << 16 | (ch.get(1).copied().unwrap_or(0) as u32) << 8 | ch.get(2).copied().unwrap_or(0) as u32;
|
||||
for i in 0..4 {
|
||||
if i <= ch.len() {
|
||||
out.push(T[(n >> (18 - 6 * i) & 63) as usize] as char);
|
||||
} else {
|
||||
out.push('=');
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
pub use craft_mime::transfer::base64 as base64_encode;
|
||||
|
||||
pub(crate) fn picture(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let bytes = if let Some(d) = p::str(v, "data") {
|
||||
|
||||
@@ -415,3 +415,22 @@ fn local_civil_date_follows_the_utc_offset() {
|
||||
assert!(crate::cmd::local_offset_secs(unix).abs() <= 26 * 3600);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_base64_preserves_command_payload_bytes() {
|
||||
for (plain, encoded) in [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foobar", "Zm9vYmFy")] {
|
||||
assert_eq!(super::objects::base64_encode(plain.as_bytes()), encoded);
|
||||
}
|
||||
let bytes: Vec<u8> = (0..513).map(|i| (i % 256) as u8).collect();
|
||||
for len in 0..=bytes.len() {
|
||||
let encoded = super::objects::base64_encode(&bytes[..len]);
|
||||
assert_eq!(encoded.len(), len.div_ceil(3) * 4);
|
||||
assert!(!encoded.contains(['\r', '\n']));
|
||||
assert_eq!(super::objects::base64_decode(&encoded), Some(bytes[..len].to_vec()));
|
||||
}
|
||||
assert_eq!(super::objects::base64_encode(&[251, 255, 255]), "+///");
|
||||
// The existing decoder intentionally accepts URL-safe symbols, whitespace and optional padding.
|
||||
assert_eq!(super::objects::base64_decode("-___"), Some(vec![251, 255, 255]));
|
||||
assert_eq!(super::objects::base64_decode("Z g\n"), Some(b"f".to_vec()));
|
||||
assert_eq!(super::objects::base64_decode("!!!!"), None);
|
||||
}
|
||||
|
||||
@@ -110,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
apply_filter(s);
|
||||
filter_result(s)
|
||||
})
|
||||
.params(r#"{"rules"?: [{"field": string, "op": "equal|notEqual|less|greater|lessOrEqual|greaterOrEqual|blank|notBlank|contains|notContains", "value"?: string, "join"?: "and|or" (with the rule before; And binds tighter)}], "sort"?: [{"field": string, "descending"?: bool}]} (replaces the filter; `sort` too when given; {} clears both). Preview, Finish & Merge and labels use only the matching records, in sort order"#)
|
||||
.params(r#"{"rules"?: [{"field": string, "op": "equal|notEqual|less|greater|lessOrEqual|greaterOrEqual|blank|notBlank|contains|notContains", "value"?: string, "join"?: "and|or" (with the rule before; And binds tighter)}], "sort"?: [{"field": string, "descending"?: bool}]} (replaces the filter; `sort` too when given; `sort` also accepts a field name, one key object or null; array entries may also be field names; {} clears both). Preview, Finish & Merge and labels use only the matching records, in sort order"#)
|
||||
.when(has_list)
|
||||
.pure(),
|
||||
CommandSpec::new("mailings.sortRecipients", "Sort Recipients", "Mailings › Start Mail Merge › Edit Recipient List", |s, v| {
|
||||
@@ -118,7 +118,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
apply_filter(s);
|
||||
filter_result(s)
|
||||
})
|
||||
.params(r#"{"sort"?: [{"field": string, "descending"?: bool}]} | {"field": string, "descending"?: bool} (no params: the list's own order)"#)
|
||||
.params(r#"{"sort"?: [{"field": string, "descending"?: bool}]} | {"field": string, "descending"?: bool} (`sort` also accepts a field name, one key object or null; array entries may also be field names; no params: the list's own order)"#)
|
||||
.when(has_list)
|
||||
.pure(),
|
||||
CommandSpec::new("mailings.insertField", "Insert Merge Field", "Mailings › Write & Insert Fields", |s, v| {
|
||||
@@ -192,6 +192,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
refresh(s);
|
||||
Ok(json!({"record": idx + 1}))
|
||||
})
|
||||
.params(r#"{"text": string}"#)
|
||||
.when(has_recipients),
|
||||
CommandSpec::new("mailings.checkErrors", "Check for Errors", "Mailings › Finish", |s, _| {
|
||||
let mut missing = Vec::new();
|
||||
|
||||
@@ -255,7 +255,7 @@ pub(super) fn parse_sort(headers: &[String], v: Option<&Value>) -> Result<Vec<So
|
||||
None | Some(Value::Null) => return Ok(Vec::new()),
|
||||
Some(Value::Array(a)) => a.clone(),
|
||||
Some(o @ (Value::Object(_) | Value::String(_))) => vec![o.clone()],
|
||||
Some(_) => return Err(CmdError::Params("`sort` must be an array of {field, descending}".into())),
|
||||
Some(_) => return Err(CmdError::Params("`sort` must be a field name, a {field, descending} object, an array of those, or null".into())),
|
||||
};
|
||||
if arr.len() > MAX_SORT_KEYS {
|
||||
return Err(CmdError::Params(format!("at most {MAX_SORT_KEYS} sort keys")));
|
||||
|
||||
@@ -22,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("file.options", "Options", "File", options)
|
||||
.params(
|
||||
r#"{"pane"?: "general|display|proofing|save|language|accessibility|advanced|agents", "author"?: string, "initials"?: string, "units"?: "inches|centimeters|millimeters|points|picas|auto" (auto: the region's), "region"?: string (a locale tag like pl-PL, saved: the paper File › New starts on, the default units and the decimal separator; auto: the system's), "typingReplacesSelection"?: bool, "insertKeyOvertype"?: bool, "overtype"?: bool, "marks"?: {"tabs"?: bool, "spaces"?: bool, "paragraphs"?: bool, "hidden"?: bool}, "checkSpelling"?: bool, "markGrammar"?: bool, "ignoreUppercase"?: bool, "ignoreNumbers"?: bool, "ignoreInternet"?: bool, "dictionariesFolder"?: string (a folder of Hunspell .aff/.dic files searched first, saved; auto: the system locations only), "userTemplatesFolder"?: string (the folder File › New lists personal templates from, saved; auto: the app's own Templates folder; not a network folder), "addWords"?: [string], "removeWords"?: [string]} — with any setting it changes them and opens nothing; without, it opens File › Options (at `pane`). Returns the settings."#,
|
||||
r#"{"pane"?: "general|display|proofing|save|language|accessibility|advanced|agents", "author"?: string, "initials"?: string, "units"?: "inches|centimeters|millimeters|points|picas|auto" (auto: the region's), "region"?: string (a locale tag like pl-PL, saved: the paper File › New starts on, the default units and the decimal separator; auto: the system's), "typingReplacesSelection"?: bool, "insertKeyOvertype"?: bool, "overtype"?: bool, "marks"?: {"tabs"?: bool, "spaces"?: bool, "paragraphs"?: bool, "hidden"?: bool}, "checkSpelling"?: bool, "markGrammar"?: bool, "ignoreUppercase"?: bool, "ignoreNumbers"?: bool, "ignoreInternet"?: bool, "dictionariesFolder"?: string (a folder of Hunspell .aff/.dic files searched first, saved; auto: clear the configured folder), "userTemplatesFolder"?: string (the folder File › New lists personal templates from, saved; auto: the app's own Templates folder; not a network folder), "addWords"?: [string], "removeWords"?: [string]} — with any setting it changes them and opens nothing; without, it opens File › Options (at `pane`). Returns the settings."#,
|
||||
)
|
||||
.pure(),
|
||||
CommandSpec::new("text.overtype", "Overtype", "File › Options › Advanced", |s, v| {
|
||||
|
||||
@@ -274,7 +274,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
st.quick = on;
|
||||
}
|
||||
sel_result(s)
|
||||
}),
|
||||
})
|
||||
.params(r#"{"style": string (name or id), "value"?: bool (default true)}"#),
|
||||
// Advanced paragraph tools (#5043, as in WPS Office): conversions and cleanup over the
|
||||
// selection, or the whole document with `scope: "all"`. One undo step per command.
|
||||
CommandSpec::new("para.convertBreaks", "Convert Line Breaks to Paragraphs", "Home › Paragraph › Paragraph Tools", convert_breaks)
|
||||
|
||||
@@ -22,7 +22,7 @@ const MODES: [&str; 5] = ["none", "readOnly", "comments", "trackedChanges", "for
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("review.restrict", "Restrict Editing", "Review › Protect", restrict).params(
|
||||
r#"{"mode"?: "none|readOnly|comments|trackedChanges|forms" (start enforcing; "none" stops), "formatting"?: bool (limit formatting to unlocked styles), "lockedStyles"?: [style id or name] (the styles that can't be applied; every other style is unlocked), "password"?: string (set when enforcing; required to stop a password-protected document), "stop"?: bool, "exception"?: "add" (the selection stays editable for everyone) | "remove" (exceptions touching the selection) | "removeAll"} → state"#,
|
||||
r#"{"mode"?: "none|readOnly|comments|trackedChanges|forms" (editing restriction; use "none" with "formatting": true for formatting-only protection), "formatting"?: bool (limit formatting to unlocked styles), "lockedStyles"?: [style id or name] (the styles that can't be applied; every other style is unlocked), "password"?: string (set when enforcing; required to stop a password-protected document), "stop"?: bool (true: stop protection), "exception"?: "add" (the selection stays editable for everyone) | "remove" (exceptions touching the selection) | "removeAll"} → state"#,
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -431,7 +431,8 @@ enum HoleMode {
|
||||
/// run formatting and paragraph formatting outside the ranges `author` may edit, in every story,
|
||||
/// and the formatting of every table, row and cell that holds any of that protected content, and what
|
||||
/// reaches the whole document: page setup, the document defaults and the existing styles
|
||||
/// (applying a style may add one), the document's settings and its metadata.
|
||||
/// (applying a style may add one), the glossary's building blocks, the document's settings and
|
||||
/// its metadata.
|
||||
pub(crate) fn outside_unchanged(before: &Document, after: &Document, author: &str) -> bool {
|
||||
// Protection can't change mid-command (`protection_lifted` guards undo and redo).
|
||||
let mode = if Some("forms") == before.settings.protection.as_deref() { HoleMode::Controls } else { HoleMode::Perms(author.into()) };
|
||||
@@ -444,6 +445,7 @@ pub(crate) fn outside_unchanged(before: &Document, after: &Document, author: &st
|
||||
&& before.settings == after.settings
|
||||
&& before.core == after.core
|
||||
&& before.custom_props == after.custom_props
|
||||
&& before.glossary == after.glossary
|
||||
&& comments_unchanged(before, after)
|
||||
&& lists_unchanged(before, after)
|
||||
&& sources_unchanged(before, after)
|
||||
|
||||
@@ -428,6 +428,23 @@ fn the_post_check_compares_the_settings_and_the_metadata() {
|
||||
assert!(super::outside_unchanged(&before, &before.clone(), "someone"), "an unchanged document isn't unchanged");
|
||||
}
|
||||
|
||||
/// The glossary's building blocks reach the whole document, so the post-check compares them.
|
||||
#[test]
|
||||
fn the_post_check_compares_the_glossary() {
|
||||
use wordcraft_doc::{BuildingBlock, CharProps, Paragraph};
|
||||
let mut before = Document::from_text("Some text.");
|
||||
before.glossary.push(BuildingBlock {
|
||||
name: "g".into(),
|
||||
blocks: vec![wordcraft_doc::para_block(Paragraph::with_text("Block", Default::default()))],
|
||||
..Default::default()
|
||||
});
|
||||
assert!(super::outside_unchanged(&before, &before.clone(), "someone"), "an unchanged glossary is unchanged");
|
||||
let mut after = before.clone();
|
||||
after.glossary[0].blocks[0] =
|
||||
wordcraft_doc::para_block(Paragraph::with_text("Block", CharProps { lang: Some("fr-FR".into()), ..Default::default() }));
|
||||
assert!(!super::outside_unchanged(&before, &after, "someone"), "a relanguaged building block is a change");
|
||||
}
|
||||
|
||||
/// Read only, no exceptions: going to a header the document doesn't have doesn't create
|
||||
/// one, and loading or filtering recipients doesn't rewrite the merge fields' shown results
|
||||
/// (both used to change the document from a non-mutating command, #1327).
|
||||
|
||||
@@ -67,13 +67,15 @@ pub fn toc_instr(v: &Value) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
/// A TOC entry: the paragraph it points at, its level (0-based), its text, and the leading page
|
||||
/// breaks of that paragraph (its page is where the text after them lands).
|
||||
/// A TOC entry: the paragraph it points at, its level (0-based), its text, the leading page
|
||||
/// breaks of that paragraph (its page is where the text after them lands), and, for a number
|
||||
/// followed by a tab, how far the heading's text starts after where its number starts.
|
||||
struct TocEntry {
|
||||
path: Path,
|
||||
level: u8,
|
||||
text: String,
|
||||
lead: usize,
|
||||
number_gap: Option<f32>,
|
||||
}
|
||||
|
||||
/// The headings of the body, in document order, as (body block, level 1–9, text, leading page
|
||||
@@ -117,9 +119,13 @@ fn toc_entries(s: &Session, f: &FieldCode) -> Vec<TocEntry> {
|
||||
.and_then(|n| counters.next_label(&s.doc.numbering, n.num, n.level))
|
||||
.filter(|(label, def)| !label.is_empty() && !matches!(def.format, NumFormat::Bullet | NumFormat::None))
|
||||
.map(|(label, def)| match def.suffix {
|
||||
LevelSuffix::Tab => format!("{label}\t"),
|
||||
LevelSuffix::Space => format!("{label} "),
|
||||
LevelSuffix::Nothing => label,
|
||||
LevelSuffix::Tab => {
|
||||
let start = def.indent - def.hanging;
|
||||
let gap = def.tab.filter(|t| *t > start).unwrap_or(def.indent) - start;
|
||||
(format!("{label}\t"), Some(gap).filter(|g| g.is_finite() && *g > 0.0))
|
||||
}
|
||||
LevelSuffix::Space => (format!("{label} "), None),
|
||||
LevelSuffix::Nothing => (label, None),
|
||||
});
|
||||
let style = p.props.style.as_deref().unwrap_or("Normal");
|
||||
if style.starts_with("TOC") {
|
||||
@@ -144,8 +150,9 @@ fn toc_entries(s: &Session, f: &FieldCode) -> Vec<TocEntry> {
|
||||
if let Some(l) = by_style.or(by_outline).or(if hidden { None } else { by_heading }) {
|
||||
let t = p.plain_text().replace(['\u{000C}', '\n', '\t'], " ").trim().to_string();
|
||||
if !t.is_empty() {
|
||||
let text = number.map_or_else(|| t.clone(), |n| format!("{n}{t}"));
|
||||
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead });
|
||||
let text = number.as_ref().map_or_else(|| t.clone(), |(n, _)| format!("{n}{t}"));
|
||||
let number_gap = number.as_ref().and_then(|(_, g)| *g);
|
||||
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead, number_gap });
|
||||
}
|
||||
}
|
||||
if let Some(id) = &tc {
|
||||
@@ -159,7 +166,7 @@ fn toc_entries(s: &Session, f: &FieldCode) -> Vec<TocEntry> {
|
||||
let l = c.arg('l').and_then(|l| l.trim().parse::<u8>().ok()).unwrap_or(1).clamp(1, 9);
|
||||
let text = c.args.first().map(|t| t.trim().to_string()).unwrap_or_default();
|
||||
if (id.is_empty() || *id == kind) && (tc_levels.0..=tc_levels.1).contains(&l) && !text.is_empty() {
|
||||
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead: off });
|
||||
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead: off, number_gap: None });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -595,6 +602,16 @@ fn regenerate_toc(s: &mut Session, leader: Option<TabLeader>, tabs: &[(String, V
|
||||
para.mark = CharProps::default();
|
||||
if e.text.contains('\t') {
|
||||
para.props.tabs = tabs.iter().find(|(style, _)| Some(style) == para.props.style.as_ref()).map(|(_, tabs)| tabs.clone());
|
||||
// Without a stop for the number (LibreOffice's Contents styles have only the page
|
||||
// number's right stop), its tab would run to the page number: the entry gets a
|
||||
// left stop as far after its indent as the heading's text is after its number.
|
||||
let style = s.doc.styles.resolve_para(¶.props);
|
||||
let has_stop =
|
||||
style.tabs.iter().any(|t| t.pos < width - 1.0 && matches!(t.align, TabAlign::Left | TabAlign::Center | TabAlign::Decimal));
|
||||
if let (None, false, Some(gap)) = (¶.props.tabs, has_stop, e.number_gap) {
|
||||
let pos = style.indent_left.max(0.0) + gap;
|
||||
para.props.tabs = (pos < width - 1.0).then(|| vec![TabStop { pos, align: TabAlign::Left, leader: TabLeader::None }]);
|
||||
}
|
||||
}
|
||||
if show_page && sep.contains('\t') {
|
||||
let right = TabStop { pos: width - 0.5, align: TabAlign::Right, leader };
|
||||
|
||||
@@ -28,12 +28,12 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("review.newComment", "New Comment", "Review › Comments", new_comment).key(super::mac_or("Mod+Alt+A / Mod+Alt+M", "Mod+Alt+M")).params(r#"{"text": string}"#),
|
||||
CommandSpec::new("review.reply", "Reply", "Review › Comments", reply)
|
||||
.params(r#"{"id": non-negative JSON integer, "text": string}"#)
|
||||
.params(r#"{"id": non-negative 32-bit JSON integer, "text": string}"#)
|
||||
.when(comments_change),
|
||||
CommandSpec::new("review.editComment", "Edit Comment", "Review › Comments", edit_comment)
|
||||
.params(r#"{"id": non-negative JSON integer, "text": string}"#)
|
||||
.params(r#"{"id": non-negative 32-bit JSON integer, "text": string}"#)
|
||||
.when(comments_change),
|
||||
CommandSpec::new("review.deleteComment", "Delete", "Review › Comments", delete_comment).params(r#"{"id"?: non-negative JSON integer (omit to use the caret), "all"?: bool}"#),
|
||||
CommandSpec::new("review.deleteComment", "Delete", "Review › Comments", delete_comment).params(r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "all"?: bool}"#),
|
||||
CommandSpec::new("review.resolveComment", "Resolve", "Review › Comments", |s, v| {
|
||||
validate_comment_id(v)?;
|
||||
let id = p::u64(v, "id").map(|x| x as u32).or_else(|| comment_at_caret(s)).ok_or_else(|| CmdError::Params("`id` required".into()))?;
|
||||
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
c.resolved = p::bool(v, "value").unwrap_or(!c.resolved);
|
||||
sel_result(s)
|
||||
})
|
||||
.params(r#"{"id"?: non-negative JSON integer (omit to use the caret), "value"?: bool (omit to toggle)}"#),
|
||||
.params(r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "value"?: bool (omit to toggle)}"#),
|
||||
CommandSpec::new("review.nextComment", "Next", "Review › Comments", |s, _| nav_comment(s, 1)).pure(),
|
||||
CommandSpec::new("review.previousComment", "Previous", "Review › Comments", |s, _| nav_comment(s, -1)).pure(),
|
||||
CommandSpec::new("review.comments", "Show Comments", "Review › Comments", list_comments).pure(),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::{Arc, CmdError, CmdResult, Document, Pos, Selection, Session, StoryRef, Value, delete_selection, json, p, sel_result};
|
||||
use wordcraft_doc::CharProps;
|
||||
|
||||
/// Options › Language › Set as default: only the saved default proofing language (what future
|
||||
/// blank documents are written in), as Word's Set as Preferred. A setting, like `file.options`: the
|
||||
@@ -14,8 +15,19 @@ pub(super) fn preferred_language(s: &mut Session, v: &Value) -> CmdResult {
|
||||
/// Set Proofing Language: the selection's language and "do not check spelling or grammar",
|
||||
/// or (`default`) the document's default and the saved language for future blank documents;
|
||||
/// `detect` is the per-user detection preference.
|
||||
/// Nothing at all sets US English, as before.
|
||||
/// Nothing at all sets US English, as before. `scope: "document"` sets it for every story.
|
||||
pub(super) fn language(s: &mut Session, v: &Value) -> CmdResult {
|
||||
// Checked first, so a bad scope changes nothing (not even the detect preference).
|
||||
let whole_document = match v.get("scope") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(Value::String(t)) if t == "selection" => false,
|
||||
Some(Value::String(t)) if t == "document" => true,
|
||||
Some(other) => return Err(CmdError::Params(format!("`scope` must be \"selection\" or \"document\", not {other}"))),
|
||||
};
|
||||
// Protection leaves only its exceptions editable, so the whole document can't be one.
|
||||
if whole_document && let Some(mode) = s.doc.settings.protection.as_deref() {
|
||||
return Err(CmdError::Disabled(format!("review.language: stop protection ({mode}) before changing the whole document's proofing language")));
|
||||
}
|
||||
let lang = match p::str(v, "lang") {
|
||||
Some(t) => Some(
|
||||
wordcraft_proof::lang::normalize_tag(t)
|
||||
@@ -45,20 +57,91 @@ pub(super) fn language(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if lang.is_none() && no_proof.is_none() {
|
||||
return Ok(json!({"detect": s.prefs.detect_language}));
|
||||
}
|
||||
let result = crate::cmd::format::apply(s, &|c| {
|
||||
let change = |c: &mut CharProps| {
|
||||
if let Some(l) = &lang {
|
||||
c.lang = Some(l.clone());
|
||||
}
|
||||
if let Some(np) = no_proof {
|
||||
c.no_proof = Some(np);
|
||||
}
|
||||
})?;
|
||||
};
|
||||
let result = if whole_document {
|
||||
let glossary_skipped = set_document_props(s, &change)?;
|
||||
// The same caret/selection result as the selection path (the selection is untouched).
|
||||
let mut r = sel_result(s)?;
|
||||
if let Some(m) = r.as_object_mut() {
|
||||
m.insert("scope".into(), json!("document"));
|
||||
if glossary_skipped {
|
||||
m.insert("glossarySkipped".into(), json!(true));
|
||||
}
|
||||
}
|
||||
r
|
||||
} else {
|
||||
crate::cmd::format::apply(s, &change)?
|
||||
};
|
||||
if p::bool(v, "default") == Some(true) {
|
||||
s.prefs.default_language = lang;
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Apply `f` to the character formatting of every story of the document (Language dialog, "Apply
|
||||
/// to the whole document"): text and paragraph marks of the body, headers, footers, notes,
|
||||
/// comments, text boxes (all `Document::parts`), table cells, and the glossary's building blocks.
|
||||
/// The selection is untouched; formatting waiting for typing follows.
|
||||
///
|
||||
/// Glossary blocks are left alone while Track Changes and Track Formatting are both on: tracked
|
||||
/// formatting (`fmt_revisions::record`) compares only the body and the parts, so a glossary change
|
||||
/// would be an untracked edit. So those blocks keep their old language while tracking; the caller
|
||||
/// reports it (`glossarySkipped`). Returns whether the glossary was skipped.
|
||||
fn set_document_props(s: &mut Session, f: &dyn Fn(&mut CharProps)) -> Result<bool, CmdError> {
|
||||
let stories: Vec<StoryRef> = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k))).collect();
|
||||
for story in stories {
|
||||
for path in s.doc.para_paths(story) {
|
||||
let para = s.doc.para_mut(story, &path)?;
|
||||
let len = para.len();
|
||||
para.format(0, len, f)?;
|
||||
f(&mut para.mark);
|
||||
para.touch();
|
||||
}
|
||||
}
|
||||
let skipped = s.doc.settings.track_changes && s.prefs.markup.track_formatting;
|
||||
if !skipped {
|
||||
for block in &mut s.doc.glossary {
|
||||
format_blocks(&mut block.blocks, f, 0);
|
||||
}
|
||||
}
|
||||
if let Some(pend) = s.pending.as_mut() {
|
||||
f(pend);
|
||||
}
|
||||
Ok(skipped)
|
||||
}
|
||||
|
||||
/// [`set_document_props`] for a block list outside any story (depth-limited like `para_paths`).
|
||||
fn format_blocks(blocks: &mut wordcraft_doc::Blocks, f: &dyn Fn(&mut CharProps), depth: usize) {
|
||||
if depth > wordcraft_doc::PARA_WALK_DEPTH {
|
||||
return;
|
||||
}
|
||||
for blk in blocks.iter_mut() {
|
||||
match Arc::make_mut(blk) {
|
||||
wordcraft_doc::Block::Para(p) => {
|
||||
let len = p.len();
|
||||
// A range inside the paragraph can't fail; the mark is formatted regardless.
|
||||
let _ = p.format(0, len, f);
|
||||
f(&mut p.mark);
|
||||
p.touch();
|
||||
}
|
||||
wordcraft_doc::Block::Table(t) => {
|
||||
for row in &mut t.rows {
|
||||
for cell in &mut row.cells {
|
||||
format_blocks(&mut cell.blocks, f, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn macros(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if let Some(d) = v.get("define") {
|
||||
let name = d.get("name").and_then(Value::as_str).unwrap_or("Macro").to_string();
|
||||
|
||||
@@ -340,7 +340,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
.params(r#"{"format": "decimal|upperRoman|lowerLetter…", "text"?: "%1.", "start"?: n}"#),
|
||||
CommandSpec::new("review.language", "Language", "Review › Language", language).params(
|
||||
r#"{"lang"?: "en-US|en-GB|pl-PL|fr-FR|…" (BCP 47; default en-US), "noProof"?: bool, "detect"?: bool (detect language automatically, a preference), "default"?: bool (also the document's default and the saved language for future blank documents)}"#,
|
||||
r#"{"lang"?: "en-US|en-GB|pl-PL|fr-FR|…" (BCP 47; default en-US), "noProof"?: bool, "detect"?: bool (detect language automatically, a preference), "default"?: bool (also the document's default and the saved language for future blank documents), "scope"?: "selection" (default) | "document" (every run and paragraph mark of every story: body, headers, footers, notes, comments, text boxes, tables, glossary (skipped while Track Changes and Track Formatting are on); one undo step, selection unchanged; returns the caret, "scope":"document" and "glossarySkipped":true when the glossary was skipped)}"#,
|
||||
),
|
||||
CommandSpec::new("review.language.preferred", "Set as Default Language", "File › Options › Language", preferred_language)
|
||||
.params(r#"{"lang": "en-US|en-GB|pl-PL|nl-NL|…" (BCP 47)} — only the saved default proofing language, what future blank documents are written in, as Options › Language › Set as default does; the open document, the selection and the undo history don't change. Returns {"preferred": tag}."#)
|
||||
|
||||
@@ -903,3 +903,150 @@ fn inspect_removals_work_when_the_document_does_not_track_changes() {
|
||||
assert!(!text.contains("Hidden"), "the hidden text is still there: {text}");
|
||||
assert!(text.contains("Visible text."), "{text}");
|
||||
}
|
||||
|
||||
/// #3518: every run and paragraph mark of a story, as (story, path, lang, noProof) rows.
|
||||
fn proofing_rows(s: &Session) -> Vec<(StoryRef, Option<String>, Option<bool>)> {
|
||||
let stories = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k)));
|
||||
let mut out = Vec::new();
|
||||
for st in stories {
|
||||
for path in s.doc.para_paths(st) {
|
||||
let Some(p) = s.doc.para(st, &path) else { continue };
|
||||
out.push((st, p.mark.lang.clone(), p.mark.no_proof));
|
||||
out.extend(p.runs.iter().map(|r| (st, r.props.lang.clone(), r.props.no_proof)));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A document with its text in German in the body, a table cell, a header, a footnote, a comment
|
||||
/// and a text box, as a Word DOCX keeps a `w:lang` on each run, plus a glossary entry.
|
||||
fn multi_story_doc() -> Session {
|
||||
use wordcraft_doc::{Block, BuildingBlock, CharProps, Paragraph, PartKind, Table};
|
||||
let de = || CharProps { lang: Some("de-DE".into()), ..Default::default() };
|
||||
let blk = |t: &str| Arc::new(Block::Para(Paragraph::with_text(t, de())));
|
||||
let mut d = Document::from_text("Guten Tag");
|
||||
d.body = vec![blk("Guten Tag")];
|
||||
let mut t = Table::new(1, 2, 200.0);
|
||||
if let Some(c) = t.rows.first_mut().and_then(|r| r.cells.first_mut()) {
|
||||
c.blocks = vec![blk("Zelle")];
|
||||
}
|
||||
d.body.push(Arc::new(Block::Table(t)));
|
||||
d.body.push(blk("Ende"));
|
||||
for kind in [PartKind::Header, PartKind::Footnote, PartKind::Comment, PartKind::TextBox] {
|
||||
d.add_part(kind, vec![blk("Teil")]);
|
||||
}
|
||||
d.glossary.push(BuildingBlock { name: "g".into(), blocks: vec![blk("Baustein")], ..Default::default() });
|
||||
Session::new(d)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn language_scope_document_sets_every_story() {
|
||||
let mut s = multi_story_doc();
|
||||
s.run("select.text", &json!({"text": "Guten"})).unwrap();
|
||||
let (sel, before) = (s.sel.clone(), s.doc.clone());
|
||||
let rows = proofing_rows(&s);
|
||||
assert!(rows.len() >= 10 && rows.iter().any(|r| r.1.as_deref() == Some("de-DE")));
|
||||
s.run("review.language", &json!({"lang": "fr-FR", "scope": "document"})).unwrap();
|
||||
// Runs that had their own language, the paragraph marks and the empty cell: all French.
|
||||
let rows = proofing_rows(&s);
|
||||
assert!(rows.iter().all(|r| r.1.as_deref() == Some("fr-FR")), "{rows:?}");
|
||||
for kind_story in s.doc.parts.keys() {
|
||||
assert!(rows.iter().any(|r| r.0 == StoryRef::Part(*kind_story)));
|
||||
}
|
||||
assert!(s.doc.plain_text(StoryRef::Body).contains("Zelle"));
|
||||
let g = &s.doc.glossary[0].blocks;
|
||||
assert_eq!(g[0].as_para().map(|p| p.runs[0].props.lang.clone()), Some(Some("fr-FR".into())));
|
||||
assert_eq!(g[0].as_para().map(|p| p.mark.lang.clone()), Some(Some("fr-FR".into())));
|
||||
// The selection stays; the document is modified.
|
||||
assert_eq!(s.sel, sel);
|
||||
assert!(s.doc != before);
|
||||
// One undo restores everything.
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc == before);
|
||||
assert_eq!(s.sel, sel);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn language_scope_document_no_proof_and_pending() {
|
||||
let mut s = multi_story_doc();
|
||||
s.run("review.language", &json!({"noProof": true, "scope": "document"})).unwrap();
|
||||
assert!(proofing_rows(&s).iter().all(|r| r.2 == Some(true)));
|
||||
// The language itself wasn't asked for and stays.
|
||||
assert!(proofing_rows(&s).iter().any(|r| r.1.as_deref() == Some("de-DE")));
|
||||
// Formatting waiting for typing follows.
|
||||
s.run("format.bold", &json!({})).unwrap();
|
||||
s.run("review.language", &json!({"lang": "pl-PL", "scope": "document"})).unwrap();
|
||||
assert_eq!(s.pending.as_ref().and_then(|p| p.lang.as_deref()), Some("pl-PL"));
|
||||
}
|
||||
|
||||
/// Document scope returns the caret/selection like the selection path, plus the scope.
|
||||
#[test]
|
||||
fn language_scope_document_returns_the_selection_result() {
|
||||
let mut s = multi_story_doc();
|
||||
s.run("select.text", &json!({"text": "Guten"})).unwrap();
|
||||
let out = s.run("review.language", &json!({"lang": "fr-FR", "scope": "document"})).unwrap();
|
||||
assert_eq!(out["scope"], "document");
|
||||
assert_eq!(out["anchor"], crate::cmd::pos_json(&s.sel.anchor), "{out}");
|
||||
assert_eq!(out["focus"], crate::cmd::pos_json(&s.sel.focus), "{out}");
|
||||
}
|
||||
|
||||
/// Tracked formatting records only the body and parts, so while it is on the glossary (outside
|
||||
/// any story) is left alone instead of changing untracked; with tracking off it changes.
|
||||
#[test]
|
||||
fn language_scope_document_skips_glossary_while_tracking_formatting() {
|
||||
let gloss = |s: &Session| s.doc.glossary[0].blocks[0].as_para().map(|p| (p.runs[0].props.lang.clone(), p.mark.lang.clone()));
|
||||
let mut s = multi_story_doc();
|
||||
s.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
s.run("review.trackingOptions", &json!({"trackFormatting": true})).unwrap();
|
||||
let out = s.run("review.language", &json!({"lang": "fr-FR", "scope": "document"})).unwrap();
|
||||
assert_eq!(out["glossarySkipped"], true, "{out}");
|
||||
assert_eq!(gloss(&s), Some((Some("de-DE".into()), Some("de-DE".into()))));
|
||||
assert!(proofing_rows(&s).iter().all(|r| r.1.as_deref() == Some("fr-FR")));
|
||||
assert!(s.doc.revisions.iter().any(|r| r.kind == wordcraft_doc::RevisionKind::Format), "the body change is tracked");
|
||||
let mut s = multi_story_doc();
|
||||
s.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
s.run("review.trackingOptions", &json!({"trackFormatting": false})).unwrap();
|
||||
let out = s.run("review.language", &json!({"lang": "fr-FR", "scope": "document"})).unwrap();
|
||||
assert!(out.get("glossarySkipped").is_none(), "{out}");
|
||||
assert_eq!(gloss(&s), Some((Some("fr-FR".into()), Some("fr-FR".into()))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn language_default_scope_is_selection_only() {
|
||||
let mut s = multi_story_doc();
|
||||
s.run("select.text", &json!({"text": "Guten"})).unwrap();
|
||||
s.run("review.language", &json!({"lang": "fr-FR"})).unwrap();
|
||||
let rows = proofing_rows(&s);
|
||||
assert!(rows.iter().any(|r| r.1.as_deref() == Some("fr-FR")));
|
||||
assert!(rows.iter().filter(|r| r.1.as_deref() == Some("fr-FR")).count() < rows.len() / 2);
|
||||
let mut s = multi_story_doc();
|
||||
s.run("select.text", &json!({"text": "Guten"})).unwrap();
|
||||
s.run("review.language", &json!({"lang": "fr-FR", "scope": "selection"})).unwrap();
|
||||
assert_eq!(proofing_rows(&s), rows);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn language_bad_scope_is_a_params_error() {
|
||||
let mut s = multi_story_doc();
|
||||
let before = s.doc.clone();
|
||||
for bad in [json!("everything"), json!(1), json!(true), json!(["document"])] {
|
||||
let e = s.run("review.language", &json!({"lang": "fr-FR", "detect": false, "scope": bad})).unwrap_err();
|
||||
assert!(matches!(e, CmdError::Params(_)), "{e:?}");
|
||||
}
|
||||
assert!(s.doc == before);
|
||||
assert!(s.prefs.detect_language);
|
||||
}
|
||||
|
||||
/// Document scope is refused under editing protection, before anything changes.
|
||||
#[test]
|
||||
fn language_document_scope_is_refused_under_protection() {
|
||||
for mode in ["readOnly", "comments", "forms"] {
|
||||
let mut s = multi_story_doc();
|
||||
s.doc.settings.protection = Some(mode.into());
|
||||
let before = s.doc.clone();
|
||||
let e = s.run("review.language", &json!({"lang": "fr-FR", "detect": false, "scope": "document"})).unwrap_err();
|
||||
assert!(matches!(e, CmdError::Disabled(_)), "{mode}: {e:?}");
|
||||
assert!(s.doc == before, "{mode}: nothing changed");
|
||||
assert!(s.prefs.detect_language, "{mode}: the detect preference is untouched");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -464,7 +464,7 @@ pub fn save_bytes_opts(name: &str, doc: &Document, opts: &ExportOptions) -> Resu
|
||||
}
|
||||
|
||||
/// [`save_bytes`], encrypted with `password` when there is one and the format is a Word package
|
||||
/// (other formats are copies and are written as they are).
|
||||
/// or OpenDocument text file (.odt, .ott); other formats are copies and are written as they are.
|
||||
pub fn save_bytes_with(name: &str, doc: &Document, password: Option<&str>, opts: &ExportOptions) -> Result<Vec<u8>, String> {
|
||||
let bytes = save_bytes_opts(name, doc, opts)?;
|
||||
match password {
|
||||
|
||||
@@ -39,7 +39,7 @@ pub struct Prefs {
|
||||
pub region: Option<String>,
|
||||
/// A folder searched for Hunspell dictionaries before the system locations (File › Options ›
|
||||
/// Language, #1063): an app started from Finder or the Dock doesn't see
|
||||
/// `WORDCRAFT_DICTIONARIES`. `None` searches the system locations only.
|
||||
/// `WORDCRAFT_DICTIONARIES`. `None` means no configured folder.
|
||||
pub dictionaries_folder: Option<String>,
|
||||
/// The user templates folder File › New lists personal templates from and Save as Word
|
||||
/// Template starts in (File › Options › Advanced › File locations, #2852). `None`: the app's
|
||||
|
||||
@@ -88,6 +88,10 @@ pub struct Session {
|
||||
pub initials: String,
|
||||
/// Format painter: copied formatting waiting to be applied (and whether it stays on).
|
||||
pub painter: Option<(CharProps, wordcraft_doc::props::ParaProps, bool)>,
|
||||
/// Formatting picked up by Copy Formatting (Mod+Shift+C): Paste Formatting applies it as often
|
||||
/// as asked, as in Word, until the next Copy Formatting. A Format Painter pick is stored here
|
||||
/// as well.
|
||||
pub copied_format: Option<(CharProps, wordcraft_doc::props::ParaProps)>,
|
||||
/// Last message for the status bar / agents.
|
||||
pub status: String,
|
||||
/// Headers/footers `insert.createHeader`/`insert.createFooter` made for a page that had none
|
||||
|
||||
@@ -259,6 +259,7 @@ impl Session {
|
||||
author: _,
|
||||
initials: _,
|
||||
painter: _,
|
||||
copied_format: _,
|
||||
// What the drawn window knows of the others: its front end sets it as it draws.
|
||||
windows: _,
|
||||
status: _,
|
||||
|
||||
@@ -109,6 +109,7 @@ impl Session {
|
||||
author: "WordCraft User".into(),
|
||||
initials: String::new(),
|
||||
painter: None,
|
||||
copied_format: None,
|
||||
status: String::new(),
|
||||
new_header_parts,
|
||||
hf_return,
|
||||
|
||||
@@ -92,6 +92,7 @@ impl Session {
|
||||
author: _,
|
||||
initials: _,
|
||||
painter: _,
|
||||
copied_format: _,
|
||||
status: _,
|
||||
// Headers just created to edit: closing checks they still exist and are empty.
|
||||
new_header_parts: _,
|
||||
|
||||
@@ -1108,6 +1108,26 @@ fn replace_under_track_changes_skips_deleted_text() {
|
||||
assert_eq!(text(&s), "one dog two dog");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_reports_whether_it_replaced_and_what_it_selected() {
|
||||
// Replace follows Word's button: the first call only selects a match. Agents read
|
||||
// `remaining` alone as done (#6877), so the result says whether anything was replaced.
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "alpha XX beta XX gamma XX"}));
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
let calls: Vec<_> = (0..5).map(|_| run(&mut s, "edit.replace", json!({"text": "XX", "with": "YY"}))).collect();
|
||||
let replaced: Vec<_> = calls.iter().map(|r| r["replaced"].clone()).collect();
|
||||
assert_eq!(replaced, [json!(0), json!(1), json!(1), json!(1), json!(0)]);
|
||||
let remaining: Vec<_> = calls.iter().map(|r| r["remaining"].clone()).collect();
|
||||
assert_eq!(remaining, [json!(3), json!(2), json!(1), json!(0), json!(0)]);
|
||||
let selected: Vec<_> = calls.iter().map(|r| (r["selected"]["start"]["off"].clone(), r["selected"]["end"]["off"].clone())).collect();
|
||||
assert_eq!(selected[0], (json!(6), json!(8)));
|
||||
assert_eq!(selected[1], (json!(14), json!(16)));
|
||||
assert_eq!(selected[2], (json!(23), json!(25)));
|
||||
assert!(calls[3]["selected"].is_null() && calls[4]["selected"].is_null(), "no match is left to select");
|
||||
assert_eq!(text(&s), "alpha YY beta YY gamma YY");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_reads_the_text_around_tracked_deletions() {
|
||||
// `edits` are (start, end) byte ranges deleted with Track Changes on, last first.
|
||||
@@ -13472,3 +13492,173 @@ fn resolving_away_an_empty_paragraph_with_a_section_break_keeps_the_next_paragra
|
||||
assert_eq!(s.doc.last_section.margin_left, 72.0, "{cmd}: the following section's setup stays");
|
||||
}
|
||||
}
|
||||
|
||||
/// #5616: Copy Formatting's formatting stays for every Paste Formatting, as in Word; it doesn't
|
||||
/// arm the one-shot Format Painter brush.
|
||||
#[test]
|
||||
fn copied_formatting_pastes_again_and_again() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Bold one two"}));
|
||||
run(&mut s, "select.text", json!({"text": "Bold"}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
run(&mut s, "edit.copyFormat", json!({}));
|
||||
assert!(s.painter.is_none());
|
||||
for word in ["one", "two"] {
|
||||
run(&mut s, "select.text", json!({"text": word}));
|
||||
run(&mut s, "edit.pasteFormat", json!({}));
|
||||
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true), "{word}");
|
||||
}
|
||||
assert_eq!(s.doc.plain_text(wordcraft_doc::StoryRef::Body), "Bold one two");
|
||||
}
|
||||
|
||||
/// #5616: Copy Formatting and the Format Painter share one format buffer: each replaces the other,
|
||||
/// so a used-up brush never hands over to older copied formatting.
|
||||
#[test]
|
||||
fn copy_formatting_and_the_format_painter_replace_each_other() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Bold one two"}));
|
||||
run(&mut s, "select.text", json!({"text": "Bold"}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
run(&mut s, "edit.formatPainter", json!({}));
|
||||
assert!(s.painter.is_some());
|
||||
run(&mut s, "edit.copyFormat", json!({}));
|
||||
assert!(s.painter.is_none(), "Copy Formatting clears an armed brush");
|
||||
assert!(s.copied_format.is_some());
|
||||
run(&mut s, "edit.formatPainter", json!({}));
|
||||
assert!(s.painter.is_some());
|
||||
run(&mut s, "select.text", json!({"text": "one"}));
|
||||
run(&mut s, "edit.pasteFormat", json!({}));
|
||||
assert!(s.painter.is_none(), "a used-up brush is gone");
|
||||
assert!(s.copied_format.is_some(), "its pick stays for Paste Formatting");
|
||||
}
|
||||
|
||||
/// #5616: arming and cancelling the Format Painter leaves Copy Formatting's pick; a brush's pick
|
||||
/// is what Paste Formatting applies next.
|
||||
#[test]
|
||||
fn cancelling_the_format_painter_keeps_the_copied_formatting() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Bold one two"}));
|
||||
run(&mut s, "select.text", json!({"text": "Bold"}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
run(&mut s, "edit.copyFormat", json!({}));
|
||||
run(&mut s, "edit.formatPainter", json!({}));
|
||||
run(&mut s, "edit.formatPainter", json!({}));
|
||||
assert!(s.painter.is_none());
|
||||
run(&mut s, "select.text", json!({"text": "one"}));
|
||||
run(&mut s, "edit.pasteFormat", json!({}));
|
||||
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true));
|
||||
// A brush picked from plain text replaces the bold pick.
|
||||
run(&mut s, "select.text", json!({"text": "two"}));
|
||||
run(&mut s, "edit.formatPainter", json!({}));
|
||||
run(&mut s, "select.text", json!({"text": "Bold"}));
|
||||
run(&mut s, "edit.pasteFormat", json!({}));
|
||||
assert_ne!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true));
|
||||
}
|
||||
|
||||
/// #5616: copied formatting carries no tracked paragraph formatting or numbering change.
|
||||
#[test]
|
||||
fn copied_paragraph_formatting_carries_no_tracked_changes() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "one\ntwo"}));
|
||||
run(&mut s, "review.trackChanges", json!({"value": true}));
|
||||
run(&mut s, "select.text", json!({"text": "one"}));
|
||||
run(&mut s, "para.alignCenter", json!({}));
|
||||
run(&mut s, "review.trackChanges", json!({"value": false}));
|
||||
run(&mut s, "select.text", json!({"text": "one"}));
|
||||
let f = s.sel.focus.clone();
|
||||
assert!(s.doc.para_at(&f).unwrap().props.fmt_change.is_some(), "the source paragraph has a tracked formatting change");
|
||||
run(&mut s, "edit.copyFormat", json!({}));
|
||||
let (_, para) = s.copied_format.clone().unwrap();
|
||||
assert!(para.fmt_change.is_none() && para.num_change.is_none());
|
||||
run(&mut s, "select.text", json!({"text": "two"}));
|
||||
run(&mut s, "edit.pasteFormat", json!({}));
|
||||
let f = s.sel.focus.clone();
|
||||
let p = s.doc.para_at(&f).unwrap().props.clone();
|
||||
assert!(p.fmt_change.is_none() && p.num_change.is_none());
|
||||
}
|
||||
|
||||
/// #5616: copied formatting carries no hyperlink or revision marks, even into a collapsed caret.
|
||||
#[test]
|
||||
fn copied_formatting_carries_no_hyperlink() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "source target"}));
|
||||
run(&mut s, "select.text", json!({"text": "source"}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
run(&mut s, "insert.link", json!({"url": "https://example.com/"}));
|
||||
run(&mut s, "select.text", json!({"text": "so"}));
|
||||
run(&mut s, "edit.copyFormat", json!({}));
|
||||
let (chr, _) = s.copied_format.clone().unwrap();
|
||||
assert_eq!(chr.bold, Some(true));
|
||||
assert!(chr.link.is_none() && chr.ins.is_none() && chr.del.is_none() && chr.fmt_change.is_none());
|
||||
run(&mut s, "select.text", json!({"text": "target"}));
|
||||
run(&mut s, "select.collapse", json!({}));
|
||||
run(&mut s, "caret.left", json!({}));
|
||||
run(&mut s, "edit.pasteFormat", json!({}));
|
||||
let f = s.sel.focus.clone();
|
||||
let link = s.doc.para_at(&f).map(|p| p.props_of_char(f.off).link.clone());
|
||||
assert_eq!(link, Some(None), "the target didn't become a link");
|
||||
}
|
||||
|
||||
/// #5616: Paste Formatting at a bare caret keeps the word's own hyperlink and tracked insertion.
|
||||
#[test]
|
||||
fn a_caret_paste_formatting_keeps_the_targets_link_and_tracked_marks() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "source target"}));
|
||||
run(&mut s, "select.text", json!({"text": "source"}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
run(&mut s, "edit.copyFormat", json!({}));
|
||||
run(&mut s, "select.text", json!({"text": "target"}));
|
||||
run(&mut s, "insert.link", json!({"url": "https://example.com/"}));
|
||||
run(&mut s, "select.collapse", json!({}));
|
||||
run(&mut s, "caret.right", json!({}));
|
||||
run(&mut s, "edit.pasteFormat", json!({}));
|
||||
let at_caret = |s: &Session| {
|
||||
let f = s.sel.focus.clone();
|
||||
s.doc.para_at(&f).map(|p| p.props_of_char(f.off).clone()).unwrap_or_default()
|
||||
};
|
||||
let c = at_caret(&s);
|
||||
assert!(c.link.is_some(), "the target kept its hyperlink");
|
||||
assert_eq!(c.bold, Some(true));
|
||||
// A tracked insertion stays tracked.
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
run(&mut s, "review.trackChanges", json!({"value": true}));
|
||||
run(&mut s, "text.insert", json!({"text": " added"}));
|
||||
run(&mut s, "review.trackChanges", json!({"value": false}));
|
||||
run(&mut s, "caret.left", json!({}));
|
||||
assert!(at_caret(&s).ins.is_some(), "the insertion is tracked before");
|
||||
run(&mut s, "edit.pasteFormat", json!({}));
|
||||
assert!(at_caret(&s).ins.is_some(), "Paste Formatting kept the insertion mark");
|
||||
}
|
||||
|
||||
/// #5616: Paste Formatting over a selection keeps the target's hyperlink and tracked marks too.
|
||||
#[test]
|
||||
fn a_range_paste_formatting_keeps_the_targets_link_and_tracked_marks() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "source target"}));
|
||||
run(&mut s, "select.text", json!({"text": "source"}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
run(&mut s, "edit.copyFormat", json!({}));
|
||||
run(&mut s, "select.text", json!({"text": "target"}));
|
||||
run(&mut s, "insert.link", json!({"url": "https://example.com/"}));
|
||||
run(&mut s, "select.text", json!({"text": "target"}));
|
||||
run(&mut s, "edit.pasteFormat", json!({}));
|
||||
let (a, _) = s.sel.ordered();
|
||||
let c = s.doc.para_at(&a).map(|p| p.props_of_char(a.off).clone()).unwrap_or_default();
|
||||
assert!(c.link.is_some(), "the target kept its hyperlink");
|
||||
assert_eq!(c.bold, Some(true));
|
||||
// A tracked insertion selected as a range stays tracked.
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
run(&mut s, "review.trackChanges", json!({"value": true}));
|
||||
run(&mut s, "text.insert", json!({"text": " added"}));
|
||||
run(&mut s, "review.trackChanges", json!({"value": false}));
|
||||
run(&mut s, "select.text", json!({"text": "added"}));
|
||||
let at_start = |s: &Session| {
|
||||
let (a, _) = s.sel.ordered();
|
||||
s.doc.para_at(&a).map(|p| p.props_of_char(a.off).clone()).unwrap_or_default()
|
||||
};
|
||||
assert!(at_start(&s).ins.is_some(), "the insertion is tracked before");
|
||||
run(&mut s, "edit.pasteFormat", json!({}));
|
||||
let c = at_start(&s);
|
||||
assert!(c.ins.is_some(), "Paste Formatting kept the insertion mark");
|
||||
assert_eq!(c.bold, Some(true));
|
||||
}
|
||||
|
||||
@@ -5,13 +5,40 @@ use wordcraft_doc::props::CharProps;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// Creates a document with `lines` lines of text.
|
||||
/// The bundled face the fixtures are set in. Their page counts are exact to a line, so they must
|
||||
/// not depend on the face the host substitutes for the default Aptos: at 11 pt, Arial and
|
||||
/// Liberation Sans fit 28 of these lines on a page and DejaVu Sans, the only candidate on a bare
|
||||
/// FreeBSD system, fits 27. Inter is the bundled face whose metrics give each 0.5 pt step its own
|
||||
/// page boundary at this page size.
|
||||
const FIXTURE_FONT: &str = "Inter";
|
||||
|
||||
/// Creates a document with `lines` lines of text in [`FIXTURE_FONT`]. Inter fits 25 lines on a
|
||||
/// page at 12 pt, 26 at 11.5 pt and 27 at 11 pt.
|
||||
fn create_multiline_doc(lines: usize) -> Session {
|
||||
let mut text = String::new();
|
||||
for i in 1..=lines {
|
||||
text.push_str(&format!("Line {i}: The quick brown fox jumps over the lazy dog.\n"));
|
||||
}
|
||||
Session::new(Document::from_text(&text))
|
||||
let mut doc = Document::from_text(&text);
|
||||
std::sync::Arc::make_mut(&mut doc.styles).default_chr.font = Some(FIXTURE_FONT.into());
|
||||
Session::new(doc)
|
||||
}
|
||||
|
||||
/// Asserts the body is laid out in the bundled [`FIXTURE_FONT`], not a substitute.
|
||||
fn assert_fixture_font(s: &mut Session) {
|
||||
let layout = s.layout();
|
||||
let mut runs = 0;
|
||||
for page in &layout.pages {
|
||||
for item in &page.items {
|
||||
if let wordcraft_layout::Placed::Lines { story: wordcraft_doc::StoryRef::Body, para, .. } = item {
|
||||
for style in ¶.styles {
|
||||
runs += 1;
|
||||
assert_eq!(style.face.family, FIXTURE_FONT, "the fixture must not fall back to another family");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(runs > 0, "the font check must inspect laid-out body text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -39,7 +66,7 @@ fn fit_one_page_fails_on_hard_page_break() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_refuses_page_break_before_before_search() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
let mut s = create_multiline_doc(26);
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
if let wordcraft_doc::Block::Para(p) = std::sync::Arc::make_mut(&mut s.doc.body[1]) {
|
||||
p.props.page_break_before = Some(true);
|
||||
@@ -74,7 +101,7 @@ fn fit_one_page_fails_on_next_page_section_break() {
|
||||
#[test]
|
||||
fn fit_one_page_condenses_slight_overflow_and_undoes() {
|
||||
// Find the boundary where the document just spills onto page 2
|
||||
let mut lines = 30;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 2;
|
||||
@@ -102,7 +129,7 @@ fn fit_one_page_condenses_slight_overflow_and_undoes() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_respects_max_delta() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
let mut s = create_multiline_doc(26);
|
||||
assert_eq!(s.layout().pages.len(), 2, "must start as 2-page document");
|
||||
|
||||
let doc_backup = s.doc.clone();
|
||||
@@ -117,11 +144,7 @@ fn fit_one_page_respects_max_delta() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_respects_step_pt() {
|
||||
let mut text = String::new();
|
||||
for i in 1..=28 {
|
||||
text.push_str(&format!("Line {i}: The quick brown fox jumps over the lazy dog.\n"));
|
||||
}
|
||||
let mut s = Session::new(Document::from_text(&text));
|
||||
let mut s = create_multiline_doc(27);
|
||||
for b in &mut s.doc.body {
|
||||
if let wordcraft_doc::Block::Para(p) = std::sync::Arc::make_mut(b) {
|
||||
p.mark.size = Some(11.4);
|
||||
@@ -131,6 +154,7 @@ fn fit_one_page_respects_step_pt() {
|
||||
}
|
||||
}
|
||||
assert_eq!(s.layout().pages.len(), 2, "must start as 2-page document at 11.4 pt");
|
||||
assert_fixture_font(&mut s);
|
||||
|
||||
// Both calls hold maxDeltaPt constant at 0.4 and disable spacing adjustments.
|
||||
// Default 0.5 pt step generates no candidates <= 0.4 pt, so it must fail.
|
||||
@@ -147,7 +171,7 @@ fn fit_one_page_respects_step_pt() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_allows_spacing_only_at_font_floor() {
|
||||
let mut lines = 35;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
let set_font = |s: &mut Session| {
|
||||
for b in &mut s.doc.body {
|
||||
@@ -178,7 +202,7 @@ fn fit_one_page_allows_spacing_only_at_font_floor() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_fails_when_body_font_already_at_minimum_readable_size() {
|
||||
let mut lines = 35;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
let set_font = |s: &mut Session| {
|
||||
for b in &mut s.doc.body {
|
||||
@@ -208,7 +232,7 @@ fn fit_one_page_fails_when_body_font_already_at_minimum_readable_size() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_bounds_fine_step_loop() {
|
||||
let mut lines = 28;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 1;
|
||||
@@ -224,7 +248,7 @@ fn fit_one_page_bounds_fine_step_loop() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_supports_max_delta_above_2pt() {
|
||||
let mut lines = 28;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 1;
|
||||
@@ -244,7 +268,7 @@ fn fit_one_page_supports_max_delta_above_2pt() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_anti_compound_guard_prevents_repeated_invocations() {
|
||||
let mut lines = 28;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
loop {
|
||||
for b in &mut s.doc.body {
|
||||
@@ -314,7 +338,7 @@ fn fit_one_page_already_fits_wins_over_exhausted_budget() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_checks_complex_script_font_floor() {
|
||||
let mut lines = 28;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 1;
|
||||
@@ -340,7 +364,7 @@ fn fit_one_page_checks_complex_script_font_floor() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_checks_editable_text_box_font_floor() {
|
||||
let mut lines = 28;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 1;
|
||||
@@ -386,7 +410,7 @@ fn fit_one_page_checks_editable_text_box_font_floor() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_fails_when_overflow_exceeds_limits() {
|
||||
let mut lines = 28;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 {
|
||||
lines += 1;
|
||||
@@ -566,7 +590,7 @@ fn fit_one_page_fails_with_failed_cmd_error() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_never_populates_custom_props() {
|
||||
let mut lines = 30;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 2;
|
||||
@@ -582,7 +606,7 @@ fn fit_one_page_never_populates_custom_props() {
|
||||
fn fit_one_page_allows_subsequent_fit_after_typography_reset() {
|
||||
use std::sync::Arc;
|
||||
|
||||
let mut lines = 28;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 1;
|
||||
@@ -625,7 +649,7 @@ fn fit_one_page_allows_subsequent_fit_after_typography_reset() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_small_paragraph_mark_with_runs_never_blocks_fit() {
|
||||
let mut lines = 30;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 2;
|
||||
@@ -646,7 +670,7 @@ fn fit_one_page_small_paragraph_mark_with_runs_never_blocks_fit() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_small_comment_font_never_blocks_body_fit() {
|
||||
let mut lines = 30;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 2;
|
||||
@@ -666,7 +690,7 @@ fn fit_one_page_small_comment_font_never_blocks_body_fit() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_anti_compound_caps_total_reduction_across_runs() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
let mut s = create_multiline_doc(26);
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
|
||||
// Initial fit with -0.5 pt font reduction (spacing disabled so font budget is exercised)
|
||||
@@ -688,7 +712,7 @@ fn fit_one_page_anti_compound_caps_total_reduction_across_runs() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_tracks_reduced_text_provenance_without_global_minimum() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
let mut s = create_multiline_doc(26);
|
||||
// Add a 9.0 pt run to the first paragraph alongside 11.0 pt runs
|
||||
if let wordcraft_doc::Block::Para(p) = std::sync::Arc::make_mut(&mut s.doc.body[0]) {
|
||||
p.runs.push(wordcraft_doc::para::Run { len: 5, props: CharProps { size: Some(9.0), ..Default::default() } });
|
||||
@@ -725,7 +749,7 @@ fn fit_one_page_tracks_reduced_text_provenance_without_global_minimum() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_allows_spill_with_bottom_placed_footnote() {
|
||||
let mut lines = 28;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 1;
|
||||
@@ -751,7 +775,7 @@ fn fit_one_page_allows_spill_with_bottom_placed_footnote() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_with_final_page_footnote() {
|
||||
let mut lines = 28;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 1;
|
||||
@@ -784,7 +808,7 @@ fn fit_one_page_with_final_page_footnote() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_skips_deleted_text_when_markup_hidden() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
let mut s = create_multiline_doc(26);
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
|
||||
// Insert a deleted text run with small font (e.g. 6.0 pt, below the 8.5 pt floor)
|
||||
@@ -815,7 +839,7 @@ fn fit_one_page_skips_deleted_text_when_markup_hidden() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_tracks_reduced_complex_script_font_sizes() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
let mut s = create_multiline_doc(26);
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
let styles_before = s.doc.styles.clone();
|
||||
|
||||
@@ -853,8 +877,9 @@ fn fit_one_page_tracks_reduced_complex_script_font_sizes() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_preserves_budget_across_document_serialization() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
let mut s = create_multiline_doc(26);
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
assert_fixture_font(&mut s);
|
||||
|
||||
// Apply fit
|
||||
let res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.5, "adjustSpacing": false}));
|
||||
@@ -900,7 +925,7 @@ fn fit_one_page_enforces_durable_limit_when_fit_state_missing() {
|
||||
s.touch();
|
||||
s.relayout();
|
||||
};
|
||||
let mut lines = 27;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
set_font(&mut s);
|
||||
while s.layout().pages.len() < 2 && lines < 120 {
|
||||
@@ -924,7 +949,7 @@ fn fit_one_page_enforces_durable_limit_when_fit_state_missing() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_skips_hidden_text_when_hidden_marks_off() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
let mut s = create_multiline_doc(26);
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
|
||||
// Insert a hidden text run with small font (6.0 pt, below the 8.5 pt floor) into an existing paragraph
|
||||
@@ -958,7 +983,7 @@ fn fit_one_page_skips_hidden_text_when_hidden_marks_off() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_accounts_for_vertical_alignment_padding() {
|
||||
let mut s = create_multiline_doc(26);
|
||||
let mut s = create_multiline_doc(25);
|
||||
let extra_p = wordcraft_doc::Paragraph::with_text("Spill line on page 2.", CharProps::default());
|
||||
s.doc.body.push(wordcraft_doc::para_block(extra_p));
|
||||
|
||||
@@ -977,7 +1002,7 @@ fn fit_one_page_accounts_for_vertical_alignment_padding() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_accounts_for_note_separator_decor_story() {
|
||||
let mut lines = 28;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 1;
|
||||
@@ -1012,7 +1037,7 @@ fn fit_one_page_accounts_for_note_separator_decor_story() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_tracks_fixed_spacing_independent_of_paragraph_mark_size() {
|
||||
let mut lines = 28;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
let set_spacing = |s: &mut Session| {
|
||||
for b in &mut s.doc.body {
|
||||
@@ -1053,7 +1078,7 @@ fn fit_one_page_tracks_fixed_spacing_independent_of_paragraph_mark_size() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_reports_search_exhaustion_when_candidates_cannot_remove_page() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
let mut s = create_multiline_doc(26);
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
|
||||
// Calling with zero maxDeltaPt and adjustSpacing: false produces no candidate steps
|
||||
@@ -1068,23 +1093,24 @@ fn fit_one_page_reports_search_exhaustion_when_candidates_cannot_remove_page() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_excludes_line_number_decorations_from_final_page_limits() {
|
||||
let mut lines = 33;
|
||||
let enable_line_numbers = |s: &mut Session| {
|
||||
s.doc.last_section.line_numbers = Some(wordcraft_doc::section::LineNumbering::default());
|
||||
s.touch();
|
||||
s.relayout();
|
||||
};
|
||||
let mut s = create_multiline_doc(lines);
|
||||
enable_line_numbers(&mut s);
|
||||
while s.layout().pages.len() < 2 && lines < 60 {
|
||||
lines += 1;
|
||||
s = create_multiline_doc(lines);
|
||||
enable_line_numbers(&mut s);
|
||||
}
|
||||
let mut s = create_multiline_doc(33);
|
||||
s.doc.last_section.line_numbers = Some(wordcraft_doc::section::LineNumbering::default());
|
||||
s.touch();
|
||||
s.relayout();
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
|
||||
// Every body line on the final page also places a line-number decoration. Counting those as
|
||||
// content would double the final-page line count and refuse before any candidate is tried.
|
||||
// content would double the final-page line count and refuse before any candidate is tried:
|
||||
// between 7 and 12 body lines are within the 12-line limit, and twice as many are not.
|
||||
let body_lines: usize = s.layout().pages[1]
|
||||
.items
|
||||
.iter()
|
||||
.map(|item| match item {
|
||||
wordcraft_layout::Placed::Lines { story: wordcraft_doc::StoryRef::Body, l0, l1, .. } => l1 - l0,
|
||||
_ => 0,
|
||||
})
|
||||
.sum();
|
||||
assert!((7..=12).contains(&body_lines), "the final page must carry 7 to 12 body lines, has {body_lines}");
|
||||
let decorated = s.layout().pages[1]
|
||||
.items
|
||||
.iter()
|
||||
@@ -1099,7 +1125,7 @@ fn fit_one_page_excludes_line_number_decorations_from_final_page_limits() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_counts_side_by_side_footnote_cells_once() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
let mut s = create_multiline_doc(26);
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
|
||||
// A footnote table whose row's cells sit side by side: their text occupies one vertical
|
||||
@@ -1134,7 +1160,7 @@ fn fit_one_page_counts_side_by_side_footnote_cells_once() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_refuses_when_formatting_changes_cannot_be_tracked() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
let mut s = create_multiline_doc(26);
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
s.doc.settings.track_changes = true;
|
||||
s.prefs.markup.track_formatting = true;
|
||||
|
||||
@@ -103,3 +103,58 @@ fn an_odt_bibliography_updates_from_its_citations_sources() {
|
||||
assert!(text.iter().any(|t| t.contains("Kilns and Fire")), "{text:?}");
|
||||
assert!(!text.iter().any(|t| t.contains("stale")), "{text:?}");
|
||||
}
|
||||
|
||||
/// #6486: LibreOffice numbers headings through its outline style, the number followed by a tab,
|
||||
/// and its Contents styles carry only the right-aligned dotted stop for the page number. After
|
||||
/// Update Table, the tab after an entry's number stops near the number, not at the page-number
|
||||
/// stop: the title stays at the left and each entry stays on one line.
|
||||
#[test]
|
||||
fn an_odt_toc_with_numbered_headings_keeps_its_entries_on_one_line() {
|
||||
let outline = |level: u8, cm: f32| {
|
||||
format!(
|
||||
r#"<text:outline-level-style text:level="{level}" style:num-format="1" style:num-suffix="." text:display-levels="{level}"><style:list-level-properties text:list-level-position-and-space-mode="label-alignment"><style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="{cm}cm" fo:text-indent="-{cm}cm" fo:margin-left="{cm}cm"/></style:list-level-properties></text:outline-level-style>"#
|
||||
)
|
||||
};
|
||||
let contents = |n: u8, indent: f32| {
|
||||
format!(
|
||||
r#"<style:style style:name="Contents_20_{n}" style:display-name="Contents {n}" style:family="paragraph"><style:paragraph-properties fo:margin-left="{indent}cm"><style:tab-stops><style:tab-stop style:position="16.99cm" style:type="right" style:leader-style="dotted" style:leader-text="."/></style:tab-stops></style:paragraph-properties></style:style>"#
|
||||
)
|
||||
};
|
||||
let styles = format!(
|
||||
r#"<office:document-styles {NS}><office:styles>{}{}<text:outline-style style:name="Outline">{}{}</text:outline-style></office:styles><office:automatic-styles><style:page-layout style:name="pm1"><style:page-layout-properties fo:page-width="21.001cm" fo:page-height="29.7cm" fo:margin-left="2cm" fo:margin-right="2cm" fo:margin-top="2cm" fo:margin-bottom="2cm"/></style:page-layout></office:automatic-styles><office:master-styles><style:master-page style:name="Standard" style:page-layout-name="pm1"/></office:master-styles></office:document-styles>"#,
|
||||
contents(1, 0.0),
|
||||
contents(2, 0.499),
|
||||
outline(1, 0.762),
|
||||
outline(2, 1.016)
|
||||
);
|
||||
let content = format!(
|
||||
r#"<office:document-content {NS}><office:body><office:text>
|
||||
<text:table-of-content text:name="T"><text:table-of-content-source text:outline-level="2"/><text:index-body><text:p text:style-name="Contents_20_1">1. Planning<text:tab/>1</text:p><text:p text:style-name="Contents_20_2">1.1. Budget<text:tab/>1</text:p></text:index-body></text:table-of-content>
|
||||
<text:h text:outline-level="1">Planning</text:h><text:p>Text.</text:p>
|
||||
<text:h text:outline-level="2">Budget</text:h><text:p>More text.</text:p>
|
||||
</office:text></office:body></office:document-content>"#
|
||||
);
|
||||
let mut z = craft_zip::Writer::new();
|
||||
for (name, data) in [("mimetype", "application/vnd.oasis.opendocument.text"), ("styles.xml", styles.as_str()), ("content.xml", content.as_str())]
|
||||
{
|
||||
z.add(name, data.as_bytes(), craft_zip::Compression::Stored).unwrap();
|
||||
}
|
||||
let mut s = Session::new(io::open_bytes("toc.odt", &z.finish().unwrap()).unwrap());
|
||||
s.run("references.updateToc", &json!({})).unwrap();
|
||||
let layout = s.layout();
|
||||
let mut checked = 0;
|
||||
for (i, b) in s.doc.body.iter().enumerate() {
|
||||
let Some(p) = b.as_para().filter(|p| p.props.style.as_deref().is_some_and(|st| st.starts_with("TOC") && st != "TOCHeading")) else {
|
||||
continue;
|
||||
};
|
||||
let Some(tab) = p.text.find('\t') else { continue };
|
||||
let pos = |off| wordcraft_doc::Pos { story: wordcraft_doc::StoryRef::Body, path: wordcraft_doc::Path::top(i), off };
|
||||
let title = layout.caret(&pos(tab + 1)).unwrap();
|
||||
let end = layout.caret(&pos(p.len())).unwrap();
|
||||
assert!(p.plain_text().contains("Planning") || p.plain_text().contains("Budget"), "{:?}", p.text);
|
||||
assert_eq!((title.page, title.top), (end.page, end.top), "{:?} wraps", p.text);
|
||||
assert!(title.x < 200.0, "{:?}: the title starts at {}", p.text, title.x);
|
||||
checked += 1;
|
||||
}
|
||||
assert_eq!(checked, 2);
|
||||
}
|
||||
|
||||
@@ -63,7 +63,13 @@ impl std::fmt::Display for UserFontError {
|
||||
match self {
|
||||
UserFontError::Empty => write!(f, "the font file is empty"),
|
||||
UserFontError::TooLarge { bytes } => {
|
||||
write!(f, "the font file is too large ({} MB; at most {} MB)", bytes.div_ceil(1 << 20), MAX_FONT_FILE_BYTES >> 20)
|
||||
write!(
|
||||
f,
|
||||
"the font is too large ({} MB; file limit {} MB, unpacked limit {} MB)",
|
||||
bytes.div_ceil(1 << 20),
|
||||
MAX_FONT_FILE_BYTES >> 20,
|
||||
MAX_DECODED_BYTES >> 20
|
||||
)
|
||||
}
|
||||
UserFontError::NotAFont => write!(f, "not a font file (TrueType, OpenType, TTC, WOFF or WOFF2)"),
|
||||
UserFontError::BadWebFont(e) => write!(f, "the web font couldn't be read: {e}"),
|
||||
|
||||
@@ -210,7 +210,9 @@ fn woff1_claiming(orig: u32) -> Vec<u8> {
|
||||
fn a_woff_claiming_a_huge_table_is_refused_before_inflating() {
|
||||
// #3703: the decoder sizes a table's buffer from the directory before inflating it.
|
||||
for orig in [200 << 20, u32::MAX] {
|
||||
assert!(matches!(decode_font_file(&woff1_claiming(orig)), Err(UserFontError::TooLarge { .. })), "{orig}");
|
||||
let error = decode_font_file(&woff1_claiming(orig)).unwrap_err();
|
||||
assert!(matches!(&error, UserFontError::TooLarge { .. }), "{orig}");
|
||||
assert!(error.to_string().contains("unpacked limit 128 MB"), "{error}");
|
||||
}
|
||||
// A small claim reaches the decoder, which finds the data doesn't inflate to it.
|
||||
assert!(matches!(decode_font_file(&woff1_claiming(64)), Err(UserFontError::BadWebFont(_))));
|
||||
@@ -311,7 +313,9 @@ fn junk_is_rejected_without_adding_anything() {
|
||||
assert_eq!(db.families().len(), n + db.user_fonts().iter().map(|u| u.families().len()).sum::<usize>());
|
||||
let mut big = regular.clone();
|
||||
big.resize(MAX_FONT_FILE_BYTES + 1, 0);
|
||||
assert!(matches!(db.install_font("big.ttf", &big), Err(UserFontError::TooLarge { .. })));
|
||||
let error = db.install_font("big.ttf", &big).unwrap_err();
|
||||
assert!(matches!(&error, UserFontError::TooLarge { .. }));
|
||||
assert!(error.to_string().contains("file limit 50 MB"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -10,9 +10,10 @@ workspace = true
|
||||
|
||||
[features]
|
||||
# Picture decoding within a memory budget (`picture`), for the crates that decode pictures.
|
||||
image = ["dep:image", "dep:craft-image-codecs"]
|
||||
image = ["dep:image", "dep:craft-image-codecs", "dep:craft-tiff"]
|
||||
|
||||
[dependencies]
|
||||
craft-image-codecs = { workspace = true, optional = true }
|
||||
craft-tiff = { workspace = true, optional = true }
|
||||
image = { workspace = true, optional = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
+24
-20
@@ -1,5 +1,4 @@
|
||||
//! WordCraft geometry and units.
|
||||
//!
|
||||
//! Layout works in **points** (1/72 inch, `f32`). File formats use other units: OOXML uses
|
||||
//! twentieths of a point (twips) for most lengths, half-points for font sizes, eighths of a point
|
||||
//! for borders and English Metric Units (EMU, 914 400 per inch) for drawings. The conversions live
|
||||
@@ -25,26 +24,32 @@ pub const EMU_PER_PT: f32 = 12_700.0;
|
||||
pub const PT_PER_CM: f32 = 72.0 / 2.54;
|
||||
|
||||
/// Twips → points.
|
||||
#[expect(clippy::cast_precision_loss, reason = "The f32 return type intentionally rounds i64 inputs to f32 precision.")]
|
||||
pub fn twips(v: i64) -> f32 {
|
||||
v as f32 / TWIPS_PER_PT
|
||||
}
|
||||
/// Points → twips (rounded).
|
||||
#[expect(clippy::cast_possible_truncation, reason = "The value is rounded first; Rust's float-to-integer cast saturates outside the i64 range.")]
|
||||
pub fn to_twips(pt: f32) -> i64 {
|
||||
finite(pt * TWIPS_PER_PT).round() as i64
|
||||
}
|
||||
/// EMU → points.
|
||||
#[expect(clippy::cast_precision_loss, reason = "The f32 return type intentionally rounds i64 inputs to f32 precision.")]
|
||||
pub fn emu(v: i64) -> f32 {
|
||||
v as f32 / EMU_PER_PT
|
||||
}
|
||||
/// Points → EMU (rounded).
|
||||
#[expect(clippy::cast_possible_truncation, reason = "The value is rounded first; Rust's float-to-integer cast saturates outside the i64 range.")]
|
||||
pub fn to_emu(pt: f32) -> i64 {
|
||||
(finite(pt) as f64 * EMU_PER_PT as f64).round() as i64
|
||||
(f64::from(finite(pt)) * f64::from(EMU_PER_PT)).round() as i64
|
||||
}
|
||||
/// Half-points (OOXML font sizes) → points.
|
||||
#[expect(clippy::cast_precision_loss, reason = "The f32 return type intentionally rounds i64 inputs to f32 precision.")]
|
||||
pub fn half_points(v: i64) -> f32 {
|
||||
v as f32 / 2.0
|
||||
}
|
||||
/// Points → half-points (rounded).
|
||||
#[expect(clippy::cast_possible_truncation, reason = "The value is rounded first; Rust's float-to-integer cast saturates outside the i64 range.")]
|
||||
pub fn to_half_points(pt: f32) -> i64 {
|
||||
(finite(pt) * 2.0).round() as i64
|
||||
}
|
||||
@@ -123,8 +128,7 @@ pub fn parse_measure(s: &str, default: Unit) -> Option<f32> {
|
||||
"cm" => PT_PER_CM,
|
||||
"mm" => PT_PER_CM / 10.0,
|
||||
"pt" | "pts" | "point" | "points" => 1.0,
|
||||
"pi" | "pc" | "pica" | "picas" => 12.0,
|
||||
"li" | "line" | "lines" => 12.0,
|
||||
"pi" | "pc" | "pica" | "picas" | "li" | "line" | "lines" => 12.0,
|
||||
"px" => 0.75,
|
||||
_ => return None,
|
||||
};
|
||||
@@ -198,7 +202,7 @@ pub fn normalize_degrees(deg: f32) -> f32 {
|
||||
}
|
||||
|
||||
/// How a drawing is turned about its centre: mirrored first (`flip_h` left to right, `flip_v` top
|
||||
/// to bottom), then rotated `deg` degrees clockwise (page space, y down), as DrawingML's `a:xfrm`
|
||||
/// to bottom), then rotated `deg` degrees clockwise (page space, y down), as `DrawingML`'s `a:xfrm`
|
||||
/// `flipH`, `flipV` and `rot` say (ECMA-376 §20.1.7.6).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Default)]
|
||||
pub struct Spin {
|
||||
@@ -219,7 +223,7 @@ impl Spin {
|
||||
}
|
||||
|
||||
/// The linear part (a, b, c, d: x' = a·x + c·y, y' = b·x + d·y).
|
||||
fn linear(&self) -> [f32; 4] {
|
||||
fn linear(self) -> [f32; 4] {
|
||||
let r = normalize_degrees(self.deg).to_radians();
|
||||
let (s, c) = r.sin_cos();
|
||||
let fx = if self.flip_h { -1.0 } else { 1.0 };
|
||||
@@ -237,17 +241,17 @@ impl Spin {
|
||||
|
||||
/// Where point (`x`, `y`) goes when turned about (`cx`, `cy`).
|
||||
pub fn apply(&self, cx: f32, cy: f32, x: f32, y: f32) -> (f32, f32) {
|
||||
let [a, b, c, d] = self.linear();
|
||||
let (u, v) = (x - cx, y - cy);
|
||||
(cx + a * u + c * v, cy + b * u + d * v)
|
||||
let [x_from_x, y_from_x, x_from_y, y_from_y] = self.linear();
|
||||
let (relative_x, relative_y) = (x - cx, y - cy);
|
||||
(cx + x_from_x * relative_x + x_from_y * relative_y, cy + y_from_x * relative_x + y_from_y * relative_y)
|
||||
}
|
||||
|
||||
/// The point that [`Spin::apply`] takes to (`x`, `y`).
|
||||
pub fn unapply(&self, cx: f32, cy: f32, x: f32, y: f32) -> (f32, f32) {
|
||||
// The linear part is orthogonal: its inverse is its transpose.
|
||||
let [a, b, c, d] = self.linear();
|
||||
let (u, v) = (x - cx, y - cy);
|
||||
(cx + a * u + b * v, cy + c * u + d * v)
|
||||
let [x_from_x, y_from_x, x_from_y, y_from_y] = self.linear();
|
||||
let (relative_x, relative_y) = (x - cx, y - cy);
|
||||
(cx + x_from_x * relative_x + y_from_x * relative_y, cy + x_from_y * relative_x + y_from_y * relative_y)
|
||||
}
|
||||
|
||||
/// The axis-aligned box `r` covers once turned about its centre.
|
||||
@@ -258,10 +262,10 @@ impl Spin {
|
||||
|
||||
/// The width and height of the box a `w` × `h` rectangle covers once turned.
|
||||
pub fn extent(&self, w: f32, h: f32) -> (f32, f32) {
|
||||
let (w, h) = (finite(w).abs(), finite(h).abs());
|
||||
let r = normalize_degrees(self.deg).to_radians();
|
||||
let (s, c) = (r.sin().abs(), r.cos().abs());
|
||||
(w * c + h * s, w * s + h * c)
|
||||
let (width, height) = (finite(w).abs(), finite(h).abs());
|
||||
let radians = normalize_degrees(self.deg).to_radians();
|
||||
let (sine, cosine) = (radians.sin().abs(), radians.cos().abs());
|
||||
(width * cosine + height * sine, width * sine + height * cosine)
|
||||
}
|
||||
|
||||
/// This spin applied inside `outer` (a group member's own spin within its group's): the one
|
||||
@@ -343,11 +347,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn unit_round_trips() {
|
||||
assert_eq!(twips(1440), 72.0);
|
||||
assert_eq!(twips(1440).to_bits(), 72.0f32.to_bits());
|
||||
assert_eq!(to_twips(72.0), 1440);
|
||||
assert_eq!(emu(914_400), 72.0);
|
||||
assert_eq!(emu(914_400).to_bits(), 72.0f32.to_bits());
|
||||
assert_eq!(to_emu(72.0), 914_400);
|
||||
assert_eq!(half_points(24), 12.0);
|
||||
assert_eq!(half_points(24).to_bits(), 12.0f32.to_bits());
|
||||
assert_eq!(to_half_points(10.5), 21);
|
||||
assert_eq!(to_twips(f32::NAN), 0);
|
||||
}
|
||||
@@ -429,7 +433,7 @@ mod tests {
|
||||
assert!(a.intersects(&b));
|
||||
assert_eq!(a.union(&b), Rect::new(0.0, 0.0, 15.0, 15.0));
|
||||
assert!(a.contains(Point::new(5.0, 5.0)));
|
||||
assert_eq!(Rect::new(0.0, 0.0, -5.0, f32::NAN).w, 0.0);
|
||||
assert_eq!(Rect::new(0.0, 0.0, -5.0, f32::NAN).w.to_bits(), 0.0f32.to_bits());
|
||||
assert_eq!(a.inset(1.0, 2.0, 3.0, 4.0), Rect::new(1.0, 2.0, 6.0, 4.0));
|
||||
}
|
||||
|
||||
|
||||
+29
-33
@@ -20,9 +20,9 @@ pub enum Refusal {
|
||||
NotAPicture,
|
||||
/// A kind of picture that is never decoded, because its decoder can't be held to a budget.
|
||||
Unsupported(&'static str),
|
||||
/// Decoding it would take more memory than the budget.
|
||||
/// Decoding would exceed the memory budget or size arithmetic overflowed.
|
||||
TooLarge { width: u32, height: u32 },
|
||||
/// The header or the data is damaged.
|
||||
/// The header or data is damaged, or the decoder rejects the input.
|
||||
Broken(String),
|
||||
}
|
||||
|
||||
@@ -179,11 +179,19 @@ pub struct Probe<'a> {
|
||||
}
|
||||
|
||||
/// TIFF compressions decoded within the caller's limits: none, CCITT Group 4, LZW, Deflate (both
|
||||
/// codes) and PackBits. The `tiff` crate decodes a JPEG strip (7) with a decoder of its own and
|
||||
/// codes) and `PackBits`. The `tiff` crate decodes a JPEG strip (7) with a decoder of its own and
|
||||
/// default limits, whatever size the TIFF declares, so such a TIFF is not decoded (#3645).
|
||||
const TIFF_COMPRESSIONS: [u16; 6] = [1, 4, 5, 8, 32946, 32773];
|
||||
|
||||
/// Read a picture's header: PNG, JPEG, GIF, WebP, BMP or TIFF.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns `Refusal::NotAPicture` for an unsupported format, `Refusal::Unsupported` for a TIFF
|
||||
/// whose compression cannot be read or budgeted (including truncation that prevents reading
|
||||
/// its compression metadata), `Refusal::TooLarge`
|
||||
/// on size arithmetic overflow, and `Refusal::Broken` for other header or inspection errors,
|
||||
/// including TIFF errors after compression metadata is accepted.
|
||||
pub fn probe(bytes: &[u8]) -> Result<Probe<'_>, Refusal> {
|
||||
let codec_fmt = detect(bytes).ok_or(Refusal::NotAPicture)?;
|
||||
let format = from_codec_format(codec_fmt).ok_or(Refusal::NotAPicture)?;
|
||||
@@ -287,6 +295,11 @@ fn dib_to_bmp(dib: &[u8]) -> Vec<u8> {
|
||||
/// Read a DIB's header: a BMP without its 14-byte file header, as the Windows clipboard holds
|
||||
/// one (`CF_DIB`, `CF_DIBV5`). Its layout is first made the one the decoder reads (see
|
||||
/// [`dib_layout`]).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns `Refusal::Broken` for an invalid DIB header and `Refusal::TooLarge` on size arithmetic
|
||||
/// overflow.
|
||||
pub fn probe_dib(dib: Vec<u8>) -> Result<Probe<'static>, Refusal> {
|
||||
let dib = dib_layout(dib);
|
||||
let bmp = dib_to_bmp(&dib);
|
||||
@@ -349,6 +362,12 @@ impl Probe<'_> {
|
||||
|
||||
/// Decode, refused before anything is allocated when the peak would pass `budget` bytes. The
|
||||
/// decoder is held to the header's size and to `budget` as well.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns `Refusal::TooLarge` when the picture does not fit `budget` or the decoder
|
||||
/// exceeds its limits, `Refusal::NotAPicture` for an unsupported format, and
|
||||
/// `Refusal::Broken` for other decoding or pixel-conversion errors.
|
||||
pub fn decode(&self, budget: u64) -> Result<DynamicImage, Refusal> {
|
||||
if !self.fits(budget) {
|
||||
return Err(Refusal::TooLarge { width: self.width, height: self.height });
|
||||
@@ -364,6 +383,10 @@ impl Probe<'_> {
|
||||
}
|
||||
|
||||
/// [`probe`], then [`Probe::decode`] within `budget` bytes.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns the probing or decoding `Refusal`; see [`probe`] and [`Probe::decode`].
|
||||
pub fn decode(bytes: &[u8], budget: u64) -> Result<DynamicImage, Refusal> {
|
||||
probe(bytes)?.decode(budget)
|
||||
}
|
||||
@@ -516,36 +539,7 @@ fn worst_coefficients(bytes: &[u8]) -> u64 {
|
||||
/// tag is missing. None when the header can't be read, or when the tag appears more than once:
|
||||
/// the decoder keeps the last copy, so a harmless first one must not hide a JPEG one after it.
|
||||
fn tiff_compression(bytes: &[u8]) -> Option<u16> {
|
||||
let le = match bytes.get(..4)? {
|
||||
b"II*\0" => true,
|
||||
b"MM\0*" => false,
|
||||
_ => return None,
|
||||
};
|
||||
let u16_at = |at: usize| -> Option<u16> {
|
||||
let b = [*bytes.get(at)?, *bytes.get(at.checked_add(1)?)?];
|
||||
Some(if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) })
|
||||
};
|
||||
let u32_at = |at: usize| -> Option<u32> {
|
||||
let b: [u8; 4] = bytes.get(at..at.checked_add(4)?)?.try_into().ok()?;
|
||||
Some(if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) })
|
||||
};
|
||||
let ifd = usize::try_from(u32_at(4)?).ok()?;
|
||||
let mut found = None;
|
||||
for i in 0..usize::from(u16_at(ifd)?) {
|
||||
let entry = ifd.checked_add(2)?.checked_add(i.checked_mul(12)?)?;
|
||||
if u16_at(entry)? != 259 {
|
||||
continue;
|
||||
}
|
||||
if found.is_some() || u32_at(entry.checked_add(4)?)? != 1 {
|
||||
return None;
|
||||
}
|
||||
found = Some(match u16_at(entry.checked_add(2)?)? {
|
||||
3 => u16_at(entry.checked_add(8)?)?,
|
||||
4 => u16::try_from(u32_at(entry.checked_add(8)?)?).ok()?,
|
||||
_ => return None,
|
||||
});
|
||||
}
|
||||
Some(found.unwrap_or(1))
|
||||
craft_tiff::probe::first_image_compression(bytes)
|
||||
}
|
||||
|
||||
/// A DIB with a V4 or V5 header in the layout the decoder reads. A 32-bit one whose alpha mask
|
||||
@@ -722,6 +716,7 @@ mod tests {
|
||||
let mut s = vec![8];
|
||||
s.extend(h.to_be_bytes());
|
||||
s.extend(w.to_be_bytes());
|
||||
#[expect(clippy::cast_possible_truncation, reason = "These fixtures contain at most four three-byte component records.")]
|
||||
s.push((comps.len() / 3) as u8);
|
||||
s.extend(comps);
|
||||
s
|
||||
@@ -736,6 +731,7 @@ mod tests {
|
||||
// A marker walk over SOI, an APP0 segment, SOF2, then the scan.
|
||||
let mut jpeg = vec![0xFF, 0xD8, 0xFF, 0xE0, 0, 4, 0, 0, 0xFF, 0xC2];
|
||||
let f = sof(64, 64, &[1, 0x11, 0]);
|
||||
#[expect(clippy::cast_possible_truncation, reason = "This fixture's nine-byte frame header and length field fit u16.")]
|
||||
jpeg.extend(((f.len() + 2) as u16).to_be_bytes());
|
||||
jpeg.extend(&f);
|
||||
jpeg.extend([0xFF, 0xDA]);
|
||||
|
||||
+22
-10
@@ -9,7 +9,7 @@ pub const MAX_RASTER_PIXELS: u64 = 100_000_000;
|
||||
|
||||
/// Bytes of a `w`×`h` RGBA8 raster, None on overflow.
|
||||
pub fn rgba_bytes(w: u32, h: u32) -> Option<u64> {
|
||||
(w as u64).checked_mul(h as u64)?.checked_mul(4)
|
||||
u64::from(w).checked_mul(u64::from(h))?.checked_mul(4)
|
||||
}
|
||||
|
||||
/// Whether a `w`×`h` RGBA8 raster fits `budget` bytes.
|
||||
@@ -29,22 +29,34 @@ pub fn decode_fits(w: u32, h: u32, budget: u64) -> bool {
|
||||
/// premultiplied copy, so the peak is the larger of `native + 4` and `8` bytes a pixel.
|
||||
pub fn decode_peak_fits(w: u32, h: u32, native: u64, budget: u64) -> bool {
|
||||
let per_pixel = native.saturating_add(4).max(8);
|
||||
w > 0 && h > 0 && (w as u64).checked_mul(h as u64).and_then(|p| p.checked_mul(per_pixel)).is_some_and(|b| b <= budget)
|
||||
w > 0 && h > 0 && u64::from(w).checked_mul(u64::from(h)).and_then(|p| p.checked_mul(per_pixel)).is_some_and(|b| b <= budget)
|
||||
}
|
||||
|
||||
/// `w`×`h` shrunk (aspect kept, each side at least 1) until it holds at most `max_pixels`.
|
||||
pub fn fit_pixels(w: u32, h: u32, max_pixels: u64) -> (u32, u32) {
|
||||
let (w, h) = (w.max(1), h.max(1));
|
||||
let max_pixels = max_pixels.max(1);
|
||||
let area = w as u64 * h as u64;
|
||||
let area = u64::from(w) * u64::from(h);
|
||||
if area <= max_pixels {
|
||||
return (w, h);
|
||||
}
|
||||
let f = (max_pixels as f64 / area as f64).sqrt();
|
||||
let nh = ((h as f64 * f) as u64).clamp(1, h as u64);
|
||||
let nw = ((w as f64 * f) as u64).clamp(1, w as u64).min(max_pixels / nh).max(1);
|
||||
let nh = nh.min(max_pixels / nw).max(1);
|
||||
(nw as u32, nh as u32)
|
||||
#[expect(clippy::cast_precision_loss, reason = "Floating point only approximates the scale; the integer clamps below enforce every bound.")]
|
||||
let scale = (max_pixels as f64 / area as f64).sqrt();
|
||||
#[expect(
|
||||
clippy::cast_possible_truncation,
|
||||
clippy::cast_sign_loss,
|
||||
reason = "The scale is finite and within 0..=1; truncation floors a positive dimension before clamping."
|
||||
)]
|
||||
let new_height = ((f64::from(h) * scale) as u64).clamp(1, u64::from(h));
|
||||
#[expect(
|
||||
clippy::cast_possible_truncation,
|
||||
clippy::cast_sign_loss,
|
||||
reason = "The scale is finite and within 0..=1; truncation floors a positive dimension before clamping."
|
||||
)]
|
||||
let new_width = ((f64::from(w) * scale) as u64).clamp(1, u64::from(w)).min(max_pixels / new_height).max(1);
|
||||
let new_height = new_height.min(max_pixels / new_width).max(1);
|
||||
#[expect(clippy::cast_possible_truncation, reason = "Both dimensions are clamped to their original u32 values above.")]
|
||||
(new_width as u32, new_height as u32)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -78,9 +90,9 @@ mod tests {
|
||||
fn fit_pixels_keeps_normal_sizes_and_shrinks_huge_ones() {
|
||||
assert_eq!(fit_pixels(612, 792, MAX_RASTER_PIXELS), (612, 792));
|
||||
let (w, h) = fit_pixels(16_000, 16_000, 1_000_000);
|
||||
assert!(w as u64 * h as u64 <= 1_000_000 && w >= 900, "{w}x{h}");
|
||||
assert!(u64::from(w) * u64::from(h) <= 1_000_000 && w >= 900, "{w}x{h}");
|
||||
let (w, h) = fit_pixels(16_000, 1, 100);
|
||||
assert!(w as u64 * h as u64 <= 100 && h == 1, "{w}x{h}");
|
||||
assert!(u64::from(w) * u64::from(h) <= 100 && h == 1, "{w}x{h}");
|
||||
assert_eq!(fit_pixels(0, 5, 10).0, 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,7 +307,7 @@ fn decode_alpha(bytes: &[u8], decoded: &mut u64) -> Result<Option<Alpha>, OverBu
|
||||
fn alpha_in_crop(img: &Alpha, crop: [f32; 4]) -> Option<Vec<(f32, f32)>> {
|
||||
let (iw, ih) = (img.w, img.h);
|
||||
// The part the renderers draw (#1899): a sliver keeps its partly covered pixels.
|
||||
let [cl, ct, vw, vh] = craft_metafile::crop_window(crop);
|
||||
let [cl, ct, vw, vh] = crate::crop_window(crop);
|
||||
let (fw, fh) = (f64::from(iw), f64::from(ih));
|
||||
let x0 = ((fw * cl) as u32).min(iw);
|
||||
let y0 = ((fh * ct) as u32).min(ih);
|
||||
|
||||
@@ -470,12 +470,41 @@ fn character_backgrounds(ctx: &LineContext<'_, '_, '_>, out: &mut Vec<Draw>) {
|
||||
}
|
||||
|
||||
fn draw_label_and_hyphen(ctx: &LineContext<'_, '_, '_>, out: &mut Vec<Draw>) {
|
||||
// A list number goes with its paragraph mark: when the mark is a tracked deletion the number
|
||||
// is drawn as deleted text is, in the deletion's colour and with its mark (struck through by
|
||||
// default, a caret, #s, bold…), and not at all where deletions aren't shown (#4828). Only
|
||||
// when the item is deleted whole, its text too: a deleted mark alone joins the item to the
|
||||
// next one, and its text and number stay as they are.
|
||||
let m = &ctx.opts.revisions;
|
||||
let whole = ctx.para.is_some_and(|p| p.runs.iter().all(|r| r.len == 0 || r.props.del.is_some()));
|
||||
let mark_del = ctx.para.filter(|_| whole).and_then(|p| p.mark.del);
|
||||
let moved = mark_del.is_some() && ctx.doc.move_name(mark_del).is_some();
|
||||
let hidden = mark_del.is_some() && (!ctx.opts.markup || m.hides_deletion(moved));
|
||||
let deleted = mark_del.filter(|_| ctx.opts.markup && m.insertions_deletions);
|
||||
let del_mark = deleted.map(|_| if moved { m.move_from_mark } else { m.delete_mark });
|
||||
// Moved-away text marked (none) is plain text, and so is its number.
|
||||
let plain_move = moved && del_mark == Some(DeleteMark::None);
|
||||
let del_color =
|
||||
deleted.filter(|_| !plain_move).map(|r| if moved { m.move_from_color } else { m.delete_color }.unwrap_or_else(|| ctx.authors.color(r)));
|
||||
if ctx.li == ctx.pl.label_line()
|
||||
&& !hidden
|
||||
&& let Some(label) = &ctx.pl.label
|
||||
{
|
||||
let gx = ctx.x + label.x;
|
||||
let first = label.runs.first().and_then(|r| ctx.pl.styles.get(r.style as usize));
|
||||
if let (Some(DeleteMark::Caret), Some(color), Some(style)) = (del_mark, del_color, first) {
|
||||
// A caret where the number was, instead of the number.
|
||||
let (h, w, y) = (style.size * 0.3, (style.size / 18.0).max(0.6), ctx.base + 1.0);
|
||||
for (x0, y0, x1, y1) in [(gx - h * 0.6, y, gx, y - h), (gx, y - h, gx + h * 0.6, y)] {
|
||||
out.push(Draw::Line { x0, y0, x1, y1, width: w, color, stroke: Stroke::Solid, alpha: ctx.alpha, text_bg: None });
|
||||
}
|
||||
return draw_hyphen(ctx, out);
|
||||
}
|
||||
for run in &label.runs {
|
||||
let Some(style) = ctx.pl.styles.get(run.style as usize) else { continue };
|
||||
let color = del_color.unwrap_or_else(|| ctx.ink(&style.rc.color, None));
|
||||
// Each deleted character shows as #.
|
||||
let hash = (del_mark == Some(DeleteMark::Hash)).then(|| style.face.glyph_for('#'));
|
||||
out.push(Draw::Glyphs {
|
||||
face: style.face,
|
||||
size: style.size,
|
||||
@@ -484,12 +513,12 @@ fn draw_label_and_hyphen(ctx: &LineContext<'_, '_, '_>, out: &mut Vec<Draw>) {
|
||||
.get(run.glyphs.clone())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|g| (g.gid, gx + g.dx, ctx.base - style.shift - g.dy))
|
||||
.map(|g| (hash.unwrap_or(g.gid), gx + g.dx, ctx.base - style.shift - g.dy))
|
||||
.collect(),
|
||||
color: ctx.ink(&style.rc.color, None),
|
||||
color,
|
||||
alpha: ctx.alpha,
|
||||
synth_bold: style.synth_bold,
|
||||
synth_italic: style.synth_italic,
|
||||
synth_bold: style.synth_bold || del_mark == Some(DeleteMark::Bold),
|
||||
synth_italic: style.synth_italic || del_mark == Some(DeleteMark::Italic),
|
||||
text: run.text.clone(),
|
||||
link: None,
|
||||
ranges: Vec::new(),
|
||||
@@ -497,7 +526,27 @@ fn draw_label_and_hyphen(ctx: &LineContext<'_, '_, '_>, out: &mut Vec<Draw>) {
|
||||
x_scale: 1.0,
|
||||
});
|
||||
}
|
||||
// Struck through or underlined once, across the whole number, in its first run's size.
|
||||
if let (Some(color), Some(mark), Some(style)) = (del_color, del_mark, first) {
|
||||
let strike_y = ctx.base - style.shift - style.size * 0.28;
|
||||
let under_y = ctx.base - style.shift + style.size * 0.12;
|
||||
let line = match mark {
|
||||
DeleteMark::Strikethrough => Some((strike_y, Stroke::Solid)),
|
||||
DeleteMark::DoubleStrikethrough => Some((strike_y, Stroke::Double)),
|
||||
DeleteMark::Underline => Some((under_y, Stroke::Solid)),
|
||||
DeleteMark::DoubleUnderline => Some((under_y, stroke_of(Underline::Double))),
|
||||
_ => None,
|
||||
};
|
||||
if let Some((y, stroke)) = line {
|
||||
let width = (style.size / 18.0).max(0.5);
|
||||
out.push(Draw::Line { x0: gx, y0: y, x1: gx + label.width, y1: y, width, color, stroke, alpha: ctx.alpha, text_bg: None });
|
||||
}
|
||||
}
|
||||
}
|
||||
draw_hyphen(ctx, out);
|
||||
}
|
||||
|
||||
fn draw_hyphen(ctx: &LineContext<'_, '_, '_>, out: &mut Vec<Draw>) {
|
||||
if let Some((style_index, glyph, advance)) = ctx.line.hyphen
|
||||
&& let Some(style) = ctx.pl.styles.get(style_index as usize)
|
||||
{
|
||||
|
||||
@@ -718,12 +718,18 @@ pub(crate) fn place_objects(ctx: &mut Ctx, req: &ObjectPlacement) -> (Vec<Placed
|
||||
// (#4250). Inline objects go with their own line.
|
||||
let first = l0 == 0;
|
||||
let late = at.late.filter(|l| !l.placed.is_empty());
|
||||
let late_lines = late.map(LateFloats::lines_here).unwrap_or_default();
|
||||
for li in 0..pl.lines.len() {
|
||||
// A later piece looks only at its own lines and those holding the anchors of the late floats
|
||||
// it draws, in order: walking every line of the paragraph for each piece made a paragraph of
|
||||
// many pages quadratic (#6757).
|
||||
let (piece, mut late_lines) =
|
||||
if first { (0..pl.lines.len(), Vec::new()) } else { (l0..l1.min(pl.lines.len()), late.map(LateFloats::lines_here).unwrap_or_default()) };
|
||||
late_lines.retain(|li| !piece.contains(li));
|
||||
late_lines.sort_unstable();
|
||||
late_lines.dedup();
|
||||
let (before, after) = late_lines.split_at(late_lines.partition_point(|li| *li < piece.start));
|
||||
for li in before.iter().copied().chain(piece).chain(after.iter().copied()) {
|
||||
crate::work::steps(1);
|
||||
let in_piece = (l0..l1).contains(&li);
|
||||
if !in_piece && !first && !late_lines.contains(&li) {
|
||||
continue;
|
||||
}
|
||||
let Some(line) = pl.lines.get(li) else { continue };
|
||||
for k in line.c0..line.c1 {
|
||||
let Some(c) = pl.clusters.get(k) else { continue };
|
||||
|
||||
@@ -292,9 +292,13 @@ fn hf_text_at(p: &Page, id: u32, x: f32, y: f32) -> bool {
|
||||
_ => None,
|
||||
})
|
||||
.any(|(para, l0, l1, lx, ly)| {
|
||||
let (Some(first), Some(last)) = (para.lines.get(*l0), para.lines.get(l1.checked_sub(1).unwrap_or(0))) else { return false };
|
||||
let bottom = ly + last.top + last.height - first.top;
|
||||
y >= *ly - 2.0 && y <= bottom + 2.0 && x >= *lx - 40.0 && x <= lx + last.right + 40.0
|
||||
let Some(first) = para.lines.get(*l0) else { return false };
|
||||
// Each line has its own band and extent: lines beside a float are shorter than the
|
||||
// ones above them, and a click on a long line past a short one's end is still text.
|
||||
(*l0..*l1).filter_map(|li| para.lines.get(li)).any(|l| {
|
||||
let top = ly + l.top - first.top;
|
||||
y >= top - 2.0 && y <= top + l.height + 2.0 && x >= lx + l.left - 40.0 && x <= lx + l.right + 40.0
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -59,6 +59,7 @@ mod ctx;
|
||||
mod floats;
|
||||
mod flow;
|
||||
mod headers;
|
||||
mod metafile;
|
||||
mod missing;
|
||||
mod notes;
|
||||
mod page;
|
||||
@@ -85,6 +86,7 @@ use headers::MAX_HEADER_ITEMS;
|
||||
#[cfg(test)]
|
||||
use headers::placed_cost;
|
||||
use headers::placed_cost_by;
|
||||
pub use metafile::{MAX_METAFILE_DASHES, crop_sides, crop_window, metafile_average_color, metafile_dashes, metafile_miter_limit};
|
||||
pub use missing::{MAX_MISSING_GLYPHS, MissingGlyphs, metafile_text_run, missing_watermark_glyphs, watermark_run};
|
||||
pub use notes::DECOR_STORY;
|
||||
pub(crate) use notes::NOTE_SEP_W;
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
//! Drawing rules the page renderer and the PDF export share for metafile pictures and picture
|
||||
//! crops, so the two outputs draw the same file the same way.
|
||||
|
||||
/// Most dashes and gaps one metafile stroke is split into. A path that a pen's pattern would split
|
||||
/// into more draws solid.
|
||||
pub const MAX_METAFILE_DASHES: f64 = 100_000.0;
|
||||
|
||||
/// The crop sides a picture is drawn with: each side of `crop` (left, top, right, bottom fractions
|
||||
/// of the source) at least 0. A negative side draws as no crop, not as padding around the source.
|
||||
pub fn crop_sides(crop: [f32; 4]) -> [f32; 4] {
|
||||
crop.map(|v| if v.is_finite() { v.max(0.0) } else { 0.0 })
|
||||
}
|
||||
|
||||
/// The part of a picture's source that `crop` keeps, as fractions of the source: [left, top,
|
||||
/// width, height] (`craft_metafile::crop_window` of [`crop_sides`]).
|
||||
pub fn crop_window(crop: [f32; 4]) -> [f64; 4] {
|
||||
craft_metafile::crop_window(crop_sides(crop))
|
||||
}
|
||||
|
||||
/// The miter limit a metafile pen is drawn with: its own when it is finite and at least 1,
|
||||
/// otherwise 10.
|
||||
pub fn metafile_miter_limit(limit: f32) -> f32 {
|
||||
if limit.is_finite() && limit >= 1.0 { limit } else { 10.0 }
|
||||
}
|
||||
|
||||
/// The dash lengths (page points) a metafile pen draws a path `length` points long with, or None
|
||||
/// for a solid line. `dash` is the placed pen's pattern (`craft_metafile::LineStyle::dash`, page
|
||||
/// points) and `pixel` is one output pixel in points.
|
||||
///
|
||||
/// A cosmetic pen (`cosmetic`: width 0) has its pattern scaled so that its shortest dash or gap is
|
||||
/// one pixel, at any zoom. A pattern with a negative or non-finite length draws solid, and so does
|
||||
/// one whose period is shorter than a pixel or that would split the path into more than
|
||||
/// [`MAX_METAFILE_DASHES`] dashes and gaps.
|
||||
pub fn metafile_dashes(dash: &[f32], cosmetic: bool, pixel: f64, length: f64) -> Option<Vec<f64>> {
|
||||
if dash.is_empty() || !pixel.is_finite() || pixel <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let mut out: Vec<f64> = dash.iter().map(|d| f64::from(*d)).collect();
|
||||
if !out.iter().all(|d| d.is_finite() && *d >= 0.0) {
|
||||
return None;
|
||||
}
|
||||
if cosmetic {
|
||||
let shortest = out.iter().copied().filter(|d| *d > 0.0).fold(f64::INFINITY, f64::min);
|
||||
if !shortest.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let k = pixel / shortest;
|
||||
out.iter_mut().for_each(|d| *d *= k);
|
||||
}
|
||||
let period: f64 = out.iter().sum();
|
||||
if !period.is_finite() || period < pixel {
|
||||
return None;
|
||||
}
|
||||
// Each length of the pattern starts a new dash or gap.
|
||||
let pieces = out.len() as f64 * if length.is_finite() { length.max(0.0) / period } else { f64::INFINITY };
|
||||
(pieces <= MAX_METAFILE_DASHES).then_some(out)
|
||||
}
|
||||
|
||||
/// The alpha-weighted average color of straight RGBA pixels (transparent when there are none): a
|
||||
/// metafile pattern fill whose tile is too small to show is filled with it.
|
||||
pub fn metafile_average_color(px: &[u8]) -> [u8; 4] {
|
||||
let (mut r, mut g, mut b, mut a, mut n) = (0u64, 0u64, 0u64, 0u64, 0u64);
|
||||
for p in px.as_chunks::<4>().0 {
|
||||
let w = u64::from(p[3]);
|
||||
r += u64::from(p[0]) * w;
|
||||
g += u64::from(p[1]) * w;
|
||||
b += u64::from(p[2]) * w;
|
||||
a += w;
|
||||
n += 1;
|
||||
}
|
||||
if a == 0 || n == 0 {
|
||||
return [0; 4];
|
||||
}
|
||||
[(r / a) as u8, (g / a) as u8, (b / a) as u8, (a / n) as u8]
|
||||
}
|
||||
@@ -151,13 +151,37 @@ pub fn watermark_run(wm: &wordcraft_doc::Watermark, max_chars: usize) -> Option<
|
||||
/// in the face its font name resolves to (no fallback face), so a character that face lacks shapes
|
||||
/// to glyph id 0. Strict export checks these same glyphs, so the check and the exporters can't
|
||||
/// drift.
|
||||
pub fn metafile_text_run(t: &craft_metafile::Text) -> (wordcraft_fonts::FaceRef, Vec<ShapedGlyph>) {
|
||||
let family = t.font.family.trim();
|
||||
let family = if family.is_empty() { METAFILE_DEFAULT_FONT } else { family };
|
||||
let face = wordcraft_fonts::word::resolve(family, t.font.weight >= 600, t.font.italic).face;
|
||||
let shaped = wordcraft_fonts::shape(&face, &t.text, &[], |c| c);
|
||||
(face, shaped)
|
||||
}
|
||||
|
||||
/// The face a metafile font with no face name is drawn in.
|
||||
const METAFILE_DEFAULT_FONT: &str = "Arial";
|
||||
/// The cell height (text units) of a metafile font whose height is 0, the file's default size.
|
||||
const METAFILE_DEFAULT_HEIGHT: f64 = 16.0;
|
||||
|
||||
/// A metafile text run laid out with a font's metrics: the em size (text units), the baseline's y
|
||||
/// and each glyph's (x, y), alignment included, in the run's text space (see
|
||||
/// `craft_metafile::Text::transform`).
|
||||
pub struct MetafileTextLayout {
|
||||
pub em: f64,
|
||||
pub baseline: f64,
|
||||
pub glyphs: Vec<(f64, f64)>,
|
||||
/// The rectangle of the character cells (x0, y0, x1, y1): from the leftmost to the rightmost
|
||||
/// pen position of the run, the font's ascent above the baseline and its descent below. An
|
||||
/// opaque background fills it.
|
||||
pub cell: [f64; 4],
|
||||
}
|
||||
|
||||
/// Lay out shaped glyphs for a metafile text run.
|
||||
/// Lays out the shaped glyphs of `t`, given as (cluster byte offset, x advance, x offset, y offset)
|
||||
/// in font units of a font with `upem` units per em, `ascent` above and `descent` below the
|
||||
/// baseline. The font height is the em size when negative and the cell height (ascent plus
|
||||
/// descent) when positive. The per-character advances `dx` place each cluster when there is one
|
||||
/// per character. None when the size is not finite and positive.
|
||||
pub fn layout_metafile_text(
|
||||
t: &craft_metafile::Text,
|
||||
upem: f64,
|
||||
@@ -166,10 +190,9 @@ pub fn layout_metafile_text(
|
||||
glyphs: &[(usize, f64, f64, f64)],
|
||||
) -> Option<MetafileTextLayout> {
|
||||
let upem = if upem.is_finite() && upem > 0.0 { upem } else { 1000.0 };
|
||||
let cell_h = ascent + descent;
|
||||
let size = if t.font.height == 0.0 { 12.0 } else { f64::from(t.font.height.abs()) };
|
||||
let cell = t.font.height > 0.0;
|
||||
let em = if cell && cell_h.is_finite() && cell_h > 0.0 { size * upem / cell_h } else { size };
|
||||
let height = if t.font.height == 0.0 { METAFILE_DEFAULT_HEIGHT } else { f64::from(t.font.height) };
|
||||
let cell = ascent + descent;
|
||||
let em = if height > 0.0 && cell.is_finite() && cell > 0.0 { height * upem / cell } else { height.abs() };
|
||||
if !em.is_finite() || em <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
@@ -187,6 +210,8 @@ pub fn layout_metafile_text(
|
||||
});
|
||||
let mut out = Vec::with_capacity(glyphs.len());
|
||||
let (mut pen, mut cluster_pen, mut last) = (0.0, 0.0, None);
|
||||
// The leftmost and rightmost pen positions: advances can move backward.
|
||||
let (mut lo, mut hi) = (0.0f64, 0.0f64);
|
||||
for &(cluster, adv, xo, yo) in glyphs {
|
||||
let ci = starts.partition_point(|&b| b <= cluster).saturating_sub(1);
|
||||
if last != Some(ci) {
|
||||
@@ -199,6 +224,10 @@ pub fn layout_metafile_text(
|
||||
};
|
||||
out.push((x + xo * k, -yo * k));
|
||||
pen += adv * k;
|
||||
(lo, hi) = (lo.min(pen), hi.max(pen));
|
||||
}
|
||||
if let Some(cum) = &dx {
|
||||
(lo, hi) = cum.iter().fold((0.0f64, 0.0f64), |(l, h), x| (l.min(*x), h.max(*x)));
|
||||
}
|
||||
let width = dx.as_ref().and_then(|c| c.last().copied()).unwrap_or(pen);
|
||||
let hoff = match t.h_align {
|
||||
@@ -212,14 +241,8 @@ pub fn layout_metafile_text(
|
||||
craft_metafile::VAlign::Bottom => -descent * k,
|
||||
};
|
||||
let glyphs = out.into_iter().map(|(x, y)| (x + hoff, y + baseline)).collect();
|
||||
Some(MetafileTextLayout { em, baseline, glyphs })
|
||||
}
|
||||
|
||||
pub fn metafile_text_run(t: &craft_metafile::Text) -> (wordcraft_fonts::FaceRef, Vec<ShapedGlyph>) {
|
||||
let bold = t.font.weight >= 600;
|
||||
let face = wordcraft_fonts::word::resolve(&t.font.family, bold, t.font.italic).face;
|
||||
let shaped = wordcraft_fonts::shape(&face, &t.text, &[], |c| c);
|
||||
(face, shaped)
|
||||
let cell = [hoff + lo, baseline - ascent * k, hoff + hi, baseline + descent * k];
|
||||
Some(MetafileTextLayout { em, baseline, glyphs, cell })
|
||||
}
|
||||
|
||||
/// The characters of the watermark that draw as an empty box (glyph id 0), counted as
|
||||
|
||||
@@ -27,6 +27,9 @@ struct Breaker<'e> {
|
||||
/// Word 2013+ (compatibility mode 15) fits more text on a justified line by shrinking its
|
||||
/// spaces (`space_room`); never on lines with tabs.
|
||||
shrink_spaces: 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,
|
||||
/// Word stretches a justified line ending in a manual line break unless the document says not to.
|
||||
expand_break: bool,
|
||||
/// Hyphenation Options: the zone, and how many lines in a row may end with a hyphen.
|
||||
@@ -190,6 +193,13 @@ 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,
|
||||
tight_indent: settings.do_not_suppress_indentation
|
||||
&& settings.compat_mode < wordcraft_doc::COMPAT_MODE_CURRENT
|
||||
&& level.is_none()
|
||||
&& pl.label.is_none()
|
||||
// A drop cap sits at the indent: starting its lines at a float's edge would put
|
||||
// them over the letter.
|
||||
&& pl.drop_cap.is_none(),
|
||||
expand_break: !settings.do_not_expand_shift_return,
|
||||
zone: Some(settings.hyphenation_zone).filter(|z| z.is_finite() && *z >= 0.0).unwrap_or(HYPHENATION_ZONE).min(1584.0),
|
||||
hyph_limit: settings.consecutive_hyphen_limit as usize,
|
||||
@@ -236,9 +246,12 @@ impl<'e> Breaker<'e> {
|
||||
let mut guard = 0;
|
||||
loop {
|
||||
let lo = self.row_left(pl);
|
||||
match row_spans(self.exclusions, self.top, self.est_h, self.table_h, lo, self.base_right).map(|mut spans| (spans.pop_front(), spans)) {
|
||||
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)) {
|
||||
Ok((Some((a, b)), rest)) => {
|
||||
let narrowed = !rest.is_empty() || a > lo || b < self.base_right;
|
||||
// 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 };
|
||||
let narrowed = !rest.is_empty() || moved || b < self.base_right;
|
||||
self.row_rest = rest;
|
||||
self.row_first = self.lines.len();
|
||||
return (a, b.max(a + MIN_LINE_WIDTH), narrowed);
|
||||
@@ -1064,6 +1077,23 @@ impl Scan {
|
||||
/// paragraph beside a floating table in a 21.3pt gap but not in an 18.6pt one.
|
||||
const MIN_SPAN: f32 = 20.0;
|
||||
|
||||
/// 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
|
||||
/// right of `lo`; `lo` if there are none.
|
||||
fn tight_row_start(exclusions: &[Exclusion], (top, h, table_h): (f32, f32, f32), lo: f32) -> f32 {
|
||||
exclusions
|
||||
.iter()
|
||||
.filter(|e| !e.top_bottom && e.side != WrapText::Left && e.right <= lo && e.intersects_row(top, h, table_h, f32::NEG_INFINITY, lo))
|
||||
.filter_map(|e| match &e.contour {
|
||||
None => Some(e.right),
|
||||
Some(c) => c.occupied(top - e.top, top + h - e.top).into_iter().map(|(_, b)| b + e.left).reduce(f32::max),
|
||||
})
|
||||
.reduce(f32::max)
|
||||
// A float out in the left margin doesn't pull the text into the margin after it.
|
||||
.map_or(lo, |edge| edge.max(0.0).min(lo))
|
||||
}
|
||||
|
||||
/// How far below a line's top its baseline sits. Multiple spacing at or above single keeps the
|
||||
/// text at the top of the line and puts the extra leading below the baseline; below single it
|
||||
/// shrinks the whole box, ascent included (Word's output for docxide-pdf's fixtures: 1.15-spaced
|
||||
@@ -1078,8 +1108,17 @@ 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).
|
||||
fn row_spans(exclusions: &[Exclusion], top: f32, h: f32, table_h: f32, lo: f32, hi: f32) -> Result<VecDeque<(f32, f32)>, f32> {
|
||||
/// 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,
|
||||
) -> 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();
|
||||
if let Some(below) = here.iter().filter(|e| e.top_bottom).map(|e| e.bottom).reduce(f32::max) {
|
||||
return Err(below);
|
||||
|
||||
@@ -914,6 +914,7 @@ fn long_word_beside_a_float(n: usize) -> Document {
|
||||
/// A word with no break opportunity in it: measuring the word for every line it takes scanned
|
||||
/// the whole paragraph each time, so the layout was quadratic in the word's length.
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the time ratio")]
|
||||
fn a_long_unbreakable_word_lays_out_in_linear_time() {
|
||||
let (t1, tk, ratio) = layout_time_ratio(long_word_beside_a_float, 50_000, &LayoutOptions::default());
|
||||
eprintln!("t(n) {t1:.4} s, t(8n) {tk:.4} s, ratio {ratio:.1}");
|
||||
@@ -1134,6 +1135,7 @@ fn long_word_with_alternating_advances_beside_a_float(n: usize) -> Document {
|
||||
/// A word whose advances alternate in sign lays out in linear time: the measurement that asks
|
||||
/// whether it would fit the full line must not walk the word again for every line it takes.
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the time ratio")]
|
||||
fn a_word_with_alternating_advances_lays_out_in_linear_time() {
|
||||
let (t1, tk, ratio) = layout_time_ratio(long_word_with_alternating_advances_beside_a_float, 50_000, &LayoutOptions::default());
|
||||
eprintln!("t(n) {t1:.4} s, t(8n) {tk:.4} s, ratio {ratio:.1}");
|
||||
@@ -1995,6 +1997,108 @@ fn break_only_list_has_no_label() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #4828: a list item deleted whole (its text and its mark) under Track Changes shows its number
|
||||
/// as deleted text, in the deletion's colour and struck through, with markup shown; without
|
||||
/// markup the number is drawn no more than the text.
|
||||
#[test]
|
||||
fn a_deleted_list_items_number_is_drawn_as_deleted_text() {
|
||||
let mut d = Document::from_text("Intro\nChapter two\nBody");
|
||||
d.revisions.push(wordcraft_doc::Revision {
|
||||
kind: wordcraft_doc::RevisionKind::Delete,
|
||||
author: "Ana".into(),
|
||||
date: String::new(),
|
||||
move_name: None,
|
||||
});
|
||||
let id = std::sync::Arc::make_mut(&mut d.numbering).add_list(wordcraft_doc::ListKind::Numbered);
|
||||
d.format_paragraphs(&Pos::body(1, 0), &Pos::body(1, 3), &|p| p.numbering = Some(wordcraft_doc::props::NumRef { num: id, level: 0 })).unwrap();
|
||||
d.format_range(&Pos::body(1, 0), &Pos::body(1, 11), &|c| c.del = Some(0)).unwrap();
|
||||
d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().mark.del = Some(0);
|
||||
let l = lay(&d);
|
||||
let draws = |markup: bool| display::page_display(&d, &l.pages[0], &display::DisplayOptions { markup, ..Default::default() });
|
||||
let glyph_color = |items: &[display::Draw], want: &str| {
|
||||
items.iter().find_map(|i| match i {
|
||||
display::Draw::Glyphs { text, color, glyphs, .. } if text.contains(want) => Some((*color, glyphs.first().map_or(0.0, |g| g.1))),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
let marked = draws(true);
|
||||
let (number, nx) = glyph_color(&marked, "1.").expect("the number is drawn with markup");
|
||||
let (text, _) = glyph_color(&marked, "Chapter").expect("the deleted text is drawn with markup");
|
||||
assert_eq!(number, text, "the number takes the deletion's colour");
|
||||
let struck = marked
|
||||
.iter()
|
||||
.any(|i| matches!(i, display::Draw::Line { x0, x1, y0, y1, .. } if (y0 - y1).abs() < 0.01 && *x0 <= nx + 0.01 && *x1 > nx + 1.0));
|
||||
assert!(struck, "the number is struck through");
|
||||
// The number takes the other deletion marks as its text does.
|
||||
let with_mark = |mark: display::DeleteMark| {
|
||||
let mut o = display::DisplayOptions { markup: true, ..Default::default() };
|
||||
o.revisions.delete_mark = mark;
|
||||
display::page_display(&d, &l.pages[0], &o)
|
||||
};
|
||||
let caret = with_mark(display::DeleteMark::Caret);
|
||||
assert!(glyph_color(&caret, "1.").is_none(), "a caret replaces the number");
|
||||
assert!(caret.iter().any(|i| matches!(i, display::Draw::Line { x1, .. } if (*x1 - nx).abs() < 0.01)), "the caret is where the number was");
|
||||
let bold = with_mark(display::DeleteMark::Bold);
|
||||
assert!(bold.iter().any(|i| matches!(i, display::Draw::Glyphs { text, synth_bold: true, .. } if text.contains("1."))));
|
||||
let hashed = with_mark(display::DeleteMark::Hash);
|
||||
let ids = |items: &[display::Draw], want: &str| {
|
||||
items.iter().find_map(|i| match i {
|
||||
display::Draw::Glyphs { text, glyphs, .. } if text.contains(want) => Some(glyphs.iter().map(|g| g.0).collect::<Vec<_>>()),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
let (numbers, hashes) = (ids(&marked, "1.").unwrap(), ids(&hashed, "1.").unwrap());
|
||||
assert!(hashes.len() == numbers.len() && hashes.windows(2).all(|w| w[0] == w[1]) && hashes != numbers, "each character shows as #");
|
||||
let plain_label = |items: &[display::Draw]| {
|
||||
items.iter().any(|i| matches!(i, display::Draw::Line { x0, x1, y0, y1, .. } if (y0 - y1).abs() < 0.01 && *x0 <= nx + 0.01 && *x1 > nx + 1.0))
|
||||
};
|
||||
assert!(!plain_label(&with_mark(display::DeleteMark::ColorOnly)), "colour only: no line through or under the number");
|
||||
// Moved-away text marked (none) is plain, its number too.
|
||||
let mut moved = d.clone();
|
||||
if let Some(r) = moved.revisions.get_mut(0) {
|
||||
r.move_name = Some("move1".into());
|
||||
}
|
||||
let mut o = display::DisplayOptions { markup: true, ..Default::default() };
|
||||
o.revisions.move_from_mark = display::DeleteMark::None;
|
||||
let shown = display::page_display(&moved, &l.pages[0], &o);
|
||||
let (moved_number, _) = glyph_color(&shown, "1.").expect("the moved number is drawn");
|
||||
let (moved_text, _) = glyph_color(&shown, "Chapter").expect("the moved text is drawn");
|
||||
assert_eq!(moved_number, moved_text, "plain, like its text");
|
||||
assert!(!plain_label(&shown));
|
||||
// With markup but deletions hidden in Track Changes Options, the number isn't drawn either.
|
||||
assert!(glyph_color(&with_mark(display::DeleteMark::Hidden), "1.").is_none(), "deletions marked hidden");
|
||||
let mut o = display::DisplayOptions { markup: true, ..Default::default() };
|
||||
o.revisions.insertions_deletions = false;
|
||||
assert!(glyph_color(&display::page_display(&d, &l.pages[0], &o), "1.").is_none(), "insertions and deletions not shown");
|
||||
// Without markup neither the text nor its number is drawn.
|
||||
let plain = draws(false);
|
||||
assert!(glyph_color(&plain, "Chapter").is_none() && glyph_color(&plain, "1.").is_none());
|
||||
// A number whose paragraph mark isn't deleted is drawn as before.
|
||||
let mut kept = Document::from_text("Intro\nChapter two\nBody");
|
||||
let id = std::sync::Arc::make_mut(&mut kept.numbering).add_list(wordcraft_doc::ListKind::Numbered);
|
||||
kept.format_paragraphs(&Pos::body(1, 0), &Pos::body(1, 3), &|p| p.numbering = Some(wordcraft_doc::props::NumRef { num: id, level: 0 })).unwrap();
|
||||
let kl = lay(&kept);
|
||||
let plain = display::page_display(&kept, &kl.pages[0], &display::DisplayOptions { markup: false, ..Default::default() });
|
||||
assert!(glyph_color(&plain, "1.").is_some());
|
||||
// #4828 review: only the paragraph mark deleted (Delete at the end of the item): the text
|
||||
// stays, and so does its number, plain, with markup and without (and in print, where markup
|
||||
// is off).
|
||||
let mut joined = kept.clone();
|
||||
joined.revisions = d.revisions.clone();
|
||||
joined.para_mut(StoryRef::Body, &Path::top(1)).unwrap().mark.del = Some(0);
|
||||
let jl = lay(&joined);
|
||||
for markup in [false, true] {
|
||||
let shown = display::page_display(&joined, &jl.pages[0], &display::DisplayOptions { markup, ..Default::default() });
|
||||
let (number, jx) = glyph_color(&shown, "1.").unwrap_or_else(|| panic!("markup {markup}: the number stays"));
|
||||
let (text, _) = glyph_color(&shown, "Chapter").unwrap_or_else(|| panic!("markup {markup}: the text stays"));
|
||||
assert_eq!(number, text, "markup {markup}: in the text's colour");
|
||||
let struck = shown
|
||||
.iter()
|
||||
.any(|i| matches!(i, display::Draw::Line { x0, x1, y0, y1, .. } if (y0 - y1).abs() < 0.01 && *x0 <= jx + 0.01 && *x1 > jx + 1.0));
|
||||
assert!(!struck, "markup {markup}: not struck through");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_list_paragraph_with_a_hidden_mark_counts_but_shows_nothing() {
|
||||
// Word (#3982): a list item whose paragraph mark is hidden, and whose text is empty or hidden
|
||||
@@ -3705,6 +3809,113 @@ fn text_wraps_around_square_float() {
|
||||
assert!(l.pages[0].items.iter().any(|i| matches!(i, Placed::Shape { .. })));
|
||||
}
|
||||
|
||||
/// The left edges of a paragraph's lines beside a 144 × 100 pt square-wrapped rectangle at the
|
||||
/// column's top left (9 pt from text), and of its first line below the rectangle, in
|
||||
/// compatibility `mode` with Word 2003's indent rules on or off. The paragraph is indented
|
||||
/// 216 pt; `float` adjusts the object, `para` the paragraph, and `numbered` makes it a list item.
|
||||
fn word_2003_indent_lefts(
|
||||
mode: u32,
|
||||
rules: bool,
|
||||
float: &dyn Fn(&mut wordcraft_doc::para::Float),
|
||||
numbered: bool,
|
||||
para: &dyn Fn(&mut ParaProps),
|
||||
) -> (Vec<f32>, Option<f32>) {
|
||||
let mut d = Document::from_text(&"Words beside the picture here. ".repeat(20));
|
||||
d.settings.compat_mode = mode;
|
||||
d.settings.do_not_suppress_indentation = rules;
|
||||
let num = numbered.then(|| Arc::make_mut(&mut d.numbering).add_list(wordcraft_doc::ListKind::Numbered));
|
||||
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| {
|
||||
p.indent_left = Some(216.0);
|
||||
p.indent_first = Some(0.0);
|
||||
p.numbering = num.map(|num| wordcraft_doc::props::NumRef { num, level: 0 });
|
||||
para(p);
|
||||
})
|
||||
.unwrap();
|
||||
let mut f = wordcraft_doc::para::Float {
|
||||
wrap: wordcraft_doc::para::Wrap::Square,
|
||||
h_rel: wordcraft_doc::para::Anchor::Column,
|
||||
v_rel: wordcraft_doc::para::Anchor::Paragraph,
|
||||
x: 0.0,
|
||||
y: 0.0,
|
||||
dist: 9.0,
|
||||
..Default::default()
|
||||
};
|
||||
float(&mut f);
|
||||
let shape = InlineObject::Shape {
|
||||
kind: wordcraft_doc::para::ShapeKind::Rectangle,
|
||||
w: 144.0,
|
||||
h: 100.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 1.0,
|
||||
float: f,
|
||||
story: None,
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: Default::default(),
|
||||
};
|
||||
// After the first word, so a drop cap takes the paragraph's first letter.
|
||||
d.insert_object(&Pos::body(0, 6), shape, &Default::default()).unwrap();
|
||||
let l = lay(&d);
|
||||
let Placed::Lines { para, .. } = l.pages[0].items.iter().find(|i| matches!(i, Placed::Lines { story: StoryRef::Body, .. })).unwrap() else {
|
||||
panic!()
|
||||
};
|
||||
let beside = para.lines.iter().filter(|ln| ln.top < 100.0).map(|ln| ln.left).collect();
|
||||
let below = para.lines.iter().find(|ln| ln.top > 120.0).map(|ln| ln.left);
|
||||
(beside, below)
|
||||
}
|
||||
|
||||
/// Word 2003's indent rules (`w:doNotSuppressIndentation`, a `.doc`'s `Copts.fWW11IndentRules`): an
|
||||
/// unnumbered paragraph indented past a floating object on its left starts its lines right after
|
||||
/// the object, its indent ignored (ECMA-376 Part 4 §14.8.3.12). In a Word 2003-mode `.doc` saved
|
||||
/// by Word, empty paragraphs indented 216 pt sit right after a text box ending 165 pt into the
|
||||
/// column, in the 71 pt gap before a second box where the indent would leave under 20 pt. Below
|
||||
/// the object, and in Word 2013's layout, the indent applies.
|
||||
#[test]
|
||||
fn word_2003_indent_rules_start_lines_right_after_a_float_before_the_indent() {
|
||||
let lefts = |mode: u32, rules: bool| word_2003_indent_lefts(mode, rules, &|_| {}, false, &|_| {});
|
||||
for mode in [11, 12, 14] {
|
||||
let (beside, below) = lefts(mode, true);
|
||||
assert!(
|
||||
!beside.is_empty() && beside.iter().all(|x| (x - 153.0).abs() < 0.01),
|
||||
"mode {mode}: lines start after the object and its 9 pt distance: {beside:?}"
|
||||
);
|
||||
assert_eq!(below, Some(216.0), "mode {mode}: below the object the indent applies");
|
||||
}
|
||||
assert_eq!(lefts(11, false).0[0], 216.0, "without the option the indent applies beside the object");
|
||||
assert_eq!(lefts(15, true).0[0], 216.0, "Word 2013's layout keeps the indent");
|
||||
}
|
||||
|
||||
/// Under Word 2003's indent rules a line starts after a Tight or Through-wrapped object's outline
|
||||
/// where the line meets it, not after the outline's widest point: here a right triangle, its
|
||||
/// point at the top left, 144 pt wide (and 9 pt from text) only at its foot.
|
||||
#[test]
|
||||
fn word_2003_indent_rules_follow_a_tight_objects_outline() {
|
||||
use wordcraft_doc::para::Wrap;
|
||||
use wordcraft_doc::wrap::WrapPolygon;
|
||||
let poly = WrapPolygon::new(true, [(0, 0), (0, 21_600), (21_600, 21_600)]).map(Arc::new);
|
||||
for wrap in [Wrap::Tight, Wrap::Through] {
|
||||
let (beside, _) = word_2003_indent_lefts(11, true, &|f| (f.wrap, f.wrap_polygon) = (wrap, poly.clone()), false, &|_| {});
|
||||
assert!(beside.len() > 2 && beside[0] < 60.0, "{wrap:?}: the first line starts near the point: {beside:?}");
|
||||
assert!(beside.windows(2).all(|w| w[0] < w[1]) && beside.iter().all(|&x| x <= 153.0 + 0.01), "{wrap:?}: each line further out: {beside:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Word 2003's indent rules leave the indent alone for a numbered paragraph (its number sits at
|
||||
/// the indent) and for one with a drop cap (the letter does), and never start a line left of the
|
||||
/// paragraph's own edge after an object out in the margin.
|
||||
#[test]
|
||||
fn word_2003_indent_rules_keep_the_indent_where_they_do_not_apply() {
|
||||
let (numbered, _) = word_2003_indent_lefts(11, true, &|_| {}, true, &|_| {});
|
||||
assert!(numbered.iter().all(|&x| x >= 216.0 - 0.01), "a numbered paragraph keeps its indent: {numbered:?}");
|
||||
let (dropped, _) = word_2003_indent_lefts(11, true, &|_| {}, false, &|p| p.drop_cap = Some(3));
|
||||
assert!(dropped.iter().all(|&x| x >= 216.0 - 0.01), "lines beside a drop cap stay right of it: {dropped:?}");
|
||||
// An object in the left margin, its right side and distance from text 44 pt short of the column.
|
||||
let (margin, _) = word_2003_indent_lefts(11, true, &|f| f.x = -197.0, false, &|_| {});
|
||||
assert!(margin.iter().all(|&x| x >= -0.01), "no line starts in the margin: {margin:?}");
|
||||
assert!((margin[0] - 0.0).abs() < 0.01, "the line starts at the paragraph's edge: {margin:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lines_arrowheads_sit_at_its_ends() {
|
||||
// A line runs from its frame's top left to its bottom right (DrawingML's `line`, as it is
|
||||
@@ -7839,6 +8050,7 @@ fn a_no_break_space_before_a_slash_still_holds() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the time ratio")]
|
||||
fn unequal_formats_lay_out_in_linear_time() {
|
||||
crate::test_fonts();
|
||||
// Runs whose formats never compare equal (NaN spacing from a hostile file) each get a style;
|
||||
@@ -15444,3 +15656,88 @@ fn turned_cell_float_keeps_its_along_text_offset() {
|
||||
assert!((confined.y - reference.y).abs() < 0.01, "{direction:?}: {confined:?} vs {reference:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A header paragraph beside a Square float on its last lines only: those lines are shorter than
|
||||
/// the first. A click on the first line past the short last line's end is still on the header's
|
||||
/// text, so a Behind Text picture under it is not grabbed there (#5601 review).
|
||||
#[test]
|
||||
fn header_text_covers_the_whole_width_of_a_wrapped_first_line() {
|
||||
use wordcraft_doc::para::{Anchor, Float, Wrap};
|
||||
let text = "Header words that wrap across the whole line and carry on over several lines of the header \
|
||||
paragraph so there are three lines here and the last one is cut short by the float beside it";
|
||||
let mut d = Document::new();
|
||||
let id =
|
||||
d.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(text, Default::default()))]);
|
||||
d.last_section.headers.default = Some(id);
|
||||
let at = |off| Pos::new(wordcraft_doc::StoryRef::Part(id), wordcraft_doc::Path(vec![0]), off);
|
||||
// The Square float narrows the lines below the first two, on the right.
|
||||
let square = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 300.0, y: 30.0, ..Default::default() };
|
||||
d.insert_object(&at(0), rect_shape(160.0, 80.0, square), &Default::default()).unwrap();
|
||||
// The Behind Text picture lies under the first line, past where the last line ends.
|
||||
let behind = Float { wrap: Wrap::BehindText, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 340.0, y: 0.0, ..Default::default() };
|
||||
d.insert_object(&at(0), rect_shape(120.0, 20.0, behind), &Default::default()).unwrap();
|
||||
let l = lay(&d);
|
||||
let page = &l.pages[0];
|
||||
let lines: Vec<_> = page
|
||||
.header
|
||||
.iter()
|
||||
.filter_map(|it| match it {
|
||||
Placed::Lines { para, l0, l1, x, y, .. } => {
|
||||
Some((*x, *y, (*l0..*l1).filter_map(|i| para.lines.get(i)).map(|l| (l.top, l.height, l.right)).collect::<Vec<_>>()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let (x, y, ls) = lines.first().expect("header lines").clone();
|
||||
let (first, last) = (ls.first().expect("first"), ls.last().expect("last"));
|
||||
assert!(last.2 + 40.0 < first.2 - 20.0, "the last line is shorter than the first: {ls:?}");
|
||||
let (px, py) = (x + first.2 - 15.0, y + first.0 + first.1 / 2.0);
|
||||
assert!(l.object_at_in(0, px, py, 0.0, wordcraft_doc::StoryRef::Part(id)).is_none(), "on the first line's text, not the picture: {lines:?}");
|
||||
}
|
||||
|
||||
/// `Line::left`/`right` are the edges available to a line, not where its ink sits: a centred or
|
||||
/// right-aligned header line covers the Behind Text picture across its whole band, so a click in
|
||||
/// the empty space beside its text is still on the header text. Beyond the band (an indent, or
|
||||
/// beside a float) and 40pt of slack the picture is hit (#5601 review).
|
||||
#[test]
|
||||
fn header_text_covers_the_whole_band_of_centred_and_right_lines() {
|
||||
use wordcraft_doc::Align;
|
||||
use wordcraft_doc::para::{Anchor, Float, Wrap};
|
||||
for align in [Align::Center, Align::Right] {
|
||||
let mut d = Document::new();
|
||||
let mut p = wordcraft_doc::Paragraph::with_text("Header", Default::default());
|
||||
p.props.align = Some(align);
|
||||
p.props.indent_left = Some(150.0);
|
||||
let id = d.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::para_block(p)]);
|
||||
d.last_section.headers.default = Some(id);
|
||||
let story = wordcraft_doc::StoryRef::Part(id);
|
||||
let at = Pos::new(story, wordcraft_doc::Path(vec![0]), 0);
|
||||
// A Behind Text picture across the whole text width, level with the header line.
|
||||
let behind = Float { wrap: Wrap::BehindText, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 0.0, y: 0.0, ..Default::default() };
|
||||
d.insert_object(&at, rect_shape(460.0, 20.0, behind), &Default::default()).unwrap();
|
||||
let l = lay(&d);
|
||||
let (x, y, left, right, height, ink0) = l.pages[0]
|
||||
.header
|
||||
.iter()
|
||||
.find_map(|it| match it {
|
||||
Placed::Lines { para, l0, x, y, .. } => {
|
||||
para.lines.get(*l0).and_then(|ln| Some((*x, *y, ln.left, ln.right, ln.height, *ln.xs.first()?)))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.expect("header line");
|
||||
// `left`/`right` are the band edges available to the line, not the ink extent.
|
||||
assert!((left - 150.0).abs() < 0.5, "{align:?}: the band's left edge is the indent: {left}");
|
||||
assert!(ink0 > left + 100.0, "{align:?}: the ink starts well inside the band: ink {ink0}, band left {left}");
|
||||
let ym = y + height / 2.0;
|
||||
let hit = |px: f32| l.object_at_in(0, px, ym, 0.0, story).is_some();
|
||||
// Inside the band, wherever the centred or right-aligned ink sits: header text.
|
||||
assert!(!hit(x + left + 5.0), "{align:?}: the band's left end is text");
|
||||
assert!(!hit(x + (left + right) / 2.0), "{align:?}: the band's middle is text");
|
||||
// Between the indent and the ink is still the text band, not the picture.
|
||||
assert!(!hit(x + left + 160.0), "{align:?}: between the indent and the ink is text");
|
||||
// Within 40pt of the band's left end is still text; further left the picture is hit.
|
||||
assert!(!hit(x + left - 30.0), "{align:?}: within 40pt left of the band is text");
|
||||
assert!(hit(x + left - 60.0), "{align:?}: beyond 40pt left of the band the picture is hit");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -223,6 +223,22 @@ fn selecting_a_long_endnote_takes_linear_time() {
|
||||
assert_linear_steps("endnote selection", 20, laid, |(d, l, (a, b))| drop(std::hint::black_box(l.selection_rects(d, a, b, 0))));
|
||||
}
|
||||
|
||||
/// One paragraph of `n` lines (a line break after each word), so it runs over many pages.
|
||||
fn many_lines(n: usize) -> Document {
|
||||
let mut d = Document::from_text("");
|
||||
d.body = vec![wordcraft_doc::para_block(Paragraph::with_text(&"x\n".repeat(n), CharProps::default()))];
|
||||
d
|
||||
}
|
||||
|
||||
/// The piece of a long paragraph on each page looked through every line of the paragraph for the
|
||||
/// pictures and shapes to draw with it (#6757).
|
||||
#[test]
|
||||
fn a_paragraph_over_many_pages_lays_out_in_linear_time() {
|
||||
let pages = lay(&many_lines(SCALE * 400), &LayoutOptions::default()).pages.len();
|
||||
assert!(pages > 40, "the paragraph runs over many pages: {pages}");
|
||||
assert_layout_linear("a paragraph over many pages", 400, many_lines, &LayoutOptions::default());
|
||||
}
|
||||
|
||||
/// A table of `n` rows of 60 cells, each row exactly half a point high, so every cell clips its
|
||||
/// (empty) paragraph and the whole table fits on the first page.
|
||||
fn clipped_table(n: usize) -> Document {
|
||||
|
||||
@@ -242,3 +242,62 @@ fn an_equation_run_names_each_glyphs_characters() {
|
||||
assert!(found.iter().any(|(t, g, _)| (t.contains('\u{1D44E}') || t == "ab") && *g == 2), "{found:?}");
|
||||
assert!(found.iter().all(|(_, g, r)| g == r), "{found:?}");
|
||||
}
|
||||
|
||||
/// A metafile text run with the given font height and advances, left-aligned at the baseline.
|
||||
fn meta_text(height: f32, dx: Vec<f32>) -> craft_metafile::Text {
|
||||
craft_metafile::Text {
|
||||
transform: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
|
||||
text: "ab".into(),
|
||||
dx,
|
||||
font: craft_metafile::Font { family: "Arial".into(), height, ..Default::default() },
|
||||
color: [0, 0, 0, 255],
|
||||
background: Some([255, 255, 255, 255]),
|
||||
h_align: craft_metafile::HAlign::Left,
|
||||
v_align: craft_metafile::VAlign::Baseline,
|
||||
clip: None,
|
||||
region: None,
|
||||
clips: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A metafile font height of 0 is the file's default size: a 16-unit cell. A negative height is
|
||||
/// the em size, and a positive one the cell (ascent plus descent, 1200 units of a 1000-unit em
|
||||
/// here).
|
||||
#[test]
|
||||
fn metafile_text_heights() {
|
||||
let glyphs = [(0, 500.0, 0.0, 0.0), (1, 500.0, 0.0, 0.0)];
|
||||
let em = |h| crate::layout_metafile_text(&meta_text(h, Vec::new()), 1000.0, 900.0, 300.0, &glyphs).map(|l| l.em);
|
||||
let near = |a: Option<f64>, b: f64| a.is_some_and(|a| (a - b).abs() < 1e-9);
|
||||
assert!(near(em(0.0), 16.0 * 1000.0 / 1200.0), "{:?}", em(0.0));
|
||||
assert!(near(em(-10.0), 10.0), "{:?}", em(-10.0));
|
||||
assert!(near(em(24.0), 20.0), "a positive height is the cell: {:?}", em(24.0));
|
||||
}
|
||||
|
||||
/// A cosmetic pen's dashes become whole output pixels (the shortest one pixel), a period under a
|
||||
/// pixel draws solid, and so does a pattern that would split the path into too many pieces.
|
||||
#[test]
|
||||
fn metafile_dashes_follow_the_output_pixel() {
|
||||
let cosmetic = crate::metafile_dashes(&[0.75, 0.25], true, 0.5, 100.0).unwrap_or_default();
|
||||
assert!(cosmetic.len() == 2 && (cosmetic[0] - 1.5).abs() < 1e-6 && (cosmetic[1] - 0.5).abs() < 1e-6, "{cosmetic:?}");
|
||||
assert_eq!(crate::metafile_dashes(&[3.0, 1.0], false, 0.5, 100.0), Some(vec![3.0, 1.0]));
|
||||
assert_eq!(crate::metafile_dashes(&[0.2, 0.2], false, 0.5, 100.0), None, "a period under a pixel");
|
||||
assert_eq!(crate::metafile_dashes(&[1.0, 1.0], false, 0.5, 1e6), None, "a million pieces");
|
||||
assert_eq!(crate::metafile_dashes(&[1.0, -1.0], false, 0.5, 100.0), None, "a negative length");
|
||||
assert_eq!(crate::metafile_dashes(&[0.0, 0.0], true, 0.5, 100.0), None, "no length at all");
|
||||
}
|
||||
|
||||
/// A negative crop side is no crop; the others stay as they are.
|
||||
#[test]
|
||||
fn negative_crop_sides_are_no_crop() {
|
||||
assert_eq!(crate::crop_sides([-0.5, 0.25, f32::NAN, 1.5]), [0.0, 0.25, 0.0, 1.5]);
|
||||
assert_eq!(crate::crop_window([-0.5, 0.0, 0.0, 0.0]), [0.0, 0.0, 1.0, 1.0]);
|
||||
}
|
||||
|
||||
/// The opaque background of a run whose advances move backward covers every pen position, not
|
||||
/// only the run's total advance.
|
||||
#[test]
|
||||
fn metafile_text_cell_spans_backward_advances() {
|
||||
let glyphs = [(0, 500.0, 0.0, 0.0), (1, 500.0, 0.0, 0.0)];
|
||||
let lay = crate::layout_metafile_text(&meta_text(-10.0, vec![50.0, -40.0]), 1000.0, 800.0, 200.0, &glyphs).expect("a layout");
|
||||
assert_eq!(lay.cell, [0.0, -8.0, 50.0, 2.0]);
|
||||
}
|
||||
|
||||
@@ -320,7 +320,7 @@ impl Exporter<'_> {
|
||||
s.set_fill(None);
|
||||
return;
|
||||
};
|
||||
let [cl, ct, vis_w, vis_h] = craft_metafile::crop_window(*crop).map(|v| v as f32);
|
||||
let [cl, ct, vis_w, vis_h] = wordcraft_layout::crop_window(*crop).map(|v| v as f32);
|
||||
let (fw, fh) = (rect.w / vis_w, rect.h / vis_h);
|
||||
let Some(size) = Size::from_wh(fw.max(0.01), fh.max(0.01)) else { return };
|
||||
let fade = alpha < 0.999;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
Exporter, FaceRef, Fill, FillRule, KrillaGlyph, Point, Rgb, Stroke, Surface, Transform, baseline, cluster_ends, fill, glyph_id, glyph_outlines,
|
||||
left_to_right, norm, ok, paint_of, rgb, split_clusters, visual_order,
|
||||
Exporter, FaceRef, Fill, FillRule, KrillaGlyph, Point, Rect, Rgb, Stroke, Surface, Transform, baseline, cluster_ends, fill, glyph_id,
|
||||
glyph_outlines, left_to_right, norm, ok, paint_of, rect_path, rgb, split_clusters, visual_order,
|
||||
};
|
||||
|
||||
/// How a run of glyphs is painted: its colour, opacity and synthetic bold and italic.
|
||||
@@ -181,7 +181,7 @@ impl Exporter<'_> {
|
||||
}
|
||||
|
||||
/// Draws a metafile text run as PDF text (outlines when the font cannot be embedded). `tf` maps
|
||||
/// the run's own space (see [`PlacedItem::Text`]) to the page.
|
||||
/// its text space (`craft_metafile::Text::transform`) to the page.
|
||||
pub(crate) fn vector_text(&mut self, s: &mut Surface, t: &craft_metafile::Text, tf: kurbo::Affine) {
|
||||
let (face, shaped) = wordcraft_layout::metafile_text_run(t);
|
||||
let glyphs: Vec<_> = shaped.iter().map(|g| (g.cluster, f64::from(g.x_advance), f64::from(g.x_offset), f64::from(g.y_offset))).collect();
|
||||
@@ -198,6 +198,15 @@ impl Exporter<'_> {
|
||||
let (paint, opacity) = paint_of(t.color);
|
||||
s.push_transform(&Transform::from_row(c[0], c[1], c[2], c[3], c[4], c[5]));
|
||||
s.set_stroke(None);
|
||||
// An opaque background mode fills the character cells first.
|
||||
if let Some(bg) = t.background {
|
||||
let [x0, y0, x1, y1] = lay.cell.map(|v| v as f32);
|
||||
if let Some(cell) = rect_path(&Rect { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }) {
|
||||
let (paint, opacity) = paint_of(bg);
|
||||
s.set_fill(Some(Fill { paint: paint.into(), opacity, rule: FillRule::NonZero }));
|
||||
s.draw_path(&cell);
|
||||
}
|
||||
}
|
||||
s.set_fill(Some(Fill { paint: paint.into(), opacity, rule: FillRule::NonZero }));
|
||||
match font {
|
||||
Some(font) => {
|
||||
|
||||
+145
-26
@@ -1,28 +1,51 @@
|
||||
use super::exporter::Exporter;
|
||||
use super::paint::{append_path, norm};
|
||||
use super::{
|
||||
Arc, Fill, FillRule, Image, LineCap, LineJoin, NormalizedF32, Path, PathBuilder, Picture, PlacedItem, Rect, Size, Stroke, Surface, Transform, rgb,
|
||||
Arc, Fill, FillRule, Image, LineCap, LineJoin, NormalizedF32, Path, PathBuilder, Picture, PlacedItem, Rect, Size, Stroke, StrokeDash, Surface,
|
||||
Transform, krilla, rgb,
|
||||
};
|
||||
use craft_metafile::Item;
|
||||
use kurbo::Shape as _;
|
||||
use wordcraft_doc::picfx::PicFx;
|
||||
|
||||
/// Largest picture side we embed (pixels).
|
||||
const MAX_IMAGE_SIDE: u32 = 30_000;
|
||||
|
||||
/// A metafile picture, parsed once. The geometry comes placed by the metafile crate; the bitmaps are
|
||||
/// embedded images, one per picture item (None for paths and undecodable bitmaps).
|
||||
/// A metafile picture, parsed once. The geometry comes placed by the metafile crate; the bitmaps and
|
||||
/// pattern tiles are embedded images, one per picture item (None for paths, text and undecodable
|
||||
/// bitmaps). Fills that share a tile share its image. `averages` holds each pattern fill's tile
|
||||
/// average color (transparent for other items), computed once a tile.
|
||||
pub(crate) struct Vector {
|
||||
pic: Picture,
|
||||
images: Vec<Option<Image>>,
|
||||
averages: Vec<[u8; 4]>,
|
||||
}
|
||||
|
||||
/// Parses a metafile and embeds its bitmaps. None when the picture has no usable size.
|
||||
/// Parses a metafile and embeds its bitmaps and pattern tiles. None when the picture has no usable
|
||||
/// size.
|
||||
pub(crate) fn build_vector(bytes: &[u8]) -> Option<Vector> {
|
||||
let mut pic = craft_metafile::parse(bytes).ok()?;
|
||||
if !pic.has_size() {
|
||||
return None;
|
||||
}
|
||||
let images = pic.items.iter_mut().map(|it| it.take_pixels().map(|(w, h, px)| Image::from_rgba8(px, w, h))).collect();
|
||||
Some(Vector { pic, images })
|
||||
let mut tiles: std::collections::HashMap<usize, (Option<Image>, [u8; 4])> = std::collections::HashMap::new();
|
||||
let (images, averages) = pic
|
||||
.items
|
||||
.iter_mut()
|
||||
.map(|it| match it {
|
||||
Item::Pattern { tile, .. } => tiles
|
||||
.entry(Arc::as_ptr(tile) as usize)
|
||||
.or_insert_with(|| {
|
||||
let n = (tile.width as usize).saturating_mul(tile.height as usize).saturating_mul(4);
|
||||
let img = (tile.width > 0 && tile.height > 0 && tile.rgba.len() == n)
|
||||
.then(|| Image::from_rgba8(tile.rgba.clone(), tile.width, tile.height));
|
||||
(img, wordcraft_layout::metafile_average_color(&tile.rgba))
|
||||
})
|
||||
.clone(),
|
||||
_ => (it.take_pixels().map(|(w, h, px)| Image::from_rgba8(px, w, h)), [0; 4]),
|
||||
})
|
||||
.unzip();
|
||||
Some(Vector { pic, images, averages })
|
||||
}
|
||||
|
||||
/// A straight RGBA colour as a krilla colour and opacity.
|
||||
@@ -36,9 +59,10 @@ pub(crate) fn paint_of(c: [u8; 4]) -> (rgb::Color, NormalizedF32) {
|
||||
const HAIRLINE: f64 = 0.25;
|
||||
|
||||
/// Draws a metafile picture into the clip (the picture frame): paths are filled and stroked in page
|
||||
/// space (strokes keep their width under non-uniform scaling), bitmaps stretched, all faded by `alpha`.
|
||||
/// Every path sets its fill and stroke, so none carries over; strokes have round caps and joins. Text
|
||||
/// runs are drawn as text.
|
||||
/// space (strokes keep their width under non-uniform scaling), bitmaps stretched (or turned by their
|
||||
/// transform), pattern fills tiled, each item inside its clip region and clip paths, all faded by
|
||||
/// `alpha`. Every path sets its fill and stroke, so none carries over; strokes take the pen's caps,
|
||||
/// joins and dashes. Text runs are drawn as text.
|
||||
pub(crate) fn vector_picture(ex: &mut Exporter, s: &mut Surface, v: &Vector, r: &Rect, crop: &[f32; 4], clip: &Path, alpha: f32) {
|
||||
let target = kurbo::Rect::new(f64::from(r.x), f64::from(r.y), f64::from(r.x + r.w), f64::from(r.y + r.h));
|
||||
let fade = alpha < 0.999;
|
||||
@@ -46,9 +70,9 @@ pub(crate) fn vector_picture(ex: &mut Exporter, s: &mut Surface, v: &Vector, r:
|
||||
s.push_opacity(norm(alpha));
|
||||
}
|
||||
s.push_clip_path(clip, &FillRule::NonZero);
|
||||
for it in v.pic.place(target, *crop) {
|
||||
for it in v.pic.place(target, wordcraft_layout::crop_sides(*crop)) {
|
||||
match it {
|
||||
PlacedItem::Path { path, fill, stroke, even_odd, .. } => {
|
||||
PlacedItem::Path { path, fill, stroke, line, even_odd, region, clips } => {
|
||||
let Some(p) = path_from(&path) else { continue };
|
||||
let fill = fill.map(|c| {
|
||||
let (paint, opacity) = paint_of(c);
|
||||
@@ -57,31 +81,63 @@ pub(crate) fn vector_picture(ex: &mut Exporter, s: &mut Surface, v: &Vector, r:
|
||||
});
|
||||
let stroke = stroke.map(|(c, w)| {
|
||||
let (paint, opacity) = paint_of(c);
|
||||
Stroke {
|
||||
paint: paint.into(),
|
||||
width: w.max(HAIRLINE) as f32,
|
||||
opacity,
|
||||
line_cap: LineCap::Round,
|
||||
line_join: LineJoin::Round,
|
||||
..Default::default()
|
||||
}
|
||||
pen(paint.into(), opacity, w, &line, &path)
|
||||
});
|
||||
let Some(n) = push_clips(s, region.as_deref(), &clips) else { continue };
|
||||
s.set_fill(fill);
|
||||
s.set_stroke(stroke);
|
||||
s.draw_path(&p);
|
||||
pop_clips(s, n);
|
||||
}
|
||||
PlacedItem::Bitmap { index, rect, .. } => {
|
||||
PlacedItem::Bitmap { index, rect, transform, region, clips } => {
|
||||
let Some(Some(img)) = v.images.get(index) else { continue };
|
||||
let Some(size) = Size::from_wh(rect.width() as f32, rect.height() as f32) else { continue };
|
||||
s.push_transform(&Transform::from_translate(rect.x0 as f32, rect.y0 as f32));
|
||||
let c = transform.as_coeffs();
|
||||
// Upright and not mirrored: the bitmap fills `rect`.
|
||||
let upright = c[1] == 0.0 && c[2] == 0.0 && c[0] > 0.0 && c[3] > 0.0;
|
||||
let (tf, size) = if upright {
|
||||
(Transform::from_translate(rect.x0 as f32, rect.y0 as f32), Size::from_wh(rect.width() as f32, rect.height() as f32))
|
||||
} else {
|
||||
// A turned, skewed or mirrored bitmap: `transform` maps the unit square onto its place.
|
||||
let c = c.map(|v| v as f32);
|
||||
(Transform::from_row(c[0], c[1], c[2], c[3], c[4], c[5]), Size::from_wh(1.0, 1.0))
|
||||
};
|
||||
let Some(size) = size else { continue };
|
||||
let Some(n) = push_clips(s, region.as_deref(), &clips) else { continue };
|
||||
s.push_transform(&tf);
|
||||
s.draw_image(img.clone(), size);
|
||||
s.pop();
|
||||
pop_clips(s, n);
|
||||
}
|
||||
PlacedItem::Pattern { .. } => {}
|
||||
PlacedItem::Text { index, transform, .. } => {
|
||||
if let Some(craft_metafile::Item::Text(t)) = v.pic.items.get(index) {
|
||||
ex.vector_text(s, t, transform);
|
||||
PlacedItem::Pattern { index, path, even_odd, tile, region, clips } => {
|
||||
let Some(p) = path_from(&path) else { continue };
|
||||
let Some(craft_metafile::Item::Pattern { tile: t, .. }) = v.pic.items.get(index) else { continue };
|
||||
let rule = if even_odd { FillRule::EvenOdd } else { FillRule::NonZero };
|
||||
let paint = match v.images.get(index) {
|
||||
Some(Some(img)) => tile_pattern(s, img, t.width, t.height, tile).map(|p| (p.into(), norm(1.0))),
|
||||
_ => None,
|
||||
};
|
||||
let (paint, opacity) = paint.unwrap_or_else(|| {
|
||||
let (c, o) = paint_of(v.averages.get(index).copied().unwrap_or([0; 4]));
|
||||
(c.into(), o)
|
||||
});
|
||||
let Some(n) = push_clips(s, region.as_deref(), &clips) else { continue };
|
||||
s.set_fill(Some(Fill { paint, opacity, rule }));
|
||||
s.set_stroke(None);
|
||||
s.draw_path(&p);
|
||||
pop_clips(s, n);
|
||||
}
|
||||
PlacedItem::Text { index, transform, clip, region, clips } => {
|
||||
let Some(craft_metafile::Item::Text(t)) = v.pic.items.get(index) else { continue };
|
||||
let Some(n) = push_clips(s, region.as_deref(), &clips) else { continue };
|
||||
let text_clip = clip.and_then(|c| path_from(&c.to_path(0.1)));
|
||||
if let Some(c) = &text_clip {
|
||||
s.push_clip_path(c, &FillRule::NonZero);
|
||||
}
|
||||
ex.vector_text(s, t, transform);
|
||||
if text_clip.is_some() {
|
||||
s.pop();
|
||||
}
|
||||
pop_clips(s, n);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -93,6 +149,69 @@ pub(crate) fn vector_picture(ex: &mut Exporter, s: &mut Surface, v: &Vector, r:
|
||||
}
|
||||
}
|
||||
|
||||
/// Pushes a metafile item's clip region and clip paths; pop them with [`pop_clips`] and the count
|
||||
/// returned. None (nothing pushed) when a clip has no area to draw in.
|
||||
fn push_clips(s: &mut Surface, region: Option<&kurbo::BezPath>, clips: &[Arc<craft_metafile::PlacedClip>]) -> Option<usize> {
|
||||
let mut paths = Vec::with_capacity(clips.len() + 1);
|
||||
if let Some(region) = region {
|
||||
paths.push((path_from(region)?, FillRule::NonZero));
|
||||
}
|
||||
for c in clips {
|
||||
paths.push((path_from(&c.path)?, if c.even_odd { FillRule::EvenOdd } else { FillRule::NonZero }));
|
||||
}
|
||||
for (p, rule) in &paths {
|
||||
s.push_clip_path(p, rule);
|
||||
}
|
||||
Some(paths.len())
|
||||
}
|
||||
|
||||
fn pop_clips(s: &mut Surface, n: usize) {
|
||||
for _ in 0..n {
|
||||
s.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/// A metafile pen for `path`: `width` (points, at least [`HAIRLINE`]), the pen's caps, joins,
|
||||
/// miter limit and dashes (`wordcraft_layout::metafile_dashes`, with the hairline as the pixel).
|
||||
fn pen(paint: krilla::paint::Paint, opacity: NormalizedF32, width: f64, line: &craft_metafile::LineStyle, path: &kurbo::BezPath) -> Stroke {
|
||||
let line_cap = match line.cap {
|
||||
craft_metafile::Cap::Round => LineCap::Round,
|
||||
craft_metafile::Cap::Square => LineCap::Square,
|
||||
craft_metafile::Cap::Flat => LineCap::Butt,
|
||||
};
|
||||
let line_join = match line.join {
|
||||
craft_metafile::Join::Round => LineJoin::Round,
|
||||
craft_metafile::Join::Bevel => LineJoin::Bevel,
|
||||
craft_metafile::Join::Miter => LineJoin::Miter,
|
||||
};
|
||||
let dash = if line.dash.is_empty() { None } else { wordcraft_layout::metafile_dashes(&line.dash, width == 0.0, HAIRLINE, path.perimeter(1.0)) };
|
||||
Stroke {
|
||||
paint,
|
||||
width: width.max(HAIRLINE) as f32,
|
||||
miter_limit: wordcraft_layout::metafile_miter_limit(line.miter_limit),
|
||||
line_cap,
|
||||
line_join,
|
||||
opacity,
|
||||
dash: dash.map(|d| StrokeDash { array: d.iter().map(|v| *v as f32).collect(), offset: 0.0 }),
|
||||
}
|
||||
}
|
||||
|
||||
/// A tiling pattern of `img` (`w` × `h` pixels); `tile` maps tile pixels to page space. None when
|
||||
/// the mapping is not finite.
|
||||
fn tile_pattern(s: &mut Surface, img: &Image, w: u32, h: u32, tile: kurbo::Affine) -> Option<krilla::paint::Pattern> {
|
||||
let c = tile.as_coeffs().map(|v| v as f32);
|
||||
if !c.iter().all(|v| v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let size = Size::from_wh(w as f32, h as f32)?;
|
||||
let mut sb = s.stream_builder();
|
||||
let mut ps = sb.surface();
|
||||
ps.draw_image(img.clone(), size);
|
||||
ps.finish();
|
||||
let stream = sb.finish();
|
||||
Some(krilla::paint::Pattern { stream, transform: Transform::from_row(c[0], c[1], c[2], c[3], c[4], c[5]), width: w as f32, height: h as f32 })
|
||||
}
|
||||
|
||||
/// A kurbo path as a krilla path (None when empty).
|
||||
fn path_from(b: &kurbo::BezPath) -> Option<Path> {
|
||||
let mut pb = PathBuilder::new();
|
||||
|
||||
@@ -1305,6 +1305,211 @@ fn emf_rec(typ: u32, fields: &[i32]) -> Vec<u8> {
|
||||
v
|
||||
}
|
||||
|
||||
/// The PDF of a document holding one 70 pt metafile picture, uncompressed.
|
||||
fn metafile_pdf(emf: Vec<u8>) -> String {
|
||||
String::from_utf8_lossy(&metafile_pdf_bytes(emf)).into_owned()
|
||||
}
|
||||
|
||||
fn metafile_pdf_bytes(emf: Vec<u8>) -> Vec<u8> {
|
||||
export(&metafile_doc(emf), &PdfOptions { compress: false, tagged: false, ..Default::default() }).unwrap()
|
||||
}
|
||||
|
||||
/// The uncompressed PDF of a document holding one 70 pt metafile picture, and the picture's box
|
||||
/// on the first page in PDF space (points, y up).
|
||||
fn metafile_pdf_and_box(emf: Vec<u8>) -> (Vec<u8>, kurbo::Rect) {
|
||||
let d = metafile_doc(emf);
|
||||
let bytes = export(&d, &PdfOptions { compress: false, tagged: false, ..Default::default() }).unwrap();
|
||||
let lay = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
|
||||
let page = &lay.pages[0];
|
||||
let h = f64::from(page.h);
|
||||
let r = wordcraft_layout::display::page_display(&d, page, &DisplayOptions::default())
|
||||
.into_iter()
|
||||
.find_map(|item| if let Draw::Image { rect, .. } = item { Some(rect) } else { None })
|
||||
.expect("the picture is laid out");
|
||||
let (x, y, w, ph) = (f64::from(r.x), f64::from(r.y), f64::from(r.w), f64::from(r.h));
|
||||
(bytes, kurbo::Rect::new(x, h - y - ph, x + w, h - y))
|
||||
}
|
||||
|
||||
/// The right half of a box.
|
||||
fn right_half(r: kurbo::Rect) -> kurbo::Rect {
|
||||
kurbo::Rect::new((r.x0 + r.x1) / 2.0, r.y0, r.x1, r.y1)
|
||||
}
|
||||
|
||||
/// Whether two boxes have the same edges, to within half a point.
|
||||
fn same_box(a: kurbo::Rect, b: kurbo::Rect) -> bool {
|
||||
[a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 0.5)
|
||||
}
|
||||
|
||||
fn metafile_doc(emf: Vec<u8>) -> Document {
|
||||
let mut d = Document::new();
|
||||
let media = d.add_media(emf, "emf");
|
||||
let mut p = Paragraph::with_text("Figure: ", CharProps::default());
|
||||
let n = p.len();
|
||||
p.insert_object(
|
||||
n,
|
||||
InlineObject::Image {
|
||||
media,
|
||||
w: 70.0,
|
||||
h: 70.0,
|
||||
alt: String::new(),
|
||||
float: Default::default(),
|
||||
crop: [0.0; 4],
|
||||
fx: Default::default(),
|
||||
ole: None,
|
||||
},
|
||||
&CharProps::default(),
|
||||
)
|
||||
.unwrap();
|
||||
d.body = vec![para_block(p)];
|
||||
d
|
||||
}
|
||||
|
||||
/// #6636: an EMF+ only file whose EmfPlusDrawImage draws a 32bppPARGB bitmap: the bitmap is
|
||||
/// embedded as an image, and the page draws it into the EmfPlusDrawImage rectangle.
|
||||
#[test]
|
||||
fn emf_plus_only_bitmap_is_embedded() {
|
||||
let plus_rec = |typ: u16, flags: u16, data: &[u8]| {
|
||||
let mut v = typ.to_le_bytes().to_vec();
|
||||
v.extend(flags.to_le_bytes());
|
||||
v.extend(((12 + data.len()) as u32).to_le_bytes());
|
||||
v.extend((data.len() as u32).to_le_bytes());
|
||||
v.extend(data);
|
||||
v
|
||||
};
|
||||
let le32 = |vals: &[i32]| -> Vec<u8> { vals.iter().flat_map(|v| v.to_le_bytes()).collect() };
|
||||
let header = plus_rec(0x4001, 0, &le32(&[0xDBC0_1002_u32 as i32, 1, 96, 96]));
|
||||
let mut image = le32(&[0xDBC0_1002_u32 as i32, 1, 2, 2, 8, 0x000E_200B, 0]);
|
||||
image.extend([0u8, 0, 255, 255].repeat(4));
|
||||
let object = plus_rec(0x4008, 0x0500, &image);
|
||||
let mut draw = le32(&[-1, 2]);
|
||||
draw.extend([0.0f32, 0.0, 2.0, 2.0, 50.0, 0.0, 50.0, 100.0].iter().flat_map(|v| v.to_le_bytes()));
|
||||
let draw = plus_rec(0x401A, 0, &draw);
|
||||
let mut comment = 0x2B46_4D45u32.to_le_bytes().to_vec();
|
||||
comment.extend([header, object, draw, plus_rec(0x4002, 0, &[])].concat());
|
||||
let mut rec = 70u32.to_le_bytes().to_vec();
|
||||
rec.extend(((12 + comment.len()) as u32).to_le_bytes());
|
||||
rec.extend((comment.len() as u32).to_le_bytes());
|
||||
rec.extend(comment);
|
||||
let (bytes, pic) = metafile_pdf_and_box(emf_file(&[rec, emf_rec(14, &[0; 3])]));
|
||||
let images = pdf_images(&bytes);
|
||||
assert!(images.iter().any(|(w, h, ..)| (*w, *h) == (2, 2)), "the 2 × 2 bitmap is embedded");
|
||||
let drawn = pdf_drawn_images(&bytes);
|
||||
assert!(
|
||||
drawn.iter().any(|&(w, h, r)| (w, h) == (2, 2) && same_box(r, right_half(pic))),
|
||||
"the page draws the bitmap over the right half of the picture at {pic:?}: {drawn:?}"
|
||||
);
|
||||
assert!(!String::from_utf8_lossy(&bytes).contains("0.8156"), "the gray placeholder box is not drawn");
|
||||
}
|
||||
|
||||
/// #6636: an EMF+ only file whose EmfPlusDrawImage draws a bitmap in PixelFormat32bppARGB,
|
||||
/// 24bppRGB or 32bppRGB, or a compressed PNG or JPEG bitmap: the bitmap is embedded as an image,
|
||||
/// and the page draws it into the EmfPlusDrawImage rectangle.
|
||||
#[test]
|
||||
fn emf_plus_only_bitmap_formats_are_embedded() {
|
||||
let plus_rec = |typ: u16, flags: u16, data: &[u8]| {
|
||||
let mut v = typ.to_le_bytes().to_vec();
|
||||
v.extend(flags.to_le_bytes());
|
||||
v.extend(((12 + data.len()) as u32).to_le_bytes());
|
||||
v.extend((data.len() as u32).to_le_bytes());
|
||||
v.extend(data);
|
||||
v
|
||||
};
|
||||
let le32 = |vals: &[i32]| -> Vec<u8> { vals.iter().flat_map(|v| v.to_le_bytes()).collect() };
|
||||
let encoded = |png: bool| {
|
||||
let red = [255u8, 0, 0].repeat(15);
|
||||
if png {
|
||||
let img = image::RgbImage::from_raw(5, 3, red).unwrap();
|
||||
wordcraft_geom::picture::encode_png(&image::DynamicImage::from(img)).unwrap()
|
||||
} else {
|
||||
wordcraft_geom::picture::encode_jpeg(&red, 5, 3, 100).unwrap()
|
||||
}
|
||||
};
|
||||
// Name, width, height, stride, pixel format, bitmap type (0 pixels, 1 compressed) and data.
|
||||
let cases: [(&str, i32, i32, i32, u32, i32, Vec<u8>); 5] = [
|
||||
("32bppARGB", 2, 2, 8, 0x0026_200A, 0, [0u8, 0, 255, 255].repeat(4)),
|
||||
("24bppRGB", 2, 2, 8, 0x0002_1808, 0, [0u8, 0, 255, 0, 0, 255, 0, 0].repeat(2)),
|
||||
("32bppRGB", 2, 2, 8, 0x0002_2009, 0, [0u8, 0, 255, 0].repeat(4)),
|
||||
("PNG", 5, 3, 0, 0, 1, encoded(true)),
|
||||
("JPEG", 5, 3, 0, 0, 1, encoded(false)),
|
||||
];
|
||||
for (name, w, h, stride, format, kind, data) in cases {
|
||||
let header = plus_rec(0x4001, 0, &le32(&[0xDBC0_1002_u32 as i32, 1, 96, 96]));
|
||||
let mut image = le32(&[0xDBC0_1002_u32 as i32, 1, w, h, stride, format as i32, kind]);
|
||||
image.extend(data);
|
||||
// Records are a multiple of 4 bytes long.
|
||||
image.resize(image.len().next_multiple_of(4), 0);
|
||||
let object = plus_rec(0x4008, 0x0500, &image);
|
||||
let mut draw = le32(&[-1, 2]);
|
||||
draw.extend([0.0f32, 0.0, w as f32, h as f32, 50.0, 0.0, 50.0, 100.0].iter().flat_map(|v| v.to_le_bytes()));
|
||||
let draw = plus_rec(0x401A, 0, &draw);
|
||||
let mut comment = 0x2B46_4D45u32.to_le_bytes().to_vec();
|
||||
comment.extend([header, object, draw, plus_rec(0x4002, 0, &[])].concat());
|
||||
let mut rec = 70u32.to_le_bytes().to_vec();
|
||||
rec.extend(((12 + comment.len()) as u32).to_le_bytes());
|
||||
rec.extend((comment.len() as u32).to_le_bytes());
|
||||
rec.extend(comment);
|
||||
let (bytes, pic) = metafile_pdf_and_box(emf_file(&[rec, emf_rec(14, &[0; 3])]));
|
||||
let images = pdf_images(&bytes);
|
||||
assert!(images.iter().any(|(iw, ih, ..)| (*iw, *ih) == (w as u32, h as u32)), "{name}: the {w} × {h} bitmap is embedded");
|
||||
let drawn = pdf_drawn_images(&bytes);
|
||||
assert!(
|
||||
drawn.iter().any(|&(iw, ih, r)| (iw, ih) == (w as u32, h as u32) && same_box(r, right_half(pic))),
|
||||
"{name}: the page draws the bitmap over the right half of the picture at {pic:?}: {drawn:?}"
|
||||
);
|
||||
assert!(!String::from_utf8_lossy(&bytes).contains("0.8156"), "{name}: the gray placeholder box is not drawn");
|
||||
}
|
||||
}
|
||||
|
||||
/// A dotted cosmetic pen (CREATEPEN, PS_DOT, width 0) draws hairline dots: its dashes and gaps are
|
||||
/// the hairline's width, not the file's device units scaled to the frame (0.7 pt here).
|
||||
#[test]
|
||||
fn metafile_cosmetic_dotted_pen_draws_hairline_dots() {
|
||||
let recs = [emf_rec(38, &[1, 2, 0, 0, 0]), emf_rec(37, &[1]), emf_rec(27, &[0, 50]), emf_rec(54, &[100, 50]), emf_rec(14, &[0; 3])];
|
||||
let raw = metafile_pdf(emf_file(&recs));
|
||||
assert!(raw.contains("[0.25 0.25]0 d"), "the dots are hairline-sized");
|
||||
}
|
||||
|
||||
/// A geometric PS_USERSTYLE pen whose dashes and gaps are far below the hairline draws its line
|
||||
/// solid: no dash array is written.
|
||||
#[test]
|
||||
fn metafile_sub_pixel_dashes_draw_solid() {
|
||||
let mut emf = emf_file(&[]);
|
||||
// 10,000 device pixels over 250 mm: a device unit is 0.025 mm. The picture is 1000 units wide.
|
||||
let le32 = |vals: &[i32]| -> Vec<u8> { vals.iter().flat_map(|v| v.to_le_bytes()).collect() };
|
||||
emf[8..24].copy_from_slice(&le32(&[0, 0, 1000, 1000]));
|
||||
emf[72..80].copy_from_slice(&le32(&[10_000, 10_000]));
|
||||
let pen = emf_rec(95, &[1, 0, 0, 0, 0, 0x0001_0207, 80, 0, 0, 0, 2, 1, 1]);
|
||||
let recs = [pen, emf_rec(37, &[1]), emf_rec(27, &[0, 500]), emf_rec(54, &[1000, 500]), emf_rec(14, &[0; 3])];
|
||||
emf.extend(recs.concat());
|
||||
let raw = metafile_pdf(emf);
|
||||
assert!(raw.contains(" w ") && !raw.contains("]0 d"), "a stroke with no dash array");
|
||||
}
|
||||
|
||||
/// A clip region (INTERSECTCLIPRECT) adds a clip around the rectangle it clips.
|
||||
#[test]
|
||||
fn metafile_clip_region_is_a_clip() {
|
||||
let clips = |raw: &str| raw.matches("\nW\nn").count() + raw.matches("\nW*\nn").count();
|
||||
let draw = |clip: bool| {
|
||||
let mut recs = vec![emf_rec(39, &[1, 0, 0x0000_00FF, 0]), emf_rec(37, &[1])];
|
||||
if clip {
|
||||
recs.push(emf_rec(30, &[0, 0, 50, 100]));
|
||||
}
|
||||
recs.extend([emf_rec(43, &[0, 0, 100, 100]), emf_rec(14, &[0; 3])]);
|
||||
metafile_pdf(emf_file(&recs))
|
||||
};
|
||||
let (with, without) = (clips(&draw(true)), clips(&draw(false)));
|
||||
assert!(without > 0 && with == without + 1, "one clip more with the region: {with} and {without}");
|
||||
}
|
||||
|
||||
/// A hatched brush (CREATEBRUSHINDIRECT, BS_HATCHED) fills through a tiling pattern, not with a
|
||||
/// solid color.
|
||||
#[test]
|
||||
fn metafile_hatch_brush_is_a_tiling_pattern() {
|
||||
let recs = [emf_rec(39, &[1, 2, 0x0000_00FF, 1]), emf_rec(37, &[1]), emf_rec(43, &[0, 0, 100, 100]), emf_rec(14, &[0; 3])];
|
||||
let raw = metafile_pdf(emf_file(&recs));
|
||||
assert!(raw.contains("/PatternType 1"), "the hatch is a tiling pattern");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metafile_strokes_use_round_caps_and_joins() {
|
||||
// A 4-unit black pen (handle 1) outlines a rectangle, so the stroke is drawn with round caps and joins.
|
||||
@@ -1425,6 +1630,17 @@ fn emf_text_records(text: &str) -> Vec<Vec<u8>> {
|
||||
vec![font, emf_rec(37, &[1]), emf_rec(24, &[0]), out]
|
||||
}
|
||||
|
||||
/// With the opaque background mode (the default) and a red background color (SETBKCOLOR), a text
|
||||
/// run's character cells are filled red behind the text.
|
||||
#[test]
|
||||
fn metafile_text_fills_its_opaque_background() {
|
||||
let mut recs = vec![emf_rec(25, &[0x0000_00FF])];
|
||||
recs.extend(emf_text_records("Hi"));
|
||||
recs.push(emf_rec(14, &[0; 3]));
|
||||
let raw = metafile_pdf(emf_file(&recs));
|
||||
assert!(raw.contains("1 0 0 rg"), "the character cells are filled red");
|
||||
}
|
||||
|
||||
/// #1764: the text of an EMF picture (EXTTEXTOUTW) is drawn, so it is in the PDF's text layer.
|
||||
#[test]
|
||||
fn metafile_text_records_are_drawn_as_text() {
|
||||
@@ -2159,6 +2375,40 @@ fn pdf_images(bytes: &[u8]) -> Vec<(u32, u32, Vec<String>, Vec<Vec<u8>>)> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The images the pages draw, through hayro's interpreter: pixel width and height, and the box each
|
||||
/// one is drawn into, in PDF space (points, y up).
|
||||
fn pdf_drawn_images(bytes: &[u8]) -> Vec<(u32, u32, kurbo::Rect)> {
|
||||
use hayro_interpret::font::Glyph;
|
||||
use hayro_interpret::{
|
||||
BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache, InterpreterSettings, Paint, PathDrawMode, SoftMask,
|
||||
interpret_page,
|
||||
};
|
||||
struct Ex(Vec<(u32, u32, kurbo::Rect)>);
|
||||
impl Device<'_> for Ex {
|
||||
fn set_soft_mask(&mut self, _: Option<SoftMask<'_>>) {}
|
||||
fn set_blend_mode(&mut self, _: BlendMode) {}
|
||||
fn draw_path(&mut self, _: &kurbo::BezPath, _: kurbo::Affine, _: &Paint<'_>, _: &PathDrawMode) {}
|
||||
fn push_clip_path(&mut self, _: &ClipPath) {}
|
||||
fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'_>>, _: BlendMode) {}
|
||||
fn draw_glyph(&mut self, _: &Glyph<'_>, _: kurbo::Affine, _: kurbo::Affine, _: &Paint<'_>, _: &GlyphDrawMode) {}
|
||||
fn draw_image(&mut self, image: Image<'_, '_>, t: kurbo::Affine) {
|
||||
// The transform maps the image's pixel grid onto the page.
|
||||
let (w, h) = (image.width(), image.height());
|
||||
self.0.push((w, h, t.transform_rect_bbox(kurbo::Rect::new(0.0, 0.0, f64::from(w), f64::from(h)))));
|
||||
}
|
||||
fn pop_clip_path(&mut self) {}
|
||||
fn pop_transparency_group(&mut self) {}
|
||||
}
|
||||
let pdf = hayro_syntax::Pdf::new(bytes.to_vec()).expect("parse");
|
||||
let cache = InterpreterCache::new();
|
||||
let mut ex = Ex(Vec::new());
|
||||
for page in pdf.pages().iter() {
|
||||
let mut ctx = Context::new(kurbo::Affine::IDENTITY, kurbo::Rect::new(0.0, 0.0, 1.0, 1.0), &cache, pdf.xref(), InterpreterSettings::default());
|
||||
interpret_page(page, &mut ctx, &mut ex);
|
||||
}
|
||||
ex.0
|
||||
}
|
||||
|
||||
/// The fill opacities (`ca`) of the PDF's graphics states.
|
||||
fn pdf_fill_opacities(bytes: &[u8]) -> Vec<f32> {
|
||||
use hayro_syntax::object::Object;
|
||||
|
||||
@@ -856,7 +856,7 @@ fn draw_image(ctx: &mut RenderContext, fr: &Frame, it: &Draw) {
|
||||
return;
|
||||
};
|
||||
let (pw, ph) = (pm.width().max(1) as f64, pm.height().max(1) as f64);
|
||||
let [cl, ct, vis_w, vis_h] = craft_metafile::crop_window(*crop);
|
||||
let [cl, ct, vis_w, vis_h] = wordcraft_layout::crop_window(*crop);
|
||||
let sx = r.width() / (pw * vis_w);
|
||||
let sy = r.height() / (ph * vis_h);
|
||||
ctx.set_transform(view);
|
||||
|
||||
+255
-37
@@ -1,4 +1,6 @@
|
||||
use super::{Affine, Arc, Document, FontDb, HashMap, Item, Mutex, Page, Picture, Pixmap, PlacedItem, RenderContext, Seg, Shape, Weak, kurbo, peniko};
|
||||
use craft_metafile::{ClipPath, Tile};
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// Upper bound on the bytes the two decoded-media caches keep together (about 256 MB), half each;
|
||||
/// past its half a cache starts over.
|
||||
@@ -140,29 +142,70 @@ pub fn metafile_size(bytes: &[u8]) -> Option<(f32, f32, &'static str)> {
|
||||
Some((w * k, h * k, ext))
|
||||
}
|
||||
|
||||
/// A metafile (WMF/EMF) picture, parsed once. The geometry comes placed by the metafile crate; the
|
||||
/// bitmaps are pixmaps, one per picture item (None for paths and undecodable bitmaps).
|
||||
/// A metafile (WMF/EMF/EMF+) picture, parsed once. The geometry comes placed by the metafile crate;
|
||||
/// the bitmaps and pattern tiles are pixmaps, one per picture item (None for paths, text and
|
||||
/// undecodable bitmaps). Fills that share a tile share its pixmap. `averages` holds each pattern
|
||||
/// fill's tile average color (transparent for other items), computed once a tile.
|
||||
pub(crate) struct Vector {
|
||||
pic: Picture,
|
||||
pixmaps: Vec<Option<Arc<Pixmap>>>,
|
||||
averages: Vec<[u8; 4]>,
|
||||
}
|
||||
|
||||
impl Vector {
|
||||
/// Approximate memory held: pixels and path segments.
|
||||
fn bytes(&self) -> usize {
|
||||
let px: usize = self.pixmaps.iter().flatten().map(|p| p.width() as usize * p.height() as usize * 4).sum();
|
||||
let segs: usize = self
|
||||
.pic
|
||||
.items
|
||||
/// Approximate memory held: pixels (a tile shared by several fills once), path segments and the
|
||||
/// per-item bookkeeping.
|
||||
pub(crate) fn bytes(&self) -> usize {
|
||||
let mut seen: HashSet<*const Pixmap> = HashSet::new();
|
||||
let px: usize = self.pixmaps.iter().flatten().filter(|p| seen.insert(Arc::as_ptr(p))).map(|p| bitmap_bytes(p)).sum();
|
||||
px.saturating_add(self.averages.capacity() * 4).saturating_add(geometry_bytes(&self.pic))
|
||||
}
|
||||
}
|
||||
|
||||
/// Memory held by one decoded bitmap: its pixels plus the pixmap and its `Arc` header.
|
||||
fn bitmap_bytes(p: &Pixmap) -> usize {
|
||||
usize::from(p.width()) * usize::from(p.height()) * 4 + std::mem::size_of::<Pixmap>() + 2 * std::mem::size_of::<usize>()
|
||||
}
|
||||
|
||||
/// Approximate memory held by a picture's items: path segments and text (charged by capacity, as a
|
||||
/// parsed vector keeps its growth slack), the item itself (a bitmap
|
||||
/// item stays in the list after its pixels move out), a path's dash array, a text's boxed record and
|
||||
/// font name, the pixmap slot kept for it, a pattern's path
|
||||
/// and tile, and every item's clip rectangles and clip paths. Tiles and clip paths are shared between
|
||||
/// the items that use them, so each is charged once.
|
||||
pub(crate) fn geometry_bytes(pic: &Picture) -> usize {
|
||||
let slot = std::mem::size_of::<Option<Arc<Pixmap>>>();
|
||||
let seg = std::mem::size_of::<Seg>();
|
||||
let mut tiles: HashSet<*const Tile> = HashSet::new();
|
||||
let mut clip_paths: HashSet<*const ClipPath> = HashSet::new();
|
||||
let mut total = 0usize;
|
||||
for it in &pic.items {
|
||||
let (region, clips): (&Option<Vec<[f32; 4]>>, &[Arc<ClipPath>]) = match it {
|
||||
Item::Path { region, clips, .. } | Item::Bitmap { region, clips, .. } | Item::Pattern { region, clips, .. } => (region, clips),
|
||||
Item::Text(t) => (&t.region, &t.clips),
|
||||
};
|
||||
let own = match it {
|
||||
Item::Path { segs, line, .. } => (segs.capacity() * seg).saturating_add(line.dash.capacity() * std::mem::size_of::<f32>()),
|
||||
Item::Bitmap { .. } => 0,
|
||||
Item::Pattern { segs, tile, .. } => {
|
||||
let tile_bytes = if tiles.insert(Arc::as_ptr(tile)) { tile.rgba.len().saturating_add(std::mem::size_of::<Tile>()) } else { 0 };
|
||||
(segs.capacity() * seg).saturating_add(tile_bytes)
|
||||
}
|
||||
Item::Text(t) => {
|
||||
std::mem::size_of::<craft_metafile::Text>() + t.text.len() + t.dx.len() * std::mem::size_of::<f32>() + t.font.family.len()
|
||||
}
|
||||
};
|
||||
let region_bytes = region.as_ref().map_or(0, |r| r.len() * std::mem::size_of::<[f32; 4]>());
|
||||
let clip_bytes: usize = clips
|
||||
.iter()
|
||||
.map(|it| match it {
|
||||
Item::Path { segs, .. } => segs.len() * std::mem::size_of::<Seg>(),
|
||||
Item::Bitmap { .. } | Item::Pattern { .. } => 0,
|
||||
Item::Text(t) => t.text.len() + t.dx.len() * 4,
|
||||
.map(|c| {
|
||||
let arc = std::mem::size_of::<usize>() * 2 + std::mem::size_of::<Arc<ClipPath>>();
|
||||
if clip_paths.insert(Arc::as_ptr(c)) { arc + std::mem::size_of::<ClipPath>() + c.segs.capacity() * seg } else { arc }
|
||||
})
|
||||
.sum();
|
||||
px + segs
|
||||
total = total.saturating_add(slot + std::mem::size_of::<Item>()).saturating_add(own).saturating_add(region_bytes).saturating_add(clip_bytes);
|
||||
}
|
||||
total
|
||||
}
|
||||
|
||||
/// The metafile picture for a media key. None when the bytes are not a metafile or do not parse, so
|
||||
@@ -184,25 +227,94 @@ pub(crate) fn vector_for(doc: &Document, key: &str) -> Option<Arc<Vector>> {
|
||||
v
|
||||
}
|
||||
|
||||
/// Parses a metafile and decodes its bitmaps. None when the picture has no usable size.
|
||||
fn build_vector(bytes: &[u8]) -> Option<Vector> {
|
||||
/// Parses a metafile and decodes its bitmaps and pattern tiles. None when the picture has no
|
||||
/// usable size.
|
||||
pub(crate) fn build_vector(bytes: &[u8]) -> Option<Vector> {
|
||||
let mut pic = craft_metafile::parse(bytes).ok()?;
|
||||
if !pic.has_size() {
|
||||
return None;
|
||||
}
|
||||
// The pixels move into the pixmaps; the picture keeps only the geometry.
|
||||
let pixmaps = pic.items.iter_mut().map(|it| it.take_pixels().and_then(|(w, h, px)| premul_pixmap(w, h, &px)).map(Arc::new)).collect();
|
||||
Some(Vector { pic, pixmaps })
|
||||
// The pixels move into the pixmaps; the picture keeps only the geometry. A tile shared by
|
||||
// several fills is converted and averaged once. Only the bitmaps are fitted to the cache: a
|
||||
// tile is small and stays as it is, but counts against the budget.
|
||||
let mut tiles: HashMap<usize, (Option<Arc<Pixmap>>, [u8; 4])> = HashMap::new();
|
||||
let mut tile_bytes = 0usize;
|
||||
let mut bitmaps: Vec<Option<Pixmap>> = Vec::with_capacity(pic.items.len());
|
||||
let mut averages: Vec<[u8; 4]> = Vec::with_capacity(pic.items.len());
|
||||
let mut patterns: Vec<Option<Arc<Pixmap>>> = Vec::with_capacity(pic.items.len());
|
||||
for it in pic.items.iter_mut() {
|
||||
if let Item::Pattern { tile, .. } = it {
|
||||
let key = Arc::as_ptr(tile) as usize;
|
||||
let fresh = !tiles.contains_key(&key);
|
||||
let (pm, avg) = tiles
|
||||
.entry(key)
|
||||
.or_insert_with(|| {
|
||||
(premul_pixmap(tile.width, tile.height, &tile.rgba).map(Arc::new), wordcraft_layout::metafile_average_color(&tile.rgba))
|
||||
})
|
||||
.clone();
|
||||
if fresh {
|
||||
tile_bytes = tile_bytes.saturating_add(pm.as_ref().map_or(0, |p| bitmap_bytes(p)));
|
||||
}
|
||||
bitmaps.push(None);
|
||||
patterns.push(pm);
|
||||
averages.push(avg);
|
||||
} else {
|
||||
bitmaps.push(it.take_pixels().and_then(|(w, h, px)| premul_pixmap(w, h, &px)));
|
||||
patterns.push(None);
|
||||
averages.push([0; 4]);
|
||||
}
|
||||
}
|
||||
let bitmaps = fit_cache(bitmaps, geometry_bytes(&pic).saturating_add(tile_bytes));
|
||||
let pixmaps = bitmaps.into_iter().zip(patterns).map(|(b, t)| b.map(Arc::new).or(t)).collect();
|
||||
Some(Vector { pic, pixmaps, averages })
|
||||
}
|
||||
|
||||
/// The bitmaps of a metafile at a size its whole picture is kept in the cache. When geometry and
|
||||
/// bitmaps together are past the cache budget (a metafile with a 6000 x 6000 bitmap is 144 MB), the
|
||||
/// cache would refuse the picture and every repaint would parse and decode the file again, so the
|
||||
/// bitmaps are box-averaged down to an eighth of the budget between them, in proportion to their
|
||||
/// size, as large raster pictures are (#3665, which uses half). An eighth because the cache starts
|
||||
/// over when full: several huge pictures on screen together must fit side by side, and not clear
|
||||
/// the small ones with them. Geometry that is itself an eighth or more still leaves the bitmaps a
|
||||
/// sixteenth, as long as the whole budget has room for it. A picture that still cannot fit after shrinking stays uncached,
|
||||
/// as before. Pictures within the budget keep their full resolution. Printing (`render_page`) draws
|
||||
/// the shrunk bitmaps too, as it does large raster pictures; PDF export parses the metafile itself
|
||||
/// and is unaffected.
|
||||
pub(crate) fn fit_cache(mut pixmaps: Vec<Option<Pixmap>>, geometry: usize) -> Vec<Option<Pixmap>> {
|
||||
let pixels = |p: &Pixmap| usize::from(p.width()) * usize::from(p.height()) * 4;
|
||||
let total: usize = pixmaps.iter().flatten().map(pixels).sum();
|
||||
let fixed: usize = pixmaps.iter().flatten().map(|p| bitmap_bytes(p) - pixels(p)).sum();
|
||||
if total.saturating_add(fixed).saturating_add(geometry) <= CACHE_BYTES {
|
||||
return pixmaps;
|
||||
}
|
||||
// The bitmaps get what is left of an eighth, but never less than a sixteenth (so the allowance does
|
||||
// not drop to nothing as geometry reaches the eighth) and never more than the whole budget leaves.
|
||||
let target = CACHE_BYTES / 8;
|
||||
let allowance = target.saturating_sub(geometry).max(target / 2).min(CACHE_BYTES.saturating_sub(geometry));
|
||||
let room = allowance.saturating_sub(fixed) / 4;
|
||||
for pm in pixmaps.iter_mut().flatten() {
|
||||
// This bitmap's share of the pixels that fit.
|
||||
let share = (room as u128 * pixels(pm) as u128 / total.max(1) as u128) as u64;
|
||||
if let Some(small) = shrink(pm, share) {
|
||||
*pm = small;
|
||||
}
|
||||
}
|
||||
pixmaps
|
||||
}
|
||||
|
||||
fn rgba_color(c: [u8; 4]) -> peniko::Color {
|
||||
peniko::Color::from_rgba8(c[0], c[1], c[2], c[3])
|
||||
}
|
||||
|
||||
/// Pattern tiles smaller than this (device pixels on both sides) are drawn as the tile's average
|
||||
/// color: a sub-pixel pattern would only alias.
|
||||
const MIN_TILE_PX: f64 = 1.5;
|
||||
|
||||
/// Draws a metafile picture into `r` (page points): fills and strokes in page space (so strokes keep
|
||||
/// their width under non-uniform scaling), bitmaps stretched, all clipped to `r` and faded by `alpha`.
|
||||
/// Strokes have round caps and joins, as GDI draws them, and are at least one device pixel wide, so
|
||||
/// cosmetic (width 0) pens show as hairlines at any zoom.
|
||||
/// their width under non-uniform scaling), bitmaps stretched (or turned by their transform),
|
||||
/// pattern fills tiled, each item inside its clip region and clip paths, all clipped to `r` and
|
||||
/// faded by `alpha`. Strokes take the pen's caps, joins and dashes and are at least one device
|
||||
/// pixel wide, so cosmetic (width 0) pens show as hairlines at any zoom.
|
||||
pub(crate) fn draw_vector(ctx: &mut RenderContext, v: &Vector, r: &kurbo::Rect, crop: &[f32; 4], alpha: f32, view: Affine) {
|
||||
ctx.set_transform(view);
|
||||
let alpha = if alpha.is_finite() { alpha.clamp(0.0, 1.0) } else { 1.0 };
|
||||
@@ -212,9 +324,9 @@ pub(crate) fn draw_vector(ctx: &mut RenderContext, v: &Vector, r: &kurbo::Rect,
|
||||
}
|
||||
ctx.push_clip_layer(&r.to_path(0.1));
|
||||
let pixel = device_pixel(view);
|
||||
for it in v.pic.place(*r, *crop) {
|
||||
for it in v.pic.place(*r, wordcraft_layout::crop_sides(*crop)) {
|
||||
match it {
|
||||
PlacedItem::Path { path, fill, stroke, even_odd, .. } => {
|
||||
PlacedItem::Path { path, fill, stroke, line, even_odd, region, clips } => clipped(ctx, region.as_deref(), &clips, |ctx| {
|
||||
if let Some(f) = fill {
|
||||
ctx.set_paint(rgba_color(f));
|
||||
ctx.set_fill_rule(if even_odd { peniko::Fill::EvenOdd } else { peniko::Fill::NonZero });
|
||||
@@ -222,26 +334,71 @@ pub(crate) fn draw_vector(ctx: &mut RenderContext, v: &Vector, r: &kurbo::Rect,
|
||||
}
|
||||
if let Some((s, w)) = stroke {
|
||||
ctx.set_paint(rgba_color(s));
|
||||
ctx.set_stroke(kurbo::Stroke::new(w.max(pixel)).with_caps(kurbo::Cap::Round).with_join(kurbo::Join::Round));
|
||||
ctx.set_stroke(pen(w, pixel, &line, &path));
|
||||
ctx.stroke_path(&path);
|
||||
}
|
||||
}
|
||||
PlacedItem::Bitmap { index, rect, .. } => {
|
||||
let Some(Some(pm)) = v.pixmaps.get(index) else { continue };
|
||||
}),
|
||||
PlacedItem::Bitmap { index, rect, transform, region, clips } => clipped(ctx, region.as_deref(), &clips, |ctx| {
|
||||
let Some(Some(pm)) = v.pixmaps.get(index) else { return };
|
||||
let (pw, ph) = (pm.width().max(1) as f64, pm.height().max(1) as f64);
|
||||
ctx.set_paint(vello_cpu::Image {
|
||||
image: vello_cpu::ImageSource::Pixmap(pm.clone()),
|
||||
sampler: peniko::ImageSampler::default().with_quality(peniko::ImageQuality::Medium),
|
||||
});
|
||||
ctx.set_paint_transform(Affine::translate((rect.x0, rect.y0)) * Affine::scale_non_uniform(rect.width() / pw, rect.height() / ph));
|
||||
ctx.fill_rect(&rect);
|
||||
ctx.reset_paint_transform();
|
||||
}
|
||||
PlacedItem::Pattern { .. } => {}
|
||||
PlacedItem::Text { index, transform, .. } => {
|
||||
if let Some(Item::Text(t)) = v.pic.items.get(index) {
|
||||
draw_vector_text(ctx, t, view * transform);
|
||||
let c = transform.as_coeffs();
|
||||
// Upright and not mirrored: the bitmap fills `rect`.
|
||||
if c[1] == 0.0 && c[2] == 0.0 && c[0] > 0.0 && c[3] > 0.0 {
|
||||
ctx.set_paint_transform(Affine::translate((rect.x0, rect.y0)) * Affine::scale_non_uniform(rect.width() / pw, rect.height() / ph));
|
||||
ctx.fill_rect(&rect);
|
||||
} else {
|
||||
// A turned, skewed or mirrored bitmap: `transform` maps the unit square onto its place.
|
||||
ctx.set_paint_transform(transform * Affine::scale_non_uniform(1.0 / pw, 1.0 / ph));
|
||||
ctx.fill_path(&(transform * kurbo::Rect::new(0.0, 0.0, 1.0, 1.0).to_path(0.1)));
|
||||
}
|
||||
ctx.reset_paint_transform();
|
||||
}),
|
||||
PlacedItem::Pattern { index, path, even_odd, tile, region, clips } => clipped(ctx, region.as_deref(), &clips, |ctx| {
|
||||
let Some(Item::Pattern { tile: t, .. }) = v.pic.items.get(index) else { return };
|
||||
ctx.set_fill_rule(if even_odd { peniko::Fill::EvenOdd } else { peniko::Fill::NonZero });
|
||||
// `tile` maps one tile pixel to page points: the tile's sides are its columns and
|
||||
// its rows under that, in device pixels. The tile is drawn when either side is at
|
||||
// least `MIN_TILE_PX`.
|
||||
let c = (view * tile).as_coeffs();
|
||||
let across = c[0].hypot(c[1]) * f64::from(t.width);
|
||||
let down = c[2].hypot(c[3]) * f64::from(t.height);
|
||||
match v.pixmaps.get(index) {
|
||||
Some(Some(pm)) if across.max(down) >= MIN_TILE_PX => {
|
||||
ctx.set_paint(vello_cpu::Image {
|
||||
image: vello_cpu::ImageSource::Pixmap(pm.clone()),
|
||||
sampler: peniko::ImageSampler {
|
||||
x_extend: peniko::Extend::Repeat,
|
||||
y_extend: peniko::Extend::Repeat,
|
||||
quality: peniko::ImageQuality::Low,
|
||||
alpha: 1.0,
|
||||
},
|
||||
});
|
||||
ctx.set_paint_transform(tile);
|
||||
ctx.fill_path(&path);
|
||||
ctx.reset_paint_transform();
|
||||
}
|
||||
_ => {
|
||||
ctx.set_paint(rgba_color(v.averages.get(index).copied().unwrap_or([0; 4])));
|
||||
ctx.fill_path(&path);
|
||||
}
|
||||
}
|
||||
}),
|
||||
PlacedItem::Text { index, transform, clip, region, clips } => {
|
||||
clipped(ctx, region.as_deref(), &clips, |ctx| {
|
||||
let Some(Item::Text(t)) = v.pic.items.get(index) else { return };
|
||||
if let Some(c) = clip {
|
||||
ctx.push_clip_layer(&c.to_path(0.1));
|
||||
}
|
||||
draw_vector_text(ctx, t, view * transform);
|
||||
ctx.set_transform(view);
|
||||
if clip.is_some() {
|
||||
ctx.pop_layer();
|
||||
}
|
||||
});
|
||||
ctx.set_transform(view);
|
||||
}
|
||||
}
|
||||
@@ -253,15 +410,76 @@ pub(crate) fn draw_vector(ctx: &mut RenderContext, v: &Vector, r: &kurbo::Rect,
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws a metafile text run: `tf` maps the run's own space (see [`PlacedItem::Text`]) to the device.
|
||||
/// Draws `draw` inside a metafile item's clip region and every one of its clip paths (page
|
||||
/// points, under the current transform). No region is the default clip.
|
||||
fn clipped(
|
||||
ctx: &mut RenderContext,
|
||||
region: Option<&kurbo::BezPath>,
|
||||
clips: &[Arc<craft_metafile::PlacedClip>],
|
||||
draw: impl FnOnce(&mut RenderContext),
|
||||
) {
|
||||
if let Some(region) = region {
|
||||
ctx.set_fill_rule(peniko::Fill::NonZero);
|
||||
ctx.push_clip_layer(region);
|
||||
}
|
||||
for c in clips {
|
||||
ctx.set_fill_rule(if c.even_odd { peniko::Fill::EvenOdd } else { peniko::Fill::NonZero });
|
||||
ctx.push_clip_layer(&c.path);
|
||||
}
|
||||
ctx.set_fill_rule(peniko::Fill::NonZero);
|
||||
draw(ctx);
|
||||
for _ in 0..clips.len() + usize::from(region.is_some()) {
|
||||
ctx.pop_layer();
|
||||
}
|
||||
}
|
||||
|
||||
/// A metafile pen for `path` as a stroke `width` wide (page points, at least one device `pixel`):
|
||||
/// its caps, joins, miter limit and dashes (`wordcraft_layout::metafile_dashes`).
|
||||
fn pen(width: f64, pixel: f64, line: &craft_metafile::LineStyle, path: &kurbo::BezPath) -> kurbo::Stroke {
|
||||
let cap = match line.cap {
|
||||
craft_metafile::Cap::Round => kurbo::Cap::Round,
|
||||
craft_metafile::Cap::Square => kurbo::Cap::Square,
|
||||
craft_metafile::Cap::Flat => kurbo::Cap::Butt,
|
||||
};
|
||||
let join = match line.join {
|
||||
craft_metafile::Join::Round => kurbo::Join::Round,
|
||||
craft_metafile::Join::Bevel => kurbo::Join::Bevel,
|
||||
craft_metafile::Join::Miter => kurbo::Join::Miter,
|
||||
};
|
||||
let stroke = kurbo::Stroke::new(width.max(pixel))
|
||||
.with_caps(cap)
|
||||
.with_join(join)
|
||||
.with_miter_limit(f64::from(wordcraft_layout::metafile_miter_limit(line.miter_limit)));
|
||||
if line.dash.is_empty() {
|
||||
return stroke;
|
||||
}
|
||||
match wordcraft_layout::metafile_dashes(&line.dash, width == 0.0, pixel, path.perimeter(1.0)) {
|
||||
Some(dash) => stroke.with_dashes(0.0, dash),
|
||||
None => stroke,
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws a metafile text run: `tf` maps its text space (`craft_metafile::Text::transform`) to the
|
||||
/// device.
|
||||
fn draw_vector_text(ctx: &mut RenderContext, t: &craft_metafile::Text, tf: Affine) {
|
||||
let (face, shaped) = wordcraft_layout::metafile_text_run(t);
|
||||
let glyphs: Vec<_> = shaped.iter().map(|g| (g.cluster, f64::from(g.x_advance), f64::from(g.x_offset), f64::from(g.y_offset))).collect();
|
||||
let Some(lay) = wordcraft_layout::layout_metafile_text(t, face.upem, face.ascent, face.descent, &glyphs) else { return };
|
||||
let k = lay.em / face.upem.max(1.0);
|
||||
let canvas = kurbo::Rect::new(0.0, 0.0, f64::from(ctx.width()), f64::from(ctx.height()));
|
||||
// An opaque background mode fills the character cells first.
|
||||
if let Some(bg) = t.background {
|
||||
let [x0, y0, x1, y1] = lay.cell;
|
||||
let cell = tf * kurbo::Rect::new(x0, y0, x1, y1).to_path(0.1);
|
||||
let b = cell.bounding_box();
|
||||
if x1 > x0 && [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_GLYPH_PIXELS * 16.0) && b.overlaps(canvas) {
|
||||
ctx.set_transform(Affine::IDENTITY);
|
||||
ctx.set_paint(rgba_color(bg));
|
||||
ctx.fill_path(&cell);
|
||||
}
|
||||
}
|
||||
ctx.set_paint(rgba_color(t.color));
|
||||
let db = FontDb::global();
|
||||
let canvas = kurbo::Rect::new(0.0, 0.0, f64::from(ctx.width()), f64::from(ctx.height()));
|
||||
let mut oversized = 0usize;
|
||||
for (g, (x, y)) in shaped.iter().zip(&lay.glyphs) {
|
||||
let o = db.outline(&face, g.gid);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::*;
|
||||
use crate::media::fit_cache;
|
||||
use wordcraft_layout::display::page_display;
|
||||
use wordcraft_layout::{LayoutCache, LayoutOptions, layout};
|
||||
|
||||
@@ -1041,6 +1042,393 @@ fn metafile_picture_is_drawn_as_vectors() {
|
||||
assert!(left[..3].iter().all(|c| *c > 200), "left half should be paper, not the grey box: {left:?}");
|
||||
}
|
||||
|
||||
/// An EMF whose only record is one `w` x `h` 1 bpp black and white bitmap over the whole picture.
|
||||
fn emf_with_1bpp_bitmap(w: i32, h: i32) -> Vec<u8> {
|
||||
let mut hdr = vec![0u8; 88];
|
||||
hdr[0..4].copy_from_slice(&1u32.to_le_bytes());
|
||||
hdr[4..8].copy_from_slice(&88u32.to_le_bytes());
|
||||
hdr[8..24].copy_from_slice(&le32(&[0, 0, 100, 100]));
|
||||
hdr[24..40].copy_from_slice(&le32(&[0, 0, 2500, 2500]));
|
||||
hdr[40..44].copy_from_slice(&0x464D_4520u32.to_le_bytes());
|
||||
hdr[72..88].copy_from_slice(&le32(&[1000, 1000, 250, 250]));
|
||||
let stride = (w as usize).div_ceil(32) * 4;
|
||||
let mut payload = vec![0u8; 16];
|
||||
payload.extend(le32(&[0, 0, 0, 0, w, h, 80, 48, 128, (stride * h as usize) as i32, 0, 0x00CC_0020, 100, 100]));
|
||||
payload.extend(le32(&[40, w, h, 1 | (1 << 16), 0, 0, 0, 0, 0, 0]));
|
||||
payload.extend([0, 0, 0, 0, 255, 255, 255, 0]);
|
||||
payload.extend((0..stride * h as usize).map(|i| (i * 31) as u8));
|
||||
[hdr, emf_rec(81, &payload), emf_rec(14, &[0; 12])].concat()
|
||||
}
|
||||
|
||||
/// #5482: a metafile whose bitmaps are past the whole cache budget was parsed and decoded again on
|
||||
/// every repaint, because the cache refused it. It is now kept (its bitmaps at a smaller size).
|
||||
#[test]
|
||||
fn a_metafile_with_a_huge_bitmap_is_parsed_once() {
|
||||
// 8000 x 5000 is 160 MB of RGBA, past the 128 MB cache, from a 5 MB file.
|
||||
let mut d = Document::new();
|
||||
// A key of its own: the vector cache is global and tests running in threads share `image1.emf`.
|
||||
let key = "huge-parsed-once.emf";
|
||||
d.media.insert(key.to_string(), Arc::new(emf_with_1bpp_bitmap(8000, 5000)));
|
||||
let first = vector_for(&d, key).expect("the metafile reads");
|
||||
let again = vector_for(&d, key).expect("the metafile reads");
|
||||
assert!(Arc::ptr_eq(&first, &again), "the second repaint reuses the parsed picture");
|
||||
assert!(first.bytes() <= CACHE_BYTES / 8, "{} bytes", first.bytes());
|
||||
}
|
||||
|
||||
/// Several huge metafiles on screen together (zoomed-out pages, thumbnails) sit side by side in the
|
||||
/// cache instead of clearing it, so a small metafile drawn with them stays a hit.
|
||||
#[test]
|
||||
fn huge_metafiles_do_not_push_a_small_one_out_of_the_cache() {
|
||||
let mut d = Document::new();
|
||||
let small = "evict-small.emf";
|
||||
d.media.insert(small.to_string(), Arc::new(emf_with_1bpp_bitmap(64, 64)));
|
||||
let huge: Vec<String> = (0..4).map(|n| format!("evict-huge-{n}.emf")).collect();
|
||||
for (n, k) in huge.iter().enumerate() {
|
||||
// Distinct bytes per file (the width differs; 8000 x 5000 is the most pixels a metafile decodes), so each is its own cache entry.
|
||||
d.media.insert(k.clone(), Arc::new(emf_with_1bpp_bitmap(8000 - n as i32, 5000)));
|
||||
}
|
||||
let small_first = vector_for(&d, small).expect("the small metafile reads");
|
||||
for round in 0..2 {
|
||||
for k in &huge {
|
||||
assert!(vector_for(&d, k).is_some(), "round {round}");
|
||||
}
|
||||
}
|
||||
let kept: Vec<_> = huge.iter().map(|k| vector_for(&d, k).unwrap()).collect();
|
||||
let again: Vec<_> = huge.iter().map(|k| vector_for(&d, k).unwrap()).collect();
|
||||
for (a, b) in kept.iter().zip(&again) {
|
||||
assert!(Arc::ptr_eq(a, b), "a huge metafile is parsed once while four are drawn together");
|
||||
}
|
||||
assert!(Arc::ptr_eq(&small_first, &vector_for(&d, small).unwrap()), "the small metafile is still cached");
|
||||
}
|
||||
|
||||
/// Time of three repaints of a picture with a 160 MB bitmap:
|
||||
/// `cargo test -p wordcraft-render --release -- --ignored --nocapture huge_metafile_repaint_time`.
|
||||
#[test]
|
||||
#[ignore = "timing only"]
|
||||
fn huge_metafile_repaint_time() {
|
||||
let mut d = Document::new();
|
||||
let key = d.add_media(emf_with_1bpp_bitmap(8000, 5000), "emf");
|
||||
for n in 1..=4 {
|
||||
let t = std::time::Instant::now();
|
||||
assert!(vector_for(&d, &key).is_some());
|
||||
eprintln!("repaint {n}: vector_for {:.1} ms", t.elapsed().as_secs_f64() * 1e3);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitmaps_are_shrunk_in_proportion_only_when_the_picture_is_past_the_cache() {
|
||||
let px = vello_cpu::color::PremulRgba8 { r: 1, g: 2, b: 3, a: 255 };
|
||||
let pm = |w: u16, h: u16| Some(Pixmap::from_parts(vec![px; usize::from(w) * usize::from(h)], w, h));
|
||||
let bytes = |v: &[Option<Pixmap>]| v.iter().flatten().map(|p| usize::from(p.width()) * usize::from(p.height()) * 4).sum::<usize>();
|
||||
// Within the budget: untouched.
|
||||
let kept = fit_cache(vec![pm(1000, 1000), None, pm(2000, 2000)], 1_000_000);
|
||||
assert_eq!(kept.iter().flatten().map(|p| (p.width(), p.height())).collect::<Vec<_>>(), [(1000, 1000), (2000, 2000)]);
|
||||
assert!(kept[1].is_none(), "a path item keeps its place in the list");
|
||||
// A 144 MB and a 36 MB bitmap: both shrink by the same factor.
|
||||
let fit = fit_cache(vec![pm(6000, 6000), pm(3000, 3000)], 4_000_000);
|
||||
assert!(bytes(&fit) + 4_000_000 <= CACHE_BYTES / 8, "{} bytes", bytes(&fit));
|
||||
let (a, b) = (fit[0].as_ref().unwrap(), fit[1].as_ref().unwrap());
|
||||
assert_eq!((a.width(), b.width()), (1500, 750), "each bitmap keeps its share of the pixels that fit");
|
||||
assert!(a.data().iter().all(|p| (p.r, p.g, p.b, p.a) == (1, 2, 3, 255)), "flat stays flat");
|
||||
}
|
||||
|
||||
/// Geometry of an eighth of the budget or more leaves the bitmaps a positive allowance, so the
|
||||
/// picture is still kept (and reused) when it fits the whole budget after shrinking; one whose
|
||||
/// geometry alone fills the budget stays uncached.
|
||||
#[test]
|
||||
fn heavy_geometry_still_leaves_the_bitmaps_a_cacheable_size() {
|
||||
let px = vello_cpu::color::PremulRgba8 { r: 1, g: 2, b: 3, a: 255 };
|
||||
let pm = |w: u16, h: u16| Some(Pixmap::from_parts(vec![px; usize::from(w) * usize::from(h)], w, h));
|
||||
let bytes = |v: &[Option<Pixmap>]| v.iter().flatten().map(|p| usize::from(p.width()) * usize::from(p.height()) * 4).sum::<usize>();
|
||||
let geometry = CACHE_BYTES / 8 + 4_000_000;
|
||||
let fit = fit_cache(vec![pm(6000, 6000)], geometry);
|
||||
let size = bytes(&fit);
|
||||
assert!(size > 0 && size < 6000 * 6000 * 4, "shrunk, not dropped: {size} bytes");
|
||||
assert!(size + geometry <= CACHE_BYTES, "{size} bytes");
|
||||
// The shrunk picture is accepted by the cache and hit again.
|
||||
let src = Arc::new(vec![0u8; 1]);
|
||||
let mut c: MediaCache<u8> = MediaCache { map: Default::default(), bytes: 0 };
|
||||
c.insert("heavy", &src, 7, size + geometry);
|
||||
assert_eq!(c.get("heavy", &src), Some(7));
|
||||
// Just under and just over the eighth: both shrink the bitmap to a positive size, none to nothing.
|
||||
for g in [CACHE_BYTES / 8 - 1, CACHE_BYTES / 8, CACHE_BYTES / 8 + 1] {
|
||||
let size = bytes(&fit_cache(vec![pm(6000, 6000)], g));
|
||||
assert!(size > 0 && size < 6000 * 6000 * 4 && size + g <= CACHE_BYTES / 4, "geometry {g}: {size} bytes");
|
||||
}
|
||||
// Geometry that takes the whole budget leaves nothing to shrink to: the bitmap stays as it is.
|
||||
let full = fit_cache(vec![pm(6000, 6000)], CACHE_BYTES);
|
||||
assert_eq!(bytes(&full), 6000 * 6000 * 4);
|
||||
}
|
||||
|
||||
/// #6636: an EMF+ only file (no plain EMF drawing records) whose EmfPlusDrawImage draws a
|
||||
/// 32bppPARGB bitmap over the right half: the bitmap's pixels are drawn.
|
||||
#[test]
|
||||
fn emf_plus_only_bitmap_is_drawn() {
|
||||
// EmfPlusObject 0, an image (type 5): a 2 × 1 bitmap in PixelFormat32bppPARGB, opaque red
|
||||
// and then red at half opacity (premultiplied BGRA 0, 0, 128, 128).
|
||||
let mut image = le32(&[0xDBC0_1002_u32 as i32, 1, 2, 1, 8, 0x000E_200B, 0]);
|
||||
image.extend([0u8, 0, 255, 255, 0, 0, 128, 128]);
|
||||
let object = plus_rec(0x4008, 0x0500, &image);
|
||||
// EmfPlusDrawImage of image 0: the whole bitmap (pixel units) into x 50..100, y 0..100.
|
||||
let mut draw = le32(&[-1, 2]);
|
||||
draw.extend([0.0f32, 0.0, 2.0, 1.0, 50.0, 0.0, 50.0, 100.0].iter().flat_map(|v| v.to_le_bytes()));
|
||||
let emf = emf_plus_file(&[object, plus_rec(0x401A, 0, &draw)]);
|
||||
|
||||
let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0);
|
||||
let at = |fx: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * 0.5) as u32);
|
||||
let (opaque, half, left) = (at(0.6), at(0.9), at(0.25));
|
||||
assert!(is_red(opaque), "the bitmap's opaque red is drawn on the right half: {opaque:?}");
|
||||
// Premultiplied half-opacity red over white paper is (255, 127, 127); read as straight
|
||||
// color it would be about (191, 127, 127).
|
||||
assert!(half[0] > 235 && (110..145).contains(&half[1]) && (110..145).contains(&half[2]), "half-opacity red: {half:?}");
|
||||
assert!(is_paper(left), "left half should be paper: {left:?}");
|
||||
}
|
||||
|
||||
/// #6636: EmfPlusDrawImage draws a bitmap in PixelFormat32bppARGB, 24bppRGB and 32bppRGB, and a
|
||||
/// compressed PNG or JPEG bitmap, in an EMF+ only file.
|
||||
#[test]
|
||||
fn emf_plus_only_bitmap_formats_are_drawn() {
|
||||
let encoded = |png: bool| {
|
||||
let red = [255u8, 0, 0].repeat(64);
|
||||
if png {
|
||||
let img = image::RgbImage::from_raw(8, 8, red).unwrap();
|
||||
wordcraft_geom::picture::encode_png(&image::DynamicImage::from(img)).unwrap()
|
||||
} else {
|
||||
wordcraft_geom::picture::encode_jpeg(&red, 8, 8, 100).unwrap()
|
||||
}
|
||||
};
|
||||
// Name, width, height, stride, pixel format, bitmap type (0 pixels, 1 compressed) and data.
|
||||
let cases: [(&str, i32, i32, i32, u32, i32, Vec<u8>); 5] = [
|
||||
("32bppARGB", 2, 1, 8, 0x0026_200A, 0, [0u8, 0, 255, 255].repeat(2)),
|
||||
("24bppRGB", 2, 1, 8, 0x0002_1808, 0, vec![0, 0, 255, 0, 0, 255, 0, 0]),
|
||||
("32bppRGB", 2, 1, 8, 0x0002_2009, 0, [0u8, 0, 255, 0].repeat(2)),
|
||||
("PNG", 8, 8, 0, 0, 1, encoded(true)),
|
||||
("JPEG", 8, 8, 0, 0, 1, encoded(false)),
|
||||
];
|
||||
for (name, w, h, stride, format, kind, data) in cases {
|
||||
let mut image = le32(&[0xDBC0_1002_u32 as i32, 1, w, h, stride, format as i32, kind]);
|
||||
image.extend(data);
|
||||
// Records are a multiple of 4 bytes long.
|
||||
image.resize(image.len().next_multiple_of(4), 0);
|
||||
let mut draw = le32(&[-1, 2]);
|
||||
draw.extend([0.0f32, 0.0, w as f32, h as f32, 50.0, 0.0, 50.0, 100.0].iter().flat_map(|v| v.to_le_bytes()));
|
||||
let emf = emf_plus_file(&[plus_rec(0x4008, 0x0500, &image), plus_rec(0x401A, 0, &draw)]);
|
||||
|
||||
let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0);
|
||||
let at = |fx: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * 0.5) as u32);
|
||||
let (right, left) = (at(0.75), at(0.25));
|
||||
assert!(is_red(right), "{name}: the red bitmap is drawn on the right half: {right:?}");
|
||||
assert!(is_paper(left), "{name}: left half should be paper: {left:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An EMF+ record for [`emf_plus_file`]: type, flags and data.
|
||||
fn plus_rec(typ: u16, flags: u16, data: &[u8]) -> Vec<u8> {
|
||||
let mut v = typ.to_le_bytes().to_vec();
|
||||
v.extend(flags.to_le_bytes());
|
||||
v.extend(((12 + data.len()) as u32).to_le_bytes());
|
||||
v.extend((data.len() as u32).to_le_bytes());
|
||||
v.extend(data);
|
||||
v
|
||||
}
|
||||
|
||||
/// An EMF+ only file with the frame of [`red_right_half_emf`]: an EmfPlusHeader (96 dpi), then
|
||||
/// `records`, then EmfPlusEndOfFile, in one comment record.
|
||||
fn emf_plus_file(records: &[Vec<u8>]) -> Vec<u8> {
|
||||
let mut comment = 0x2B46_4D45u32.to_le_bytes().to_vec();
|
||||
comment.extend(plus_rec(0x4001, 0, &le32(&[0xDBC0_1002_u32 as i32, 1, 96, 96])));
|
||||
comment.extend(records.concat());
|
||||
comment.extend(plus_rec(0x4002, 0, &[]));
|
||||
let mut payload = (comment.len() as u32).to_le_bytes().to_vec();
|
||||
payload.extend(comment);
|
||||
let mut emf = red_right_half_emf()[..88].to_vec();
|
||||
emf.extend([emf_rec(70, &payload), emf_rec(14, &[0; 12])].concat());
|
||||
emf
|
||||
}
|
||||
|
||||
/// Renders a document holding one 70 pt metafile picture with `crop` at `scale`: the page and the
|
||||
/// picture's frame (points).
|
||||
fn emf_on_page(emf: Vec<u8>, crop: [f32; 4], scale: f32) -> (Rendered, wordcraft_geom::Rect) {
|
||||
emf_on_page_sized(emf, (70.0, 70.0), crop, scale)
|
||||
}
|
||||
|
||||
/// [`emf_on_page`] with the picture `size` (points).
|
||||
fn emf_on_page_sized(emf: Vec<u8>, size: (f32, f32), crop: [f32; 4], scale: f32) -> (Rendered, wordcraft_geom::Rect) {
|
||||
let mut d = Document::new();
|
||||
let media = d.add_media(emf, "emf");
|
||||
let mut p = wordcraft_doc::Paragraph::new();
|
||||
let obj = wordcraft_doc::para::InlineObject::Image {
|
||||
media,
|
||||
w: size.0,
|
||||
h: size.1,
|
||||
alt: String::new(),
|
||||
float: Default::default(),
|
||||
crop,
|
||||
fx: Default::default(),
|
||||
ole: None,
|
||||
};
|
||||
p.insert_object(0, obj, &Default::default()).unwrap();
|
||||
d.body = vec![wordcraft_doc::para_block(p)];
|
||||
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
|
||||
let opts = RenderOptions::default();
|
||||
let rect = page_display(&d, &l.pages[0], &opts.display)
|
||||
.iter()
|
||||
.find_map(|i| match i {
|
||||
Draw::Image { rect, .. } => Some(*rect),
|
||||
_ => None,
|
||||
})
|
||||
.expect("a picture on the page");
|
||||
(render_page(&d, &l.pages[0], scale, &opts), rect)
|
||||
}
|
||||
|
||||
/// Whether a pixel is close to pure red.
|
||||
fn is_red(p: [u8; 4]) -> bool {
|
||||
p[0] > 200 && p[1] < 60 && p[2] < 60
|
||||
}
|
||||
|
||||
/// Whether a pixel is paper.
|
||||
fn is_paper(p: [u8; 4]) -> bool {
|
||||
p[..3].iter().all(|c| *c > 200)
|
||||
}
|
||||
|
||||
/// A clip region (INTERSECTCLIPRECT to the left half) keeps a red rectangle over the whole
|
||||
/// picture to that half; once RESTOREDC drops it, a second rectangle across the bottom shows on
|
||||
/// both halves.
|
||||
#[test]
|
||||
fn metafile_clip_region_clips_and_ends() {
|
||||
let mut emf = red_right_half_emf()[..88].to_vec();
|
||||
let brush = emf_rec(39, &le32(&[1, 0, 0x0000_00FF, 0]));
|
||||
let recs = [
|
||||
brush,
|
||||
emf_rec(37, &le32(&[1])),
|
||||
emf_rec(33, &[]),
|
||||
emf_rec(30, &le32(&[0, 0, 50, 100])),
|
||||
emf_rec(43, &le32(&[0, 0, 100, 60])),
|
||||
emf_rec(34, &le32(&[-1])),
|
||||
emf_rec(43, &le32(&[0, 80, 100, 100])),
|
||||
emf_rec(14, &[0; 12]),
|
||||
];
|
||||
emf.extend(recs.concat());
|
||||
let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0);
|
||||
let at = |fx: f32, fy: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * fy) as u32);
|
||||
assert!(is_red(at(0.25, 0.3)), "inside the clip: {:?}", at(0.25, 0.3));
|
||||
assert!(is_paper(at(0.75, 0.3)), "outside the clip: {:?}", at(0.75, 0.3));
|
||||
assert!(is_red(at(0.75, 0.9)), "after the clip is restored away: {:?}", at(0.75, 0.9));
|
||||
}
|
||||
|
||||
/// The vector cache counts each item's copy of the clip region: 100 rectangles drawn inside a
|
||||
/// clip region hold 100 copies of its rectangle more than without it.
|
||||
#[test]
|
||||
fn metafile_cache_counts_clip_regions() {
|
||||
let bytes = |clip: bool| {
|
||||
let mut emf = red_right_half_emf()[..88].to_vec();
|
||||
if clip {
|
||||
emf.extend(emf_rec(30, &le32(&[0, 0, 50, 100])));
|
||||
}
|
||||
for i in 0..100 {
|
||||
emf.extend(emf_rec(43, &le32(&[i % 50, 0, i % 50 + 10, 10])));
|
||||
}
|
||||
emf.extend(emf_rec(14, &[0; 12]));
|
||||
media::build_vector(&emf).map(|v| v.bytes())
|
||||
};
|
||||
let (with, without) = (bytes(true).expect("a picture"), bytes(false).expect("a picture"));
|
||||
assert!(with >= without + 100 * 16, "{with} and {without}");
|
||||
}
|
||||
|
||||
/// A hatch tile squeezed to well under a pixel tall but several pixels wide (the picture is 70 pt
|
||||
/// wide and 2 pt tall) keeps its vertical lines: the row crosses red lines and the background
|
||||
/// between them, not one blended color.
|
||||
#[test]
|
||||
fn metafile_narrow_hatch_tile_keeps_its_lines() {
|
||||
let mut emf = red_right_half_emf()[..88].to_vec();
|
||||
let brush = emf_rec(39, &le32(&[1, 2, 0x0000_00FF, 1]));
|
||||
// The stock NULL_PEN leaves the rectangle without an outline.
|
||||
let no_pen = emf_rec(37, &le32(&[0x8000_0008_u32 as i32]));
|
||||
emf.extend([brush, emf_rec(37, &le32(&[1])), no_pen, emf_rec(43, &le32(&[0, 0, 100, 100])), emf_rec(14, &[0; 12])].concat());
|
||||
let (img, rect) = emf_on_page_sized(emf, (70.0, 2.0), [0.0; 4], 1.0);
|
||||
let y = (rect.y + rect.h / 2.0) as u32;
|
||||
let row: Vec<u8> = ((rect.x + 2.0) as u32..(rect.x + rect.w - 2.0) as u32).map(|x| img.pixel(x, y)[1]).collect();
|
||||
assert!(row.iter().any(|g| *g < 160) && row.iter().any(|g| *g > 240), "red lines and background: {row:?}");
|
||||
}
|
||||
|
||||
/// A clip path (a rectangle path over the left half, SELECTCLIPPATH with RGN_COPY) keeps a red
|
||||
/// rectangle over the whole picture to that half.
|
||||
#[test]
|
||||
fn metafile_clip_path_clips() {
|
||||
let mut emf = red_right_half_emf()[..88].to_vec();
|
||||
let brush = emf_rec(39, &le32(&[1, 0, 0x0000_00FF, 0]));
|
||||
let recs = [
|
||||
brush,
|
||||
emf_rec(37, &le32(&[1])),
|
||||
emf_rec(59, &[]),
|
||||
emf_rec(43, &le32(&[0, 0, 50, 100])),
|
||||
emf_rec(60, &[]),
|
||||
emf_rec(67, &le32(&[5])),
|
||||
emf_rec(43, &le32(&[0, 0, 100, 100])),
|
||||
emf_rec(14, &[0; 12]),
|
||||
];
|
||||
emf.extend(recs.concat());
|
||||
let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0);
|
||||
let at = |fx: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * 0.5) as u32);
|
||||
assert!(is_red(at(0.25)), "inside the clip path: {:?}", at(0.25));
|
||||
assert!(is_paper(at(0.75)), "outside the clip path: {:?}", at(0.75));
|
||||
}
|
||||
|
||||
/// A bitmap under a world transform that turns it a quarter turn clockwise about the picture's
|
||||
/// center (EmfPlusSetWorldTransform): its left pixel (red) is drawn at the top and its right pixel
|
||||
/// (blue) at the bottom.
|
||||
#[test]
|
||||
fn emf_plus_turned_bitmap_is_drawn_turned() {
|
||||
let mut image = le32(&[0xDBC0_1002_u32 as i32, 1, 2, 1, 8, 0x000E_200B, 0]);
|
||||
// BGRA: red, then blue.
|
||||
image.extend([0u8, 0, 255, 255, 255, 0, 0, 255]);
|
||||
let turn = plus_rec(0x402A, 0, &[0.0f32, 1.0, -1.0, 0.0, 100.0, 0.0].iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>());
|
||||
let mut draw = le32(&[-1, 2]);
|
||||
draw.extend([0.0f32, 0.0, 2.0, 1.0, 25.0, 25.0, 50.0, 50.0].iter().flat_map(|v| v.to_le_bytes()));
|
||||
let emf = emf_plus_file(&[plus_rec(0x4008, 0x0500, &image), turn, plus_rec(0x401A, 0, &draw)]);
|
||||
let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0);
|
||||
let at = |fx: f32, fy: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * fy) as u32);
|
||||
let (top_right, bottom_left) = (at(0.65, 0.37), at(0.35, 0.62));
|
||||
assert!(is_red(top_right), "red at the top: {top_right:?}");
|
||||
assert!(bottom_left[2] > 200 && bottom_left[0] < 60, "blue at the bottom: {bottom_left:?}");
|
||||
}
|
||||
|
||||
/// A geometric PS_USERSTYLE pen whose dashes and gaps are far below a pixel draws its line solid
|
||||
/// instead of splitting it into dashes too small to see.
|
||||
#[test]
|
||||
fn metafile_sub_pixel_dashes_draw_solid() {
|
||||
let mut emf = red_right_half_emf()[..88].to_vec();
|
||||
// 10,000 device pixels over 250 mm: a device unit is 0.025 mm. The picture is 1000 units wide.
|
||||
emf[8..24].copy_from_slice(&le32(&[0, 0, 1000, 1000]));
|
||||
emf[72..80].copy_from_slice(&le32(&[10_000, 10_000]));
|
||||
// EXTCREATEPEN 1: PS_GEOMETRIC | PS_ENDCAP_FLAT | PS_USERSTYLE, 80 units wide, black, two
|
||||
// entries of 1 unit.
|
||||
let pen = emf_rec(95, &le32(&[1, 0, 0, 0, 0, 0x0001_0207, 80, 0, 0, 0, 2, 1, 1]));
|
||||
let recs = [pen, emf_rec(37, &le32(&[1])), emf_rec(27, &le32(&[0, 500])), emf_rec(54, &le32(&[1000, 500])), emf_rec(14, &[0; 12])];
|
||||
emf.extend(recs.concat());
|
||||
let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0);
|
||||
let y = (rect.y + rect.h * 0.5) as u32;
|
||||
let (x0, x1) = ((rect.x + 5.0) as u32, (rect.x + rect.w - 5.0) as u32);
|
||||
let dark = (x0..x1).filter(|&x| img.pixel(x, y)[..3].iter().all(|c| *c < 60)).count();
|
||||
assert_eq!(dark, (x1 - x0) as usize, "the line is solid black");
|
||||
}
|
||||
|
||||
/// A hatched brush (CREATEBRUSHINDIRECT, BS_HATCHED, HS_VERTICAL) fills with its red lines over
|
||||
/// the background, not with a solid red.
|
||||
#[test]
|
||||
fn metafile_hatch_brush_draws_its_lines() {
|
||||
let mut emf = red_right_half_emf()[..88].to_vec();
|
||||
let brush = emf_rec(39, &le32(&[1, 2, 0x0000_00FF, 1]));
|
||||
emf.extend([brush, emf_rec(37, &le32(&[1])), emf_rec(43, &le32(&[0, 0, 100, 100])), emf_rec(14, &[0; 12])].concat());
|
||||
let scale = 4.0;
|
||||
let (img, rect) = emf_on_page(emf, [0.0; 4], scale);
|
||||
let y = ((rect.y + rect.h / 2.0) * scale) as u32;
|
||||
let (x0, x1) = (((rect.x + 2.0) * scale) as u32, ((rect.x + rect.w - 2.0) * scale) as u32);
|
||||
let red = (x0..x1).filter(|&x| img.pixel(x, y)[1] < 128).count();
|
||||
let n = (x1 - x0) as usize;
|
||||
assert!(red > 0 && red < n * 3 / 4, "the row crosses red lines and the background between them: {red} of {n} red");
|
||||
}
|
||||
|
||||
/// #1899: a crop that keeps a sliver of the picture (3% here; a header's bar can be 2.7% of a
|
||||
/// page-sized metafile) stretches that sliver over the frame, as the file says, for vector and
|
||||
/// bitmap pictures alike. Both pictures are paper on the left half and red on the right.
|
||||
@@ -1084,6 +1472,43 @@ fn a_crop_keeping_a_sliver_fills_the_frame_with_it() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A negative crop side draws as no crop on that side, for vector and bitmap pictures alike: a
|
||||
/// left side of -0.5 does not pad the source, so the frame at 55% shows the source at 55% (red).
|
||||
#[test]
|
||||
fn a_negative_crop_side_draws_uncropped() {
|
||||
let img = image::RgbaImage::from_fn(100, 100, |x, _| image::Rgba(if x >= 50 { [255, 0, 0, 255] } else { [255; 4] }));
|
||||
let png = wordcraft_geom::picture::encode_png(&image::DynamicImage::from(img)).unwrap();
|
||||
for (bytes, ext) in [(red_right_half_emf(), "emf"), (png, "png")] {
|
||||
let mut d = Document::new();
|
||||
let media = d.add_media(bytes, ext);
|
||||
let mut p = wordcraft_doc::Paragraph::new();
|
||||
let obj = wordcraft_doc::para::InlineObject::Image {
|
||||
media,
|
||||
w: 70.0,
|
||||
h: 70.0,
|
||||
alt: String::new(),
|
||||
float: Default::default(),
|
||||
crop: [-0.5, 0.0, 0.0, 0.0],
|
||||
fx: Default::default(),
|
||||
ole: None,
|
||||
};
|
||||
p.insert_object(0, obj, &Default::default()).unwrap();
|
||||
d.body = vec![wordcraft_doc::para_block(p)];
|
||||
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
|
||||
let opts = RenderOptions::default();
|
||||
let rect = page_display(&d, &l.pages[0], &opts.display)
|
||||
.iter()
|
||||
.find_map(|i| match i {
|
||||
Draw::Image { rect, .. } => Some(*rect),
|
||||
_ => None,
|
||||
})
|
||||
.expect("a picture on the page");
|
||||
let img = render_page(&d, &l.pages[0], 1.0, &opts);
|
||||
let px = img.pixel((rect.x + rect.w * 0.55) as u32, (rect.y + rect.h * 0.5) as u32);
|
||||
assert!(is_red(px), "{ext}: {px:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cosmetic_metafile_pen_is_one_device_pixel_wide() {
|
||||
// MOVETO (0, 50), LINETO (100, 50) with the default cosmetic black pen: a hairline across the middle.
|
||||
@@ -1168,6 +1593,29 @@ fn metafile_text_records_are_painted() {
|
||||
assert!(dark > 50, "the text is painted inside the picture: {dark} dark pixels");
|
||||
}
|
||||
|
||||
/// With the opaque background mode (the default) and a red background color (SETBKCOLOR), a text
|
||||
/// run's character cells are filled red behind the black text.
|
||||
#[test]
|
||||
fn metafile_text_fills_its_opaque_background() {
|
||||
let mut font = emf_rec(82, &le32(&[1, -20, 0, 0, 0, 400, 0, 0]));
|
||||
let mut name: Vec<u8> = "Arial".encode_utf16().flat_map(|u| u.to_le_bytes()).collect();
|
||||
name.resize(64, 0);
|
||||
font.extend(name);
|
||||
font[4..8].copy_from_slice(&104u32.to_le_bytes());
|
||||
let mut text = emf_rec(84, &le32(&[0, 0, 100, 100, 1, 0, 0, 5, 40, 4, 76, 0, 0, 0, 0, 0, 0]));
|
||||
text.extend("WWWW".encode_utf16().flat_map(|u| u.to_le_bytes()));
|
||||
text[4..8].copy_from_slice(&84u32.to_le_bytes());
|
||||
let mut emf = red_right_half_emf()[..88].to_vec();
|
||||
let bk = emf_rec(25, &le32(&[0x0000_00FF]));
|
||||
emf.extend([bk, font, emf_rec(37, &le32(&[1])), emf_rec(24, &le32(&[0])), text, emf_rec(14, &[0; 12])].concat());
|
||||
let scale = 2.0;
|
||||
let (img, rect) = emf_on_page(emf, [0.0; 4], scale);
|
||||
let (x0, y0) = ((rect.x * scale) as u32, (rect.y * scale) as u32);
|
||||
let (x1, y1) = (((rect.x + rect.w) * scale) as u32, ((rect.y + rect.h) * scale) as u32);
|
||||
let red = (y0..y1).flat_map(|y| (x0..x1).map(move |x| (x, y))).filter(|&(x, y)| is_red(img.pixel(x, y))).count();
|
||||
assert!(red > 50, "the character cells are filled red: {red} red pixels");
|
||||
}
|
||||
|
||||
/// An EMF text run whose anchor sits inside the picture but whose font is billions of units
|
||||
/// tall: each glyph's curves would span billions of device pixels, which the rasteriser
|
||||
/// subdivides for ever. Glyphs that big (or off the raster) are left out; the page renders.
|
||||
@@ -1528,3 +1976,102 @@ fn undecodable_pictures_keep_their_grey_box_pixels() {
|
||||
let h = img.pixels.iter().fold(0xcbf29ce484222325u64, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x100000001b3));
|
||||
assert_eq!(h, 0x79f9f1d3602a9925, "{h:#x}");
|
||||
}
|
||||
|
||||
/// The cache charge for a metafile's geometry covers what its items keep after their pixels move
|
||||
/// out: a pattern's path and tile, and the clip rectangles and clip paths of every kind of item.
|
||||
/// A tile or clip path shared by several items is charged once.
|
||||
#[test]
|
||||
fn geometry_bytes_counts_pattern_tiles_and_clips_once() {
|
||||
use craft_metafile::{ClipPath, Tile};
|
||||
let segs = |n: usize| vec![Seg::Line(0.0, 0.0); n];
|
||||
let pic = |items: Vec<Item>| Picture { width: 10.0, height: 10.0, items, skipped_records: 0 };
|
||||
let base = crate::media::geometry_bytes(&pic(vec![]));
|
||||
let tile = Arc::new(Tile { width: 1000, height: 1000, rgba: vec![0; 4_000_000], cell: [1.0, 1.0], origin: [0.0, 0.0] });
|
||||
let pattern = |tile: &Arc<Tile>| Item::Pattern { segs: segs(1000), even_odd: false, tile: tile.clone(), region: None, clips: vec![] };
|
||||
let one = crate::media::geometry_bytes(&pic(vec![pattern(&tile)]));
|
||||
assert!(one - base >= 4_000_000 + 1000 * std::mem::size_of::<Seg>(), "{} bytes", one - base);
|
||||
// Two fills of the same brush keep one tile.
|
||||
let two = crate::media::geometry_bytes(&pic(vec![pattern(&tile), pattern(&tile)]));
|
||||
assert!(two - one < 1_000_000, "the shared tile is charged once: {} bytes more", two - one);
|
||||
// A clip path shared by two bitmaps is charged once; a clip region is charged per item.
|
||||
let clip = Arc::new(ClipPath { segs: segs(100_000), even_odd: false });
|
||||
let bitmap = |clips: Vec<Arc<ClipPath>>, region: Option<Vec<[f32; 4]>>| Item::Bitmap {
|
||||
rect: [0.0; 4],
|
||||
transform: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
|
||||
width: 0,
|
||||
height: 0,
|
||||
rgba: vec![],
|
||||
region,
|
||||
clips,
|
||||
};
|
||||
let plain = crate::media::geometry_bytes(&pic(vec![bitmap(vec![], None)]));
|
||||
let clipped = crate::media::geometry_bytes(&pic(vec![bitmap(vec![clip.clone()], None), bitmap(vec![clip.clone()], None)]));
|
||||
let clip_bytes = 100_000 * std::mem::size_of::<Seg>();
|
||||
assert!(clipped - 2 * plain >= clip_bytes && clipped - 2 * plain < 2 * clip_bytes, "{} bytes", clipped - 2 * plain);
|
||||
let region = crate::media::geometry_bytes(&pic(vec![bitmap(vec![], Some(vec![[0.0; 4]; 1000]))]));
|
||||
assert!(region - plain >= 1000 * 16, "{} bytes", region - plain);
|
||||
}
|
||||
|
||||
/// The parser collects segments and dashes without shrinking them, so the charge follows the
|
||||
/// capacity a vector keeps, not only its length.
|
||||
#[test]
|
||||
fn geometry_bytes_charges_the_capacity_of_segment_and_dash_vectors() {
|
||||
use craft_metafile::LineStyle;
|
||||
let pic = |items: Vec<Item>| Picture { width: 10.0, height: 10.0, items, skipped_records: 0 };
|
||||
let path = |segs: Vec<Seg>, dash: Vec<f32>| Item::Path {
|
||||
segs,
|
||||
fill: None,
|
||||
stroke: Some(([0, 0, 0, 255], 1.0)),
|
||||
line: LineStyle { dash, ..LineStyle::default() },
|
||||
even_odd: false,
|
||||
region: None,
|
||||
clips: vec![],
|
||||
};
|
||||
let tight = crate::media::geometry_bytes(&pic(vec![path(vec![Seg::Line(0.0, 0.0); 2], vec![1.0; 2])]));
|
||||
let mut segs = Vec::with_capacity(10_000);
|
||||
segs.extend([Seg::Line(0.0, 0.0); 2]);
|
||||
let mut dash = Vec::with_capacity(1_000);
|
||||
dash.extend([1.0f32; 2]);
|
||||
let slack = crate::media::geometry_bytes(&pic(vec![path(segs, dash)]));
|
||||
assert!(slack - tight >= 9_000 * std::mem::size_of::<Seg>(), "{} bytes more", slack - tight);
|
||||
}
|
||||
|
||||
/// A stroked path keeps its dash array on the heap, and a text item keeps its boxed record and font
|
||||
/// name; the cache charge counts both, so many dashed paths or text records are not under-counted.
|
||||
#[test]
|
||||
fn geometry_bytes_counts_dash_arrays_and_text_records() {
|
||||
use craft_metafile::{Font, HAlign, LineStyle, Text, VAlign};
|
||||
let pic = |items: Vec<Item>| Picture { width: 10.0, height: 10.0, items, skipped_records: 0 };
|
||||
let path = |dash: usize| Item::Path {
|
||||
segs: vec![Seg::Line(0.0, 0.0); 2],
|
||||
fill: None,
|
||||
stroke: Some(([0, 0, 0, 255], 1.0)),
|
||||
line: LineStyle { dash: vec![1.0; dash], ..LineStyle::default() },
|
||||
even_odd: false,
|
||||
region: None,
|
||||
clips: vec![],
|
||||
};
|
||||
let solid = crate::media::geometry_bytes(&pic(vec![path(0)]));
|
||||
let dashed = crate::media::geometry_bytes(&pic(vec![path(16)]));
|
||||
assert_eq!(dashed - solid, 16 * std::mem::size_of::<f32>());
|
||||
let text = |family: &str| {
|
||||
Item::Text(Box::new(Text {
|
||||
transform: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
|
||||
text: "ab".into(),
|
||||
dx: vec![1.0; 2],
|
||||
font: Font { family: family.into(), ..Font::default() },
|
||||
color: [0, 0, 0, 255],
|
||||
background: None,
|
||||
h_align: HAlign::default(),
|
||||
v_align: VAlign::default(),
|
||||
clip: None,
|
||||
region: None,
|
||||
clips: vec![],
|
||||
}))
|
||||
};
|
||||
let bare = crate::media::geometry_bytes(&pic(vec![text("")]));
|
||||
let named = crate::media::geometry_bytes(&pic(vec![text("Some Long Face Name")]));
|
||||
assert_eq!(named - bare, "Some Long Face Name".len());
|
||||
let empty = crate::media::geometry_bytes(&pic(vec![]));
|
||||
assert!(bare - empty >= std::mem::size_of::<Text>(), "the boxed Text struct is charged: {} bytes", bare - empty);
|
||||
}
|
||||
|
||||
@@ -90,7 +90,8 @@ pub fn alt_text(app: &mut WordApp, ui: &mut Ui) {
|
||||
let decorative = obj.is_decorative();
|
||||
ui.label(egui::RichText::new(tl!("Describe what this object shows, for people who can't see it.")).weak());
|
||||
ui.add_space(4.0);
|
||||
if let Some(text) = draft_box(ui, ("alt_obj", &pos), obj.alt_text(), !decorative, true)
|
||||
let label = ui.label(tl!("Description:"));
|
||||
if let Some(text) = draft_box(ui, ("alt_obj", &pos), label.id, obj.alt_text(), !decorative, true)
|
||||
&& still_selected(app, &pos)
|
||||
{
|
||||
let _ = app.run("object.altText", json!({"text": text}));
|
||||
@@ -111,13 +112,13 @@ pub fn alt_text(app: &mut WordApp, ui: &mut Ui) {
|
||||
if let Some((tp, caption, description)) = table {
|
||||
ui.label(egui::RichText::new(tl!("Describe what this table shows, for people who can't see it.")).weak());
|
||||
ui.add_space(4.0);
|
||||
ui.label(tl!("Title:"));
|
||||
if let Some(t) = draft_box(ui, ("alt_table_title", &tp), caption.as_deref().unwrap_or(""), true, false) {
|
||||
let label = ui.label(tl!("Title:"));
|
||||
if let Some(t) = draft_box(ui, ("alt_table_title", &tp), label.id, caption.as_deref().unwrap_or(""), true, false) {
|
||||
let _ = app.run("table.altText", json!({"title": t}));
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
ui.label(tl!("Description:"));
|
||||
if let Some(t) = draft_box(ui, ("alt_table_text", &tp), description.as_deref().unwrap_or(""), true, true) {
|
||||
let label = ui.label(tl!("Description:"));
|
||||
if let Some(t) = draft_box(ui, ("alt_table_text", &tp), label.id, description.as_deref().unwrap_or(""), true, true) {
|
||||
let _ = app.run("table.altText", json!({"text": t}));
|
||||
}
|
||||
return;
|
||||
@@ -131,11 +132,18 @@ fn still_selected(app: &WordApp, pos: &Pos) -> bool {
|
||||
|
||||
/// A text box editing `current`; the draft lives in egui memory while it has focus (frame-local
|
||||
/// buffers lose keystrokes). Returns the new text when editing ends with a change.
|
||||
fn draft_box(ui: &mut Ui, key: impl std::hash::Hash + std::fmt::Debug, current: &str, enabled: bool, multiline: bool) -> Option<String> {
|
||||
fn draft_box(
|
||||
ui: &mut Ui,
|
||||
key: impl std::hash::Hash + std::fmt::Debug,
|
||||
label: egui::Id,
|
||||
current: &str,
|
||||
enabled: bool,
|
||||
multiline: bool,
|
||||
) -> Option<String> {
|
||||
let key = egui::Id::unique(key);
|
||||
let mut text = ui.data(|d| d.get_temp::<String>(key)).unwrap_or_else(|| current.to_string());
|
||||
let edit = if multiline { egui::TextEdit::multiline(&mut text).desired_rows(5) } else { egui::TextEdit::singleline(&mut text) };
|
||||
let r = ui.add_enabled(enabled, edit.desired_width(f32::INFINITY));
|
||||
let r = ui.add_enabled(enabled, edit.desired_width(f32::INFINITY)).labelled_by(label);
|
||||
if r.changed() {
|
||||
ui.data_mut(|d| d.insert_temp(key, text.clone()));
|
||||
}
|
||||
@@ -148,3 +156,70 @@ fn draft_box(ui: &mut Ui, key: impl std::hash::Hash + std::fmt::Debug, current:
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
|
||||
fn harness(app: WordApp) -> egui_kittest::Harness<'static, WordApp> {
|
||||
let mut fonts = false;
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(400.0, 400.0)).build_ui_state(
|
||||
move |ui, app: &mut WordApp| {
|
||||
if fonts {
|
||||
alt_text(app, ui);
|
||||
} else {
|
||||
crate::theme::install_fonts_for(ui.ctx(), false);
|
||||
fonts = true;
|
||||
}
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_description_is_named_commits_and_disables_when_decorative() {
|
||||
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app.run("insert.shape", json!({"kind": "ellipse"})).unwrap();
|
||||
let mut h = harness(app);
|
||||
h.get_by_role_and_label(Role::MultilineTextInput, "Description:").click();
|
||||
h.run_steps(2);
|
||||
h.get_by_role_and_label(Role::MultilineTextInput, "Description:").type_text("A green circle");
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.get_by_role_and_label(Role::MultilineTextInput, "Description:").value().as_deref(), Some("A green circle"));
|
||||
h.get_by_role_and_label(Role::CheckBox, "Mark as decorative").click();
|
||||
h.run_steps(2);
|
||||
let (_, object) = wordcraft_engine::cmd::objects::selected(&h.state().session).unwrap();
|
||||
assert_eq!(object.alt_text(), "A green circle");
|
||||
assert!(object.is_decorative());
|
||||
assert!(h.get_by_role_and_label(Role::MultilineTextInput, "Description:").accesskit_node().is_disabled());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_title_and_description_are_named_and_commit_independently() {
|
||||
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app.run("insert.table", json!({"rows": 1, "cols": 1})).unwrap();
|
||||
let mut h = harness(app);
|
||||
h.get_by_role_and_label(Role::TextInput, "Title:").click();
|
||||
h.run_steps(2);
|
||||
h.get_by_role_and_label(Role::TextInput, "Title:").type_text("Prices");
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.get_by_role_and_label(Role::TextInput, "Title:").value().as_deref(), Some("Prices"));
|
||||
h.get_by_role_and_label(Role::MultilineTextInput, "Description:").click();
|
||||
h.run_steps(2);
|
||||
h.get_by_role_and_label(Role::MultilineTextInput, "Description:").type_text("Prices by year");
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.get_by_role_and_label(Role::MultilineTextInput, "Description:").value().as_deref(), Some("Prices by year"));
|
||||
h.get_by_role_and_label(Role::TextInput, "Title:").click();
|
||||
h.run_steps(2);
|
||||
let app = h.state();
|
||||
let focus = &app.session.sel.focus;
|
||||
let (path, _, _) = focus.path.cell().unwrap();
|
||||
let table = app.session.doc.table(focus.story, &path).unwrap();
|
||||
assert_eq!(table.props.caption.as_deref(), Some("Prices"));
|
||||
assert_eq!(table.props.description.as_deref(), Some("Prices by year"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,7 +58,9 @@ impl WordApp {
|
||||
seen_full_screen,
|
||||
escape_free,
|
||||
status_counts,
|
||||
print_memo,
|
||||
missing_fonts,
|
||||
export_error,
|
||||
last_autosave,
|
||||
equation_prev_tab,
|
||||
smart_art_item,
|
||||
@@ -104,6 +106,7 @@ impl WordApp {
|
||||
clipboard_published: false,
|
||||
printing: Default::default(),
|
||||
print_feedback_seen: None,
|
||||
print_gen: 0,
|
||||
integrated_titlebar: false,
|
||||
mac_titlebar: chrome::MacTitleBar::default(),
|
||||
updates_rt: updates_ui::Runtime::default(),
|
||||
@@ -131,6 +134,8 @@ impl WordApp {
|
||||
fonts_frames: 0,
|
||||
applied_theme: None,
|
||||
native_scale: 1.0,
|
||||
auto_scale_limit: f32::INFINITY,
|
||||
monitor_zoom: 1.0,
|
||||
legacy_interface_size: None,
|
||||
// Inert until the app binary calls `watch_desktop_theme`.
|
||||
desktop_theme: desktop_theme::DesktopTheme::default(),
|
||||
@@ -176,7 +181,9 @@ impl WordApp {
|
||||
seen_full_screen,
|
||||
escape_free,
|
||||
status_counts,
|
||||
print_memo,
|
||||
missing_fonts,
|
||||
export_error,
|
||||
last_autosave,
|
||||
equation_prev_tab,
|
||||
smart_art_item,
|
||||
@@ -301,7 +308,25 @@ impl WordApp {
|
||||
{
|
||||
self.ui.interface_size = theme::migrate_legacy_interface_size(old, native);
|
||||
}
|
||||
let zoom = self.ui.interface_size.zoom_factor(self.native_scale);
|
||||
// Auto never draws larger than the screen holds (#4030): a system that guesses 3× on a
|
||||
// 1366x768 panel would put the window's controls off screen. The zoom is shared by every
|
||||
// window, so the smallest screen of all the open windows sets the cap. A viewport's
|
||||
// `monitor_size` is in points of the zoom in force before a pending change applied, so
|
||||
// its pixels are that size times `monitor_zoom` and the window's own native scale; each window's allowed zoom is its own, the smallest is shared.
|
||||
let monitors: Vec<_> = self
|
||||
.windows
|
||||
.viewport_ids()
|
||||
.into_iter()
|
||||
.filter_map(|v| {
|
||||
ctx.input_for(v, |i| {
|
||||
let info = i.viewport();
|
||||
Some(((info.monitor_size?.x, info.monitor_size?.y), info.native_pixels_per_point?))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
self.auto_scale_limit = theme::auto_scale_limit_over(monitors, self.monitor_zoom, self.native_scale);
|
||||
self.monitor_zoom = ctx.zoom_factor();
|
||||
let zoom = self.ui.interface_size.zoom_factor_within(self.native_scale, self.auto_scale_limit);
|
||||
if ctx.zoom_factor() != zoom {
|
||||
ctx.set_zoom_factor(zoom);
|
||||
}
|
||||
@@ -410,6 +435,15 @@ impl WordApp {
|
||||
/// Pane's Tab keys and dropped files are read in the first UI pass
|
||||
/// ([`WordApp::handle_ui_input_events`]).
|
||||
pub(crate) fn window_input(&mut self, ctx: &egui::Context) {
|
||||
// The way back when a large interface size has pushed File › Options off screen (#4030).
|
||||
// A modal dialog keeps the keys (Customize Keyboard records them), and a command the user
|
||||
// bound to the chord runs instead.
|
||||
if !self.modal_open()
|
||||
&& self.session.keymap.resolve(&self.session.registry, "Mod+Shift+0").is_none()
|
||||
&& ctx.input_mut(super::consume_reset_interface_size)
|
||||
{
|
||||
let _ = self.run("ui.interfaceSize", serde_json::json!({"value": "auto"}));
|
||||
}
|
||||
if self.windows.native() && ctx.input_mut(|i| i.consume_shortcut(&QUIT)) {
|
||||
self.quit();
|
||||
}
|
||||
@@ -468,6 +502,7 @@ impl WordApp {
|
||||
if !self.ui.backstage {
|
||||
backstage::forget_open_error(&ctx);
|
||||
backstage::forget_save_as_error(&ctx);
|
||||
self.export_error.clear();
|
||||
}
|
||||
self.paint_window(ui, &ctx, t);
|
||||
if !moved(self) {
|
||||
|
||||
@@ -145,7 +145,9 @@ impl WordApp {
|
||||
// Web: saving and exporting become downloads.
|
||||
if self.services.download.is_some() && matches!(id, "file.save" | "file.saveAs" | "file.exportPdf" | "file.exportPng") {
|
||||
let name = params.get("path").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| self.web_save_name(id));
|
||||
let name = if id == "file.exportPdf" && !name.ends_with(".pdf") { format!("{name}.pdf") } else { name };
|
||||
// Inspect only the suffix bytes: no full-name allocation or UTF-8 slicing.
|
||||
let has_pdf_suffix = name.as_bytes().last_chunk::<4>().is_some_and(|suffix| suffix.eq_ignore_ascii_case(b".pdf"));
|
||||
let name = if id == "file.exportPdf" && !has_pdf_suffix { format!("{name}.pdf") } else { name };
|
||||
// A save with a password encrypts this and later saves (`file.save`'s `password`).
|
||||
if matches!(id, "file.save" | "file.saveAs")
|
||||
&& let Some(pw) = params.get("password").filter(|v| !v.is_null())
|
||||
@@ -667,7 +669,7 @@ impl WordApp {
|
||||
}
|
||||
}
|
||||
let size = self.ui.interface_size;
|
||||
json!({"auto": size.is_auto(), "percent": size.drawn_percent(self.native_scale)})
|
||||
json!({"auto": size.is_auto(), "percent": size.drawn_percent_within(self.native_scale, self.auto_scale_limit)})
|
||||
}
|
||||
"ui.animations" => {
|
||||
// `system` (follow the system's animation setting), `on` or `off`; no value reads
|
||||
@@ -775,7 +777,7 @@ impl WordApp {
|
||||
json!({"dir": dir})
|
||||
}
|
||||
// The built-in file browser (#576), for when the system's file dialog doesn't show up
|
||||
// (desktop only): `purpose` is document (default), picture, recipients or save. A system
|
||||
// (desktop only): `purpose` is document (default), picture, recipients, save or export. A system
|
||||
// dialog still waiting for an answer is given up as cancelled.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
"ui.fileBrowser" => {
|
||||
|
||||
@@ -320,6 +320,8 @@ impl WordApp {
|
||||
return;
|
||||
}
|
||||
self.print_feedback_seen = self.printing.message.clone();
|
||||
// A new message: what any window said before no longer stands for it.
|
||||
self.print_gen = self.print_gen.wrapping_add(1);
|
||||
let Some(message @ (printing::Feedback::Submitted(_) | printing::Feedback::Failed(_) | printing::Feedback::WorkerStopped)) =
|
||||
self.printing.message.clone()
|
||||
else {
|
||||
@@ -334,6 +336,11 @@ impl WordApp {
|
||||
self.ui.backstage = false;
|
||||
self.canvas.want_focus = true;
|
||||
}
|
||||
// Said only where the status bar is drawn: not under File's other pages, and a failure on
|
||||
// the Print page is the page's to show.
|
||||
if !self.ui.backstage {
|
||||
self.print_memo.said = Some(self.print_gen);
|
||||
}
|
||||
}
|
||||
|
||||
/// Files dropped on the native window. Raw input is taken only in the first UI pass: a
|
||||
|
||||
@@ -759,6 +759,11 @@ fn save_as_page(app: &mut WordApp, ui: &mut Ui) {
|
||||
if ui.button(egui::RichText::new(tl!("Browse…")).font(medium(14.0))).clicked() {
|
||||
app.save_as_dialog();
|
||||
}
|
||||
// Linux and the BSDs (#3535): WordCraft's own browser when the system dialog doesn't appear.
|
||||
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
|
||||
if ui.button(egui::RichText::new(tl!("Browse in WordCraft…")).font(medium(14.0))).clicked() {
|
||||
let _ = app.run("ui.fileBrowser", json!({"purpose": "save"}));
|
||||
}
|
||||
// A Word template in the user templates folder, which File › New lists under Personal (#2852).
|
||||
ui.add_space(8.0);
|
||||
if ui
|
||||
|
||||
@@ -859,6 +859,77 @@ fn save_as_page_shows_browse_and_no_open_list() {
|
||||
assert!(h.query_by_label("Recent").is_none(), "Save As has no list that opens documents");
|
||||
}
|
||||
|
||||
/// #3467, #3535: a system dialog that never shows up doesn't leave Save As stuck: Browse in
|
||||
/// WordCraft… gives it up and saves through WordCraft's own browser.
|
||||
#[test]
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn save_as_saves_in_wordcraft_when_the_system_dialog_never_shows() {
|
||||
// A host that takes every request and never answers, like a portal that shows nothing.
|
||||
let senders: std::rc::Rc<std::cell::RefCell<Vec<std::sync::mpsc::Sender<crate::FileDialogAnswer>>>> = Default::default();
|
||||
let keep = senders.clone();
|
||||
let services = Services {
|
||||
file_dialog: Some(Box::new(move |_| {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
keep.borrow_mut().push(tx);
|
||||
rx
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-backstage-builtin-save-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), services);
|
||||
a.run("text.insert", json!({"text": "Saved past a silent portal"})).unwrap();
|
||||
a.run("ui.backstage", json!({"value": true, "page": "saveAs"})).unwrap();
|
||||
let mut h = egui_kittest::Harness::builder().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);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(4);
|
||||
h.get_by_label("Browse…").click();
|
||||
h.run_steps(4);
|
||||
assert!(h.state().file_dialog.is_some(), "the system dialog was asked for and never answered");
|
||||
h.get_by_label("Browse in WordCraft…").click();
|
||||
h.run_steps(4);
|
||||
let a = h.state_mut();
|
||||
assert!(a.file_dialog.is_none(), "the silent system dialog is given up");
|
||||
let b = a.file_browser.open.as_mut().expect("WordCraft's own browser is open");
|
||||
b.navigate(dir.clone());
|
||||
b.name = "kept".into();
|
||||
let crate::file_browser::Step::Pick(path) = b.accept() else { panic!("picked") };
|
||||
a.close_file_browser(Some(path));
|
||||
let saved = dir.join("kept.docx");
|
||||
assert_eq!(a.session.path.as_deref(), Some(saved.as_path()));
|
||||
let back = wordcraft_engine::io::open_path(&saved).unwrap();
|
||||
assert!(back.plain_text(wordcraft_doc::StoryRef::Body).contains("Saved past a silent portal"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #3535: File › Export offers WordCraft's own browser as well, for its formats.
|
||||
#[test]
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn export_page_offers_wordcrafts_own_browser() {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
|
||||
a.run("ui.backstage", json!({"value": true, "page": "export"})).unwrap();
|
||||
let mut h = egui_kittest::Harness::builder().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);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(4);
|
||||
h.get_by_label("Browse in WordCraft…").click();
|
||||
h.run_steps(4);
|
||||
let b = h.state().file_browser.open.as_ref().expect("WordCraft's own browser is open");
|
||||
assert!(matches!(&b.after, crate::file_dialogs::AfterPick::Export { ext } if ext == "pdf"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backstage_save_navigates_to_save_as_when_unnamed() {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
|
||||
@@ -1292,3 +1363,106 @@ fn rtl_template_titles_are_right_aligned() {
|
||||
wide_text_right,
|
||||
);
|
||||
}
|
||||
|
||||
/// A refused Word XML export (the typed name's `.xml` twin already exists) is said on the Export
|
||||
/// page itself: Backstage hides the status bar, so the person would otherwise see nothing.
|
||||
#[test]
|
||||
fn export_refusal_shows_on_the_export_page() {
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-backstage-export-error-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("letter.xml"), "taken").unwrap();
|
||||
let bare = dir.join("letter").to_string_lossy().into_owned();
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
|
||||
a.run("text.insert", json!({"text": "Dear reader"})).unwrap();
|
||||
a.run("ui.backstage", json!({"value": true, "page": "export"})).unwrap();
|
||||
let mut h = egui_kittest::Harness::builder().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);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(4);
|
||||
let err = h.state_mut().finish_pick(crate::file_dialogs::AfterPick::Export { ext: "xml".into() }, Some(bare)).unwrap_err();
|
||||
h.run_steps(4);
|
||||
assert!(h.state().ui.backstage, "still on the Export page");
|
||||
assert!(err.contains("letter.xml already exists"), "{err}");
|
||||
h.get_by_label(err.as_str());
|
||||
assert_eq!(std::fs::read_to_string(dir.join("letter.xml")).unwrap(), "taken", "nothing replaced");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A refused Word XML export (the typed name's `.xml` twin already exists) is said on the Export
|
||||
/// page itself: Backstage hides the status bar, so the person would otherwise see nothing.
|
||||
#[test]
|
||||
fn export_refusal_shows_on_the_print_page() {
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-backstage-print-export-error-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("letter.xml"), "taken").unwrap();
|
||||
let bare = dir.join("letter").to_string_lossy().into_owned();
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
|
||||
a.run("text.insert", json!({"text": "Dear reader"})).unwrap();
|
||||
a.run("ui.backstage", json!({"value": true, "page": "print"})).unwrap();
|
||||
let mut h = egui_kittest::Harness::builder().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);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(4);
|
||||
let err = h.state_mut().finish_pick(crate::file_dialogs::AfterPick::Export { ext: "xml".into() }, Some(bare)).unwrap_err();
|
||||
h.run_steps(4);
|
||||
assert!(h.state().ui.backstage, "still on the Print page");
|
||||
assert!(err.contains("letter.xml already exists"), "{err}");
|
||||
h.get_by_label(err.as_str());
|
||||
assert_eq!(std::fs::read_to_string(dir.join("letter.xml")).unwrap(), "taken", "nothing replaced");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A cancelled export dialog drops an earlier refusal: it is not news any more.
|
||||
#[test]
|
||||
fn cancelling_an_export_clears_its_page_error() {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
|
||||
a.export_error = "old refusal".into();
|
||||
a.finish_pick(crate::file_dialogs::AfterPick::Export { ext: "xml".into() }, None).unwrap();
|
||||
assert!(a.export_error.is_empty());
|
||||
}
|
||||
|
||||
/// The export error belongs to the window that refused the export: another window running a
|
||||
/// frame outside Backstage must not erase it while this one still shows the Export page.
|
||||
#[test]
|
||||
fn export_error_belongs_to_its_window() {
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-backstage-export-two-windows-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("letter.xml"), "taken").unwrap();
|
||||
let bare = dir.join("letter").to_string_lossy().into_owned();
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
|
||||
a.run("text.insert", json!({"text": "Dear reader"})).unwrap();
|
||||
a.run("ui.backstage", json!({"value": true, "page": "export"})).unwrap();
|
||||
// Window A (this one) is refused; window B is another window's state, outside Backstage.
|
||||
let mut b = crate::window_ui::WindowUi::new(a.session.document_id());
|
||||
let err = a.finish_pick(crate::file_dialogs::AfterPick::Export { ext: "xml".into() }, Some(bare)).unwrap_err();
|
||||
assert_eq!(a.export_error, err);
|
||||
// B's frame: swap its state in, run frames outside Backstage, swap back.
|
||||
a.swap_window(&mut b);
|
||||
assert!(!a.ui.backstage && a.export_error.is_empty(), "B has its own, empty, error");
|
||||
let mut h = egui_kittest::Harness::builder().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);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(4);
|
||||
h.state_mut().swap_window(&mut b);
|
||||
assert!(h.state().ui.backstage, "A is still on the Export page");
|
||||
assert_eq!(h.state().export_error, err, "B's frames left A's message alone");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -253,6 +253,18 @@ pub struct CanvasState {
|
||||
pub(crate) v_pressed: bool,
|
||||
/// The modifiers last held with Mod, for a Mod+V whose Mod is released before V.
|
||||
pub(crate) paste_mods: Option<egui::Modifiers>,
|
||||
/// The modifiers a paste event is read with: those of Mod+V's press or a Mod change, until an
|
||||
/// unrelated key, a pointer press or a focus change. (`paste_mods` also serves the release path.)
|
||||
pub(crate) paste_event_mods: Option<egui::Modifiers>,
|
||||
/// On the web, Mod+Shift+V pasted formatting from its key press: the browser's paste event
|
||||
/// that follows is the same keystroke and pastes nothing (#5616). Any other key press clears it.
|
||||
pub(crate) ignore_next_paste: bool,
|
||||
/// When `ignore_next_paste` was set (input time, seconds): the browser's paired paste comes
|
||||
/// with the key, so the wait ends after `PASTE_WAIT` and a later paste isn't dropped.
|
||||
pub(crate) paste_wait_since: Option<f64>,
|
||||
/// The platform sends a paste event after Mod+Shift+V's key (a browser does; a desktop shell
|
||||
/// doesn't). Only then does the key leave a paste event to ignore or to let paste text.
|
||||
pub(crate) paste_event_follows_chord: bool,
|
||||
/// Draw Table or Eraser is on (`table_pen`): presses draw instead of moving the caret.
|
||||
pub table_tool: Option<crate::table_pen::TableTool>,
|
||||
/// The Draw Table stroke (or eraser press) in progress.
|
||||
@@ -436,6 +448,10 @@ impl Default for CanvasState {
|
||||
pasted: false,
|
||||
v_pressed: false,
|
||||
paste_mods: None,
|
||||
paste_event_mods: None,
|
||||
ignore_next_paste: false,
|
||||
paste_wait_since: None,
|
||||
paste_event_follows_chord: cfg!(target_arch = "wasm32"),
|
||||
swallow_text: false,
|
||||
ime_join_text: None,
|
||||
ime_reset: false,
|
||||
|
||||
@@ -635,12 +635,12 @@ fn multi_click_drag_extends_by_units() {
|
||||
for _ in 0..6 {
|
||||
h.step();
|
||||
}
|
||||
let screen = |h: &mut egui_kittest::Harness<'_, WordApp>, pos: Pos| {
|
||||
let screen = |h: &mut H, pos: Pos| {
|
||||
let c = h.state_mut().session.layout().caret(&pos).expect("caret");
|
||||
page_to_screen(h.state_mut(), c.page, c.x + 1.0, c.top + c.height / 2.0).expect("on screen")
|
||||
};
|
||||
let button = |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
let multi_drag = |h: &mut egui_kittest::Harness<'_, WordApp>, from: Pos2, to: Pos2, clicks: usize| {
|
||||
let multi_drag = |h: &mut H, from: Pos2, to: Pos2, clicks: usize| {
|
||||
h.event(Event::PointerMoved(from));
|
||||
for i in 0..clicks {
|
||||
h.event(button(from, true));
|
||||
@@ -871,7 +871,7 @@ fn clicking_vertical_scrollbar_track_advances_one_screen() {
|
||||
|
||||
let button = |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
|
||||
let click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: Pos2| {
|
||||
let click = |h: &mut H, at: Pos2| {
|
||||
h.event(Event::PointerMoved(at));
|
||||
h.step();
|
||||
h.event(button(at, true));
|
||||
@@ -939,7 +939,7 @@ fn clicking_vertical_scrollbar_track_advances_one_screen_in_rtl() {
|
||||
|
||||
let button = |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
|
||||
let click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: Pos2| {
|
||||
let click = |h: &mut H, at: Pos2| {
|
||||
h.event(Event::PointerMoved(at));
|
||||
h.step();
|
||||
h.event(button(at, true));
|
||||
@@ -1002,7 +1002,7 @@ fn clicking_thin_vertical_scrollbar_track_advances_one_screen() {
|
||||
|
||||
let button = |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
|
||||
let click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: Pos2| {
|
||||
let click = |h: &mut H, at: Pos2| {
|
||||
h.event(Event::PointerMoved(at));
|
||||
h.step();
|
||||
h.event(button(at, true));
|
||||
@@ -1195,11 +1195,11 @@ fn ctrl_drag_copies_an_object() {
|
||||
for _ in 0..6 {
|
||||
h.step();
|
||||
}
|
||||
let objects = |h: &mut egui_kittest::Harness<'_, WordApp>| {
|
||||
let objects = |h: &mut H| {
|
||||
let doc = &h.state().session.doc;
|
||||
doc.para(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).map_or(0, |p| p.objects.len())
|
||||
};
|
||||
let xs = |h: &mut egui_kittest::Harness<'_, WordApp>| {
|
||||
let xs = |h: &mut H| {
|
||||
let mut v: Vec<i32> = Vec::new();
|
||||
for x in (0..600).step_by(50) {
|
||||
if h.state_mut().session.layout().find_object(0, |o| (o.rect.x - x as f32).abs() < 0.5).is_some() {
|
||||
@@ -1208,7 +1208,7 @@ fn ctrl_drag_copies_an_object() {
|
||||
}
|
||||
v
|
||||
};
|
||||
let drag = |h: &mut egui_kittest::Harness<'_, WordApp>, mods: Modifiers| {
|
||||
let drag = |h: &mut H, mods: Modifiers| {
|
||||
let from = page_to_screen(h.state_mut(), 0, 250.0, 330.0).expect("on screen");
|
||||
let to = page_to_screen(h.state_mut(), 0, 400.0, 330.0).expect("on screen");
|
||||
h.event(Event::ModifiersChanged(mods));
|
||||
@@ -1257,19 +1257,19 @@ fn selection_bar_clicks_select_lines() {
|
||||
h.step();
|
||||
}
|
||||
// A point in the left margin beside the line `li` lines below the one holding `pos`.
|
||||
let margin = |h: &mut egui_kittest::Harness<'_, WordApp>, pos: Pos, li: f32| {
|
||||
let margin = |h: &mut H, pos: Pos, li: f32| {
|
||||
let c = h.state_mut().session.layout().caret(&pos).expect("caret");
|
||||
page_to_screen(h.state_mut(), c.page, 30.0, c.top + c.height * (li + 0.5)).expect("on screen")
|
||||
};
|
||||
let line_start = |h: &mut egui_kittest::Harness<'_, WordApp>, at: Pos2| {
|
||||
let line_start = |h: &mut H, at: Pos2| {
|
||||
let (rects, scale) = (h.state().canvas.page_rects.clone(), h.state().canvas.scale);
|
||||
let layout = h.state_mut().session.layout();
|
||||
let (pg, x, y) = page_at(&rects, &layout, scale, at).expect("page");
|
||||
layout.selection_bar_at(pg, x, y).expect("in the selection bar")
|
||||
};
|
||||
let span = |h: &mut egui_kittest::Harness<'_, WordApp>, pos: &Pos| h.state_mut().session.layout().line_span(pos, 0).expect("line");
|
||||
let span = |h: &mut H, pos: &Pos| h.state_mut().session.layout().line_span(pos, 0).expect("line");
|
||||
let button = |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
let clicks_drag = |h: &mut egui_kittest::Harness<'_, WordApp>, from: Pos2, to: Pos2, clicks: usize| {
|
||||
let clicks_drag = |h: &mut H, from: Pos2, to: Pos2, clicks: usize| {
|
||||
h.event(Event::PointerMoved(from));
|
||||
for i in 0..clicks {
|
||||
h.event(button(from, true));
|
||||
@@ -1288,7 +1288,7 @@ fn selection_bar_clicks_select_lines() {
|
||||
h.step();
|
||||
}
|
||||
};
|
||||
let pause = |h: &mut egui_kittest::Harness<'_, WordApp>| {
|
||||
let pause = |h: &mut H| {
|
||||
for _ in 0..40 {
|
||||
h.step();
|
||||
}
|
||||
@@ -1361,7 +1361,7 @@ fn selection_bar_of_a_right_to_left_paragraph_is_on_the_right() {
|
||||
let y = c.top + c.height / 2.0;
|
||||
let right = page_to_screen(h.state_mut(), c.page, (body_x + page_w) / 2.0, y).expect("on screen");
|
||||
let left = page_to_screen(h.state_mut(), c.page, 30.0, y).expect("on screen");
|
||||
let click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: Pos2| {
|
||||
let click = |h: &mut H, at: Pos2| {
|
||||
h.event(Event::PointerMoved(at));
|
||||
h.step();
|
||||
h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Default::default() });
|
||||
@@ -1408,7 +1408,7 @@ fn an_armed_format_painter_changes_the_pointer() {
|
||||
let c = h.state_mut().session.layout().caret(&Pos::body(0, 6)).expect("caret");
|
||||
let over_text = page_to_screen(h.state_mut(), c.page, c.x, c.top + c.height / 2.0).expect("on screen");
|
||||
let over_bar = page_to_screen(h.state_mut(), c.page, 30.0, c.top + c.height / 2.0).expect("on screen");
|
||||
let pointer_after = |h: &mut egui_kittest::Harness<'_, WordApp>, cmd: Option<&str>| {
|
||||
let pointer_after = |h: &mut H, cmd: Option<&str>| {
|
||||
if let Some(cmd) = cmd {
|
||||
h.state_mut().run(cmd, json!({})).unwrap();
|
||||
}
|
||||
@@ -1493,7 +1493,7 @@ fn an_empty_comment_balloon_deletes() {
|
||||
for _ in 0..6 {
|
||||
h.step();
|
||||
}
|
||||
let click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: egui::Pos2| {
|
||||
let click = |h: &mut H, at: egui::Pos2| {
|
||||
h.event(egui::Event::PointerMoved(at));
|
||||
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() });
|
||||
h.step();
|
||||
@@ -2137,7 +2137,7 @@ fn double_click_margin_creates_header_and_footer() {
|
||||
for _ in 0..6 {
|
||||
h.step();
|
||||
}
|
||||
let double_click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: Pos2| {
|
||||
let double_click = |h: &mut H, at: Pos2| {
|
||||
h.event(Event::PointerMoved(at));
|
||||
for _ in 0..2 {
|
||||
h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Default::default() });
|
||||
@@ -2150,7 +2150,7 @@ fn double_click_margin_creates_header_and_footer() {
|
||||
h.step();
|
||||
}
|
||||
};
|
||||
let kind = |h: &egui_kittest::Harness<'_, WordApp>| part_kind(h.state(), h.state().session.sel.focus.story);
|
||||
let kind = |h: &H| part_kind(h.state(), h.state().session.sel.focus.story);
|
||||
let page = h.state_mut().session.layout().pages[0].clone();
|
||||
assert!(page.header_story.is_none() && page.footer_story.is_none());
|
||||
let (x, top, bottom) = (page.body.x + 20.0, page.body.y / 2.0, (page.body.bottom() + page.h) / 2.0);
|
||||
@@ -2250,7 +2250,7 @@ fn double_click_switches_between_header_and_footer() {
|
||||
for _ in 0..6 {
|
||||
h.step();
|
||||
}
|
||||
let double_click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: Pos2| {
|
||||
let double_click = |h: &mut H, at: Pos2| {
|
||||
h.event(Event::PointerMoved(at));
|
||||
for _ in 0..2 {
|
||||
h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Default::default() });
|
||||
@@ -2262,7 +2262,7 @@ fn double_click_switches_between_header_and_footer() {
|
||||
h.step();
|
||||
}
|
||||
};
|
||||
let kind = |h: &egui_kittest::Harness<'_, WordApp>| part_kind(h.state(), h.state().session.sel.focus.story);
|
||||
let kind = |h: &H| part_kind(h.state(), h.state().session.sel.focus.story);
|
||||
let page = h.state_mut().session.layout().pages[0].clone();
|
||||
let (x, top, bottom) = (page.body.x + 20.0, page.body.y / 2.0, (page.body.bottom() + page.h) / 2.0);
|
||||
let head_at = page_to_screen(h.state_mut(), 0, x, top).expect("top margin on screen");
|
||||
@@ -2885,7 +2885,7 @@ fn control_click_on_macos_opens_the_context_menu() {
|
||||
h.step();
|
||||
let ctrl = egui::Modifiers { ctrl: true, ..Default::default() };
|
||||
// The events winit delivers for a Control-click, through the app's input hook as eframe runs it.
|
||||
let send = |h: &mut egui_kittest::Harness<'_, WordApp>, events: Vec<egui::Event>| {
|
||||
let send = |h: &mut H, events: Vec<egui::Event>| {
|
||||
let mut raw = egui::RawInput { events, ..Default::default() };
|
||||
let ctx = h.ctx.clone();
|
||||
h.state_mut().raw_input_hook(&ctx, &mut raw);
|
||||
@@ -2973,7 +2973,10 @@ fn drag_floating_picture(wrap: &str, header: bool, preselect: bool) {
|
||||
for _ in 0..3 {
|
||||
h.step();
|
||||
}
|
||||
assert!(wordcraft_engine::cmd::objects::object_selection(&h.state().session).is_none(), "a click still selects text");
|
||||
// In the header the picture lies over the body area, clear of the header's own text, so a
|
||||
// click on it selects it (Word); in the body a click still reaches the text behind it.
|
||||
let picked = wordcraft_engine::cmd::objects::object_selection(&h.state().session).is_some();
|
||||
assert_eq!(picked, header, "a click selects the header's picture, but only edits the body's text");
|
||||
if preselect {
|
||||
let end = Pos { off: pos.off + wordcraft_doc::para::OBJ.len_utf8(), ..pos.clone() };
|
||||
h.state_mut().run("select.range", json!({"anchor": pos, "focus": end})).unwrap();
|
||||
@@ -3138,7 +3141,7 @@ fn right_clicking_a_link_hides_the_hover_tooltip() {
|
||||
let at = screen(&mut h, c.x, c.top + c.height / 2.0);
|
||||
h.event(egui::Event::PointerMoved(at));
|
||||
steps(&mut h, 2);
|
||||
let tips = |h: &egui_kittest::Harness<'_, WordApp>| h.query_all_by_label_contains("Click to follow link").count();
|
||||
let tips = |h: &H| h.query_all_by_label_contains("Click to follow link").count();
|
||||
assert!(tips(&h) > 0, "hovering the link shows its target");
|
||||
for pressed in [true, false] {
|
||||
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() });
|
||||
@@ -3171,7 +3174,7 @@ fn a_handled_press_skips_the_link_tooltip() {
|
||||
let at = screen(&mut h, c.x, c.top + c.height / 2.0);
|
||||
h.event(Event::PointerMoved(at));
|
||||
steps(&mut h, 2);
|
||||
let tips = |h: &egui_kittest::Harness<'_, WordApp>| h.query_all_by_label_contains("Click to follow link").count();
|
||||
let tips = |h: &H| h.query_all_by_label_contains("Click to follow link").count();
|
||||
assert!(tips(&h) > 0, "hovering the link shows its target");
|
||||
h.event(Event::ModifiersChanged(Modifiers::COMMAND));
|
||||
h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::COMMAND });
|
||||
@@ -4029,13 +4032,13 @@ fn ruler_tab_gestures_are_primary_only_and_cancellable() {
|
||||
h.step();
|
||||
}
|
||||
let area = h.state().canvas.canvas_rect.expect("the canvas is laid out");
|
||||
let ruler_x = |h: &mut egui_kittest::Harness<'_, WordApp>, d: f32| {
|
||||
let ruler_x = |h: &mut H, d: f32| {
|
||||
let body_x = h.state_mut().session.layout().pages[0].body.x;
|
||||
page_to_screen(h.state_mut(), 0, body_x + d, 0.0).expect("on screen").x
|
||||
};
|
||||
let on_ruler = |h: &mut egui_kittest::Harness<'_, WordApp>, d: f32| pos2(ruler_x(h, d), area.min.y - 7.0);
|
||||
let on_ruler = |h: &mut H, d: f32| pos2(ruler_x(h, d), area.min.y - 7.0);
|
||||
let button = |at: Pos2, b: PointerButton, pressed: bool| Event::PointerButton { pos: at, button: b, pressed, modifiers: Default::default() };
|
||||
let drag_events = |h: &mut egui_kittest::Harness<'_, WordApp>, from: Pos2, to: Pos2, b: PointerButton| {
|
||||
let drag_events = |h: &mut H, from: Pos2, to: Pos2, b: PointerButton| {
|
||||
h.event(Event::PointerMoved(from));
|
||||
h.event(button(from, b, true));
|
||||
h.step();
|
||||
@@ -4048,7 +4051,7 @@ fn ruler_tab_gestures_are_primary_only_and_cancellable() {
|
||||
h.step();
|
||||
}
|
||||
};
|
||||
let stops_of = |h: &egui_kittest::Harness<'_, WordApp>, block: usize| {
|
||||
let stops_of = |h: &H, block: usize| {
|
||||
let s = &h.state().session;
|
||||
let para = s.doc.para_at(&Pos::body(block, 0)).expect("a paragraph");
|
||||
s.doc.styles.resolve_para(¶.props).tabs.iter().map(|t| (t.pos, t.align)).collect::<Vec<_>>()
|
||||
@@ -4134,13 +4137,13 @@ fn ruler_tab_stops_are_set_moved_and_cleared_with_the_pointer() {
|
||||
}
|
||||
let area = h.state().canvas.canvas_rect.expect("the canvas is laid out");
|
||||
// The middle of the ruler's strip, over a point `d` points from the paragraph's start.
|
||||
let on_ruler = |h: &mut egui_kittest::Harness<'_, WordApp>, d: f32| {
|
||||
let on_ruler = |h: &mut H, d: f32| {
|
||||
let body_x = h.state_mut().session.layout().pages[0].body.x;
|
||||
let x = page_to_screen(h.state_mut(), 0, body_x + d, 0.0).expect("on screen").x;
|
||||
pos2(x, area.min.y - 7.0)
|
||||
};
|
||||
let button = |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
let click = |h: &mut egui_kittest::Harness<'_, WordApp>, at: Pos2| {
|
||||
let click = |h: &mut H, at: Pos2| {
|
||||
h.event(Event::PointerMoved(at));
|
||||
h.event(button(at, true));
|
||||
h.step();
|
||||
@@ -4153,7 +4156,7 @@ fn ruler_tab_stops_are_set_moved_and_cleared_with_the_pointer() {
|
||||
h.step();
|
||||
}
|
||||
};
|
||||
let drag = |h: &mut egui_kittest::Harness<'_, WordApp>, from: Pos2, to: Pos2| {
|
||||
let drag = |h: &mut H, from: Pos2, to: Pos2| {
|
||||
h.event(Event::PointerMoved(from));
|
||||
h.event(button(from, true));
|
||||
h.step();
|
||||
@@ -4166,7 +4169,7 @@ fn ruler_tab_stops_are_set_moved_and_cleared_with_the_pointer() {
|
||||
h.step();
|
||||
}
|
||||
};
|
||||
let stops = |h: &egui_kittest::Harness<'_, WordApp>| {
|
||||
let stops = |h: &H| {
|
||||
let s = &h.state().session;
|
||||
let para = s.doc.para_at(&s.sel.focus).expect("a paragraph");
|
||||
s.doc.styles.resolve_para(¶.props).tabs.iter().map(|t| (t.pos, t.align)).collect::<Vec<_>>()
|
||||
@@ -4253,8 +4256,7 @@ fn space_and_enter_on_the_canvas_do_not_interrupt_ime() {
|
||||
}
|
||||
assert!(h.state().canvas.focused, "the canvas takes focus when the window opens");
|
||||
let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
|
||||
let ime_interrupted =
|
||||
|h: &egui_kittest::Harness<'_, WordApp>| h.output().platform_output.ime.as_ref().map(|ime| ime.should_interrupt_composition);
|
||||
let ime_interrupted = |h: &H| h.output().platform_output.ime.as_ref().map(|ime| ime.should_interrupt_composition);
|
||||
h.event(key(egui::Key::Space));
|
||||
h.event(egui::Event::Text(" ".into()));
|
||||
h.step();
|
||||
@@ -4340,7 +4342,7 @@ fn the_caret_follows_the_input_method_cursor_in_the_composition() {
|
||||
for _ in 0..8 {
|
||||
h.step();
|
||||
}
|
||||
let ime_x = |h: &egui_kittest::Harness<'_, WordApp>| h.output().platform_output.ime.as_ref().map(|ime| ime.cursor_rect.min.x);
|
||||
let ime_x = |h: &H| h.output().platform_output.ime.as_ref().map(|ime| ime.cursor_rect.min.x);
|
||||
let start = ime_x(&h).expect("the canvas places the candidate window");
|
||||
let mut compose = |range: Option<std::ops::Range<usize>>| {
|
||||
h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "にほん".into(), active_range_chars: range }));
|
||||
@@ -4386,10 +4388,8 @@ fn ime_descriptor_reports_visible_logical_text_and_exact_cause() {
|
||||
}
|
||||
h.state_mut().session.sel = wordcraft_engine::Selection::caret(wordcraft_doc::Pos::body(0, 2));
|
||||
h.step();
|
||||
let text = |h: &egui_kittest::Harness<'_, WordApp>| {
|
||||
h.output().platform_output.ime.as_ref().and_then(|i| i.surrounding_text.available()).map(|p| p.text.clone())
|
||||
};
|
||||
let cause = |h: &egui_kittest::Harness<'_, WordApp>| h.output().platform_output.ime.as_ref().map(|i| i.change_cause);
|
||||
let text = |h: &H| h.output().platform_output.ime.as_ref().and_then(|i| i.surrounding_text.available()).map(|p| p.text.clone());
|
||||
let cause = |h: &H| h.output().platform_output.ime.as_ref().map(|i| i.change_cause);
|
||||
assert_eq!(text(&h), Some("ab".into()), "the committed text is available");
|
||||
h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "に".into(), active_range_chars: None }));
|
||||
h.step();
|
||||
@@ -4433,8 +4433,7 @@ fn ime_descriptor_hides_tracked_deletions_and_preserves_reversed_selection() {
|
||||
}
|
||||
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 2), focus: wordcraft_doc::Pos::body(0, 7) };
|
||||
h.step();
|
||||
let payload =
|
||||
|h: &egui_kittest::Harness<'_, WordApp>| h.output().platform_output.ime.as_ref().and_then(|i| i.surrounding_text.available()).cloned();
|
||||
let payload = |h: &H| h.output().platform_output.ime.as_ref().and_then(|i| i.surrounding_text.available()).cloned();
|
||||
let p = payload(&h).expect("the visible text is available");
|
||||
assert_eq!(p.text, "abcd");
|
||||
assert_eq!(p.cursor, 4);
|
||||
@@ -4460,10 +4459,10 @@ fn ime_byte_deletion_preserves_the_selection_and_earns_input_method() {
|
||||
}
|
||||
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 3), focus: wordcraft_doc::Pos::body(0, 1) };
|
||||
h.step();
|
||||
let cause = |h: &egui_kittest::Harness<'_, WordApp>| h.output().platform_output.ime.as_ref().map(|i| i.change_cause);
|
||||
let cause = |h: &H| h.output().platform_output.ime.as_ref().map(|i| i.change_cause);
|
||||
h.event(egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 1, after_bytes: 1 }));
|
||||
h.step();
|
||||
let body = |h: &egui_kittest::Harness<'_, WordApp>| h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body).trim_end().to_string();
|
||||
let body = |h: &H| h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body).trim_end().to_string();
|
||||
assert_eq!(body(&h), "bc", "the selected text is preserved");
|
||||
assert_eq!(h.state().session.sel.anchor.off, 2, "the selection anchor moved with the erased prefix");
|
||||
assert_eq!(h.state().session.sel.focus.off, 0);
|
||||
@@ -4510,7 +4509,7 @@ fn ime_generation_changes_on_document_replacement_but_not_on_caret_motion() {
|
||||
for _ in 0..8 {
|
||||
h.step();
|
||||
}
|
||||
let generation = |h: &egui_kittest::Harness<'_, WordApp>| h.output().platform_output.ime.as_ref().map(|i| i.context_generation);
|
||||
let generation = |h: &H| h.output().platform_output.ime.as_ref().map(|i| i.context_generation);
|
||||
let first = generation(&h).expect("an IME context");
|
||||
h.state_mut().run("caret.right", json!({})).unwrap();
|
||||
h.step();
|
||||
@@ -4715,7 +4714,7 @@ fn ime_generation_changes_on_undo_and_version_restore() {
|
||||
for _ in 0..8 {
|
||||
h.step();
|
||||
}
|
||||
let generation = |h: &egui_kittest::Harness<'_, WordApp>| h.output().platform_output.ime.as_ref().map(|i| i.context_generation);
|
||||
let generation = |h: &H| h.output().platform_output.ime.as_ref().map(|i| i.context_generation);
|
||||
let first = generation(&h).expect("an IME context");
|
||||
h.state_mut().run("edit.undo", json!({})).unwrap();
|
||||
h.step();
|
||||
@@ -5014,9 +5013,7 @@ fn ime_equation_byte_delete_drops_only_its_immediate_replacement() {
|
||||
for _ in 0..8 {
|
||||
h.step();
|
||||
}
|
||||
let linear = |h: &mut egui_kittest::Harness<'_, WordApp>| {
|
||||
h.state_mut().run("equation.get", json!({})).unwrap()["linear"].as_str().unwrap_or_default().to_string()
|
||||
};
|
||||
let linear = |h: &mut H| h.state_mut().run("equation.get", json!({})).unwrap()["linear"].as_str().unwrap_or_default().to_string();
|
||||
// Harness::event steps each queued event in a separate frame. Insert the complete
|
||||
// protocol replacement into RawInput to exercise a single native input batch.
|
||||
h.input_mut().events.extend([
|
||||
@@ -5388,6 +5385,176 @@ fn a_long_comment_balloon_paints_only_its_first_ten_rows() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A Behind Text header picture: while editing the header a click on it selects it wherever no
|
||||
/// header text covers it (far down over the body, or in the band clear of the text), as in Word;
|
||||
/// over the header text the click edits the text. From the body a click there is body text.
|
||||
#[test]
|
||||
fn header_picture_clear_of_header_text_is_selected_while_editing_the_header() {
|
||||
// Far down the page, over the body.
|
||||
header_picture_click(false, 200.0, 400.0, Some((300.0, f32::MAX)), true);
|
||||
// In the header band, below the header's text line.
|
||||
header_picture_click(false, 300.0, 56.0, Some((50.0, 72.0)), true);
|
||||
// Over the header's text, at its start: the click goes to the text.
|
||||
header_picture_click(false, 72.0, 36.0, None, false);
|
||||
}
|
||||
|
||||
/// The same for a footer, which is a `StoryRef::Part` like the header.
|
||||
#[test]
|
||||
fn footer_picture_clear_of_footer_text_is_selected_while_editing_the_footer() {
|
||||
header_picture_click(true, 200.0, 400.0, Some((300.0, f32::MAX)), true);
|
||||
}
|
||||
|
||||
/// Dragging a header picture that no header text covers moves it, rather than starting the
|
||||
/// deferred drag-over-text path.
|
||||
#[test]
|
||||
fn dragging_a_header_picture_clear_of_header_text_moves_it() {
|
||||
let (mut h, pos, rect) = header_picture_app(false, 200.0, 400.0, 1);
|
||||
edit_story(&mut h, false, 0);
|
||||
let at = picture_point(&h, 0, rect);
|
||||
h.event(egui::Event::PointerMoved(at));
|
||||
h.event(pointer_button(at, egui::PointerButton::Primary, true));
|
||||
h.step();
|
||||
let to = at + egui::vec2(60.0, 30.0);
|
||||
for p in [at + egui::vec2(20.0, 10.0), to] {
|
||||
h.event(egui::Event::PointerMoved(p));
|
||||
h.step();
|
||||
}
|
||||
h.event(pointer_button(to, egui::PointerButton::Primary, false));
|
||||
steps(&mut h, 3);
|
||||
let moved = h.state_mut().session.layout().object(&pos, 0).unwrap().rect;
|
||||
assert!(moved.x > rect.x + 10.0 && moved.y > rect.y + 5.0, "the picture moved with the drag: {rect:?} -> {moved:?}");
|
||||
assert_eq!(wordcraft_engine::cmd::objects::object_selection(&h.state().session).map(|(p, _)| p), Some(pos), "and stays selected");
|
||||
}
|
||||
|
||||
/// A right-click on the header picture repeated on page 2 while editing the header on page 1
|
||||
/// selects that copy: the frame and handles belong on page 2, not the page last edited.
|
||||
#[test]
|
||||
fn right_clicking_a_repeated_header_picture_selects_it_on_its_own_page() {
|
||||
let (mut h, pos, _) = header_picture_app(false, 200.0, 400.0, 2);
|
||||
edit_story(&mut h, false, 0);
|
||||
assert_eq!(h.state().session.page_hint, 0, "editing the header on page 1");
|
||||
let rect = h.state_mut().session.layout().object(&pos, 1).unwrap().rect;
|
||||
assert_eq!(h.state_mut().session.layout().object(&pos, 1).unwrap().page, 1, "the picture is repeated on page 2");
|
||||
let at = picture_point(&h, 1, rect);
|
||||
press(&mut h, at, egui::PointerButton::Secondary);
|
||||
assert_eq!(wordcraft_engine::cmd::objects::object_selection(&h.state().session).map(|(p, _)| p), Some(pos), "the right-click selected it");
|
||||
assert_eq!(h.state().session.page_hint, 1, "its frame is drawn on the page clicked");
|
||||
}
|
||||
|
||||
/// The same for a left-click: it selects the page-2 copy and moves the frame there, not the copy
|
||||
/// on page 1 that was being edited.
|
||||
#[test]
|
||||
fn left_clicking_a_repeated_header_picture_selects_it_on_its_own_page() {
|
||||
let (mut h, pos, _) = header_picture_app(false, 200.0, 400.0, 2);
|
||||
edit_story(&mut h, false, 0);
|
||||
assert_eq!(h.state().session.page_hint, 0, "editing the header on page 1");
|
||||
let rect = h.state_mut().session.layout().object(&pos, 1).unwrap().rect;
|
||||
assert_eq!(h.state_mut().session.layout().object(&pos, 1).unwrap().page, 1, "the picture is repeated on page 2");
|
||||
let at = picture_point(&h, 1, rect);
|
||||
press(&mut h, at, egui::PointerButton::Primary);
|
||||
assert_eq!(wordcraft_engine::cmd::objects::object_selection(&h.state().session).map(|(p, _)| p), Some(pos), "the left-click selected it");
|
||||
assert_eq!(h.state().session.page_hint, 1, "its frame is drawn on the page clicked");
|
||||
}
|
||||
|
||||
fn pointer_button(pos: egui::Pos2, button: egui::PointerButton, pressed: bool) -> egui::Event {
|
||||
egui::Event::PointerButton { pos, button, pressed, modifiers: Default::default() }
|
||||
}
|
||||
|
||||
/// Moves to `at`, presses and releases `button` there and lets the frames settle.
|
||||
fn press(h: &mut H, at: egui::Pos2, button: egui::PointerButton) {
|
||||
h.event(egui::Event::PointerMoved(at));
|
||||
h.event(pointer_button(at, button, true));
|
||||
h.step();
|
||||
h.event(pointer_button(at, button, false));
|
||||
steps(h, 3);
|
||||
}
|
||||
|
||||
/// Near the top-left corner of the picture's `rect` on `page`: on the header text line when the
|
||||
/// picture is placed over it.
|
||||
fn picture_point(h: &H, page: usize, rect: wordcraft_geom::Rect) -> egui::Pos2 {
|
||||
let scale = h.state().canvas.scale;
|
||||
crate::frame::to_screen(h.state().canvas.page_rects[page], scale, rect).min + egui::vec2(10.0, 6.0) * scale
|
||||
}
|
||||
|
||||
/// Starts editing the header (or footer) of `page` and lets the frames settle.
|
||||
fn edit_story(h: &mut H, footer: bool, page: usize) {
|
||||
let command = if footer { "insert.editFooter" } else { "insert.editHeader" };
|
||||
h.state_mut().run(command, json!({"page": page})).unwrap();
|
||||
// Entering the footer scrolls the page to it: wait until the page stops moving.
|
||||
let (mut last, mut still) = (h.state().canvas.page_rects[0], 0);
|
||||
for _ in 0..600 {
|
||||
h.step();
|
||||
let now = h.state().canvas.page_rects[0];
|
||||
still = if now == last { still + 1 } else { 0 };
|
||||
last = now;
|
||||
if still >= 10 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A body-mode window on a document of `pages` pages whose header (or footer) holds text and a
|
||||
/// 160pt Behind Text picture at (`x`, `y`) on the page. Returns it, the picture's position and
|
||||
/// its first-page rectangle.
|
||||
fn header_picture_app(footer: bool, x: f32, y: f32, pages: usize) -> (H, Pos, wordcraft_geom::Rect) {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
for _ in 1..pages {
|
||||
a.run("insert.pageBreak", json!({})).unwrap();
|
||||
}
|
||||
a.run(if footer { "insert.editFooter" } else { "insert.editHeader" }, json!({})).unwrap();
|
||||
a.run("text.insert", json!({"text": if footer { "Footer" } else { "Header" }})).unwrap();
|
||||
let mut png = Vec::new();
|
||||
let img = image::RgbaImage::from_pixel(40, 20, image::Rgba([200, 30, 30, 255]));
|
||||
image::DynamicImage::ImageRgba8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
a.run("insert.picture", json!({"data": wordcraft_engine::cmd::insert::base64_encode(&png), "width": 160})).unwrap();
|
||||
let pos = wordcraft_engine::cmd::objects::selected(&a.session).unwrap().0;
|
||||
a.run("arrange.bounds", json!({"x": x, "y": y})).unwrap();
|
||||
a.run("arrange.wrap", json!({"wrap": "behindText"})).unwrap();
|
||||
let rect = a.session.layout().object(&pos, 0).unwrap().rect;
|
||||
a.run("insert.closeHeader", json!({})).unwrap();
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.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,
|
||||
);
|
||||
// Zoomed out so the whole page is on screen and entering the footer scrolls nothing.
|
||||
h.state_mut().run("view.zoom", json!({"value": 40})).unwrap();
|
||||
steps(&mut h, 20);
|
||||
(h, pos, rect)
|
||||
}
|
||||
|
||||
/// Puts a Behind Text header (or footer) picture at (`x`, `y`), checks its top lies within `band`
|
||||
/// (when given), clicks near its top-left corner from the body and then while editing, and checks
|
||||
/// the second click selects it (`selects`) or leaves the caret in the text; a right-click picks it
|
||||
/// only where the click does, so the context menu (Reset Picture, Wrap Text) acts on it.
|
||||
fn header_picture_click(footer: bool, x: f32, y: f32, band: Option<(f32, f32)>, selects: bool) {
|
||||
let (mut h, pos, rect) = header_picture_app(footer, x, y, 1);
|
||||
if let Some((lo, hi)) = band {
|
||||
assert!(rect.y >= lo && rect.y < hi, "the picture sits where the case wants it: {rect:?}");
|
||||
}
|
||||
let at = picture_point(&h, 0, rect);
|
||||
let picked = |h: &H| wordcraft_engine::cmd::objects::object_selection(&h.state().session).map(|(p, _)| p);
|
||||
press(&mut h, at, egui::PointerButton::Primary);
|
||||
assert!(picked(&h).is_none(), "from the body the picture isn't selectable");
|
||||
assert_eq!(h.state().session.sel.focus.story, StoryRef::Body);
|
||||
edit_story(&mut h, footer, 0);
|
||||
press(&mut h, at, egui::PointerButton::Primary);
|
||||
if selects {
|
||||
assert_eq!(picked(&h), Some(pos.clone()), "while editing a click on its picture selects it ({x}, {y})");
|
||||
} else {
|
||||
assert_eq!(picked(&h), None, "over the text the click edits the text ({x}, {y})");
|
||||
assert!(matches!(h.state().session.sel.focus.story, StoryRef::Part(_)), "still in the header or footer");
|
||||
}
|
||||
h.state_mut().session.sel = wordcraft_engine::Selection::caret(Pos { off: 0, ..pos.clone() });
|
||||
press(&mut h, at, egui::PointerButton::Secondary);
|
||||
assert_eq!(picked(&h), selects.then(|| pos.clone()), "a right-click picks the picture only where a click does ({x}, {y})");
|
||||
h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() });
|
||||
h.step();
|
||||
}
|
||||
|
||||
/// #1961 review: what a picture draws must be in its page's fingerprint itself. Reset Picture on
|
||||
/// one never edited keeps its media and clears only its corrections and crop, and undo puts them
|
||||
/// back; the anchor paragraph's layout pointer also moves then, but only as long as the old
|
||||
|
||||
@@ -225,7 +225,21 @@ pub fn show(app: &mut WordApp, ctx: &egui::Context) {
|
||||
let held = (app.file_browser_open() || app.colors.is_some()).then(|| ctx.input_mut(|i| std::mem::take(&mut i.events)));
|
||||
let shown = place_dialog(ctx, id, window).show(ctx, |ui| {
|
||||
ui.set_min_width(340.0);
|
||||
close = crate::rtl::root(ui, |ui| body(app, ui, &mut d));
|
||||
// Scrolls only when the last frame's body was taller than the screen.
|
||||
let room = (ui.ctx().content_rect().height() - 110.0).max(160.0);
|
||||
let key = id.with("body_height");
|
||||
let tall = ui.ctx().data(|data| data.get_temp::<f32>(key)).is_some_and(|h| h > room);
|
||||
let mut content = |ui: &mut egui::Ui| {
|
||||
let top = ui.cursor().min.y;
|
||||
close = crate::rtl::root(ui, |ui| body(app, ui, &mut d));
|
||||
let height = ui.min_rect().max.y - top;
|
||||
ui.ctx().data_mut(|data| data.insert_temp(key, height));
|
||||
};
|
||||
if tall {
|
||||
egui::ScrollArea::vertical().max_height(room).auto_shrink([true, true]).show(ui, content);
|
||||
} else {
|
||||
content(ui);
|
||||
}
|
||||
});
|
||||
if let Some(events) = held {
|
||||
ctx.input_mut(|i| i.events = events);
|
||||
|
||||
@@ -234,8 +234,9 @@ pub fn customize_keyboard(app: &mut WordApp, ui: &mut Ui, f: &mut KeyboardForm)
|
||||
}
|
||||
});
|
||||
crate::rtl::vertical(ui, |ui| {
|
||||
ui.label(tl!("New shortcut:"));
|
||||
close = capture(ui, f);
|
||||
let label = tl!("New shortcut:");
|
||||
ui.label(label);
|
||||
close = capture(ui, f, label);
|
||||
ui.add_space(4.0);
|
||||
if !f.pressed.is_empty() {
|
||||
let owner = match app.session.keymap.resolve(®, &f.pressed) {
|
||||
@@ -291,7 +292,7 @@ pub fn customize_keyboard(app: &mut WordApp, ui: &mut Ui, f: &mut KeyboardForm)
|
||||
|
||||
/// The "New shortcut" box: takes keyboard focus and records the combination pressed.
|
||||
/// True when plain Escape asks to close the dialog.
|
||||
fn capture(ui: &mut Ui, f: &mut KeyboardForm) -> bool {
|
||||
fn capture(ui: &mut Ui, f: &mut KeyboardForm, label: &str) -> bool {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(300.0, 26.0), Sense::click());
|
||||
// Keys belong to the box whenever nothing else in the dialog has focus, so a shortcut pressed
|
||||
@@ -312,6 +313,8 @@ fn capture(ui: &mut Ui, f: &mut KeyboardForm) -> bool {
|
||||
f.pressed = k;
|
||||
}
|
||||
}
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::TextInput, ui.is_enabled(), label));
|
||||
ui.ctx().accesskit_node_builder(resp.id, |node| node.set_value(key_text(&f.pressed)));
|
||||
let stroke = egui::Stroke::new(if focused { 1.5 } else { 1.0 }, if focused { t.accent } else { t.input_border });
|
||||
ui.painter().rect(rect, 2.0, t.input, stroke, egui::StrokeKind::Inside);
|
||||
let (text, color) = if f.pressed.is_empty() { (tl!("Press a key combination").to_string(), t.text_dim) } else { (key_text(&f.pressed), t.text) };
|
||||
@@ -416,6 +419,22 @@ mod tests {
|
||||
h
|
||||
}
|
||||
|
||||
/// The shortcut capture field has a name and reports the combination it records.
|
||||
#[test]
|
||||
fn shortcut_capture_exposes_its_name_and_current_value() {
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let mut h = harness("", Some("format.bold"));
|
||||
let input = h.get_by_role_and_label(Role::TextInput, "New shortcut:");
|
||||
assert_eq!(input.value().as_deref(), Some(""));
|
||||
input.focus();
|
||||
h.run_steps(2);
|
||||
h.key_press(egui::Key::F6);
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().1.pressed, "F6");
|
||||
assert_eq!(h.get_by_role_and_label(Role::TextInput, "New shortcut:").value().as_deref(), Some("F6"));
|
||||
}
|
||||
|
||||
type KbHarness<'a> = egui_kittest::Harness<'a, (WordApp, super::KeyboardForm)>;
|
||||
|
||||
/// The area of the Commands list that is on screen: 170 high, below the title, the item
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{MeasureExt, Serialize, Ui, Value, WordApp, buttons, fit_size, heading, json, run, unit, vec2};
|
||||
use super::{MeasureExt, Serialize, Ui, Value, WordApp, buttons, fit_size, json, run, unit, vec2};
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Size
|
||||
@@ -163,46 +163,49 @@ pub(super) fn size_ui(app: &mut WordApp, ui: &mut Ui, f: &mut SizeForm) -> bool
|
||||
let changed = r.cell(|ui| ui.add(field.update_while_editing(false)).labelled_by(name.id).changed());
|
||||
(changed && v != was).then_some(v)
|
||||
};
|
||||
heading(ui, "Size");
|
||||
crate::rtl::Table::new("size_lengths").columns(4).spacing(vec2(10.0, 6.0)).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
if let Some(h) = length(r, "Height:", f.height) {
|
||||
f.set_height(h);
|
||||
}
|
||||
if let Some(w) = length(r, "Width:", f.width) {
|
||||
f.set_width(w);
|
||||
}
|
||||
crate::widgets::section(ui, tl!("Size"), |ui| {
|
||||
crate::rtl::Table::new("size_lengths").columns(4).spacing(vec2(10.0, 6.0)).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
if let Some(h) = length(r, "Height:", f.height) {
|
||||
f.set_height(h);
|
||||
}
|
||||
if let Some(w) = length(r, "Width:", f.width) {
|
||||
f.set_width(w);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
heading(ui, "Scale");
|
||||
let (sw, sh) = f.scale();
|
||||
crate::rtl::Table::new("size_scale").columns(4).spacing(vec2(10.0, 6.0)).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
if let Some(p) = percent(r, "Height:", sh) {
|
||||
f.set_scale_height(p);
|
||||
}
|
||||
if let Some(w) = percent(r, "Width:", sw) {
|
||||
f.set_scale_width(w);
|
||||
}
|
||||
crate::widgets::section(ui, tl!("Scale"), |ui| {
|
||||
let (sw, sh) = f.scale();
|
||||
crate::rtl::Table::new("size_scale").columns(4).spacing(vec2(10.0, 6.0)).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
if let Some(p) = percent(r, "Height:", sh) {
|
||||
f.set_scale_height(p);
|
||||
}
|
||||
if let Some(w) = percent(r, "Width:", sw) {
|
||||
f.set_scale_width(w);
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.checkbox(&mut f.lock, tl!("Lock aspect ratio"));
|
||||
ui.add_enabled_ui(f.original.is_some(), |ui| ui.checkbox(&mut f.relative, tl!("Relative to original picture size")));
|
||||
});
|
||||
ui.checkbox(&mut f.lock, tl!("Lock aspect ratio"));
|
||||
ui.add_enabled_ui(f.original.is_some(), |ui| ui.checkbox(&mut f.relative, tl!("Relative to original picture size")));
|
||||
if let Some((w, h)) = f.uncropped {
|
||||
heading(ui, "Original size");
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(format!("{} {}", tl!("Height:"), crate::options::length(h)));
|
||||
ui.add_space(12.0);
|
||||
ui.label(format!("{} {}", tl!("Width:"), crate::options::length(w)));
|
||||
if let Some((pw, ph)) = f.pixels {
|
||||
crate::widgets::section(ui, tl!("Original size"), |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(format!("{} {}", tl!("Height:"), crate::options::length(h)));
|
||||
ui.add_space(12.0);
|
||||
let (pw, ph) = (pw.to_string(), ph.to_string());
|
||||
ui.weak(crate::i18n::fmt(tl!("{width} × {height} pixels"), &[("width", &pw), ("height", &ph)]));
|
||||
}
|
||||
ui.add_space(12.0);
|
||||
if ui.button(tl!("Reset")).clicked() {
|
||||
f.reset();
|
||||
}
|
||||
ui.label(format!("{} {}", tl!("Width:"), crate::options::length(w)));
|
||||
if let Some((pw, ph)) = f.pixels {
|
||||
ui.add_space(12.0);
|
||||
let (pw, ph) = (pw.to_string(), ph.to_string());
|
||||
ui.weak(crate::i18n::fmt(tl!("{width} × {height} pixels"), &[("width", &pw), ("height", &ph)]));
|
||||
}
|
||||
ui.add_space(12.0);
|
||||
if ui.button(tl!("Reset")).clicked() {
|
||||
f.reset();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
let (ok, cancel) = buttons(ui, "OK", true);
|
||||
@@ -268,11 +271,12 @@ pub(super) fn page_numbers_ui(app: &mut WordApp, ui: &mut Ui, f: &mut PageNumber
|
||||
ui.selectable_value(&mut f.format, v.to_string(), l);
|
||||
}
|
||||
});
|
||||
heading(ui, "Page numbering");
|
||||
ui.radio_value(&mut f.cont, true, tl!("Continue from previous section"));
|
||||
ui.horizontal(|ui| {
|
||||
ui.radio_value(&mut f.cont, false, tl!("Start at:"));
|
||||
ui.add_enabled(!f.cont, egui::DragValue::new(&mut f.start).range(1..=100_000));
|
||||
crate::widgets::section(ui, tl!("Page numbering"), |ui| {
|
||||
ui.radio_value(&mut f.cont, true, tl!("Continue from previous section"));
|
||||
ui.horizontal(|ui| {
|
||||
ui.radio_value(&mut f.cont, false, tl!("Start at:"));
|
||||
ui.add_enabled(!f.cont, egui::DragValue::new(&mut f.start).range(1..=100_000));
|
||||
});
|
||||
});
|
||||
let (ok, cancel) = buttons(ui, "OK", true);
|
||||
if ok {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{ENVELOPE_SIZES, LABEL_PRODUCTS, Serialize, Ui, Value, WordApp, buttons, heading, json, run};
|
||||
use super::{ENVELOPE_SIZES, LABEL_PRODUCTS, Serialize, Ui, Value, WordApp, buttons, json, run};
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Envelopes
|
||||
@@ -163,15 +163,16 @@ pub(super) fn labels_ui(app: &mut WordApp, ui: &mut Ui, f: &mut LabelsForm) -> b
|
||||
});
|
||||
});
|
||||
let (rows, cols) = LABEL_PRODUCTS.get(f.product).map_or((1, 1), |p| (p.rows, p.cols));
|
||||
heading(ui, "Print");
|
||||
ui.radio_value(&mut f.single, false, tl!("Full page of the same label"));
|
||||
ui.horizontal(|ui| {
|
||||
ui.radio_value(&mut f.single, true, tl!("Single label"));
|
||||
ui.add_enabled_ui(f.single, |ui| {
|
||||
ui.label(tl!("Row:"));
|
||||
ui.add(egui::DragValue::new(&mut f.row).range(1..=rows));
|
||||
ui.label(tl!("Column:"));
|
||||
ui.add(egui::DragValue::new(&mut f.col).range(1..=cols));
|
||||
crate::widgets::section(ui, tl!("Print"), |ui| {
|
||||
ui.radio_value(&mut f.single, false, tl!("Full page of the same label"));
|
||||
ui.horizontal(|ui| {
|
||||
ui.radio_value(&mut f.single, true, tl!("Single label"));
|
||||
ui.add_enabled_ui(f.single, |ui| {
|
||||
ui.label(tl!("Row:"));
|
||||
ui.add(egui::DragValue::new(&mut f.row).range(1..=rows));
|
||||
ui.label(tl!("Column:"));
|
||||
ui.add(egui::DragValue::new(&mut f.col).range(1..=cols));
|
||||
});
|
||||
});
|
||||
});
|
||||
f.row = f.row.clamp(1, rows.max(1));
|
||||
|
||||
@@ -118,23 +118,25 @@ impl SortForm {
|
||||
}
|
||||
|
||||
pub(super) fn sort_ui(app: &mut WordApp, ui: &mut Ui, f: &mut SortForm) -> bool {
|
||||
heading(ui, "Sort by");
|
||||
ui.horizontal(|ui| {
|
||||
craft_ui::ComboBox::from_id_salt("sort_column").selected_text(f.column_label(f.column)).width(180.0).show_ui(ui, |ui| {
|
||||
for i in 0..f.headers.len() {
|
||||
let label = f.column_label(i);
|
||||
ui.selectable_value(&mut f.column, i, label);
|
||||
}
|
||||
});
|
||||
crate::rtl::vertical(ui, |ui| {
|
||||
ui.radio_value(&mut f.descending, false, tl!("Ascending"));
|
||||
ui.radio_value(&mut f.descending, true, tl!("Descending"));
|
||||
crate::widgets::section(ui, tl!("Sort by"), |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
craft_ui::ComboBox::from_id_salt("sort_column").selected_text(f.column_label(f.column)).width(180.0).show_ui(ui, |ui| {
|
||||
for i in 0..f.headers.len() {
|
||||
let label = f.column_label(i);
|
||||
ui.selectable_value(&mut f.column, i, label);
|
||||
}
|
||||
});
|
||||
crate::rtl::vertical(ui, |ui| {
|
||||
ui.radio_value(&mut f.descending, false, tl!("Ascending"));
|
||||
ui.radio_value(&mut f.descending, true, tl!("Descending"));
|
||||
});
|
||||
});
|
||||
});
|
||||
heading(ui, "My list has");
|
||||
ui.horizontal(|ui| {
|
||||
ui.radio_value(&mut f.header, true, tl!("Header row"));
|
||||
ui.radio_value(&mut f.header, false, tl!("No header row"));
|
||||
crate::widgets::section(ui, tl!("My list has"), |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.radio_value(&mut f.header, true, tl!("Header row"));
|
||||
ui.radio_value(&mut f.header, false, tl!("No header row"));
|
||||
});
|
||||
});
|
||||
let (ok, cancel) = buttons(ui, "OK", true);
|
||||
if ok {
|
||||
@@ -380,39 +382,42 @@ impl TextToTableForm {
|
||||
|
||||
pub(super) fn text_to_table_ui(app: &mut WordApp, ui: &mut Ui, f: &mut TextToTableForm) -> bool {
|
||||
let before = (f.separator.clone(), f.other_char.clone(), f.columns);
|
||||
heading(ui, "Table size");
|
||||
crate::rtl::Table::new("text_to_table").columns(2).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Number of columns:")));
|
||||
r.cell(|ui| ui.add(egui::DragValue::new(&mut f.columns).range(1..=63)));
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Number of rows:")));
|
||||
r.cell(|ui| ui.label(f.rows.to_string()));
|
||||
crate::widgets::section(ui, tl!("Table size"), |ui| {
|
||||
crate::rtl::Table::new("text_to_table").columns(2).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Number of columns:")));
|
||||
r.cell(|ui| ui.add(egui::DragValue::new(&mut f.columns).range(1..=63)));
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Number of rows:")));
|
||||
r.cell(|ui| ui.label(f.rows.to_string()));
|
||||
});
|
||||
});
|
||||
});
|
||||
heading(ui, "AutoFit behavior");
|
||||
ui.horizontal(|ui| {
|
||||
ui.radio_value(&mut f.autofit, "initial".to_string(), tl!("Initial column width:"));
|
||||
ui.add_enabled(f.autofit == "initial", egui::TextEdit::singleline(&mut f.width).desired_width(72.0));
|
||||
});
|
||||
ui.radio_value(&mut f.autofit, "contents".to_string(), tl!("AutoFit to contents"));
|
||||
ui.radio_value(&mut f.autofit, "window".to_string(), tl!("AutoFit to window"));
|
||||
heading(ui, "Separate text at");
|
||||
crate::rtl::Table::new("text_to_table_sep").columns(2).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.radio_value(&mut f.separator, "paragraph".to_string(), tl!("Paragraphs")));
|
||||
r.cell(|ui| ui.radio_value(&mut f.separator, "comma".to_string(), tl!("Commas")));
|
||||
crate::widgets::section(ui, tl!("AutoFit behavior"), |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.radio_value(&mut f.autofit, "initial".to_string(), tl!("Initial column width:"));
|
||||
ui.add_enabled(f.autofit == "initial", egui::TextEdit::singleline(&mut f.width).desired_width(72.0));
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.radio_value(&mut f.separator, "tab".to_string(), tl!("Tabs")));
|
||||
r.cell(|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.radio_value(&mut f.separator, "other".to_string(), tl!("Other:"));
|
||||
let edit = ui.add(egui::TextEdit::singleline(&mut f.other_char).char_limit(1).desired_width(24.0));
|
||||
if edit.changed() {
|
||||
f.separator = "other".into();
|
||||
}
|
||||
ui.radio_value(&mut f.autofit, "contents".to_string(), tl!("AutoFit to contents"));
|
||||
ui.radio_value(&mut f.autofit, "window".to_string(), tl!("AutoFit to window"));
|
||||
});
|
||||
crate::widgets::section(ui, tl!("Separate text at"), |ui| {
|
||||
crate::rtl::Table::new("text_to_table_sep").columns(2).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.radio_value(&mut f.separator, "paragraph".to_string(), tl!("Paragraphs")));
|
||||
r.cell(|ui| ui.radio_value(&mut f.separator, "comma".to_string(), tl!("Commas")));
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.radio_value(&mut f.separator, "tab".to_string(), tl!("Tabs")));
|
||||
r.cell(|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.radio_value(&mut f.separator, "other".to_string(), tl!("Other:"));
|
||||
let edit = ui.add(egui::TextEdit::singleline(&mut f.other_char).char_limit(1).desired_width(24.0));
|
||||
if edit.changed() {
|
||||
f.separator = "other".into();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -208,7 +208,14 @@ fn language_dialog_default_survives_a_restart() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let mut a = app();
|
||||
a.ui.language = "en".into();
|
||||
a.dialog = Some(Dialog::Layout(Box::new(LayoutDialog::Language(LanguageForm { lang: "fr-FR".into(), no_proof: false, detect: false }))));
|
||||
a.dialog = Some(Dialog::Layout(Box::new(LayoutDialog::Language(LanguageForm {
|
||||
lang: "fr-FR".into(),
|
||||
no_proof: false,
|
||||
detect: false,
|
||||
whole_document: false,
|
||||
initial: ("fr-FR".into(), false),
|
||||
proof_touched: false,
|
||||
}))));
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
app.logic(&ui.ctx().clone());
|
||||
@@ -232,6 +239,143 @@ fn language_dialog_default_survives_a_restart() {
|
||||
assert_eq!(LanguageForm::read(&b).lang, "fr-FR");
|
||||
}
|
||||
|
||||
/// #3518: ticking "Apply to the whole document" makes OK send `scope: "document"`; unticked sends none.
|
||||
#[test]
|
||||
fn language_dialog_whole_document_checkbox_sends_scope() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let f = LanguageForm {
|
||||
lang: "fr-FR".into(),
|
||||
no_proof: false,
|
||||
detect: false,
|
||||
whole_document: false,
|
||||
initial: ("fr-FR".into(), false),
|
||||
proof_touched: false,
|
||||
};
|
||||
assert!(f.params().get("scope").is_none());
|
||||
assert_eq!(LanguageForm { whole_document: true, ..f.clone() }.params()["scope"], "document");
|
||||
let mut a = app();
|
||||
a.ui.language = "en".into();
|
||||
let para = wordcraft_doc::Paragraph::with_text("Header", Default::default());
|
||||
let header = a.session.doc.add_part(wordcraft_doc::PartKind::Header, vec![Arc::new(wordcraft_doc::Block::Para(para))]);
|
||||
a.dialog = Some(Dialog::Layout(Box::new(LayoutDialog::Language(f))));
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
app.logic(&ui.ctx().clone());
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(3);
|
||||
h.get_by_label("Apply to the whole document").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_label("OK").click();
|
||||
h.run_steps(3);
|
||||
// The header, which the caret isn't in, took the language.
|
||||
let doc = &h.state().session.doc;
|
||||
let hp = doc.para(wordcraft_doc::StoryRef::Part(header), &wordcraft_doc::Path::top(0)).unwrap();
|
||||
assert_eq!(hp.runs.first().and_then(|r| r.props.lang.as_deref()), Some("fr-FR"));
|
||||
}
|
||||
|
||||
/// "Plain text, then a Do-not-check run", the caret in the plain text.
|
||||
fn proofing_mix_app() -> WordApp {
|
||||
let mut a = app();
|
||||
a.run("text.insert", json!({"text": "Plain code"})).unwrap();
|
||||
a.run("select.text", json!({"text": "code"})).unwrap();
|
||||
a.run("review.language", json!({"lang": "de-DE", "noProof": true})).unwrap();
|
||||
a.run("select.text", json!({"text": "Plain"})).unwrap();
|
||||
a.run("review.language", json!({"lang": "en-US", "noProof": false})).unwrap();
|
||||
a.run("select.text", json!({"text": "Plain"})).unwrap();
|
||||
a
|
||||
}
|
||||
|
||||
fn run_proofing(a: &mut WordApp, text: &str) -> (Option<String>, Option<bool>) {
|
||||
a.run("select.text", json!({"text": text})).unwrap();
|
||||
let st = a.run("format.state", json!({})).unwrap();
|
||||
(st["lang"].as_str().map(String::from), st["noProof"].as_bool())
|
||||
}
|
||||
|
||||
/// #3518: whole-document OK sends only what the user changed.
|
||||
#[test]
|
||||
fn language_dialog_whole_document_sends_only_changes() {
|
||||
// Changing only the language leaves the Do-not-check run alone.
|
||||
let mut a = proofing_mix_app();
|
||||
let mut f = LanguageForm::read(&a);
|
||||
f.whole_document = true;
|
||||
f.lang = "en-GB".into();
|
||||
let p = f.params();
|
||||
assert!(p.get("noProof").is_none());
|
||||
a.run("review.language", p).unwrap();
|
||||
assert_eq!(run_proofing(&mut a, "code"), (Some("en-GB".into()), Some(true)));
|
||||
assert_eq!(run_proofing(&mut a, "Plain"), (Some("en-GB".into()), Some(false)));
|
||||
|
||||
// Changing only Do-not-check leaves each run's language alone.
|
||||
let mut a = proofing_mix_app();
|
||||
let mut f = LanguageForm::read(&a);
|
||||
f.whole_document = true;
|
||||
f.no_proof = true;
|
||||
f.proof_touched = true;
|
||||
let p = f.params();
|
||||
assert!(p.get("lang").is_none());
|
||||
a.run("review.language", p).unwrap();
|
||||
assert_eq!(run_proofing(&mut a, "code"), (Some("de-DE".into()), Some(true)));
|
||||
assert_eq!(run_proofing(&mut a, "Plain"), (Some("en-US".into()), Some(true)));
|
||||
|
||||
// No edits: the caret's language, no noProof (never the engine's en-US default).
|
||||
let mut a = proofing_mix_app();
|
||||
let mut f = LanguageForm::read(&a);
|
||||
f.lang = "fr-FR".into();
|
||||
f.initial.0 = "fr-FR".into();
|
||||
f.whole_document = true;
|
||||
let p = f.params();
|
||||
assert_eq!(p["lang"], "fr-FR");
|
||||
assert!(p.get("noProof").is_none());
|
||||
a.run("review.language", p).unwrap();
|
||||
assert_eq!(run_proofing(&mut a, "code"), (Some("fr-FR".into()), Some(true)));
|
||||
|
||||
// Selection mode is unchanged: both are sent.
|
||||
f.whole_document = false;
|
||||
assert_eq!(f.params()["noProof"], false);
|
||||
}
|
||||
|
||||
/// #3518: a ticked Do-not-check box the user did not change (the caret sits in a no-proof run)
|
||||
/// is not sent, so a language-only whole-document apply leaves other runs' proofing state alone.
|
||||
#[test]
|
||||
fn language_dialog_whole_document_unchanged_no_proof_is_not_sent() {
|
||||
let mut a = proofing_mix_app();
|
||||
a.run("select.text", json!({"text": "code"})).unwrap();
|
||||
let mut f = LanguageForm::read(&a);
|
||||
assert!(f.no_proof && f.initial.1);
|
||||
f.whole_document = true;
|
||||
f.lang = "en-GB".into();
|
||||
let p = f.params();
|
||||
assert!(p.get("noProof").is_none(), "{p}");
|
||||
a.run("review.language", p).unwrap();
|
||||
assert_eq!(run_proofing(&mut a, "code"), (Some("en-GB".into()), Some(true)));
|
||||
assert_eq!(run_proofing(&mut a, "Plain"), (Some("en-GB".into()), Some(false)));
|
||||
}
|
||||
|
||||
/// #3518: with the caret in a no-proof run, ticking the whole-document box and clicking Do not
|
||||
/// check off and on again (ending ticked) still marks the whole document no-proof.
|
||||
#[test]
|
||||
fn language_dialog_whole_document_retoggled_no_proof_is_sent() {
|
||||
let mut a = proofing_mix_app();
|
||||
a.run("select.text", json!({"text": "code"})).unwrap();
|
||||
let mut f = LanguageForm::read(&a);
|
||||
assert!(f.no_proof && f.initial.1 && !f.proof_touched);
|
||||
f.whole_document = true;
|
||||
for _ in 0..2 {
|
||||
f.no_proof = !f.no_proof;
|
||||
f.proof_touched = true;
|
||||
}
|
||||
assert!(f.no_proof);
|
||||
let p = f.params();
|
||||
assert_eq!(p["noProof"], true, "{p}");
|
||||
assert!(p.get("lang").is_none(), "{p}");
|
||||
a.run("review.language", p).unwrap();
|
||||
assert_eq!(run_proofing(&mut a, "Plain"), (Some("en-US".into()), Some(true)));
|
||||
assert_eq!(run_proofing(&mut a, "code"), (Some("de-DE".into()), Some(true)));
|
||||
}
|
||||
|
||||
/// #407: Envelopes starts from the selected address; Add to Document puts an envelope
|
||||
/// section before the letter without asking to save (nothing is replaced).
|
||||
#[test]
|
||||
|
||||
@@ -320,6 +320,16 @@ pub struct LanguageForm {
|
||||
pub lang: String,
|
||||
pub no_proof: bool,
|
||||
pub detect: bool,
|
||||
/// "Apply to the whole document": OK sends `scope: "document"` (every story), not the selection.
|
||||
pub whole_document: bool,
|
||||
/// The language and Do-not-check state the dialog opened with, to tell what the user changed.
|
||||
#[serde(skip)]
|
||||
pub initial: (String, bool),
|
||||
/// The Do-not-check box was clicked (even back to where it started). A whole-document OK sends
|
||||
/// `noProof` only then: the caret's value alone says nothing about runs that differ elsewhere,
|
||||
/// but a click is a request to mark the whole document that way (#3518).
|
||||
#[serde(skip)]
|
||||
pub proof_touched: bool,
|
||||
}
|
||||
|
||||
impl LanguageForm {
|
||||
@@ -328,12 +338,36 @@ impl LanguageForm {
|
||||
let style = s.doc.para_at(&s.sel.focus).and_then(|p| p.props.style.as_deref());
|
||||
let here = s.doc.styles.resolve_char(style, &s.typing_props());
|
||||
let lang = here.lang.unwrap_or_else(|| "en-US".into());
|
||||
LanguageForm { lang, no_proof: here.no_proof, detect: s.prefs.detect_language }
|
||||
LanguageForm {
|
||||
initial: (lang.clone(), here.no_proof),
|
||||
lang,
|
||||
no_proof: here.no_proof,
|
||||
detect: s.prefs.detect_language,
|
||||
whole_document: false,
|
||||
proof_touched: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// `review.language` parameters for OK.
|
||||
pub fn params(&self) -> Value {
|
||||
json!({"lang": self.lang, "noProof": self.no_proof, "detect": self.detect})
|
||||
if !self.whole_document {
|
||||
return json!({"lang": self.lang, "noProof": self.no_proof, "detect": self.detect});
|
||||
}
|
||||
// Whole document: the caret's values must not flatten what differs elsewhere, so send only
|
||||
// what was changed. With no edits at all the language goes (never the engine's en-US default).
|
||||
let (lang_changed, proof_touched) = (self.lang != self.initial.0, self.proof_touched);
|
||||
let mut v = json!({"scope": "document", "detect": self.detect});
|
||||
if let Some(m) = v.as_object_mut() {
|
||||
if lang_changed || !proof_touched {
|
||||
m.insert("lang".into(), json!(self.lang));
|
||||
}
|
||||
// Only a clicked box is sent: the caret's value untouched says nothing about runs that
|
||||
// differ elsewhere, and resending it would flatten them.
|
||||
if proof_touched {
|
||||
m.insert("noProof".into(), json!(self.no_proof));
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
@@ -343,7 +377,7 @@ pub(super) fn language_name(tag: &str) -> String {
|
||||
}
|
||||
|
||||
pub(super) fn language_ui(app: &mut WordApp, ui: &mut Ui, f: &mut LanguageForm) -> bool {
|
||||
ui.label(tl!("Mark selected text as:"));
|
||||
ui.label(if f.whole_document { tl!("Mark the whole document as:") } else { tl!("Mark selected text as:") });
|
||||
let list = crate::ribbon::language_list(&f.lang);
|
||||
egui::Frame::NONE.stroke(egui::Stroke::new(1.0, crate::theme::Tokens::get(ui.ctx()).border_strong)).inner_margin(4.0).show(ui, |ui| {
|
||||
egui::ScrollArea::vertical().max_height(220.0).min_scrolled_height(220.0).show(ui, |ui| {
|
||||
@@ -358,8 +392,11 @@ pub(super) fn language_ui(app: &mut WordApp, ui: &mut Ui, f: &mut LanguageForm)
|
||||
});
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
ui.checkbox(&mut f.no_proof, tl!("Do not check spelling or grammar"));
|
||||
if ui.checkbox(&mut f.no_proof, tl!("Do not check spelling or grammar")).clicked() {
|
||||
f.proof_touched = true;
|
||||
}
|
||||
ui.checkbox(&mut f.detect, tl!("Detect language automatically"));
|
||||
ui.checkbox(&mut f.whole_document, tl!("Apply to the whole document"));
|
||||
ui.add_space(4.0);
|
||||
let set_default = ui.button(tl!("Set As Default")).clicked();
|
||||
if set_default && run(app, "review.language", json!({"lang": f.lang, "default": true, "detect": f.detect})) {
|
||||
|
||||
@@ -534,69 +534,70 @@ const MOVE_TO_MARKS: &[(&str, &str)] = &[
|
||||
/// Track Changes Options. Returns true to close.
|
||||
pub fn track_options(app: &mut WordApp, ui: &mut Ui, f: &mut TrackForm) -> bool {
|
||||
let theme = app.session.doc.settings.theme_colors.clone();
|
||||
let heading = |ui: &mut Ui, s: &str| {
|
||||
ui.add_space(4.0);
|
||||
ui.label(egui::RichText::new(tl!(s)).font(semibold(12.5)));
|
||||
};
|
||||
heading(ui, "Show");
|
||||
crate::rtl::Table::new("tco_show").columns(2).spacing(vec2(16.0, 4.0)).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.checkbox(&mut f.comments, tl!("Comments")));
|
||||
r.cell(|ui| ui.checkbox(&mut f.ink, tl!("Ink")));
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.checkbox(&mut f.insertions_deletions, tl!("Insertions and Deletions")));
|
||||
r.cell(|ui| ui.checkbox(&mut f.formatting, tl!("Formatting")));
|
||||
});
|
||||
});
|
||||
heading(ui, "Balloons");
|
||||
for (v, l) in [
|
||||
("revisions", "Show revisions in balloons"),
|
||||
("inline", "Show all revisions inline"),
|
||||
("commentsAndFormatting", "Show only comments and formatting in balloons"),
|
||||
] {
|
||||
ui.radio_value(&mut f.balloons, v.to_string(), tl!(l));
|
||||
}
|
||||
heading(ui, "Comments");
|
||||
for (v, l) in [("margin", "In the margin"), ("selected", "Only for the selected text")] {
|
||||
ui.radio_value(&mut f.comment_display, v.to_string(), tl!(l));
|
||||
}
|
||||
heading(ui, "Advanced");
|
||||
crate::rtl::Table::new("tco_advanced").columns(3).spacing(vec2(10.0, 6.0)).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Insertions:")));
|
||||
r.cell(|ui| choice(ui, "tco_ins", &mut f.insert_mark, INSERT_MARKS));
|
||||
r.cell(|ui| color(ui, &theme, &mut f.insert_color, "By author", None));
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Deletions:")));
|
||||
r.cell(|ui| choice(ui, "tco_del", &mut f.delete_mark, DELETE_MARKS));
|
||||
r.cell(|ui| color(ui, &theme, &mut f.delete_color, "By author", None));
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Changed lines:")));
|
||||
r.cell(|ui| {
|
||||
choice(
|
||||
ui,
|
||||
"tco_bar",
|
||||
&mut f.changed_lines,
|
||||
&[("outside", "Outside border"), ("left", "Left border"), ("right", "Right border"), ("none", "None")],
|
||||
)
|
||||
crate::widgets::section(ui, tl!("Show"), |ui| {
|
||||
crate::rtl::Table::new("tco_show").columns(2).spacing(vec2(16.0, 4.0)).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.checkbox(&mut f.comments, tl!("Comments")));
|
||||
r.cell(|ui| ui.checkbox(&mut f.ink, tl!("Ink")));
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.checkbox(&mut f.insertions_deletions, tl!("Insertions and Deletions")));
|
||||
r.cell(|ui| ui.checkbox(&mut f.formatting, tl!("Formatting")));
|
||||
});
|
||||
r.cell(|ui| color(ui, &theme, &mut f.changed_lines_color, "Automatic", Some(wordcraft_layout::display::CHANGE_BAR)));
|
||||
});
|
||||
});
|
||||
heading(ui, "Moves");
|
||||
crate::rtl::Table::new("tco_moves").columns(3).spacing(vec2(10.0, 6.0)).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Moved from:")));
|
||||
r.cell(|ui| choice(ui, "tco_move_from", &mut f.move_from_mark, DELETE_MARKS));
|
||||
r.cell(|ui| ui.push_id("tco_move_from_color", |ui| color(ui, &theme, &mut f.move_from_color, "By author", None)));
|
||||
crate::widgets::section(ui, tl!("Balloons"), |ui| {
|
||||
for (v, l) in [
|
||||
("revisions", "Show revisions in balloons"),
|
||||
("inline", "Show all revisions inline"),
|
||||
("commentsAndFormatting", "Show only comments and formatting in balloons"),
|
||||
] {
|
||||
ui.radio_value(&mut f.balloons, v.to_string(), tl!(l));
|
||||
}
|
||||
});
|
||||
crate::widgets::section(ui, tl!("Comments"), |ui| {
|
||||
for (v, l) in [("margin", "In the margin"), ("selected", "Only for the selected text")] {
|
||||
ui.radio_value(&mut f.comment_display, v.to_string(), tl!(l));
|
||||
}
|
||||
});
|
||||
crate::widgets::section(ui, tl!("Advanced"), |ui| {
|
||||
crate::rtl::Table::new("tco_advanced").columns(3).spacing(vec2(10.0, 6.0)).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Insertions:")));
|
||||
r.cell(|ui| choice(ui, "tco_ins", &mut f.insert_mark, INSERT_MARKS));
|
||||
r.cell(|ui| color(ui, &theme, &mut f.insert_color, "By author", None));
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Deletions:")));
|
||||
r.cell(|ui| choice(ui, "tco_del", &mut f.delete_mark, DELETE_MARKS));
|
||||
r.cell(|ui| color(ui, &theme, &mut f.delete_color, "By author", None));
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Changed lines:")));
|
||||
r.cell(|ui| {
|
||||
choice(
|
||||
ui,
|
||||
"tco_bar",
|
||||
&mut f.changed_lines,
|
||||
&[("outside", "Outside border"), ("left", "Left border"), ("right", "Right border"), ("none", "None")],
|
||||
)
|
||||
});
|
||||
r.cell(|ui| color(ui, &theme, &mut f.changed_lines_color, "Automatic", Some(wordcraft_layout::display::CHANGE_BAR)));
|
||||
});
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Moved to:")));
|
||||
r.cell(|ui| choice(ui, "tco_move_to", &mut f.move_to_mark, MOVE_TO_MARKS));
|
||||
r.cell(|ui| ui.push_id("tco_move_to_color", |ui| color(ui, &theme, &mut f.move_to_color, "By author", None)));
|
||||
});
|
||||
crate::widgets::section(ui, tl!("Moves"), |ui| {
|
||||
crate::rtl::Table::new("tco_moves").columns(3).spacing(vec2(10.0, 6.0)).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Moved from:")));
|
||||
r.cell(|ui| choice(ui, "tco_move_from", &mut f.move_from_mark, DELETE_MARKS));
|
||||
r.cell(|ui| ui.push_id("tco_move_from_color", |ui| color(ui, &theme, &mut f.move_from_color, "By author", None)));
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Moved to:")));
|
||||
r.cell(|ui| choice(ui, "tco_move_to", &mut f.move_to_mark, MOVE_TO_MARKS));
|
||||
r.cell(|ui| ui.push_id("tco_move_to_color", |ui| color(ui, &theme, &mut f.move_to_color, "By author", None)));
|
||||
});
|
||||
});
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
|
||||
@@ -8,7 +8,6 @@ use serde::Serialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::WordApp;
|
||||
use crate::theme::semibold;
|
||||
|
||||
/// Number formats notes offer: OOXML name and a sample (not translated). The Format Page Numbers
|
||||
/// dialog offers the same list (#1113).
|
||||
@@ -80,84 +79,83 @@ fn choice(ui: &mut Ui, id: &str, value: &mut String, options: &[(&str, &str)], t
|
||||
|
||||
/// Footnote and Endnote. Returns true to close.
|
||||
pub fn note_options(app: &mut WordApp, ui: &mut Ui, f: &mut NoteForm) -> bool {
|
||||
let heading = |ui: &mut Ui, s: &str| {
|
||||
ui.add_space(4.0);
|
||||
ui.label(egui::RichText::new(tl!(s)).font(semibold(12.5)));
|
||||
};
|
||||
heading(ui, "Location");
|
||||
let mut convert = None;
|
||||
crate::rtl::grid(ui, egui::Grid::new("notes_location").num_columns(2).spacing(vec2(10.0, 6.0)), |ui| {
|
||||
ui.radio_value(&mut f.endnote, false, tl!("Footnotes"));
|
||||
ui.add_enabled_ui(!f.endnote, |ui| {
|
||||
choice(ui, "notes_fpos", &mut f.pos[0], &[("pageBottom", "Bottom of Page"), ("beneathText", "Below text")], true);
|
||||
});
|
||||
ui.end_row();
|
||||
ui.radio_value(&mut f.endnote, true, tl!("Endnotes"));
|
||||
ui.add_enabled_ui(f.endnote, |ui| {
|
||||
choice(ui, "notes_epos", &mut f.pos[1], &[("sectEnd", "End of section"), ("docEnd", "End of document")], true);
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label("");
|
||||
ui.menu_button(format!("{}…", tl!("Convert")), |ui| {
|
||||
crate::rtl::root(ui, |ui| {
|
||||
for (to, l) in [("endnote", "Footnotes to endnotes"), ("footnote", "Endnotes to footnotes"), ("swap", "Swap footnotes and endnotes")]
|
||||
{
|
||||
if ui.button(tl!(l)).clicked() {
|
||||
convert = Some(to);
|
||||
ui.close();
|
||||
crate::widgets::section(ui, tl!("Location"), |ui| {
|
||||
let mut convert = None;
|
||||
crate::rtl::grid(ui, egui::Grid::new("notes_location").num_columns(2).spacing(vec2(10.0, 6.0)), |ui| {
|
||||
ui.radio_value(&mut f.endnote, false, tl!("Footnotes"));
|
||||
ui.add_enabled_ui(!f.endnote, |ui| {
|
||||
choice(ui, "notes_fpos", &mut f.pos[0], &[("pageBottom", "Bottom of Page"), ("beneathText", "Below text")], true);
|
||||
});
|
||||
ui.end_row();
|
||||
ui.radio_value(&mut f.endnote, true, tl!("Endnotes"));
|
||||
ui.add_enabled_ui(f.endnote, |ui| {
|
||||
choice(ui, "notes_epos", &mut f.pos[1], &[("sectEnd", "End of section"), ("docEnd", "End of document")], true);
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label("");
|
||||
ui.menu_button(format!("{}…", tl!("Convert")), |ui| {
|
||||
crate::rtl::root(ui, |ui| {
|
||||
for (to, l) in
|
||||
[("endnote", "Footnotes to endnotes"), ("footnote", "Endnotes to footnotes"), ("swap", "Swap footnotes and endnotes")]
|
||||
{
|
||||
if ui.button(tl!(l)).clicked() {
|
||||
convert = Some(to);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
});
|
||||
ui.end_row();
|
||||
});
|
||||
ui.end_row();
|
||||
if let Some(to) = convert
|
||||
&& let Err(e) = app.run("references.convertNotes", json!({ "to": to }))
|
||||
{
|
||||
app.status(e);
|
||||
}
|
||||
});
|
||||
if let Some(to) = convert
|
||||
&& let Err(e) = app.run("references.convertNotes", json!({ "to": to }))
|
||||
{
|
||||
app.status(e);
|
||||
}
|
||||
heading(ui, "Format");
|
||||
let k = usize::from(f.endnote);
|
||||
crate::rtl::Table::new("notes_format").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Number format")));
|
||||
r.cell(|ui| {
|
||||
if let Some(v) = f.fmt.get_mut(k) {
|
||||
choice(ui, "notes_fmt", v, &FORMATS, false);
|
||||
}
|
||||
crate::widgets::section(ui, tl!("Format"), |ui| {
|
||||
let k = usize::from(f.endnote);
|
||||
crate::rtl::Table::new("notes_format").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Number format")));
|
||||
r.cell(|ui| {
|
||||
if let Some(v) = f.fmt.get_mut(k) {
|
||||
choice(ui, "notes_fmt", v, &FORMATS, false);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Custom mark:")));
|
||||
r.cell(|ui| ui.add(egui::TextEdit::singleline(&mut f.mark).desired_width(60.0).char_limit(10)));
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Start at:")));
|
||||
r.cell(|ui| {
|
||||
if let Some(v) = f.start.get_mut(k) {
|
||||
ui.add(egui::DragValue::new(v).range(1..=32_767).speed(0.2));
|
||||
}
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Custom mark:")));
|
||||
r.cell(|ui| ui.add(egui::TextEdit::singleline(&mut f.mark).desired_width(60.0).char_limit(10)));
|
||||
});
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Numbering")));
|
||||
r.cell(|ui| {
|
||||
if let Some(v) = f.restart.get_mut(k) {
|
||||
let each_page: &[(&str, &str)] = if f.endnote { &[] } else { &[("eachPage", "Restart Each Page")] };
|
||||
let options: Vec<(&str, &str)> = [("continuous", "Continuous numbering"), ("eachSect", "Restart Each Section")]
|
||||
.into_iter()
|
||||
.chain(each_page.iter().copied())
|
||||
.collect();
|
||||
choice(ui, "notes_restart", v, &options, true);
|
||||
}
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Start at:")));
|
||||
r.cell(|ui| {
|
||||
if let Some(v) = f.start.get_mut(k) {
|
||||
ui.add(egui::DragValue::new(v).range(1..=32_767).speed(0.2));
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Apply to:")));
|
||||
r.cell(|ui| {
|
||||
let mut scope = if f.whole { "document" } else { "section" }.to_string();
|
||||
choice(ui, "notes_scope", &mut scope, &[("document", "Whole document"), ("section", "This section")], true);
|
||||
f.whole = scope == "document";
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Numbering")));
|
||||
r.cell(|ui| {
|
||||
if let Some(v) = f.restart.get_mut(k) {
|
||||
let each_page: &[(&str, &str)] = if f.endnote { &[] } else { &[("eachPage", "Restart Each Page")] };
|
||||
let options: Vec<(&str, &str)> = [("continuous", "Continuous numbering"), ("eachSect", "Restart Each Section")]
|
||||
.into_iter()
|
||||
.chain(each_page.iter().copied())
|
||||
.collect();
|
||||
choice(ui, "notes_restart", v, &options, true);
|
||||
}
|
||||
});
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Apply to:")));
|
||||
r.cell(|ui| {
|
||||
let mut scope = if f.whole { "document" } else { "section" }.to_string();
|
||||
choice(ui, "notes_scope", &mut scope, &[("document", "Whole document"), ("section", "This section")], true);
|
||||
f.whole = scope == "document";
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::common::{LEADERS, choice, heading, leader_char, sample};
|
||||
use super::common::{LEADERS, choice, leader_char, sample};
|
||||
use super::shell::{Next, go};
|
||||
use super::{FieldCode, RefsDialog, Serialize, Ui, Value, WordApp, buttons, json, vec2};
|
||||
|
||||
@@ -161,40 +161,43 @@ impl MarkForm {
|
||||
/// Draws the index-entry fields and page, cross-reference or bookmark-range options, with Mark
|
||||
/// and Mark All running `references.markEntry`.
|
||||
pub(super) fn mark_ui(app: &mut WordApp, ui: &mut Ui, f: &mut MarkForm) -> Next {
|
||||
heading(ui, "Index");
|
||||
crate::rtl::Table::new("xe").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
let entry_label = r.cell(|ui| ui.label(tl!("Main entry:")));
|
||||
r.cell(|ui| ui.add(egui::TextEdit::singleline(&mut f.entry).desired_width(220.0)).labelled_by(entry_label.id));
|
||||
});
|
||||
t.row(|r| {
|
||||
let subentry_label = r.cell(|ui| ui.label(tl!("Subentry:")));
|
||||
r.cell(|ui| ui.add(egui::TextEdit::singleline(&mut f.subentry).desired_width(220.0)).labelled_by(subentry_label.id));
|
||||
});
|
||||
});
|
||||
heading(ui, "Options");
|
||||
ui.horizontal(|ui| {
|
||||
let see_label = ui.radio_value(&mut f.option, "see".to_string(), tl!("Cross-reference:"));
|
||||
ui.add_enabled(f.option == "see", egui::TextEdit::singleline(&mut f.see).desired_width(160.0)).labelled_by(see_label.id);
|
||||
});
|
||||
ui.radio_value(&mut f.option, "page".to_string(), tl!("This page"));
|
||||
ui.horizontal(|ui| {
|
||||
let bookmark_label =
|
||||
ui.add_enabled_ui(!f.bookmarks.is_empty(), |ui| ui.radio_value(&mut f.option, "range".to_string(), tl!("Pages of bookmark:"))).inner;
|
||||
ui.add_enabled_ui(f.option == "range", |ui| {
|
||||
let opts: Vec<(String, &str)> = f.bookmarks.iter().map(|b| (b.clone(), b.as_str())).collect();
|
||||
let combo = craft_ui::ComboBox::from_id_salt("xe_bm").selected_text(f.bookmark.clone()).width(140.0).show_ui(ui, |ui| {
|
||||
for (v, l) in &opts {
|
||||
ui.selectable_value(&mut f.bookmark, v.clone(), *l);
|
||||
}
|
||||
crate::widgets::section(ui, tl!("Index"), |ui| {
|
||||
crate::rtl::Table::new("xe").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
let entry_label = r.cell(|ui| ui.label(tl!("Main entry:")));
|
||||
r.cell(|ui| ui.add(egui::TextEdit::singleline(&mut f.entry).desired_width(220.0)).labelled_by(entry_label.id));
|
||||
});
|
||||
t.row(|r| {
|
||||
let subentry_label = r.cell(|ui| ui.label(tl!("Subentry:")));
|
||||
r.cell(|ui| ui.add(egui::TextEdit::singleline(&mut f.subentry).desired_width(220.0)).labelled_by(subentry_label.id));
|
||||
});
|
||||
combo.response.labelled_by(bookmark_label.id);
|
||||
});
|
||||
});
|
||||
heading(ui, "Page number style");
|
||||
ui.horizontal(|ui| {
|
||||
ui.checkbox(&mut f.bold, tl!("Bold"));
|
||||
ui.checkbox(&mut f.italic, tl!("Italic"));
|
||||
crate::widgets::section(ui, tl!("Options"), |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
let see_label = ui.radio_value(&mut f.option, "see".to_string(), tl!("Cross-reference:"));
|
||||
ui.add_enabled(f.option == "see", egui::TextEdit::singleline(&mut f.see).desired_width(160.0)).labelled_by(see_label.id);
|
||||
});
|
||||
ui.radio_value(&mut f.option, "page".to_string(), tl!("This page"));
|
||||
ui.horizontal(|ui| {
|
||||
let bookmark_label =
|
||||
ui.add_enabled_ui(!f.bookmarks.is_empty(), |ui| ui.radio_value(&mut f.option, "range".to_string(), tl!("Pages of bookmark:"))).inner;
|
||||
ui.add_enabled_ui(f.option == "range", |ui| {
|
||||
let opts: Vec<(String, &str)> = f.bookmarks.iter().map(|b| (b.clone(), b.as_str())).collect();
|
||||
let combo = craft_ui::ComboBox::from_id_salt("xe_bm").selected_text(f.bookmark.clone()).width(140.0).show_ui(ui, |ui| {
|
||||
for (v, l) in &opts {
|
||||
ui.selectable_value(&mut f.bookmark, v.clone(), *l);
|
||||
}
|
||||
});
|
||||
combo.response.labelled_by(bookmark_label.id);
|
||||
});
|
||||
});
|
||||
});
|
||||
crate::widgets::section(ui, tl!("Page number style"), |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.checkbox(&mut f.bold, tl!("Bold"));
|
||||
ui.checkbox(&mut f.italic, tl!("Italic"));
|
||||
});
|
||||
});
|
||||
if !f.message.is_empty() {
|
||||
ui.label(egui::RichText::new(&f.message).small());
|
||||
|
||||
@@ -288,6 +288,7 @@ fn edge_glyph(ui: &mut Ui, edges: &str) {
|
||||
fn align_button(ui: &mut Ui, (v, h): (VAlign, Align), on: bool, tip: &str) -> egui::Response {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(22.0, 22.0), Sense::click());
|
||||
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), on, tip));
|
||||
let resp = resp.on_hover_text(tip);
|
||||
let p = ui.painter_at(r);
|
||||
let bg = if on {
|
||||
@@ -523,9 +524,9 @@ pub fn body(app: &mut WordApp, ui: &mut Ui, f: Form) -> bool {
|
||||
}
|
||||
let size = ui.add(egui::TextEdit::singleline(&mut r.size).desired_width(36.0));
|
||||
size.on_hover_text(tl!("Size:")).accessible_name(tl!("Size:"));
|
||||
ui.toggle_value(&mut r.bold, egui::RichText::new("B").strong()).on_hover_text(tl!("Bold"));
|
||||
ui.toggle_value(&mut r.italic, egui::RichText::new("I").italics()).on_hover_text(tl!("Italic"));
|
||||
ui.toggle_value(&mut r.underline, egui::RichText::new("U").underline()).on_hover_text(tl!("Underline"));
|
||||
ui.toggle_value(&mut r.bold, egui::RichText::new("B").strong()).on_hover_text(tl!("Bold")).accessible_name(tl!("Bold"));
|
||||
ui.toggle_value(&mut r.italic, egui::RichText::new("I").italics()).on_hover_text(tl!("Italic")).accessible_name(tl!("Italic"));
|
||||
ui.toggle_value(&mut r.underline, egui::RichText::new("U").underline()).on_hover_text(tl!("Underline")).accessible_name(tl!("Underline"));
|
||||
ui.push_id("tstyle_color", |ui| {
|
||||
ui.label(tl!("Font color:"));
|
||||
color_menu(ui, &theme, &mut r.color);
|
||||
@@ -661,6 +662,42 @@ mod tests {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use wordcraft_engine::Session;
|
||||
|
||||
/// Alignment choices expose their names and current selection, and can be toggled.
|
||||
#[test]
|
||||
fn alignment_buttons_expose_names_selection_and_clicks() {
|
||||
use egui::accesskit::{Role, Toggled};
|
||||
use egui_kittest::kittest::NodeT;
|
||||
let mut h = egui_kittest::Harness::builder().with_size(vec2(200.0, 120.0)).build_ui_state(
|
||||
|ui, selected: &mut Option<usize>| {
|
||||
for (i, align, label) in
|
||||
[(0, (VAlign::Top, Align::Left), "Align Top Left"), (1, (VAlign::Bottom, Align::Right), "Align Bottom Right")]
|
||||
{
|
||||
let on = *selected == Some(i);
|
||||
if align_button(ui, align, on, label).clicked() {
|
||||
*selected = if on { None } else { Some(i) };
|
||||
}
|
||||
}
|
||||
ui.add_enabled_ui(false, |ui| {
|
||||
align_button(ui, (VAlign::Center, Align::Center), false, "Align Center");
|
||||
});
|
||||
},
|
||||
Some(0usize),
|
||||
);
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.get_by_role_and_label(Role::Button, "Align Top Left").accesskit_node().toggled(), Some(Toggled::True));
|
||||
assert_eq!(h.get_by_role_and_label(Role::Button, "Align Bottom Right").accesskit_node().toggled(), Some(Toggled::False));
|
||||
assert!(h.get_by_role_and_label(Role::Button, "Align Center").accesskit_node().is_disabled());
|
||||
h.get_by_role_and_label(Role::Button, "Align Bottom Right").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(*h.state(), Some(1));
|
||||
assert_eq!(h.get_by_role_and_label(Role::Button, "Align Top Left").accesskit_node().toggled(), Some(Toggled::False));
|
||||
assert_eq!(h.get_by_role_and_label(Role::Button, "Align Bottom Right").accesskit_node().toggled(), Some(Toggled::True));
|
||||
h.get_by_role_and_label(Role::Button, "Align Bottom Right").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(*h.state(), None);
|
||||
assert_eq!(h.get_by_role_and_label(Role::Button, "Align Bottom Right").accesskit_node().toggled(), Some(Toggled::False));
|
||||
}
|
||||
|
||||
fn steps(h: &mut egui_kittest::Harness<'_, WordApp>) {
|
||||
for _ in 0..4 {
|
||||
h.step();
|
||||
@@ -671,11 +708,15 @@ mod tests {
|
||||
/// even banded rows) and no other.
|
||||
#[test]
|
||||
fn the_part_picker_edits_the_part_it_shows() {
|
||||
use egui::accesskit::Toggled;
|
||||
use egui_kittest::kittest::NodeT;
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app.run("insert.table", json!({"rows": 4, "cols": 3})).unwrap();
|
||||
app.run("table.newStyle", json!({"name": "Parts"})).unwrap();
|
||||
app.dialog = Dialog::open("modifyTableStyle", &mut app);
|
||||
assert!(matches!(app.dialog, Some(Dialog::TableStyle { .. })));
|
||||
// Keep the background ribbon's character controls out of the dialog's label queries.
|
||||
app.ui.tab = "Insert".into();
|
||||
let mut h = egui_kittest::Harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
@@ -691,15 +732,25 @@ mod tests {
|
||||
h.get_by_label("Even Banded Rows").click();
|
||||
steps(&mut h);
|
||||
assert!(matches!(&h.state().dialog, Some(Dialog::TableStyle { region, .. }) if *region == part_index(TablePart::Band2Horz)));
|
||||
h.get_by_label("B").click();
|
||||
steps(&mut h);
|
||||
for label in ["Bold", "Italic", "Underline"] {
|
||||
assert_eq!(h.get_by_label(label).accesskit_node().toggled(), Some(Toggled::False));
|
||||
h.get_by_label(label).click();
|
||||
steps(&mut h);
|
||||
assert_eq!(h.get_by_label(label).accesskit_node().toggled(), Some(Toggled::True));
|
||||
}
|
||||
h.get_by_label("OK").click();
|
||||
steps(&mut h);
|
||||
assert!(h.state().dialog.is_none(), "OK closes the dialog");
|
||||
let st = h.state().session.doc.styles.get("Parts").cloned().unwrap();
|
||||
assert_eq!(st.table_part(TablePart::Band2Horz).chr.bold, Some(true));
|
||||
let chr = st.table_part(TablePart::Band2Horz).chr;
|
||||
assert_eq!(chr.bold, Some(true));
|
||||
assert_eq!(chr.italic, Some(true));
|
||||
assert!(chr.underline.is_some_and(|u| u != Underline::None));
|
||||
for other in [TablePart::WholeTable, TablePart::Band1Horz, TablePart::FirstRow, TablePart::Band2Vert] {
|
||||
assert_ne!(st.table_part(other).chr.bold, Some(true), "{}", other.ooxml());
|
||||
let chr = st.table_part(other).chr;
|
||||
assert_ne!(chr.bold, Some(true), "{}", other.ooxml());
|
||||
assert_ne!(chr.italic, Some(true), "{}", other.ooxml());
|
||||
assert!(!chr.underline.is_some_and(|u| u != Underline::None), "{}", other.ooxml());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -122,128 +122,130 @@ fn font_dialog(app: &mut WordApp, ui: &mut Ui, d: &mut Dialog) -> bool {
|
||||
};
|
||||
let sample_props =
|
||||
font_sample_props(app, sample_paper(app), font, size, color, (*bold, *italic, *underline, *strike), (*small_caps, *caps, *hidden), *spacing);
|
||||
crate::rtl::Table::new("fontdlg").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
|
||||
// Word's two font boxes when East Asian text is in use: the Latin text font and
|
||||
// the Asian text font, each with its own list (type to find a font).
|
||||
let prev = app.previews.font_preview_fn();
|
||||
if *asian {
|
||||
crate::widgets::section(ui, "", |ui| {
|
||||
crate::rtl::Table::new("fontdlg").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
|
||||
// Word's two font boxes when East Asian text is in use: the Latin text font and
|
||||
// the Asian text font, each with its own list (type to find a font).
|
||||
let prev = app.previews.font_preview_fn();
|
||||
if *asian {
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Asian text font:")));
|
||||
r.cell(|ui| {
|
||||
let fams = app.previews.east_asian_families();
|
||||
let stored = app.previews.font_stored(font_ea);
|
||||
let latin = app.previews.font_stored(font);
|
||||
let warning = app.east_asian_font_box_warning(&stored, &latin);
|
||||
if let Some(f) = font_box(ui, ("fontdlg_asian", font_ea.as_str()), &fams, &*prev, warning.as_deref()) {
|
||||
if f == crate::widgets::ADD_FONT {
|
||||
let _ = app.run("font.add", json!({}));
|
||||
} else if f == crate::widgets::LOAD_SYSTEM_FONTS {
|
||||
let _ = app.run("font.loadSystem", json!({}));
|
||||
} else {
|
||||
*font_ea = f;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Asian text font:")));
|
||||
r.cell(|ui| ui.label(if *asian { tl!("Latin text font:") } else { tl!("Font:") }));
|
||||
r.cell(|ui| {
|
||||
let fams = app.previews.east_asian_families();
|
||||
let stored = app.previews.font_stored(font_ea);
|
||||
let latin = app.previews.font_stored(font);
|
||||
let warning = app.east_asian_font_box_warning(&stored, &latin);
|
||||
if let Some(f) = font_box(ui, ("fontdlg_asian", font_ea.as_str()), &fams, &*prev, warning.as_deref()) {
|
||||
let fams = app.previews.families();
|
||||
let stored = app.previews.font_stored(font);
|
||||
let warning = app.font_dialog_warning(&stored);
|
||||
if let Some(f) = font_box(ui, ("fontdlg_font", font.as_str()), &fams, &*prev, warning.as_deref()) {
|
||||
if f == crate::widgets::ADD_FONT {
|
||||
let _ = app.run("font.add", json!({}));
|
||||
} else if f == crate::widgets::LOAD_SYSTEM_FONTS {
|
||||
let _ = app.run("font.loadSystem", json!({}));
|
||||
} else {
|
||||
*font_ea = f;
|
||||
*font = f;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(if *asian { tl!("Latin text font:") } else { tl!("Font:") }));
|
||||
r.cell(|ui| {
|
||||
let fams = app.previews.families();
|
||||
let stored = app.previews.font_stored(font);
|
||||
let warning = app.font_dialog_warning(&stored);
|
||||
if let Some(f) = font_box(ui, ("fontdlg_font", font.as_str()), &fams, &*prev, warning.as_deref()) {
|
||||
if f == crate::widgets::ADD_FONT {
|
||||
let _ = app.run("font.add", json!({}));
|
||||
} else if f == crate::widgets::LOAD_SYSTEM_FONTS {
|
||||
let _ = app.run("font.loadSystem", json!({}));
|
||||
} else {
|
||||
*font = f;
|
||||
}
|
||||
}
|
||||
t.row(|r| {
|
||||
let size_label = r.cell(|ui| ui.label(tl!("Size:")));
|
||||
r.cell(|ui| ui.text_edit_singleline(size).labelled_by(size_label.id));
|
||||
});
|
||||
});
|
||||
t.row(|r| {
|
||||
let size_label = r.cell(|ui| ui.label(tl!("Size:")));
|
||||
r.cell(|ui| ui.text_edit_singleline(size).labelled_by(size_label.id));
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Font color:")));
|
||||
r.cell(|ui| {
|
||||
let theme = app.session.doc.settings.theme_colors.clone();
|
||||
color_field(ui, &theme, color, "Automatic", "auto");
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Font color:")));
|
||||
r.cell(|ui| {
|
||||
let theme = app.session.doc.settings.theme_colors.clone();
|
||||
color_field(ui, &theme, color, "Automatic", "auto");
|
||||
});
|
||||
});
|
||||
});
|
||||
t.row(|r| {
|
||||
let spacing_label = r.cell(|ui| ui.label(tl!("Spacing (pt):")));
|
||||
r.cell(|ui| ui.add(egui::DragValue::new(spacing).speed(0.1).range(-20.0..=20.0)).labelled_by(spacing_label.id));
|
||||
});
|
||||
t.row(|r| {
|
||||
let label = tl!("Kerning for fonts:");
|
||||
r.cell(|ui| match kern {
|
||||
Some(on) => {
|
||||
ui.checkbox(on, label);
|
||||
}
|
||||
None => {
|
||||
if ui.add(egui::Checkbox::new(&mut false, label).indeterminate(true)).clicked() {
|
||||
*kern = Some(true);
|
||||
}
|
||||
}
|
||||
t.row(|r| {
|
||||
let spacing_label = r.cell(|ui| ui.label(tl!("Spacing (pt):")));
|
||||
r.cell(|ui| ui.add(egui::DragValue::new(spacing).speed(0.1).range(-20.0..=20.0)).labelled_by(spacing_label.id));
|
||||
});
|
||||
r.cell(|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
let enabled = *kern == Some(true);
|
||||
let field = egui::DragValue::new(kern_at).speed(0.5).range(1.0..=1638.0).max_decimals(1);
|
||||
// The number comes first in the reading order, then "points and above"; a left-to-right
|
||||
// row in a right-to-left interface runs the other way, so there the label is first.
|
||||
if crate::rtl::on() && !crate::rtl::flows(ui) {
|
||||
let points_label = ui.label(tl!("Points and above"));
|
||||
ui.add_enabled(enabled, field).labelled_by(points_label.id);
|
||||
} else {
|
||||
let points = ui.add_enabled(enabled, field);
|
||||
let points_label = ui.label(tl!("Points and above"));
|
||||
points.labelled_by(points_label.id);
|
||||
t.row(|r| {
|
||||
let label = tl!("Kerning for fonts:");
|
||||
r.cell(|ui| match kern {
|
||||
Some(on) => {
|
||||
ui.checkbox(on, label);
|
||||
}
|
||||
None => {
|
||||
if ui.add(egui::Checkbox::new(&mut false, label).indeterminate(true)).clicked() {
|
||||
*kern = Some(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
r.cell(|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
let enabled = *kern == Some(true);
|
||||
let field = egui::DragValue::new(kern_at).speed(0.5).range(1.0..=1638.0).max_decimals(1);
|
||||
// The number comes first in the reading order, then "points and above"; a left-to-right
|
||||
// row in a right-to-left interface runs the other way, so there the label is first.
|
||||
if crate::rtl::on() && !crate::rtl::flows(ui) {
|
||||
let points_label = ui.label(tl!("Points and above"));
|
||||
ui.add_enabled(enabled, field).labelled_by(points_label.id);
|
||||
} else {
|
||||
let points = ui.add_enabled(enabled, field);
|
||||
let points_label = ui.label(tl!("Points and above"));
|
||||
points.labelled_by(points_label.id);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
ui.separator();
|
||||
ui.label(egui::RichText::new(tl!("Effects")).font(semibold(12.5)));
|
||||
crate::rtl::Table::new("fx").columns(2).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.checkbox(bold, tl!("Bold")));
|
||||
r.cell(|ui| ui.checkbox(italic, tl!("Italic")));
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.checkbox(underline, tl!("Underline")));
|
||||
r.cell(|ui| ui.checkbox(strike, tl!("Strikethrough")));
|
||||
});
|
||||
t.row(|r| {
|
||||
// Superscript and Subscript exclude each other: the one just ticked wins.
|
||||
let was_sup = *sup;
|
||||
r.cell(|ui| ui.checkbox(sup, tl!("Superscript")));
|
||||
r.cell(|ui| ui.checkbox(sub, tl!("Subscript")));
|
||||
if *sup && *sub {
|
||||
if was_sup {
|
||||
*sup = false;
|
||||
} else {
|
||||
*sub = false;
|
||||
crate::widgets::section(ui, tl!("Effects"), |ui| {
|
||||
crate::rtl::Table::new("fx").columns(2).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.checkbox(bold, tl!("Bold")));
|
||||
r.cell(|ui| ui.checkbox(italic, tl!("Italic")));
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.checkbox(underline, tl!("Underline")));
|
||||
r.cell(|ui| ui.checkbox(strike, tl!("Strikethrough")));
|
||||
});
|
||||
t.row(|r| {
|
||||
// Superscript and Subscript exclude each other: the one just ticked wins.
|
||||
let was_sup = *sup;
|
||||
r.cell(|ui| ui.checkbox(sup, tl!("Superscript")));
|
||||
r.cell(|ui| ui.checkbox(sub, tl!("Subscript")));
|
||||
if *sup && *sub {
|
||||
if was_sup {
|
||||
*sup = false;
|
||||
} else {
|
||||
*sub = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.checkbox(small_caps, tl!("Small caps")));
|
||||
r.cell(|ui| ui.checkbox(caps, tl!("All caps")));
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.checkbox(hidden, tl!("Hidden")));
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.checkbox(small_caps, tl!("Small caps")));
|
||||
r.cell(|ui| ui.checkbox(caps, tl!("All caps")));
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.checkbox(hidden, tl!("Hidden")));
|
||||
});
|
||||
});
|
||||
});
|
||||
// Live preview of the chosen font/size/colour/effects.
|
||||
ui.separator();
|
||||
ui.label(egui::RichText::new(tl!("Preview")).small().weak());
|
||||
font_sample_box(app, ui, sample_paper(app), &sample_props, (*sup, *sub), *hidden);
|
||||
crate::widgets::section(ui, tl!("Preview"), |ui| {
|
||||
font_sample_box(app, ui, sample_paper(app), &sample_props, (*sup, *sub), *hidden);
|
||||
});
|
||||
let (ok, cancel) = buttons(ui, tl!("OK"));
|
||||
if ok {
|
||||
apply_font(app, d);
|
||||
@@ -281,86 +283,92 @@ fn paragraph_dialog(app: &mut WordApp, ui: &mut Ui, d: &mut Dialog) -> bool {
|
||||
ui.add_space(6.0);
|
||||
match *tab {
|
||||
0 => {
|
||||
ui.label(egui::RichText::new(tl!("General")).font(semibold(12.5)));
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tl!("Direction:"));
|
||||
// Neither while the selected paragraphs differ.
|
||||
let blank = mixed.contains("bidi");
|
||||
for (value, text) in [(true, tl!("Right-to-left")), (false, tl!("Left-to-right"))] {
|
||||
if ui.radio(!blank && *rtl == value, text).clicked() {
|
||||
*rtl = value;
|
||||
mixed.remove("bidi");
|
||||
}
|
||||
}
|
||||
});
|
||||
const ALIGNS: [(&str, &str); 4] = [("left", "Left"), ("center", "Center"), ("right", "Right"), ("justify", "Justify")];
|
||||
ui.horizontal(|ui| {
|
||||
let align_label = ui.label(tl!("Alignment:"));
|
||||
let shown =
|
||||
if mixed.contains("align") { "" } else { ALIGNS.iter().find(|(v, _)| v == align).map_or(align.as_str(), |(_, l)| tl!(l)) };
|
||||
let combo = craft_ui::ComboBox::from_id_salt("para_align").selected_text(shown).show_ui(ui, |ui| {
|
||||
for (v, l) in ALIGNS {
|
||||
if ui.selectable_value(align, v.to_string(), tl!(l)).clicked() {
|
||||
mixed.remove("align");
|
||||
crate::widgets::section(ui, tl!("General"), |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tl!("Direction:"));
|
||||
// Neither while the selected paragraphs differ.
|
||||
let blank = mixed.contains("bidi");
|
||||
for (value, text) in [(true, tl!("Right-to-left")), (false, tl!("Left-to-right"))] {
|
||||
if ui.radio(!blank && *rtl == value, text).clicked() {
|
||||
*rtl = value;
|
||||
mixed.remove("bidi");
|
||||
}
|
||||
}
|
||||
});
|
||||
combo.response.labelled_by(align_label.id);
|
||||
});
|
||||
ui.label(egui::RichText::new(tl!("Indentation")).font(semibold(12.5)));
|
||||
// Mirrored indents are the inside and outside ones (they swap on even pages).
|
||||
let (l_label, r_label) = if opts[0] { ("Inside:", "Outside:") } else { ("Left:", "Right:") };
|
||||
crate::rtl::Table::new("ind").columns(4).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
let left_label = r.cell(|ui| ui.label(tl!(l_label)));
|
||||
r.cell(|ui| para_number(ui, left, ParaNumber::Length, "left", mixed, &left_label));
|
||||
let right_label = r.cell(|ui| ui.label(tl!(r_label)));
|
||||
r.cell(|ui| para_number(ui, right, ParaNumber::Length, "right", mixed, &right_label));
|
||||
});
|
||||
t.row(|r| {
|
||||
let first_label = r.cell(|ui| ui.label(tl!("First line:")));
|
||||
r.cell(|ui| para_number(ui, first, ParaNumber::Length, "indentFirst", mixed, &first_label));
|
||||
const ALIGNS: [(&str, &str); 4] = [("left", "Left"), ("center", "Center"), ("right", "Right"), ("justify", "Justify")];
|
||||
ui.horizontal(|ui| {
|
||||
let align_label = ui.label(tl!("Alignment:"));
|
||||
let shown =
|
||||
if mixed.contains("align") { "" } else { ALIGNS.iter().find(|(v, _)| v == align).map_or(align.as_str(), |(_, l)| tl!(l)) };
|
||||
let combo = craft_ui::ComboBox::from_id_salt("para_align").selected_text(shown).show_ui(ui, |ui| {
|
||||
for (v, l) in ALIGNS {
|
||||
if ui.selectable_value(align, v.to_string(), tl!(l)).clicked() {
|
||||
mixed.remove("align");
|
||||
}
|
||||
}
|
||||
});
|
||||
combo.response.labelled_by(align_label.id);
|
||||
});
|
||||
});
|
||||
para_check(ui, &mut opts[0], tl!("Mirror indents"), "mirrorIndents", mixed);
|
||||
ui.label(egui::RichText::new(tl!("Spacing")).font(semibold(12.5)));
|
||||
crate::rtl::Table::new("sp").columns(4).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
let before_label = r.cell(|ui| ui.label(tl!("Before:")));
|
||||
r.cell(|ui| para_number(ui, before, ParaNumber::Points, "spaceBefore", mixed, &before_label));
|
||||
let line_label = r.cell(|ui| ui.label(tl!("Line spacing:")));
|
||||
r.cell(|ui| para_number(ui, line, ParaNumber::Lines, "lineSpacing", mixed, &line_label));
|
||||
crate::widgets::section(ui, tl!("Indentation"), |ui| {
|
||||
// Mirrored indents are the inside and outside ones (they swap on even pages).
|
||||
let (l_label, r_label) = if opts[0] { ("Inside:", "Outside:") } else { ("Left:", "Right:") };
|
||||
crate::rtl::Table::new("ind").columns(4).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
let left_label = r.cell(|ui| ui.label(tl!(l_label)));
|
||||
r.cell(|ui| para_number(ui, left, ParaNumber::Length, "left", mixed, &left_label));
|
||||
let right_label = r.cell(|ui| ui.label(tl!(r_label)));
|
||||
r.cell(|ui| para_number(ui, right, ParaNumber::Length, "right", mixed, &right_label));
|
||||
});
|
||||
t.row(|r| {
|
||||
let first_label = r.cell(|ui| ui.label(tl!("First line:")));
|
||||
r.cell(|ui| para_number(ui, first, ParaNumber::Length, "indentFirst", mixed, &first_label));
|
||||
});
|
||||
});
|
||||
t.row(|r| {
|
||||
let after_label = r.cell(|ui| ui.label(tl!("After:")));
|
||||
r.cell(|ui| para_number(ui, after, ParaNumber::Points, "spaceAfter", mixed, &after_label));
|
||||
para_check(ui, &mut opts[0], tl!("Mirror indents"), "mirrorIndents", mixed);
|
||||
});
|
||||
crate::widgets::section(ui, tl!("Spacing"), |ui| {
|
||||
crate::rtl::Table::new("sp").columns(4).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
let before_label = r.cell(|ui| ui.label(tl!("Before:")));
|
||||
r.cell(|ui| para_number(ui, before, ParaNumber::Points, "spaceBefore", mixed, &before_label));
|
||||
let line_label = r.cell(|ui| ui.label(tl!("Line spacing:")));
|
||||
r.cell(|ui| para_number(ui, line, ParaNumber::Lines, "lineSpacing", mixed, &line_label));
|
||||
});
|
||||
t.row(|r| {
|
||||
let after_label = r.cell(|ui| ui.label(tl!("After:")));
|
||||
r.cell(|ui| para_number(ui, after, ParaNumber::Points, "spaceAfter", mixed, &after_label));
|
||||
});
|
||||
});
|
||||
});
|
||||
para_check(ui, &mut opts[1], tl!("Don't add space between paragraphs of the same style"), "contextualSpacing", mixed);
|
||||
}
|
||||
1 => {
|
||||
ui.label(egui::RichText::new(tl!("Line and Page Breaks")).font(semibold(12.5)));
|
||||
para_check(ui, widow, tl!("Widow/Orphan control"), "widowControl", mixed);
|
||||
para_check(ui, keep_next, tl!("Keep with next"), "keepNext", mixed);
|
||||
para_check(ui, keep_lines, tl!("Keep lines together"), "keepLines", mixed);
|
||||
para_check(ui, page_break, tl!("Page break before"), "pageBreakBefore", mixed);
|
||||
ui.label(egui::RichText::new(tl!("Formatting exceptions")).font(semibold(12.5)));
|
||||
para_check(ui, &mut opts[2], tl!("Suppress line numbers"), "suppressLineNumbers", mixed);
|
||||
para_check(ui, &mut opts[3], tl!("Don't hyphenate"), "suppressHyphens", mixed);
|
||||
crate::widgets::section(ui, tl!("Line and Page Breaks"), |ui| {
|
||||
para_check(ui, widow, tl!("Widow/Orphan control"), "widowControl", mixed);
|
||||
para_check(ui, keep_next, tl!("Keep with next"), "keepNext", mixed);
|
||||
para_check(ui, keep_lines, tl!("Keep lines together"), "keepLines", mixed);
|
||||
para_check(ui, page_break, tl!("Page break before"), "pageBreakBefore", mixed);
|
||||
});
|
||||
crate::widgets::section(ui, tl!("Formatting exceptions"), |ui| {
|
||||
para_check(ui, &mut opts[2], tl!("Suppress line numbers"), "suppressLineNumbers", mixed);
|
||||
para_check(ui, &mut opts[3], tl!("Don't hyphenate"), "suppressHyphens", mixed);
|
||||
});
|
||||
}
|
||||
_ => {
|
||||
let [kinsoku, word_wrap, overflow, top_line, de, dn] = asian;
|
||||
ui.label(egui::RichText::new(tl!("Line breaking")).font(semibold(12.5)));
|
||||
para_check(ui, kinsoku, tl!("Apply Asian line-breaking rules (kinsoku)"), "kinsoku", mixed);
|
||||
// The model's flag is "wrap whole words"; the box offers the opposite.
|
||||
let mut mid_word = !*word_wrap;
|
||||
para_check(ui, &mut mid_word, tl!("Allow Latin text to wrap in the middle of a word"), "wordWrap", mixed);
|
||||
*word_wrap = !mid_word;
|
||||
para_check(ui, overflow, tl!("Allow hanging punctuation"), "overflowPunct", mixed);
|
||||
ui.label(egui::RichText::new(tl!("Character Spacing")).font(semibold(12.5)));
|
||||
para_check(ui, top_line, tl!("Compress punctuation at the start of a line"), "topLinePunct", mixed);
|
||||
para_check(ui, de, tl!("Add space between Asian and Latin text"), "autoSpaceDE", mixed);
|
||||
para_check(ui, dn, tl!("Add space between Asian text and numbers"), "autoSpaceDN", mixed);
|
||||
crate::widgets::section(ui, tl!("Line breaking"), |ui| {
|
||||
para_check(ui, kinsoku, tl!("Apply Asian line-breaking rules (kinsoku)"), "kinsoku", mixed);
|
||||
// The model's flag is "wrap whole words"; the box offers the opposite.
|
||||
let mut mid_word = !*word_wrap;
|
||||
para_check(ui, &mut mid_word, tl!("Allow Latin text to wrap in the middle of a word"), "wordWrap", mixed);
|
||||
*word_wrap = !mid_word;
|
||||
para_check(ui, overflow, tl!("Allow hanging punctuation"), "overflowPunct", mixed);
|
||||
});
|
||||
crate::widgets::section(ui, tl!("Character Spacing"), |ui| {
|
||||
para_check(ui, top_line, tl!("Compress punctuation at the start of a line"), "topLinePunct", mixed);
|
||||
para_check(ui, de, tl!("Add space between Asian and Latin text"), "autoSpaceDE", mixed);
|
||||
para_check(ui, dn, tl!("Add space between Asian text and numbers"), "autoSpaceDN", mixed);
|
||||
});
|
||||
}
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
@@ -619,57 +627,66 @@ fn page_setup_dialog(app: &mut WordApp, ui: &mut Ui, d: &mut Dialog) -> bool {
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
ui.label(egui::RichText::new(tl!("Margins")).font(semibold(12.5)));
|
||||
crate::rtl::Table::new("ps").columns(4).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
let top_label = r.cell(|ui| ui.label(tl!("Top:")));
|
||||
r.cell(|ui| ui.add(margin(top)).labelled_by(top_label.id));
|
||||
let bottom_label = r.cell(|ui| ui.label(tl!("Bottom:")));
|
||||
r.cell(|ui| ui.add(margin(bottom)).labelled_by(bottom_label.id));
|
||||
});
|
||||
t.row(|r| {
|
||||
let left_label = r.cell(|ui| ui.label(if *mirror { tl!("Inside:") } else { tl!("Left:") }));
|
||||
r.cell(|ui| ui.add(margin(left)).labelled_by(left_label.id));
|
||||
let right_label = r.cell(|ui| ui.label(if *mirror { tl!("Outside:") } else { tl!("Right:") }));
|
||||
r.cell(|ui| ui.add(margin(right)).labelled_by(right_label.id));
|
||||
crate::widgets::section(ui, tl!("Margins"), |ui| {
|
||||
crate::rtl::Table::new("ps").columns(4).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
let top_label = r.cell(|ui| ui.label(tl!("Top:")));
|
||||
r.cell(|ui| ui.add(margin(top)).labelled_by(top_label.id));
|
||||
let bottom_label = r.cell(|ui| ui.label(tl!("Bottom:")));
|
||||
r.cell(|ui| ui.add(margin(bottom)).labelled_by(bottom_label.id));
|
||||
});
|
||||
t.row(|r| {
|
||||
let left_label = r.cell(|ui| ui.label(if *mirror { tl!("Inside:") } else { tl!("Left:") }));
|
||||
r.cell(|ui| ui.add(margin(left)).labelled_by(left_label.id));
|
||||
let right_label = r.cell(|ui| ui.label(if *mirror { tl!("Outside:") } else { tl!("Right:") }));
|
||||
r.cell(|ui| ui.add(margin(right)).labelled_by(right_label.id));
|
||||
});
|
||||
});
|
||||
});
|
||||
ui.label(egui::RichText::new(tl!("Orientation")).font(semibold(12.5)));
|
||||
ui.horizontal(|ui| {
|
||||
ui.radio_value(landscape, false, tl!("Portrait"));
|
||||
ui.radio_value(landscape, true, tl!("Landscape"));
|
||||
});
|
||||
ui.label(egui::RichText::new(tl!("Pages")).font(semibold(12.5)));
|
||||
ui.checkbox(mirror, tl!("Mirror margins"));
|
||||
page_paper_group(ui, paper, landscape, paper_custom);
|
||||
ui.label(egui::RichText::new(tl!("Document Grid")).font(semibold(12.5)));
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.radio_value(&mut grid.0, 0, tl!("No grid"));
|
||||
ui.radio_value(&mut grid.0, 1, tl!("Lines only"));
|
||||
ui.radio_value(&mut grid.0, 2, tl!("Lines and characters"));
|
||||
ui.radio_value(&mut grid.0, 3, tl!("Text snaps to characters"));
|
||||
});
|
||||
crate::rtl::Table::new("ps_grid").columns(4).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
let chars_label = r.cell(|ui| ui.add_enabled(grid.0 >= 2, egui::Label::new(tl!("Characters per line:"))));
|
||||
r.cell(|ui| ui.add_enabled(grid.0 >= 2, egui::DragValue::new(&mut grid.2).range(1..=1000).clip_text(true)).labelled_by(chars_label.id));
|
||||
let lines_label = r.cell(|ui| ui.add_enabled(grid.0 >= 1, egui::Label::new(tl!("Lines per page:"))));
|
||||
r.cell(|ui| ui.add_enabled(grid.0 >= 1, egui::DragValue::new(&mut grid.1).range(1..=1000).clip_text(true)).labelled_by(lines_label.id));
|
||||
crate::widgets::section(ui, tl!("Orientation"), |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.radio_value(landscape, false, tl!("Portrait"));
|
||||
ui.radio_value(landscape, true, tl!("Landscape"));
|
||||
});
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tl!("Section direction:"));
|
||||
ui.radio_value(rtl, false, tl!("Left-to-right"));
|
||||
ui.radio_value(rtl, true, tl!("Right-to-left"));
|
||||
crate::widgets::section(ui, tl!("Pages"), |ui| {
|
||||
ui.checkbox(mirror, tl!("Mirror margins"));
|
||||
page_paper_group(ui, paper, landscape, paper_custom);
|
||||
});
|
||||
crate::widgets::section(ui, tl!("Document Grid"), |ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.radio_value(&mut grid.0, 0, tl!("No grid"));
|
||||
ui.radio_value(&mut grid.0, 1, tl!("Lines only"));
|
||||
ui.radio_value(&mut grid.0, 2, tl!("Lines and characters"));
|
||||
ui.radio_value(&mut grid.0, 3, tl!("Text snaps to characters"));
|
||||
});
|
||||
crate::rtl::Table::new("ps_grid").columns(4).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
let chars_label = r.cell(|ui| ui.add_enabled(grid.0 >= 2, egui::Label::new(tl!("Characters per line:"))));
|
||||
r.cell(|ui| {
|
||||
ui.add_enabled(grid.0 >= 2, egui::DragValue::new(&mut grid.2).range(1..=1000).clip_text(true)).labelled_by(chars_label.id)
|
||||
});
|
||||
let lines_label = r.cell(|ui| ui.add_enabled(grid.0 >= 1, egui::Label::new(tl!("Lines per page:"))));
|
||||
r.cell(|ui| {
|
||||
ui.add_enabled(grid.0 >= 1, egui::DragValue::new(&mut grid.1).range(1..=1000).clip_text(true)).labelled_by(lines_label.id)
|
||||
});
|
||||
});
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tl!("Section direction:"));
|
||||
ui.radio_value(rtl, false, tl!("Left-to-right"));
|
||||
ui.radio_value(rtl, true, tl!("Right-to-left"));
|
||||
});
|
||||
if !message.is_empty() {
|
||||
ui.label(egui::RichText::new(message.as_str()).small().color(ui.visuals().error_fg_color));
|
||||
}
|
||||
page_valign_combo(ui, valign);
|
||||
});
|
||||
crate::widgets::section(ui, tl!("Headers and footers"), |ui| {
|
||||
// Word's Page Setup › Layout: a title page without the page number (#1230).
|
||||
ui.checkbox(odd_even, tl!("Different Odd & Even Pages"));
|
||||
ui.checkbox(first_page, tl!("Different First Page"));
|
||||
});
|
||||
if !message.is_empty() {
|
||||
ui.label(egui::RichText::new(message.as_str()).small().color(ui.visuals().error_fg_color));
|
||||
}
|
||||
page_valign_combo(ui, valign);
|
||||
// Word's Page Setup › Layout: a title page without the page number (#1230).
|
||||
ui.label(egui::RichText::new(tl!("Headers and footers")).font(semibold(12.5)));
|
||||
ui.checkbox(odd_even, tl!("Different Odd & Even Pages"));
|
||||
ui.checkbox(first_page, tl!("Different First Page"));
|
||||
let (mut ok, cancel) = buttons(ui, tl!("OK"));
|
||||
if ok {
|
||||
// Everything OK changes is one undo step; a refused command applies nothing.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::chrome::buttons;
|
||||
use super::{MeasureExt, Sense, Serialize, Tokens, Ui, Value, WordApp, json, semibold, vec2};
|
||||
use super::{MeasureExt, Sense, Serialize, Tokens, Ui, Value, WordApp, json, vec2};
|
||||
|
||||
/// The Custom tab of File › Info › Properties › Advanced Properties (#2982): the document's
|
||||
/// custom properties, edited as a working copy. OK sends the whole difference from what the
|
||||
@@ -385,85 +385,88 @@ pub(super) fn table_properties(ui: &mut Ui, f: &mut TableForm) {
|
||||
fn len(v: &mut f32, lo: f32, unit: wordcraft_geom::Unit) -> egui::DragValue<'_> {
|
||||
egui::DragValue::new(v).speed(0.01).range(lo..=22.0).measure(unit).max_decimals(2)
|
||||
}
|
||||
let heading = |ui: &mut Ui, s: &str| {
|
||||
ui.add_space(4.0);
|
||||
ui.label(egui::RichText::new(tl!(s)).font(semibold(12.5)));
|
||||
};
|
||||
heading(ui, "Table");
|
||||
crate::rtl::Table::new("tp_table").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.checkbox(&mut f.width_on, tl!("Preferred width:")));
|
||||
r.cell(|ui| ui.add_enabled(f.width_on, len(&mut f.width, 0.1, unit)));
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Alignment:")));
|
||||
r.cell(|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
for (v, l) in [("left", "Left"), ("center", "Center"), ("right", "Right")] {
|
||||
ui.radio_value(&mut f.align, v.to_string(), tl!(l));
|
||||
}
|
||||
crate::widgets::section(ui, tl!("Table"), |ui| {
|
||||
crate::rtl::Table::new("tp_table").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.checkbox(&mut f.width_on, tl!("Preferred width:")));
|
||||
r.cell(|ui| ui.add_enabled(f.width_on, len(&mut f.width, 0.1, unit)));
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Alignment:")));
|
||||
r.cell(|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
for (v, l) in [("left", "Left"), ("center", "Center"), ("right", "Right")] {
|
||||
ui.radio_value(&mut f.align, v.to_string(), tl!(l));
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Indent from left:")));
|
||||
r.cell(|ui| {
|
||||
ui.add_enabled(f.align == "left", egui::DragValue::new(&mut f.indent).speed(0.01).range(-11.0..=22.0).measure(unit).max_decimals(2))
|
||||
});
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Table direction:")));
|
||||
r.cell(|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.radio_value(&mut f.rtl, false, tl!("Left-to-right"));
|
||||
ui.radio_value(&mut f.rtl, true, tl!("Right-to-left"));
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Indent from left:")));
|
||||
r.cell(|ui| {
|
||||
ui.add_enabled(
|
||||
f.align == "left",
|
||||
egui::DragValue::new(&mut f.indent).speed(0.01).range(-11.0..=22.0).measure(unit).max_decimals(2),
|
||||
)
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
heading(ui, "Row");
|
||||
crate::rtl::Table::new("tp_row").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
let specify = r.cell(|ui| ui.checkbox(&mut f.row_height_on, tl!("Specify height:")));
|
||||
r.cell(|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_enabled(f.row_height_on, len(&mut f.row_height, 0.02, unit));
|
||||
ui.add_enabled_ui(f.row_height_on, |ui| {
|
||||
let rule = craft_ui::ComboBox::from_id_salt("tp_rule")
|
||||
.selected_text(tl!(if f.row_exact { "Exactly" } else { "At least" }))
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut f.row_exact, false, tl!("At least"));
|
||||
ui.selectable_value(&mut f.row_exact, true, tl!("Exactly"));
|
||||
});
|
||||
// A screen reader names the rule by the box it belongs to.
|
||||
rule.response.labelled_by(specify.id);
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Table direction:")));
|
||||
r.cell(|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.radio_value(&mut f.rtl, false, tl!("Left-to-right"));
|
||||
ui.radio_value(&mut f.rtl, true, tl!("Right-to-left"));
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
super::paragraph::para_check(ui, &mut f.allow_break, tl!("Allow row to break across pages"), "allowBreak", &mut f.mixed);
|
||||
super::paragraph::para_check(ui, &mut f.header_row, tl!("Repeat as header row on each page"), "headerRow", &mut f.mixed);
|
||||
heading(ui, "Column");
|
||||
crate::rtl::Table::new("tp_col").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Preferred width:")));
|
||||
r.cell(|ui| ui.add(len(&mut f.column_width, 0.1, unit)));
|
||||
crate::widgets::section(ui, tl!("Row"), |ui| {
|
||||
crate::rtl::Table::new("tp_row").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
let specify = r.cell(|ui| ui.checkbox(&mut f.row_height_on, tl!("Specify height:")));
|
||||
r.cell(|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_enabled(f.row_height_on, len(&mut f.row_height, 0.02, unit));
|
||||
ui.add_enabled_ui(f.row_height_on, |ui| {
|
||||
let rule = craft_ui::ComboBox::from_id_salt("tp_rule")
|
||||
.selected_text(tl!(if f.row_exact { "Exactly" } else { "At least" }))
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut f.row_exact, false, tl!("At least"));
|
||||
ui.selectable_value(&mut f.row_exact, true, tl!("Exactly"));
|
||||
});
|
||||
// A screen reader names the rule by the box it belongs to.
|
||||
rule.response.labelled_by(specify.id);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
super::paragraph::para_check(ui, &mut f.allow_break, tl!("Allow row to break across pages"), "allowBreak", &mut f.mixed);
|
||||
super::paragraph::para_check(ui, &mut f.header_row, tl!("Repeat as header row on each page"), "headerRow", &mut f.mixed);
|
||||
});
|
||||
crate::widgets::section(ui, tl!("Column"), |ui| {
|
||||
crate::rtl::Table::new("tp_col").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Preferred width:")));
|
||||
r.cell(|ui| ui.add(len(&mut f.column_width, 0.1, unit)));
|
||||
});
|
||||
});
|
||||
});
|
||||
heading(ui, "Cell");
|
||||
crate::rtl::Table::new("tp_cell").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.checkbox(&mut f.cell_width_on, tl!("Preferred width:")));
|
||||
r.cell(|ui| ui.add_enabled(f.cell_width_on, len(&mut f.cell_width, 0.1, unit)));
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Vertical alignment:")));
|
||||
r.cell(|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
for (v, l) in [("top", "Top"), ("center", "Center"), ("bottom", "Bottom")] {
|
||||
ui.radio_value(&mut f.valign, v.to_string(), tl!(l));
|
||||
}
|
||||
crate::widgets::section(ui, tl!("Cell"), |ui| {
|
||||
crate::rtl::Table::new("tp_cell").columns(2).spacing(vec2(10.0, 6.0)).show(ui, |t| {
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.checkbox(&mut f.cell_width_on, tl!("Preferred width:")));
|
||||
r.cell(|ui| ui.add_enabled(f.cell_width_on, len(&mut f.cell_width, 0.1, unit)));
|
||||
});
|
||||
t.row(|r| {
|
||||
r.cell(|ui| ui.label(tl!("Vertical alignment:")));
|
||||
r.cell(|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
for (v, l) in [("top", "Top"), ("center", "Center"), ("bottom", "Bottom")] {
|
||||
ui.radio_value(&mut f.valign, v.to_string(), tl!(l));
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1868,6 +1868,27 @@ fn the_custom_properties_dialog_leaves_imported_non_text_properties_alone() {
|
||||
assert_eq!(kinds, [("Status", "lpwstr"), ("Count", "i4")], "Cancel leaves the imported property as it was");
|
||||
}
|
||||
|
||||
/// A tall dialog on a short screen stays inside it and scrolls.
|
||||
#[test]
|
||||
fn a_tall_dialog_fits_a_short_screen() {
|
||||
let mut app = app_with("Some text");
|
||||
app.dialog = Dialog::open("pageSetup", &mut app);
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 360.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
for _ in 0..4 {
|
||||
h.step();
|
||||
}
|
||||
let id = egui::Id::unique(("dialog", "Page Setup"));
|
||||
let rect = h.ctx.memory(|m| m.area_rect(id)).expect("the dialog is open");
|
||||
assert!(rect.height() <= 360.5, "the dialog is {}pt tall on a 360pt screen", rect.height());
|
||||
}
|
||||
|
||||
/// #3859: a dialog is modal, as in Word. While Font is open, typing (from the frame it opens),
|
||||
/// Mod+O and a click on File reach nothing behind it, and the dialog itself still works. Find
|
||||
/// and Replace is modeless: with it open, File still opens.
|
||||
|
||||
@@ -12,6 +12,7 @@ use std::path::{Path, PathBuf};
|
||||
use egui::{Align2, Rect, Sense, Ui, pos2, vec2};
|
||||
|
||||
use crate::file_dialogs::{AfterPick, FileDialogRequest, open_filters};
|
||||
use crate::print_page::{EXPORT_FORMATS, export_file_ext, export_name, is_document_ext};
|
||||
use crate::theme::{Tokens, regular};
|
||||
use crate::{WordApp, icons};
|
||||
|
||||
@@ -138,6 +139,8 @@ pub(crate) struct FileBrowser {
|
||||
/// The file types, as (label, extensions).
|
||||
filters: Vec<(String, Vec<String>)>,
|
||||
filter: usize,
|
||||
/// Exporting: the format behind each type, which `after` follows; empty otherwise.
|
||||
exports: Vec<String>,
|
||||
listing: Result<Listing, String>,
|
||||
/// The highlighted entry.
|
||||
selected: Option<PathBuf>,
|
||||
@@ -158,6 +161,15 @@ impl FileBrowser {
|
||||
(name.clone(), f)
|
||||
}
|
||||
};
|
||||
// Exporting (#3535): File › Export's formats are the types, starting on the one asked for.
|
||||
let (filters, filter, exports) = match &after {
|
||||
AfterPick::Export { ext } => (
|
||||
EXPORT_FORMATS.iter().map(|&(l, f)| (l.to_string(), vec![export_file_ext(f).to_string()])).collect(),
|
||||
EXPORT_FORMATS.iter().position(|&(_, f)| f == ext.as_str()).unwrap_or(0),
|
||||
EXPORT_FORMATS.iter().map(|&(_, f)| f.to_string()).collect(),
|
||||
),
|
||||
_ => (filters, 0, Vec::new()),
|
||||
};
|
||||
let mut b = FileBrowser {
|
||||
req,
|
||||
after,
|
||||
@@ -166,7 +178,8 @@ impl FileBrowser {
|
||||
location: String::new(),
|
||||
name,
|
||||
filters,
|
||||
filter: 0,
|
||||
filter,
|
||||
exports,
|
||||
listing: Ok(Listing::default()),
|
||||
selected: None,
|
||||
note: Note::None,
|
||||
@@ -189,6 +202,16 @@ impl FileBrowser {
|
||||
self.note = Note::None;
|
||||
}
|
||||
|
||||
/// A type was chosen: when exporting it is the format, and the name's export extension follows it.
|
||||
fn type_changed(&mut self) {
|
||||
let Some(format) = self.exports.get(self.filter).cloned() else { return };
|
||||
// Only a known document extension is replaced; `notes.v2` keeps its `.v2`.
|
||||
if Path::new(&self.name).extension().and_then(|e| e.to_str()).is_some_and(is_document_ext) {
|
||||
self.name = export_name(&self.name, &format);
|
||||
}
|
||||
self.after = AfterPick::Export { ext: format };
|
||||
}
|
||||
|
||||
fn up(&mut self) {
|
||||
if let Some(parent) = self.dir.parent().map(Path::to_path_buf) {
|
||||
self.navigate(parent);
|
||||
@@ -196,8 +219,8 @@ impl FileBrowser {
|
||||
}
|
||||
|
||||
/// OK: a highlighted folder, or a typed folder, is opened; otherwise the typed name is the
|
||||
/// pick. Save adds the chosen type's extension to a name without one and asks once more
|
||||
/// before replacing a file; Open wants a file that exists.
|
||||
/// pick. Save adds the chosen type's extension to a name without one (an export replaces a
|
||||
/// known document extension with the type's) and asks once more before replacing a file; Open wants a file that exists.
|
||||
pub(crate) fn accept(&mut self) -> Step {
|
||||
if let Some(dir) = self.selected.take().filter(|p| p.is_dir()) {
|
||||
self.navigate(dir);
|
||||
@@ -218,7 +241,11 @@ impl FileBrowser {
|
||||
Step::Stay
|
||||
}
|
||||
FileDialogRequest::Save { .. } => {
|
||||
if path.extension().is_none()
|
||||
if let AfterPick::Export { ext } = &self.after {
|
||||
// The chosen type is the format: its extension replaces a known document
|
||||
// extension on the name, and is added to any other.
|
||||
path = PathBuf::from(export_name(&path.to_string_lossy(), ext));
|
||||
} else if path.extension().is_none()
|
||||
&& let Some(ext) = self.exts().first().filter(|e| e.as_str() != "*")
|
||||
{
|
||||
path.set_extension(ext);
|
||||
@@ -273,10 +300,11 @@ impl WordApp {
|
||||
self.file_browser.open = Some(Box::new(FileBrowser::new(req, after, start, unavailable)));
|
||||
}
|
||||
|
||||
/// `ui.fileBrowser`: the built-in browser for `purpose` (document, picture, recipients, save),
|
||||
/// even when a system dialog was asked for and never showed up (it is given up as cancelled).
|
||||
/// `ui.fileBrowser`: the built-in browser for `purpose` (document, picture, recipients, save,
|
||||
/// export), even when a system dialog was asked for and never showed up (it is given up as cancelled).
|
||||
pub(crate) fn browse_builtin(&mut self, purpose: &str) {
|
||||
self.give_up_file_dialog();
|
||||
// An export that was waiting on the system dialog keeps its format.
|
||||
let pending = self.give_up_file_dialog();
|
||||
if self.file_browser.open.is_some() {
|
||||
return;
|
||||
}
|
||||
@@ -287,6 +315,11 @@ impl WordApp {
|
||||
FileDialogRequest::Save { name: self.default_save_name(), dir: None },
|
||||
AfterPick::SaveAs { after: crate::file_dialogs::AfterSave::Nothing, document: self.session.document_id() },
|
||||
),
|
||||
"export" => {
|
||||
let ext = pending.unwrap_or_else(|| "pdf".into());
|
||||
let name = format!("{}.{}", self.title_stem(), export_file_ext(&ext));
|
||||
(FileDialogRequest::Save { name, dir: None }, AfterPick::Export { ext })
|
||||
}
|
||||
_ => (FileDialogRequest::Open { purpose: "document".into() }, AfterPick::OpenDocument { document: self.session.document_id() }),
|
||||
};
|
||||
self.show_file_browser(req, after, false);
|
||||
@@ -386,6 +419,9 @@ fn body(ui: &mut Ui, b: &mut FileBrowser, t: &Tokens) -> Option<Option<PathBuf>>
|
||||
}
|
||||
for e in entries.get(range).unwrap_or(&[]) {
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), ROW), Sense::click());
|
||||
resp.widget_info(|| {
|
||||
egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), b.selected.as_ref() == Some(&e.path), &e.name)
|
||||
});
|
||||
if b.selected.as_ref() == Some(&e.path) {
|
||||
ui.painter().rect_filled(r, 2.0, t.checked);
|
||||
} else if resp.hovered() {
|
||||
@@ -471,6 +507,7 @@ fn body(ui: &mut Ui, b: &mut FileBrowser, t: &Tokens) -> Option<Option<PathBuf>>
|
||||
refilter = b.filter != before;
|
||||
});
|
||||
if refilter {
|
||||
b.type_changed();
|
||||
b.navigate(b.dir.clone());
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
@@ -731,6 +768,206 @@ mod tests {
|
||||
assert!(crate::keytips::suppressed(&a, &ctx));
|
||||
}
|
||||
|
||||
/// Drawn entries have names and selection state, and choosing one still picks its path.
|
||||
#[test]
|
||||
fn entries_expose_names_selection_and_picking() {
|
||||
use egui::accesskit::{Role, Toggled};
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
let dir = scratch("entry_accessibility");
|
||||
let folder = dir.join("Drafts");
|
||||
let file = dir.join("chapter.docx");
|
||||
std::fs::create_dir(&folder).unwrap();
|
||||
std::fs::write(&file, b"x").unwrap();
|
||||
let browser =
|
||||
FileBrowser::new(FileDialogRequest::Open { purpose: "document".into() }, AfterPick::OpenDocument { document: 0 }, dir.clone(), false);
|
||||
// Font changes take effect next frame; the buttons need the named semibold family.
|
||||
let mut fonts = false;
|
||||
let mut h = egui_kittest::Harness::builder().with_size(vec2(760.0, 520.0)).build_ui_state(
|
||||
move |ui, state: &mut (FileBrowser, Option<Option<PathBuf>>)| {
|
||||
if !fonts {
|
||||
crate::theme::install_fonts(ui.ctx());
|
||||
fonts = true;
|
||||
return;
|
||||
}
|
||||
let t = Tokens::get(ui.ctx());
|
||||
if let Some(picked) = body(ui, &mut state.0, &t) {
|
||||
state.1 = Some(picked);
|
||||
}
|
||||
},
|
||||
(browser, None),
|
||||
);
|
||||
h.run_steps(4);
|
||||
for name in ["Drafts", "chapter.docx"] {
|
||||
assert_eq!(h.get_by_role_and_label(Role::Button, name).accesskit_node().toggled(), Some(Toggled::False));
|
||||
}
|
||||
h.get_by_role_and_label(Role::Button, "Drafts").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().0.selected.as_ref(), Some(&folder));
|
||||
assert_eq!(h.get_by_role_and_label(Role::Button, "Drafts").accesskit_node().toggled(), Some(Toggled::True));
|
||||
h.get_by_role_and_label(Role::Button, "chapter.docx").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().0.selected.as_ref(), Some(&file));
|
||||
assert_eq!(h.state().0.name, "chapter.docx");
|
||||
assert_eq!(h.get_by_role_and_label(Role::Button, "Drafts").accesskit_node().toggled(), Some(Toggled::False));
|
||||
assert_eq!(h.get_by_role_and_label(Role::Button, "chapter.docx").accesskit_node().toggled(), Some(Toggled::True));
|
||||
h.get_by_role_and_label(Role::Button, "Open").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().1, Some(Some(file)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #3535: exporting offers File › Export's formats as the types; the chosen one is the format,
|
||||
/// the name's extension follows it, and the export writes that format.
|
||||
#[test]
|
||||
fn export_types_choose_the_format_and_the_extension() {
|
||||
let dir = scratch("export");
|
||||
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
|
||||
a.run("text.insert", json!({"text": "Exported in WordCraft"})).unwrap();
|
||||
a.run("ui.fileBrowser", json!({"purpose": "export"})).unwrap();
|
||||
let b = a.file_browser.open.as_mut().expect("the built-in browser is open");
|
||||
assert_eq!(b.filters.len(), EXPORT_FORMATS.len());
|
||||
assert_eq!(b.filters[b.filter].0, "PDF document (*.pdf)");
|
||||
assert!(b.name.ends_with(".pdf"), "{}", b.name);
|
||||
b.filter = b.filters.iter().position(|(l, _)| l == "Plain text (*.txt)").unwrap();
|
||||
b.type_changed();
|
||||
assert!(b.name.ends_with(".txt"), "{}", b.name);
|
||||
assert!(matches!(&b.after, AfterPick::Export { ext } if ext == "txt"));
|
||||
b.navigate(dir.clone());
|
||||
// A name typed afterwards with another document extension gets the chosen format's instead,
|
||||
// and a name with an unknown one keeps it.
|
||||
b.name = "notes.v2".into();
|
||||
let Step::Pick(v2) = b.accept() else { panic!("picked") };
|
||||
assert_eq!(v2.file_name().unwrap(), "notes.v2.txt");
|
||||
b.name = "notes.docx".into();
|
||||
let Step::Pick(path) = b.accept() else { panic!("picked") };
|
||||
assert_eq!(path.file_name().unwrap(), "notes.txt");
|
||||
for (typed, want) in [
|
||||
("a.PDF", "a.txt"),
|
||||
("a.htm", "a.txt"),
|
||||
("a", "a.txt"),
|
||||
("a.TXT", "a.TXT"),
|
||||
("sub/a.rtf", "sub/a.txt"),
|
||||
(".txt", ".txt.txt"),
|
||||
(".docx", ".docx.txt"),
|
||||
("sub/.docx", "sub/.docx.txt"),
|
||||
("a.", "a.txt"),
|
||||
("a..", "a.txt"),
|
||||
] {
|
||||
assert_eq!(crate::print_page::export_name(typed, "txt"), want);
|
||||
}
|
||||
a.close_file_browser(Some(path.clone()));
|
||||
assert!(std::fs::read_to_string(&path).unwrap().contains("Exported in WordCraft"));
|
||||
// Word 2003 XML starts on its own type, though Word XML writes .xml too.
|
||||
let req = FileDialogRequest::Save { name: "x.xml".into(), dir: None };
|
||||
let b = FileBrowser::new(req, AfterPick::Export { ext: crate::print_page::EXPORT_WORD_2003.into() }, dir.clone(), false);
|
||||
assert_eq!(b.filters[b.filter].0, "Word 2003 XML Document (*.xml)");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The OpenDocument template and flat-XML exports are types of their own: the name gets
|
||||
/// their extension, and the export saves by it.
|
||||
#[test]
|
||||
fn export_types_include_the_opendocument_template_and_flat_xml() {
|
||||
let dir = scratch("export_ott");
|
||||
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
|
||||
a.run("text.insert", json!({"text": "Template text"})).unwrap();
|
||||
for (label, ext) in [("OpenDocument Text Template (*.ott)", "ott"), ("Flat OpenDocument Text (*.fodt)", "fodt")] {
|
||||
let req = FileDialogRequest::Save { name: "x.pdf".into(), dir: None };
|
||||
let mut b = FileBrowser::new(req, AfterPick::Export { ext: "pdf".into() }, dir.clone(), false);
|
||||
b.filter = b.filters.iter().position(|(l, _)| l == label).unwrap();
|
||||
b.type_changed();
|
||||
assert_eq!(b.name, format!("x.{ext}"));
|
||||
b.navigate(dir.clone());
|
||||
let Step::Pick(path) = b.accept() else { panic!("picked") };
|
||||
assert_eq!(path, dir.join(format!("x.{ext}")));
|
||||
a.finish_pick(AfterPick::Export { ext: ext.into() }, Some(path.to_string_lossy().into_owned())).unwrap();
|
||||
assert!(path.is_file(), "{ext} written");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// An export waiting on a system dialog that never showed up keeps its format when Browse
|
||||
/// in WordCraft… takes over, instead of starting over on PDF.
|
||||
#[test]
|
||||
fn browse_in_wordcraft_keeps_a_pending_exports_format() {
|
||||
let services = Services {
|
||||
file_dialog: Some(Box::new(|_req| {
|
||||
let (tx, rx) = channel();
|
||||
// The system dialog never answers.
|
||||
std::mem::forget(tx);
|
||||
rx
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), services);
|
||||
a.export_dialog("rtf");
|
||||
assert!(a.file_dialog.is_some(), "waiting on the system dialog");
|
||||
a.run("ui.fileBrowser", json!({"purpose": "export"})).unwrap();
|
||||
assert!(a.file_dialog.is_none(), "the system dialog is given up");
|
||||
let b = a.file_browser.open.as_ref().expect("the built-in browser is open");
|
||||
assert!(matches!(&b.after, AfterPick::Export { ext } if ext == "rtf"));
|
||||
assert_eq!(b.filters[b.filter].0, "Rich Text Format (*.rtf)");
|
||||
assert!(b.name.ends_with(".rtf"), "{}", b.name);
|
||||
}
|
||||
|
||||
/// Word XML chosen as the export type wins over a Word 2003 XML file already at that path,
|
||||
/// whose format a save by path alone would keep.
|
||||
#[test]
|
||||
fn exporting_word_xml_over_a_word_2003_file_writes_word_xml() {
|
||||
let dir = scratch("export_xml");
|
||||
let path = dir.join("letter.xml").to_string_lossy().into_owned();
|
||||
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
|
||||
a.run("text.insert", json!({"text": "Dear reader"})).unwrap();
|
||||
a.finish_pick(AfterPick::Export { ext: crate::print_page::EXPORT_WORD_2003.into() }, Some(path.clone())).unwrap();
|
||||
assert!(std::fs::read_to_string(&path).unwrap().contains("w:wordDocument"));
|
||||
a.finish_pick(AfterPick::Export { ext: "xml".into() }, Some(path.clone())).unwrap();
|
||||
let xml = std::fs::read_to_string(&path).unwrap();
|
||||
assert!(xml.contains("pkg:package") && !xml.contains("w:wordDocument"), "Word XML, not Word 2003 XML");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A system Save dialog lets the user type a name without `.xml`; Word XML export still
|
||||
/// writes `<name>.xml` (as the built-in browser does) and won't silently replace an existing one.
|
||||
#[test]
|
||||
fn exporting_word_xml_to_a_name_without_xml_appends_the_extension() {
|
||||
let dir = scratch("export_xml_ext");
|
||||
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
|
||||
a.run("text.insert", json!({"text": "Dear reader"})).unwrap();
|
||||
let bare = dir.join("letter").to_string_lossy().into_owned();
|
||||
a.finish_pick(AfterPick::Export { ext: "xml".into() }, Some(bare)).unwrap();
|
||||
let xml = std::fs::read_to_string(dir.join("letter.xml")).unwrap();
|
||||
assert!(xml.contains("pkg:package"), "Word XML written at letter.xml");
|
||||
// A known document extension gives way to .xml; an unknown one stays.
|
||||
let docx = dir.join("notes.docx").to_string_lossy().into_owned();
|
||||
a.finish_pick(AfterPick::Export { ext: "xml".into() }, Some(docx)).unwrap();
|
||||
assert!(dir.join("notes.xml").is_file());
|
||||
let v2 = dir.join("notes.v2").to_string_lossy().into_owned();
|
||||
a.finish_pick(AfterPick::Export { ext: "xml".into() }, Some(v2)).unwrap();
|
||||
assert!(dir.join("notes.v2.xml").is_file());
|
||||
// The resulting name already exists: the system dialog never confirmed it, so refuse.
|
||||
let bare = dir.join("letter").to_string_lossy().into_owned();
|
||||
assert!(a.finish_pick(AfterPick::Export { ext: "xml".into() }, Some(bare)).is_err());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A name that is only a known extension (`.docx`) is a stem for `Path::extension`, which the
|
||||
/// engine's explicit-format guard reads too: exporting Word XML to it must name a real
|
||||
/// `.xml` file and write it (a bare `.xml` would be refused, writing nothing).
|
||||
#[test]
|
||||
fn exporting_word_xml_to_a_dotfile_name_writes_the_file() {
|
||||
let dir = scratch("export_xml_dotfile");
|
||||
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
|
||||
a.run("text.insert", json!({"text": "Dear reader"})).unwrap();
|
||||
for format in ["xml", crate::print_page::EXPORT_WORD_2003] {
|
||||
let typed = dir.join(".docx").to_string_lossy().into_owned();
|
||||
a.finish_pick(AfterPick::Export { ext: format.into() }, Some(typed)).unwrap();
|
||||
let written = dir.join(".docx.xml");
|
||||
assert!(std::fs::read_to_string(&written).unwrap().contains(if format == "xml" { "pkg:package" } else { "w:wordDocument" }));
|
||||
let _ = std::fs::remove_file(&written);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #3037: an empty folder (or a type filter that matches nothing) says so instead of a blank
|
||||
/// box; a matching file replaces the hint.
|
||||
#[test]
|
||||
|
||||
@@ -171,15 +171,17 @@ impl WordApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Treat the system dialog the host is showing as cancelled, e.g. one that never showed up.
|
||||
/// Treat the system dialog the host is showing as cancelled, e.g. one that never showed up;
|
||||
/// returns the format of the export it was for, if any.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn give_up_file_dialog(&mut self) {
|
||||
pub(crate) fn give_up_file_dialog(&mut self) -> Option<String> {
|
||||
if let Some(cancel) = &self.services.cancel_file_dialog {
|
||||
cancel();
|
||||
}
|
||||
if let Some(d) = self.file_dialog.take() {
|
||||
let _ = self.finish_pick(d.after, None);
|
||||
}
|
||||
let d = self.file_dialog.take()?;
|
||||
let export = if let AfterPick::Export { ext } = &d.after { Some(ext.clone()) } else { None };
|
||||
let _ = self.finish_pick(d.after, None);
|
||||
export
|
||||
}
|
||||
|
||||
/// The host couldn't show a system dialog (#576): ask in the built-in browser instead, which
|
||||
@@ -295,16 +297,40 @@ impl WordApp {
|
||||
Ok(json!({"picked": true}))
|
||||
}
|
||||
AfterPick::Export { ext } => {
|
||||
let Some(path) = picked else { return Ok(json!({"cancelled": true})) };
|
||||
let Some(mut path) = picked else {
|
||||
// Cancelled: an earlier refusal is not news any more.
|
||||
self.clear_export_error();
|
||||
return Ok(json!({"cancelled": true}));
|
||||
};
|
||||
let r = if ext == "png" {
|
||||
self.run("file.exportPng", json!({"path": path}))
|
||||
} else if ext == crate::print_page::EXPORT_WORD_2003 {
|
||||
self.run("file.saveAs", json!({"path": path, "format": ext}))
|
||||
} else if ext == "xml" || ext == crate::print_page::EXPORT_WORD_2003 {
|
||||
// The engine takes an explicit format only for an .xml path, and a system Save
|
||||
// dialog lets the user type any name: give it the extension, as the built-in
|
||||
// browser does (`notes.docx` becomes `notes.xml`, `notes.v2` `notes.v2.xml`).
|
||||
let named = crate::print_page::export_name(&path, "xml");
|
||||
if named != path {
|
||||
path = named;
|
||||
// The dialog only confirmed the name it was given, not this one.
|
||||
if std::path::Path::new(&path).exists() {
|
||||
// Callers drop the result, so say it where the person sees it.
|
||||
return Err(self.fail_export(format!("{path} already exists; choose another name")));
|
||||
}
|
||||
}
|
||||
// Word XML even over a Word 2003 XML file, which a save by path would keep.
|
||||
let format = if ext == "xml" { wordcraft_engine::cmd::file::FORMAT_FLAT_OPC } else { crate::print_page::EXPORT_WORD_2003 };
|
||||
self.run("file.saveAs", json!({"path": path, "format": format}))
|
||||
} else {
|
||||
self.run("file.saveAs", json!({"path": path}))
|
||||
};
|
||||
if r.is_ok() {
|
||||
self.status(crate::i18n::fmt(tl!("Exported {path}"), &[("path", &crate::i18n::isolate_path(&path))]));
|
||||
match &r {
|
||||
Ok(_) => {
|
||||
self.clear_export_error();
|
||||
self.status(crate::i18n::fmt(tl!("Exported {path}"), &[("path", &crate::i18n::isolate_path(&path))]));
|
||||
}
|
||||
Err(e) => {
|
||||
self.fail_export(e.clone());
|
||||
}
|
||||
}
|
||||
r
|
||||
}
|
||||
@@ -383,6 +409,18 @@ impl WordApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// An export failed or was refused: say so on the status bar and, for the Export page,
|
||||
/// there too, since Backstage's render loop skips the status bar (callers drop the result).
|
||||
fn fail_export(&mut self, error: String) -> String {
|
||||
self.status(error.clone());
|
||||
self.export_error = error.clone();
|
||||
error
|
||||
}
|
||||
|
||||
fn clear_export_error(&mut self) {
|
||||
self.export_error.clear();
|
||||
}
|
||||
|
||||
/// Drop a Save As page error once a later attempt has actually saved.
|
||||
fn clear_save_as_error(&mut self) {
|
||||
if let Some(ctx) = self.ctx.clone() {
|
||||
@@ -436,8 +474,8 @@ impl WordApp {
|
||||
|
||||
/// File › Export: ask where to save a copy in this format, then write it.
|
||||
pub(crate) fn export_dialog(&mut self, ext: &str) {
|
||||
let file_ext = if ext == crate::print_page::EXPORT_WORD_2003 { "xml" } else { ext };
|
||||
let name = format!("{}.{file_ext}", self.title_stem());
|
||||
let name = format!("{}.{}", self.title_stem(), crate::print_page::export_file_ext(ext));
|
||||
// A refusal or failure is reported by `finish_pick` itself (Export page and status bar).
|
||||
let _ = self.ask_file(FileDialogRequest::Save { name, dir: None }, AfterPick::Export { ext: ext.to_string() });
|
||||
}
|
||||
|
||||
|
||||
@@ -465,6 +465,39 @@ fn export_pdf_without_a_path_asks_where_to_save() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// An explicit web PDF export keeps an existing PDF suffix regardless of ASCII case.
|
||||
#[test]
|
||||
fn web_pdf_export_keeps_an_existing_suffix_in_any_case() {
|
||||
let downloaded = Rc::new(RefCell::new(Vec::new()));
|
||||
let captured = downloaded.clone();
|
||||
let services = Services {
|
||||
download: Some(Box::new(move |name, bytes| {
|
||||
captured.borrow_mut().push((name.to_string(), bytes.starts_with(b"%PDF")));
|
||||
Ok(())
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), services);
|
||||
for (name, expected) in [
|
||||
("Report.pdf", "Report.pdf"),
|
||||
("Report.PDF", "Report.PDF"),
|
||||
("Résumé.PdF", "Résumé.PdF"),
|
||||
("😀.PDF", "😀.PDF"),
|
||||
(".hidden.PDF", ".hidden.PDF"),
|
||||
("Report..PDF", "Report..PDF"),
|
||||
("é", "é.pdf"),
|
||||
("😀", "😀.pdf"),
|
||||
("Report.pdf.exe", "Report.pdf.exe.pdf"),
|
||||
("Report.PDF", "Report.PDF.pdf"),
|
||||
("Report.pdf.", "Report.pdf..pdf"),
|
||||
("Report", "Report.pdf"),
|
||||
] {
|
||||
let result = a.execute("file.exportPdf", json!({"path": name})).unwrap();
|
||||
assert_eq!(result["downloaded"], expected, "{name}");
|
||||
assert_eq!(downloaded.borrow().last().cloned(), Some((expected.to_string(), true)), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Open, Save As and Export PNG from the command search (no path) ask for a file the same way.
|
||||
#[test]
|
||||
fn file_commands_without_a_path_ask_for_one() {
|
||||
|
||||
@@ -70,7 +70,7 @@ pub struct LangInfo {
|
||||
|
||||
/// The languages WordCraft offers, when their catalogs are embedded. English first: it is the
|
||||
/// fallback and the source language.
|
||||
pub static LANGUAGES: [LangInfo; 28] = [
|
||||
pub static LANGUAGES: [LangInfo; 29] = [
|
||||
LangInfo { code: "en", prefer_hans: false, editing_lang: None },
|
||||
// Simplified Chinese; `zh`, `zh-CN`, `zh-SG` and `zh-Hans-*` resolve here (the crate's matching).
|
||||
LangInfo { code: "zh-hans", prefer_hans: true, editing_lang: None },
|
||||
@@ -129,6 +129,9 @@ pub static LANGUAGES: [LangInfo; 28] = [
|
||||
LangInfo { code: "ar", prefer_hans: false, editing_lang: None },
|
||||
// Slovenian; `sl`, `sl-SI` and `sl_SI.UTF-8` resolve here.
|
||||
LangInfo { code: "sl", prefer_hans: false, editing_lang: None },
|
||||
// Bosnian, Latin script; `bs`, `bs-BA`, `bs_BA.UTF-8` and `bs-Latn-BA` resolve here. Cyrillic
|
||||
// Bosnian (`bs-Cyrl-*`) has no catalog, so it stays in English.
|
||||
LangInfo { code: "bs", prefer_hans: false, editing_lang: None },
|
||||
];
|
||||
|
||||
/// Interface languages written right to left. Their catalogs are written in typing order and
|
||||
|
||||
@@ -1143,6 +1143,75 @@ fn bundled_interface_fonts_cover_slovenian_letters() {
|
||||
assert!(!lang("sl").uses_cjk());
|
||||
}
|
||||
|
||||
/// Bosnian (Latin script) follows `bs-BA` system locales and a saved choice, and choosing it leaves
|
||||
/// the document as it was. Cyrillic Bosnian has no catalog: a script is never crossed.
|
||||
#[test]
|
||||
fn bosnian_locales_and_saved_preference_work_without_changing_the_document() {
|
||||
needs_catalogs!();
|
||||
let bs = lang("bs");
|
||||
for tag in ["bs", "bs-BA", "bs_BA.UTF-8", "BS-ba", "bs-Latn-BA"] {
|
||||
assert_eq!(lang_from_tag(tag), Some(bs), "{tag}");
|
||||
}
|
||||
assert_eq!(lang_from_tag("bs-Cyrl-BA"), None, "Cyrillic Bosnian has no catalog");
|
||||
assert_eq!(first_supported([UNSUPPORTED, "bs-BA", "en-US"]), Some(bs));
|
||||
let mut app = crate::WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
let before = serde_json::to_value(&app.session.doc).unwrap();
|
||||
let result = app.run("ui.language", serde_json::json!({"value": "BS"})).unwrap();
|
||||
assert_eq!(result["effective"], "bs");
|
||||
assert_eq!(app.ui.language, "bs");
|
||||
assert!(result["available"].as_array().unwrap().iter().any(|l| l["code"] == "bs" && l["name"] == "Bosanski"));
|
||||
assert_eq!(serde_json::to_value(&app.session.doc).unwrap(), before);
|
||||
let saved = serde_json::to_string(&app.ui).unwrap();
|
||||
let restored: crate::UiState = serde_json::from_str(&saved).unwrap();
|
||||
assert_eq!(Lang::from_pref(&restored.language), bs);
|
||||
assert_eq!(bs.editing_lang(), None, "WordCraft doesn't proof Bosnian, so documents stay in its default");
|
||||
assert!(!bs.uses_cjk());
|
||||
}
|
||||
|
||||
/// Bosnian counts take CLDR's three forms through the embedded catalog: `one` for 1, 21, 101 (not
|
||||
/// 11), `few` for 2–4, 22–24 (not 12–14) and `other` for the rest.
|
||||
#[test]
|
||||
fn bosnian_plurals_take_one_few_other() {
|
||||
needs_catalogs!();
|
||||
let bs = lang("bs");
|
||||
let count = |n| I18N.trn_plain(bs.lang, n, "{n} item", "{n} items");
|
||||
for (n, want) in [
|
||||
(1, "1 stavka"),
|
||||
(21, "21 stavka"),
|
||||
(101, "101 stavka"),
|
||||
(2, "2 stavke"),
|
||||
(4, "4 stavke"),
|
||||
(22, "22 stavke"),
|
||||
(0, "0 stavki"),
|
||||
(5, "5 stavki"),
|
||||
(11, "11 stavki"),
|
||||
(12, "12 stavki"),
|
||||
(14, "14 stavki"),
|
||||
(111, "111 stavki"),
|
||||
] {
|
||||
assert_eq!(count(n), want, "{n}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The bundled interface faces draw every Bosnian letter (č ć đ š ž), every other accented letter
|
||||
/// the catalog uses, and its punctuation, without a system fallback.
|
||||
#[test]
|
||||
fn bundled_interface_fonts_cover_bosnian_letters() {
|
||||
let db = wordcraft_fonts::FontDb::with_font_dirs(Vec::new());
|
||||
needs_catalogs!();
|
||||
let extra = ['č', 'ć', 'đ', 'š', 'ž', 'Č', 'Ć', 'Đ', 'Š', 'Ž', '„', '”', '–', '…'];
|
||||
// Every accented Latin letter the catalog uses (Latin-1 and Latin Extended-A), and the above.
|
||||
let accented = |c: &char| ('\u{C0}'..='\u{17F}').contains(c) && c.is_alphabetic();
|
||||
let chars: std::collections::HashSet<char> = translations("bs").iter().flat_map(|e| e.chars()).filter(accented).chain(extra).collect();
|
||||
for (family, style) in [("Inter", "Regular"), ("Inter", "Medium"), ("Inter", "SemiBold"), ("JetBrains Mono", "Regular")] {
|
||||
let face = db.face(family, style);
|
||||
assert_eq!(face.family, family, "must use the bundled interface face");
|
||||
for ch in &chars {
|
||||
assert_ne!(face.glyph_for(*ch), 0, "{family} {style} lacks {ch}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The "Open" paragraph-spacing preset is roomy spacing, not the file verb: only a `spacing` row
|
||||
/// translates it.
|
||||
#[test]
|
||||
|
||||
@@ -1645,9 +1645,19 @@ fn shape(pen: &Pen, kind: &str) -> bool {
|
||||
"triangle" => solid(&[(10.0, 3.5), (17.0, 16.5), (3.0, 16.5)]),
|
||||
"diamond" => solid(&[(10.0, 3.0), (17.0, 10.0), (10.0, 17.0), (3.0, 10.0)]),
|
||||
"line" => pen.line(&[(4.0, 16.0), (16.0, 4.0)]),
|
||||
// The block arrow the tile inserts (#6768), from the outline the document draws it with.
|
||||
"arrow" => {
|
||||
pen.line(&[(4.0, 16.0), (14.5, 5.5)]);
|
||||
head((16.5, 3.5), (4.0, 16.0));
|
||||
let (x0, y0, w, h) = (3.0, 5.0, 14.0, 10.0);
|
||||
let pts: Vec<(f32, f32)> = wordcraft_doc::wrap::arrow_outline(wordcraft_doc::para::ShapeKind::Arrow, w, h)
|
||||
.iter()
|
||||
.map(|&(u, v)| (x0 + u * w, y0 + v * h))
|
||||
.collect();
|
||||
// Concave: the shaft and the head are tinted apart, then the outline.
|
||||
if let [tail_top, neck_top, barb_top, tip, barb_bottom, neck_bottom, tail_bottom] = pts[..] {
|
||||
pen.fill(&[tail_top, neck_top, neck_bottom, tail_bottom], tint);
|
||||
pen.fill(&[barb_top, tip, barb_bottom], tint);
|
||||
}
|
||||
pen.closed(&pts, c);
|
||||
}
|
||||
"star" => {
|
||||
let pts: Vec<(f32, f32)> = (0..10)
|
||||
@@ -1745,6 +1755,32 @@ mod tests {
|
||||
assert!(!has_default_highlight_bar("shadingNoBar"));
|
||||
}
|
||||
|
||||
/// #6768: the Insert › Shapes Arrow tile is the block arrow that tile inserts, outlined as the
|
||||
/// document draws it, not a thin line with a head.
|
||||
#[test]
|
||||
fn the_arrow_tile_is_the_block_arrow_it_inserts() {
|
||||
let ctx = egui::Context::default();
|
||||
let output = ctx.run_ui(egui::RawInput::default(), |ui| {
|
||||
paint(ui.painter(), Rect::from_min_size(Pos2::ZERO, egui::vec2(20.0, 20.0)), "shape.arrow", Color32::BLACK, Color32::BLUE);
|
||||
});
|
||||
let outline: Vec<Pos2> = output
|
||||
.shapes
|
||||
.iter()
|
||||
.find_map(|s| match &s.shape {
|
||||
// The outline, not the tinted fills (closed too, but without a stroke).
|
||||
Shape::Path(path) if path.closed && path.stroke.width > 0.0 => Some(path.points.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the arrow is outlined");
|
||||
output.drop_without_applying_deltas();
|
||||
let want = wordcraft_doc::wrap::arrow_outline(wordcraft_doc::para::ShapeKind::Arrow, 14.0, 10.0);
|
||||
assert_eq!(outline.len(), want.len(), "{outline:?}");
|
||||
for (got, (u, v)) in outline.iter().zip(want) {
|
||||
let expected = pos2(3.0 + u * 14.0, 5.0 + v * 10.0);
|
||||
assert!(got.distance(expected) < 0.01, "{got:?} vs {expected:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Verify that the fitOnePage vector icon renders without panics and emits shapes.
|
||||
#[test]
|
||||
fn fit_one_page_icon_paints_without_panic() {
|
||||
|
||||
@@ -46,6 +46,8 @@ pub fn canvas_events(app: &mut WordApp, ctx: &egui::Context) {
|
||||
interrupted_preedit: std::mem::take(&mut app.canvas.ime_interrupted_preedit),
|
||||
interrupted_replacement: EquationReplacementDrop::None,
|
||||
};
|
||||
let now = ctx.input(|i| i.time);
|
||||
expire_paste_wait(app, now);
|
||||
let held = ctx.input(|i| i.modifiers);
|
||||
if held.command {
|
||||
app.canvas.paste_mods = Some(held);
|
||||
@@ -60,7 +62,8 @@ pub fn canvas_events(app: &mut WordApp, ctx: &egui::Context) {
|
||||
continue;
|
||||
}
|
||||
note_key_state(app, &e);
|
||||
if drop_refused_replacement(app, &e, &mut batch)
|
||||
if ignored_paste(app, &e)
|
||||
|| drop_refused_replacement(app, &e, &mut batch)
|
||||
|| prefilter(app, ctx, &e, alt_codes)
|
||||
|| paste_release(app, &e)
|
||||
|| equation_event(app, ctx, &e, &mut batch)
|
||||
@@ -69,6 +72,27 @@ pub fn canvas_events(app: &mut WordApp, ctx: &egui::Context) {
|
||||
}
|
||||
handle_event(app, ctx, e);
|
||||
}
|
||||
if app.canvas.ignore_next_paste && app.canvas.paste_wait_since.is_none() {
|
||||
app.canvas.paste_wait_since = Some(now);
|
||||
}
|
||||
}
|
||||
|
||||
/// How long the paste event paired with Mod+Shift+V is waited for. A browser sends it with the
|
||||
/// key, in the same frame; with no text on the clipboard it sends none at all.
|
||||
const PASTE_WAIT: f64 = 1.0;
|
||||
|
||||
/// Ends a wait for the paired paste event that never came, so a later paste (a browser menu's,
|
||||
/// say) isn't dropped (#5616).
|
||||
fn expire_paste_wait(app: &mut WordApp, now: f64) {
|
||||
if !app.canvas.ignore_next_paste {
|
||||
app.canvas.paste_wait_since = None;
|
||||
} else if app.canvas.paste_wait_since.is_some_and(|t| now - t > PASTE_WAIT) {
|
||||
app.canvas.ignore_next_paste = false;
|
||||
app.canvas.paste_wait_since = None;
|
||||
// No key came since the chord (any key ends the wait), so noted modifiers are the
|
||||
// chord's: a later paste reads the modifiers held then.
|
||||
app.canvas.paste_event_mods = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// State carried across the events of one raw batch.
|
||||
@@ -158,20 +182,54 @@ fn stale_composition(app: &mut WordApp, e: &egui::Event, b: &mut Batch) -> bool
|
||||
fn note_key_state(app: &mut WordApp, e: &egui::Event) {
|
||||
// Which presses reached the canvas, and the modifiers held with Mod, in event order: Mod
|
||||
// can go down and up within one frame, leaving the frame's modifiers without it.
|
||||
if matches!(e, egui::Event::Key { pressed: true, key, .. } if !is_modifier_key(*key))
|
||||
|| matches!(e, egui::Event::WindowFocused(_) | egui::Event::PointerButton { pressed: true, .. })
|
||||
{
|
||||
app.canvas.ignore_next_paste = false;
|
||||
}
|
||||
match &e {
|
||||
egui::Event::ModifiersChanged(m) if m.command => app.canvas.paste_mods = Some(*m),
|
||||
egui::Event::Key { key: Key::V | Key::Paste, pressed: true, .. } => app.canvas.v_pressed = true,
|
||||
egui::Event::ModifiersChanged(m) => {
|
||||
app.canvas.paste_event_mods = m.command.then_some(*m);
|
||||
if m.command {
|
||||
app.canvas.paste_mods = Some(*m);
|
||||
}
|
||||
}
|
||||
egui::Event::Key { key: Key::V | Key::Paste, pressed: true, modifiers, .. } => {
|
||||
app.canvas.v_pressed = true;
|
||||
app.canvas.paste_event_mods = modifiers.command.then_some(*modifiers);
|
||||
}
|
||||
egui::Event::Key { key, pressed: true, modifiers, .. } if !is_modifier_key(*key) => {
|
||||
app.canvas.paste_mods = modifiers.command.then_some(*modifiers);
|
||||
// An unrelated key's modifiers mustn't steer a later keyless paste.
|
||||
app.canvas.paste_event_mods = None;
|
||||
}
|
||||
egui::Event::PointerButton { pressed: true, .. } => app.canvas.paste_event_mods = None,
|
||||
egui::Event::WindowFocused(_) => {
|
||||
app.canvas.v_pressed = false;
|
||||
// A V release lost to a focus change must not swallow a later Mod+V's picture.
|
||||
app.canvas.pasted = false;
|
||||
app.canvas.paste_mods = None;
|
||||
app.canvas.paste_event_mods = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The browser's paste event that follows a Mod+Shift+V that pasted formatting is the same
|
||||
/// keystroke: ignored before an equation or a picture-file paste can take it (#5616).
|
||||
/// With no text on the clipboard eframe sends no paste event, so the wait ends at the next key,
|
||||
/// pointer press or focus change, or after `PASTE_WAIT`.
|
||||
fn ignored_paste(app: &mut WordApp, e: &egui::Event) -> bool {
|
||||
if matches!(e, egui::Event::Paste(_)) && std::mem::take(&mut app.canvas.ignore_next_paste) {
|
||||
// Not a Mod+V with no text either: the release mustn't paste a picture.
|
||||
app.canvas.pasted = true;
|
||||
// Its Mod+Shift is used up too, or a later menu-bar paste would read as Keep Text Only.
|
||||
app.canvas.paste_event_mods = None;
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The replacement paired with a refused equation deletion is dropped.
|
||||
fn drop_refused_replacement(app: &mut WordApp, e: &egui::Event, b: &mut Batch) -> bool {
|
||||
// The replacement is the event immediately after the refused deletion: one `Commit`,
|
||||
@@ -509,10 +567,15 @@ fn handle_event(app: &mut WordApp, ctx: &egui::Context, e: egui::Event) {
|
||||
egui::Event::Ime(egui::ImeEvent::Commit(text)) => ime_commit(app, text),
|
||||
egui::Event::Paste(t) => {
|
||||
// Mod+Alt+V arrives as a paste too (the shell reads the clipboard): Paste Special.
|
||||
let m = ctx.input(|i| i.modifiers);
|
||||
// The modifiers held with Mod in event order: Shift may be up by the frame's end.
|
||||
app.canvas.paste_mods = None;
|
||||
let m = app.canvas.paste_event_mods.take().unwrap_or_else(|| ctx.input(|i| i.modifiers));
|
||||
// A browser sends Mod+Shift+V as a paste too: Keep Text Only, as the key does on the
|
||||
// desktop (#1537). (egui-winit sends that chord as a key, and Shift+Insert has no Mod.)
|
||||
let id = match (m.alt, m.shift) {
|
||||
(true, true) => "edit.pasteText",
|
||||
(true, false) => "edit.pasteSpecial",
|
||||
(false, true) if m.command => "edit.pasteText",
|
||||
_ => "edit.paste",
|
||||
};
|
||||
let _ = app.run(id, json!({"text": t}));
|
||||
|
||||
@@ -132,7 +132,32 @@ pub(super) fn dispatch(app: &mut WordApp, key: Key, m: Modifiers) -> bool {
|
||||
if m.alt && !crate::widgets::enabled(app, spec.id) {
|
||||
return false;
|
||||
}
|
||||
let _ = app.run(spec.id, json!({}));
|
||||
// Mod+Shift+V pastes the formatting Mod+Shift+C (or the Format Painter) picked up; with
|
||||
// none picked up it pastes the clipboard as text only, as Word for Windows does (#1537,
|
||||
// #4943). Another key bound to Paste Formatting only pastes formatting.
|
||||
let id = if spec.id == "edit.pasteFormat" {
|
||||
let formatting = app.session.painter.is_some() || app.session.copied_format.is_some();
|
||||
let chord = key == Key::V && m.command && m.shift && !m.alt;
|
||||
// A browser sends a paste event after that chord (the desktop doesn't): after
|
||||
// pasting formatting it's ignored; with none, it pastes the text there, once. A
|
||||
// rebinding to another key makes no paste event.
|
||||
let paste_follows = chord && app.canvas.paste_event_follows_chord;
|
||||
app.canvas.ignore_next_paste = formatting && paste_follows;
|
||||
// Handled from the canvas's key events: its V release (Shift may go up first, so the
|
||||
// release reads as plain Mod+V) mustn't paste again through the picture hook. Not
|
||||
// from `global_shortcuts` (canvas unfocused), where no release is ever seen.
|
||||
if chord && app.canvas.focused {
|
||||
app.canvas.pasted = true;
|
||||
}
|
||||
app.canvas.paste_wait_since = None;
|
||||
if !formatting && paste_follows {
|
||||
return true;
|
||||
}
|
||||
if !formatting && chord { "edit.pasteText" } else { spec.id }
|
||||
} else {
|
||||
spec.id
|
||||
};
|
||||
let _ = app.run(id, json!({}));
|
||||
return true;
|
||||
}
|
||||
let Some(name) = name else { return false };
|
||||
|
||||
@@ -133,6 +133,124 @@ fn only_plain_paste_releases_paste_a_clipboard_picture() {
|
||||
assert!(!is_paste_special_release(Key::V, m(true, true, true)) && !is_paste_special_release(Key::V, m(true, false, false)));
|
||||
}
|
||||
|
||||
/// #1537: a browser sends Mod+Shift+V as a paste event; it pastes text only, in the destination's
|
||||
/// formatting, though the clipboard also holds bold HTML. Plain Mod+V keeps the HTML's bold.
|
||||
#[test]
|
||||
fn a_mod_shift_paste_event_keeps_text_only() {
|
||||
for (modifiers, bold) in [(Modifiers::COMMAND | Modifiers::SHIFT, false), (Modifiers::COMMAND, true)] {
|
||||
let services = crate::Services { clipboard_html: Some(Box::new(|| Some("<p><b>external</b></p>".into()))), ..Default::default() };
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), services);
|
||||
let ctx = egui::Context::default();
|
||||
mods_frame(&ctx, &mut a, modifiers, vec![egui::Event::Paste("external".into())]);
|
||||
assert_eq!(a.session.doc.plain_text(wordcraft_doc::StoryRef::Body), "external", "{modifiers:?}");
|
||||
let state = a.session.run("format.state", &json!({})).unwrap();
|
||||
assert_eq!(state.get("bold").and_then(serde_json::Value::as_bool) == Some(true), bold, "{modifiers:?}: {state}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #5616: a browser sends Mod+Shift+V as its key and then a paste event. After Mod+Shift+C the
|
||||
/// key pastes the formatting and the paste event that follows doesn't replace the text; a later
|
||||
/// Mod+V still pastes.
|
||||
#[test]
|
||||
fn a_paste_event_after_mod_shift_v_pasted_formatting_is_ignored() {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
a.canvas.paste_event_follows_chord = true;
|
||||
a.run("text.insert", json!({"text": "source target"})).unwrap();
|
||||
a.run("select.text", json!({"text": "source"})).unwrap();
|
||||
a.run("format.bold", json!({})).unwrap();
|
||||
a.run("edit.copyFormat", json!({})).unwrap();
|
||||
a.run("select.text", json!({"text": "target"})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
let chord = Modifiers::COMMAND | Modifiers::SHIFT;
|
||||
mods_frame(&ctx, &mut a, chord, vec![key_event(Key::V, true, chord), egui::Event::Paste("clipboard text".into())]);
|
||||
let body = |a: &WordApp| a.session.doc.plain_text(wordcraft_doc::StoryRef::Body);
|
||||
assert_eq!(body(&a), "source target", "the paste event didn't replace the formatted text");
|
||||
let bold = a.session.run("format.state", &json!({})).unwrap().get("bold").and_then(serde_json::Value::as_bool);
|
||||
assert_eq!(bold, Some(true), "the key pasted the formatting");
|
||||
mods_frame(&ctx, &mut a, Modifiers::COMMAND, vec![key_event(Key::V, true, Modifiers::COMMAND), egui::Event::Paste("pasted".into())]);
|
||||
assert_eq!(body(&a), "source pasted", "the next Mod+V pastes");
|
||||
}
|
||||
|
||||
/// #5616: on a desktop, Mod+Shift+V with nothing copied pastes the text; releasing Shift before V
|
||||
/// leaves the V release as plain Mod+V, which mustn't paste a second time through the picture hook.
|
||||
/// Likewise after pasting copied formatting.
|
||||
#[test]
|
||||
fn mod_shift_v_released_shift_first_pastes_once() {
|
||||
let chord = Modifiers { ctrl: true, command: true, shift: true, ..Default::default() };
|
||||
let ctrl = Modifiers { shift: false, ..chord };
|
||||
for formatting in [false, true] {
|
||||
let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let seen = calls.clone();
|
||||
let services = crate::Services {
|
||||
clipboard_picture: Some(Box::new(move || {
|
||||
seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
None
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), services);
|
||||
a.canvas.paste_event_follows_chord = false;
|
||||
a.canvas.focused = true;
|
||||
a.run("text.insert", json!({"text": "source target"})).unwrap();
|
||||
if formatting {
|
||||
a.run("select.text", json!({"text": "source"})).unwrap();
|
||||
a.run("format.bold", json!({})).unwrap();
|
||||
a.run("edit.copyFormat", json!({})).unwrap();
|
||||
}
|
||||
// The clipboard holds "source"; "target" is selected.
|
||||
a.run("select.text", json!({"text": "source"})).unwrap();
|
||||
a.run("edit.copy", json!({})).unwrap();
|
||||
a.run("select.text", json!({"text": "target"})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
mods_frame(&ctx, &mut a, chord, vec![key_event(Key::V, true, chord)]);
|
||||
mods_frame(&ctx, &mut a, ctrl, vec![key_event(Key::ShiftLeft, false, ctrl)]);
|
||||
mods_frame(&ctx, &mut a, ctrl, vec![key_event(Key::V, false, ctrl)]);
|
||||
let body = a.session.doc.plain_text(wordcraft_doc::StoryRef::Body);
|
||||
assert_eq!(body, if formatting { "source target" } else { "source source" }, "formatting={formatting}");
|
||||
assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0, "formatting={formatting}: the release asked for a picture");
|
||||
// The release used it up: a later plain Mod+V release still pastes a picture.
|
||||
assert!(!a.canvas.pasted);
|
||||
}
|
||||
}
|
||||
|
||||
/// #5616: Mod+Shift+V pressed with the canvas unfocused (after a ribbon click) runs through the
|
||||
/// global shortcuts, and its V release never reaches the canvas: it mustn't leave a paste marked
|
||||
/// done that swallows the clipboard picture of a later Mod+V.
|
||||
#[test]
|
||||
fn a_global_mod_shift_v_leaves_the_next_mod_v_picture_paste_alone() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut a = picture_app();
|
||||
a.canvas.paste_event_follows_chord = false;
|
||||
a.canvas.focused = false;
|
||||
let chord = Modifiers { ctrl: true, command: true, shift: true, ..Default::default() };
|
||||
let events = vec![egui::Event::ModifiersChanged(chord), key_event(Key::V, true, chord)];
|
||||
ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| super::shortcuts::global_shortcuts(&mut a, ui.ctx()))
|
||||
.drop_without_applying_deltas();
|
||||
assert!(!a.canvas.pasted, "no canvas release is coming to use the mark up");
|
||||
a.canvas.focused = true;
|
||||
let ctrl = Modifiers { shift: false, ..chord };
|
||||
mods_frame(&ctx, &mut a, ctrl, vec![key_event(Key::V, false, ctrl)]);
|
||||
assert_eq!(pictures(&mut a), 1);
|
||||
}
|
||||
|
||||
/// #5616: Mod+Shift+V pressed, then focus leaves before V is released: the lost release mustn't
|
||||
/// swallow a later Mod+V's picture.
|
||||
#[test]
|
||||
fn a_focus_change_clears_the_mod_shift_v_paste_mark() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut a = picture_app();
|
||||
a.canvas.paste_event_follows_chord = false;
|
||||
a.canvas.focused = true;
|
||||
let chord = Modifiers { ctrl: true, command: true, shift: true, ..Default::default() };
|
||||
mods_frame(&ctx, &mut a, chord, vec![key_event(Key::V, true, chord)]);
|
||||
assert!(a.canvas.pasted);
|
||||
mods_frame(&ctx, &mut a, Modifiers::NONE, vec![egui::Event::WindowFocused(false)]);
|
||||
mods_frame(&ctx, &mut a, Modifiers::NONE, vec![egui::Event::WindowFocused(true)]);
|
||||
let ctrl = Modifiers { shift: false, ..chord };
|
||||
mods_frame(&ctx, &mut a, ctrl, vec![key_event(Key::V, false, ctrl)]);
|
||||
assert_eq!(pictures(&mut a), 1);
|
||||
}
|
||||
|
||||
/// An empty document whose clipboard holds a 4 × 4 picture.
|
||||
fn picture_app() -> WordApp {
|
||||
use crate::paste_picture::ClipboardPicture;
|
||||
@@ -154,6 +272,129 @@ fn mods_frame(ctx: &egui::Context, a: &mut WordApp, modifiers: Modifiers, events
|
||||
ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| canvas_events(a, ui.ctx())).drop_without_applying_deltas();
|
||||
}
|
||||
|
||||
/// A source word in bold with Copy Formatting picked up, and "target" selected.
|
||||
fn copied_bold_app() -> WordApp {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
a.run("text.insert", json!({"text": "source target"})).unwrap();
|
||||
a.run("select.text", json!({"text": "source"})).unwrap();
|
||||
a.run("format.bold", json!({})).unwrap();
|
||||
a.run("edit.copyFormat", json!({})).unwrap();
|
||||
a.run("select.text", json!({"text": "target"})).unwrap();
|
||||
a
|
||||
}
|
||||
|
||||
/// #5616: on a desktop no paste event follows Mod+Shift+V's key, so none is swallowed: a later
|
||||
/// paste (from a menu, say) pastes.
|
||||
#[test]
|
||||
fn a_desktop_paste_after_mod_shift_v_is_not_swallowed() {
|
||||
let mut a = copied_bold_app();
|
||||
assert!(!a.canvas.paste_event_follows_chord || cfg!(target_arch = "wasm32"));
|
||||
a.canvas.paste_event_follows_chord = false;
|
||||
let ctx = egui::Context::default();
|
||||
let chord = Modifiers::COMMAND | Modifiers::SHIFT;
|
||||
mods_frame(&ctx, &mut a, chord, vec![key_event(Key::V, true, chord)]);
|
||||
assert!(!a.canvas.ignore_next_paste);
|
||||
mods_frame(&ctx, &mut a, Modifiers::NONE, vec![egui::Event::Paste("later".into())]);
|
||||
assert_eq!(a.session.doc.plain_text(wordcraft_doc::StoryRef::Body), "source later");
|
||||
}
|
||||
|
||||
/// #5616: a pointer press ends the wait for the browser's paste event, so a later keyless paste
|
||||
/// (context menu, touch) isn't swallowed.
|
||||
#[test]
|
||||
fn a_pointer_press_ends_the_wait_for_the_ignored_paste() {
|
||||
let mut a = copied_bold_app();
|
||||
a.canvas.ignore_next_paste = true;
|
||||
let ctx = egui::Context::default();
|
||||
let press =
|
||||
egui::Event::PointerButton { pos: egui::pos2(5.0, 5.0), button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE };
|
||||
mods_frame(&ctx, &mut a, Modifiers::NONE, vec![press]);
|
||||
assert!(!a.canvas.ignore_next_paste);
|
||||
}
|
||||
|
||||
/// #5616: the modifiers noted for a paste are used up by it: a later paste with no Mod held
|
||||
/// keeps the HTML's formatting instead of reading the stale Mod+Shift.
|
||||
#[test]
|
||||
fn a_paste_event_uses_up_the_noted_paste_modifiers() {
|
||||
let services = crate::Services { clipboard_html: Some(Box::new(|| Some("<p><b>external</b></p>".into()))), ..Default::default() };
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), services);
|
||||
let ctx = egui::Context::default();
|
||||
mods_frame(&ctx, &mut a, Modifiers::COMMAND | Modifiers::SHIFT, vec![egui::Event::Paste("external".into())]);
|
||||
assert!(a.canvas.paste_mods.is_none());
|
||||
a.run("select.all", json!({})).unwrap();
|
||||
mods_frame(&ctx, &mut a, Modifiers::NONE, vec![egui::Event::Paste("external".into())]);
|
||||
let bold = a.session.run("format.state", &json!({})).unwrap().get("bold").and_then(serde_json::Value::as_bool);
|
||||
assert_eq!(bold, Some(true), "the later paste was a plain paste");
|
||||
}
|
||||
|
||||
/// #5616: the dropped browser paste uses up its Mod+Shift, so a later menu-bar paste with no key
|
||||
/// or pointer press in between isn't read as Keep Text Only.
|
||||
#[test]
|
||||
fn the_ignored_paste_uses_up_its_paste_modifiers() {
|
||||
let mut a = copied_bold_app();
|
||||
a.canvas.paste_event_follows_chord = true;
|
||||
let ctx = egui::Context::default();
|
||||
let chord = Modifiers::COMMAND | Modifiers::SHIFT;
|
||||
mods_frame(&ctx, &mut a, chord, vec![key_event(Key::V, true, chord), egui::Event::Paste("x".into())]);
|
||||
assert!(!a.canvas.ignore_next_paste);
|
||||
assert!(a.canvas.paste_event_mods.is_none());
|
||||
}
|
||||
|
||||
/// #5616: with no text on the clipboard the browser sends no paste event after Mod+Shift+V; the
|
||||
/// wait for it ends, so a later menu-bar paste with no key or pointer press in between pastes.
|
||||
#[test]
|
||||
fn a_menu_bar_paste_after_an_unpaired_mod_shift_v_pastes() {
|
||||
let mut a = copied_bold_app();
|
||||
a.canvas.paste_event_follows_chord = true;
|
||||
let ctx = egui::Context::default();
|
||||
let chord = Modifiers::COMMAND | Modifiers::SHIFT;
|
||||
let frame = |a: &mut WordApp, time: f64, events: Vec<egui::Event>| {
|
||||
ctx.run_ui(egui::RawInput { time: Some(time), events, ..Default::default() }, |ui| canvas_events(a, ui.ctx())).drop_without_applying_deltas();
|
||||
};
|
||||
frame(&mut a, 10.0, vec![egui::Event::ModifiersChanged(chord), key_event(Key::V, true, chord)]);
|
||||
assert!(a.canvas.ignore_next_paste, "the key waits for its paired paste");
|
||||
// No Mod release reaches the canvas (the menu bar takes it).
|
||||
frame(&mut a, 10.5, vec![]);
|
||||
assert!(a.canvas.ignore_next_paste, "still within the wait");
|
||||
frame(&mut a, 12.0, vec![]);
|
||||
assert!(!a.canvas.ignore_next_paste, "the wait is over");
|
||||
assert!(a.canvas.paste_event_mods.is_none(), "the chord's Mod+Shift is used up");
|
||||
frame(&mut a, 12.1, vec![egui::Event::Paste("menu".into())]);
|
||||
assert_eq!(a.session.doc.plain_text(wordcraft_doc::StoryRef::Body), "source menu", "the menu-bar paste pasted");
|
||||
}
|
||||
|
||||
/// #5616: the browser paste event after a formatting paste is dropped before an open equation
|
||||
/// can type it.
|
||||
#[test]
|
||||
fn the_ignored_paste_event_never_reaches_an_open_equation() {
|
||||
let mut a = copied_bold_app();
|
||||
a.canvas.paste_event_follows_chord = true;
|
||||
a.run("insert.equation", json!({"linear": "abc"})).unwrap();
|
||||
a.canvas.ignore_next_paste = true;
|
||||
let ctx = egui::Context::default();
|
||||
let before = a.session.math.clone();
|
||||
mods_frame(&ctx, &mut a, Modifiers::COMMAND, vec![egui::Event::Paste("zzz".into())]);
|
||||
assert_eq!(a.session.math, before, "the ignored paste typed nothing into the equation");
|
||||
assert!(!a.canvas.ignore_next_paste);
|
||||
}
|
||||
|
||||
/// #5616: only Mod+Shift+V leaves a browser paste event; Paste Formatting on another key neither
|
||||
/// arms the ignore flag nor waits for a paste.
|
||||
#[test]
|
||||
fn paste_formatting_on_another_key_leaves_no_paste_to_ignore() {
|
||||
for formatting in [true, false] {
|
||||
let mut a = if formatting {
|
||||
copied_bold_app()
|
||||
} else {
|
||||
WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default())
|
||||
};
|
||||
a.canvas.paste_event_follows_chord = true;
|
||||
a.session.keymap = wordcraft_engine::keymap::KeyMap::from_value(&json!({"assigned": {"Mod+Alt+P": "edit.pasteFormat"}}));
|
||||
let m = Modifiers::COMMAND | Modifiers::ALT;
|
||||
super::shortcuts::dispatch(&mut a, Key::P, m);
|
||||
assert!(!a.canvas.ignore_next_paste, "formatting={formatting}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A press or release of `key` with `modifiers`.
|
||||
fn key_event(key: Key, pressed: bool, modifiers: Modifiers) -> egui::Event {
|
||||
egui::Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers }
|
||||
@@ -1336,6 +1577,24 @@ fn typing_with_smart_art_selected_types_into_an_item() {
|
||||
assert_eq!(g.items[0].text, "Ada", "one undo step for the typing");
|
||||
}
|
||||
|
||||
/// #5616: modifiers recorded for an unrelated key (Mod+Shift+C) don't steer a later keyless paste,
|
||||
/// whether Mod was released or is still held with no change event.
|
||||
#[test]
|
||||
fn an_unrelated_keys_modifiers_do_not_steer_a_later_paste() {
|
||||
for mod_still_held in [false, true] {
|
||||
let services = crate::Services { clipboard_html: Some(Box::new(|| Some("<p><b>external</b></p>".into()))), ..Default::default() };
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), services);
|
||||
let ctx = egui::Context::default();
|
||||
let chord = Modifiers::COMMAND | Modifiers::SHIFT;
|
||||
mods_frame(&ctx, &mut a, chord, vec![key_event(Key::C, true, chord)]);
|
||||
// Shift released, Mod still held: Mod+C's chord isn't the paste's modifiers.
|
||||
let after = if mod_still_held { Modifiers::COMMAND } else { Modifiers::NONE };
|
||||
mods_frame(&ctx, &mut a, after, vec![egui::Event::Paste("external".into())]);
|
||||
let bold = a.session.run("format.state", &json!({})).unwrap().get("bold").and_then(serde_json::Value::as_bool);
|
||||
assert_eq!(bold, Some(true), "held={mod_still_held}: a plain paste keeps the HTML's bold");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_previous_sentence_shortcut_dispatches_and_can_be_reassigned() {
|
||||
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
|
||||
@@ -449,6 +449,24 @@ pub const DEFAULT_TAB: &str = "Home";
|
||||
|
||||
/// ⌘Q, which only the Mac sends: quit.
|
||||
const QUIT: egui::KeyboardShortcut = egui::KeyboardShortcut::new(egui::Modifiers::MAC_CMD, egui::Key::Q);
|
||||
/// Ctrl+Shift+0 (⌘⇧0): back to the Auto interface size (#4030). Not Ctrl+Alt+0, which is AltGr+0
|
||||
/// on some layouts and types a character there (#3424).
|
||||
const RESET_INTERFACE_SIZE: egui::KeyboardShortcut =
|
||||
egui::KeyboardShortcut::new(egui::Modifiers::COMMAND.plus(egui::Modifiers::SHIFT), egui::Key::Num0);
|
||||
|
||||
/// Consume Ctrl+Shift+0 (⌘⇧0), matched on the key the layout types and exactly these modifiers.
|
||||
/// Where Shift+0 types `=` (German, Swiss and Nordic layouts) the press is Ctrl+Shift+=, which
|
||||
/// stays Superscript; an extra Alt (AltGr+Shift+0) doesn't match.
|
||||
fn consume_reset_interface_size(input: &mut egui::InputState) -> bool {
|
||||
let mut found = false;
|
||||
input.events.retain(|e| {
|
||||
let hit = matches!(e, egui::Event::Key { key: egui::Key::Num0, pressed: true, modifiers, .. }
|
||||
if modifiers.matches_exact(RESET_INTERFACE_SIZE.modifiers));
|
||||
found |= hit;
|
||||
!hit
|
||||
});
|
||||
found
|
||||
}
|
||||
/// Most recent documents kept (File › Options › Advanced offers 0–50, as Word does).
|
||||
pub const MAX_RECENT: usize = 50;
|
||||
/// Most custom dictionary words read back from `ui.json`.
|
||||
@@ -638,6 +656,9 @@ pub struct WordApp {
|
||||
pub clipboard_published: bool,
|
||||
pub printing: printing::State,
|
||||
print_feedback_seen: Option<printing::Feedback>,
|
||||
/// Which job message is current: bumped when a job starts and whenever the message changes,
|
||||
/// so a window can tell a new result from one it already said even when the text is the same.
|
||||
print_gen: u64,
|
||||
pub canvas: canvas::CanvasState,
|
||||
/// Content control frames, check boxes and lists on the page.
|
||||
pub controls: content_controls::ControlUi,
|
||||
@@ -730,6 +751,12 @@ pub struct WordApp {
|
||||
/// The display scale (native pixels per point) seen in the last frame, 1.0 before the first;
|
||||
/// `ui.interfaceSize` reports the size Auto draws at with it.
|
||||
native_scale: f32,
|
||||
/// The most pixels per point Auto may draw at on this screen ([`theme::auto_scale_limit`], #4030).
|
||||
auto_scale_limit: f32,
|
||||
/// The zoom factor in force during the previous frame's `logic`: egui-winit turns each
|
||||
/// window's monitor size into points with the zoom of the frame before a pending change is
|
||||
/// applied, so the physical size is that size times this zoom ([`theme::auto_scale_limit_over`]).
|
||||
monitor_zoom: f32,
|
||||
/// A pre-#822 interface size (percent on top of the display scale) waiting for the first frame
|
||||
/// that knows the display's scale, to become the absolute size it drew at
|
||||
/// ([`theme::migrate_legacy_interface_size`]).
|
||||
@@ -759,8 +786,13 @@ pub struct WordApp {
|
||||
/// The document's fonts that aren't installed, for the status bar and the font box, and the
|
||||
/// layout they were read from.
|
||||
pub missing_fonts: crate::chrome::MissingFontsMemo,
|
||||
/// This window's refused or failed export, shown on its Export and Print pages; see [`WordApp::fail_export`].
|
||||
pub export_error: String,
|
||||
/// The document's [`StatusCounts`] and the key they were computed for; see [`WordApp::cached_status_counts`].
|
||||
pub status_counts: (u64, StatusCounts),
|
||||
/// What this window's Print page knows of the last job's message (the viewport and pass it was
|
||||
/// last drawn in, and the generations of the result it said and holds back); per window.
|
||||
print_memo: crate::print_page::Memo,
|
||||
last_autosave: f64,
|
||||
/// The tab shown before the Equation tab came up (restored when editing ends).
|
||||
pub(crate) equation_prev_tab: Option<String>,
|
||||
|
||||
@@ -407,7 +407,15 @@ pub fn pointer(app: &mut WordApp, ui: &Ui, resp: &egui::Response, pages: &[Rect]
|
||||
let _ = app.run("select.addObject", json!({"pos": object.pos()}));
|
||||
return true;
|
||||
}
|
||||
if pressed && grab == Grab::Move && object.behind() && behind_draggable(app, &object) {
|
||||
// While editing a header/footer, a click on its Behind Text picture where no header/footer
|
||||
// text covers it (the plain hit test picked it: down over the body, or clear of the text in
|
||||
// the band) selects it, as in Word; only over text does the click defer to that text.
|
||||
// ponytail: headers/footers only; body Behind Text pictures clear of text could do the same.
|
||||
let clear_of_text = matches!(object.story, StoryRef::Part(_))
|
||||
&& crate::canvas::page_at(pages, layout, scale, at)
|
||||
.and_then(|(page, x, y)| layout.object_at_in(page, x, y, EDGE / scale.max(0.01), object.story))
|
||||
.is_some_and(|o| o.pos() == object.pos());
|
||||
if pressed && grab == Grab::Move && object.behind() && !clear_of_text && behind_draggable(app, &object) {
|
||||
let (min, picture) = match app.session.doc.para_at(&object.pos()).and_then(|p| p.object_at(object.pos().off)) {
|
||||
Some(o) => (wordcraft_engine::cmd::objects::min_size(o), matches!(o, InlineObject::Image { .. })),
|
||||
None => return false,
|
||||
@@ -431,6 +439,8 @@ pub fn pointer(app: &mut WordApp, ui: &Ui, resp: &egui::Response, pages: &[Rect]
|
||||
let pos = object.pos();
|
||||
let end = Pos { off: pos.off + OBJ.len_utf8(), ..pos.clone() };
|
||||
let _ = app.run("select.range", json!({"anchor": pos, "focus": end}));
|
||||
// A header/footer picture repeats on every page: select the copy clicked, as `select_at` does.
|
||||
app.session.page_hint = object.page;
|
||||
let (min, picture) = match selected(app) {
|
||||
Some((_, o)) => (wordcraft_engine::cmd::objects::min_size(o), matches!(o, InlineObject::Image { .. })),
|
||||
None => return true,
|
||||
@@ -601,9 +611,8 @@ fn link_click(app: &mut WordApp, layout: &DocLayout, pages: &[Rect], scale: f32,
|
||||
/// Right-click at `at`: the picture, shape or text box under it becomes the selection (as a click
|
||||
/// would, without a drag), so the context menu acts on it. Returns whether there was one.
|
||||
pub fn select_at(app: &mut WordApp, layout: &DocLayout, pages: &[Rect], scale: f32, at: Pos2) -> bool {
|
||||
if crate::canvas::editing_header_footer(app, layout) {
|
||||
return false;
|
||||
}
|
||||
// While editing a header/footer, `grab_at` looks at its own objects, so its picture is picked
|
||||
// too and the menu's Reset Picture or Wrap Text acts on it.
|
||||
let Some((object, _)) = grab_at(app, layout, pages, scale, at) else { return false };
|
||||
let pos = object.pos();
|
||||
// Already selected (alone or among several picked for Group): keep the selection.
|
||||
@@ -611,6 +620,9 @@ pub fn select_at(app: &mut WordApp, layout: &DocLayout, pages: &[Rect], scale: f
|
||||
let end = Pos { off: pos.off + OBJ.len_utf8(), ..pos.clone() };
|
||||
let _ = app.run("select.range", json!({"anchor": pos, "focus": end}));
|
||||
}
|
||||
// A header/footer picture repeats on every page: its frame belongs on the page clicked, not
|
||||
// the one last edited.
|
||||
app.session.page_hint = object.page;
|
||||
true
|
||||
}
|
||||
|
||||
|
||||
@@ -771,8 +771,8 @@ fn interface_size_picker(app: &mut WordApp, ui: &mut Ui) {
|
||||
let native = ui.ctx().native_pixels_per_point().unwrap_or(1.0);
|
||||
// The template keeps the percent sign outside its placeholder, so `fmt` isolates the number
|
||||
// without it and a right-to-left line draws "(%200)": the sign goes inside the isolate.
|
||||
let auto = crate::i18n::fmt(tl!("Auto ({percent}%)"), &[("percent", &InterfaceSize::AUTO.drawn_percent(native).to_string())])
|
||||
.replace("\u{2069}%", "%\u{2069}");
|
||||
let drawn = InterfaceSize::AUTO.drawn_percent_within(native, app.auto_scale_limit);
|
||||
let auto = crate::i18n::fmt(tl!("Auto ({percent}%)"), &[("percent", &drawn.to_string())]).replace("\u{2069}%", "%\u{2069}");
|
||||
let selected = size.percent().map_or_else(|| auto.clone(), |pct| format!("{pct}%"));
|
||||
ui.horizontal(|ui| {
|
||||
let label = ui.label(tl!("Interface size:"));
|
||||
|
||||
@@ -170,6 +170,18 @@ fn return_prints(ctx: &egui::Context) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// Per window: what the Print page needs to know about the last job's message.
|
||||
#[derive(Default)]
|
||||
pub struct Memo {
|
||||
/// The viewport and pass the page was last drawn in: a gap means it was just opened.
|
||||
pass: Option<(egui::ViewportId, u64)>,
|
||||
/// The generation (`WordApp::print_gen`) of the job result this window has already said, in
|
||||
/// its status bar or on this page: a result of the same text from a later job is another one.
|
||||
pub(crate) said: Option<u64>,
|
||||
/// The generation of the result held back on this opening of the page.
|
||||
hidden: Option<u64>,
|
||||
}
|
||||
|
||||
/// The Print page: settings on the left, the preview on the right.
|
||||
pub fn show(app: &mut WordApp, ui: &mut Ui) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
@@ -178,6 +190,30 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) {
|
||||
let total = lay.pages.len();
|
||||
let current = app.session.current_pages(&lay);
|
||||
app.ui.print.preview = app.ui.print.preview.min(total.saturating_sub(1));
|
||||
// Opened afresh, the page doesn't repeat how the last job went when this window already said
|
||||
// it (its status bar, or this page): `printing.message` itself stays, as `ui.printSettings`
|
||||
// and other windows still report it. What the printers are doing (finding them, none found)
|
||||
// always shows. Passes are counted per viewport, so the marker is per window.
|
||||
let here = (ctx.viewport_id(), ctx.cumulative_pass_nr());
|
||||
let opened = app.print_memo.pass.is_none_or(|(viewport, last)| viewport != here.0 || last.saturating_add(1) < here.1);
|
||||
app.print_memo.pass = Some(here);
|
||||
let result = |m: &Option<crate::printing::Feedback>| {
|
||||
matches!(m, Some(crate::printing::Feedback::Submitted(_) | crate::printing::Feedback::Failed(_) | crate::printing::Feedback::WorkerStopped))
|
||||
};
|
||||
let message = app.printing.message.clone();
|
||||
let generation = app.print_gen;
|
||||
if opened {
|
||||
app.print_memo.hidden = (result(&message) && app.print_memo.said == Some(generation)).then_some(generation);
|
||||
}
|
||||
// A later message (a job started again, then failed the same way) is shown afresh.
|
||||
if app.print_memo.hidden != Some(generation) {
|
||||
app.print_memo.hidden = None;
|
||||
}
|
||||
let hide_message = app.print_memo.hidden.is_some();
|
||||
if !hide_message {
|
||||
// Shown here, so the next opening needn't repeat it.
|
||||
app.print_memo.said = result(&message).then_some(generation);
|
||||
}
|
||||
|
||||
let settings = |app: &mut WordApp, ui: &mut Ui| {
|
||||
{
|
||||
@@ -206,7 +242,7 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) {
|
||||
}
|
||||
if native {
|
||||
if let Some(discover) = &app.services.printers {
|
||||
crate::printing::show(&mut app.printing, ui, discover, |label| crate::i18n::t(label).to_owned());
|
||||
crate::printing::show(&mut app.printing, ui, discover, hide_message, |label| crate::i18n::t(label).to_owned());
|
||||
}
|
||||
// A job can wait long on a sleeping printer's driver; Cancel frees the page.
|
||||
if app.printing.busy() && app.services.cancel_print.is_some() && ui.button(tl!("Cancel printing")).clicked() {
|
||||
@@ -454,28 +490,71 @@ fn preview(app: &mut WordApp, ui: &mut Ui, lay: &DocLayout) {
|
||||
/// The export "format" of a Word 2003 XML Document: an `.xml` file saved with `format: "wordml2003"`.
|
||||
pub(crate) const EXPORT_WORD_2003: &str = "wordml2003";
|
||||
|
||||
/// The "save a copy" formats as (label, format), also the built-in browser's types when exporting.
|
||||
pub(crate) const EXPORT_FORMATS: &[(&str, &str)] = &[
|
||||
("PDF document (*.pdf)", "pdf"),
|
||||
("Word document (*.docx)", "docx"),
|
||||
("Word XML Document (*.xml)", "xml"),
|
||||
("Word 2003 XML Document (*.xml)", EXPORT_WORD_2003),
|
||||
("OpenDocument Text (*.odt)", "odt"),
|
||||
("OpenDocument Text Template (*.ott)", "ott"),
|
||||
("Flat OpenDocument Text (*.fodt)", "fodt"),
|
||||
("Rich Text Format (*.rtf)", "rtf"),
|
||||
("Web page (*.html)", "html"),
|
||||
("Markdown (*.md)", "md"),
|
||||
("LaTeX (*.tex)", "tex"),
|
||||
("Plain text (*.txt)", "txt"),
|
||||
("Page image (*.png)", "png"),
|
||||
];
|
||||
|
||||
/// The file extension an export format writes.
|
||||
pub(crate) fn export_file_ext(format: &str) -> &str {
|
||||
if format == EXPORT_WORD_2003 { "xml" } else { format }
|
||||
}
|
||||
|
||||
/// Is `ext` an extension of a document or export type (the Export types, plus the older `.doc`
|
||||
/// and `.htm`)? Such an extension on a typed name gives way to the chosen type's; any other
|
||||
/// (`notes.v2`) is part of the name.
|
||||
pub(crate) fn is_document_ext(ext: &str) -> bool {
|
||||
["doc", "htm"].iter().any(|e| e.eq_ignore_ascii_case(ext)) || EXPORT_FORMATS.iter().any(|&(_, f)| export_file_ext(f).eq_ignore_ascii_case(ext))
|
||||
}
|
||||
|
||||
/// The name an export to `format` is saved under: the chosen type's extension replaces a known
|
||||
/// document extension (`notes.docx` as plain text is `notes.txt`) and is added to any other name.
|
||||
pub(crate) fn export_name(name: &str, format: &str) -> String {
|
||||
let want = export_file_ext(format);
|
||||
let path = std::path::Path::new(name);
|
||||
// A dotfile name (`.docx`) has no extension for `Path::extension`, which the engine's save also
|
||||
// reads, so it is a stem and gets one (`.docx.xml`); a bare extension would be refused.
|
||||
match path.extension().and_then(|e| e.to_str()) {
|
||||
Some(e) if e.eq_ignore_ascii_case(want) => name.to_string(),
|
||||
Some(e) if is_document_ext(e) => path.with_extension(want).to_string_lossy().into_owned(),
|
||||
// `a.` has an empty extension: its dot is dropped before the type's is added.
|
||||
_ => format!("{}.{want}", name.trim_end_matches('.')),
|
||||
}
|
||||
}
|
||||
|
||||
/// The "save a copy" formats (File › Export, and below the settings on the Print page).
|
||||
pub fn export_formats(app: &mut WordApp, ui: &mut Ui) {
|
||||
for (label, ext) in [
|
||||
("PDF document (*.pdf)", "pdf"),
|
||||
("Word document (*.docx)", "docx"),
|
||||
("Word XML Document (*.xml)", "xml"),
|
||||
("Word 2003 XML Document (*.xml)", EXPORT_WORD_2003),
|
||||
("OpenDocument Text (*.odt)", "odt"),
|
||||
("OpenDocument Text Template (*.ott)", "ott"),
|
||||
("Flat OpenDocument Text (*.fodt)", "fodt"),
|
||||
("Rich Text Format (*.rtf)", "rtf"),
|
||||
("Web page (*.html)", "html"),
|
||||
("Markdown (*.md)", "md"),
|
||||
("LaTeX (*.tex)", "tex"),
|
||||
("Plain text (*.txt)", "txt"),
|
||||
("Page image (*.png)", "png"),
|
||||
] {
|
||||
// A refused or failed export, said here because Backstage hides the status bar (Export and Print pages both draw this).
|
||||
if !app.export_error.is_empty() {
|
||||
ui.label(egui::RichText::new(&app.export_error).color(ui.visuals().error_fg_color));
|
||||
ui.add_space(6.0);
|
||||
}
|
||||
for &(label, ext) in EXPORT_FORMATS {
|
||||
if ui.add(egui::Button::new(egui::RichText::new(tl!(label)).font(medium(13.5))).min_size(vec2(320.0, 34.0))).clicked() {
|
||||
app.export_dialog(ext);
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
}
|
||||
// Linux and the BSDs (#3535): WordCraft's own browser when the system dialog doesn't appear.
|
||||
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
|
||||
{
|
||||
ui.add_space(8.0);
|
||||
if ui.add(egui::Button::new(egui::RichText::new(tl!("Browse in WordCraft…")).font(medium(13.5))).min_size(vec2(320.0, 34.0))).clicked() {
|
||||
let _ = app.run("ui.fileBrowser", json!({"purpose": "export"}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user