Compare commits

..
Author SHA1 Message Date
Martin BallandClaude Opus 5.5 695d358ed1 Customize Ribbon: the "Show" column header is not clipped (#7981)
The toggle column was only as wide as its check box, so its header read "S...". It is now as wide as its header.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx
2026-11-30 19:28:59 +00:00
52 changed files with 331 additions and 3647 deletions
+3 -3
View File
@@ -35,7 +35,7 @@ jobs:
CARGO_INCREMENTAL: 0
steps:
- name: Harden runner
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -121,7 +121,7 @@ jobs:
shell: pwsh
steps:
- name: Harden runner
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -181,7 +181,7 @@ jobs:
CARGO_INCREMENTAL: 0
steps:
- name: Harden runner
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+2 -2
View File
@@ -28,7 +28,7 @@ jobs:
runs-on: windows-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -58,7 +58,7 @@ jobs:
contents: read
steps:
- name: Harden runner
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
Generated
+4 -41
View File
@@ -4670,7 +4670,7 @@ dependencies = [
"skrifa 0.42.1",
"smallvec",
"subsetter",
"tiny-skia-path 0.12.0",
"tiny-skia-path",
"xmp-writer",
"yoke",
"zune-jpeg",
@@ -6555,7 +6555,7 @@ dependencies = [
"pico-args",
"rgb",
"svgtypes",
"tiny-skia 0.12.0",
"tiny-skia",
"usvg",
]
@@ -6818,17 +6818,6 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "sctk-adwaita"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec"
dependencies = [
"log",
"smithay-client-toolkit 0.19.2",
"tiny-skia 0.11.4",
]
[[package]]
name = "security-framework"
version = "3.7.0"
@@ -7717,20 +7706,6 @@ dependencies = [
"time-core",
]
[[package]]
name = "tiny-skia"
version = "0.11.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab"
dependencies = [
"arrayref",
"arrayvec",
"bytemuck",
"cfg-if",
"log",
"tiny-skia-path 0.11.4",
]
[[package]]
name = "tiny-skia"
version = "0.12.0"
@@ -7743,18 +7718,7 @@ dependencies = [
"cfg-if",
"log",
"png 0.18.1",
"tiny-skia-path 0.12.0",
]
[[package]]
name = "tiny-skia-path"
version = "0.11.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93"
dependencies = [
"arrayref",
"bytemuck",
"strict-num",
"tiny-skia-path",
]
[[package]]
@@ -8169,7 +8133,7 @@ dependencies = [
"siphasher",
"strict-num",
"svgtypes",
"tiny-skia-path 0.12.0",
"tiny-skia-path",
]
[[package]]
@@ -9028,7 +8992,6 @@ dependencies = [
"raw-window-handle",
"redox_syscall 0.4.1",
"rustix 0.38.44",
"sctk-adwaita",
"smithay-client-toolkit 0.19.2",
"smol_str",
"tracing",
-31
View File
@@ -188,34 +188,3 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Linux Wayland window decorations
-------------------------------
sctk-adwaita 0.10.1 (https://github.com/PolyMeilex/sctk-adwaita,
commit d5f343c45c04d4a026db57f76760819b7325db00) is used by winit on Linux
for vector window controls. Its title-font features are disabled: no Cantarell
font is embedded by this dependency and no font file is added to this repo.
sctk-adwaita's MIT licence:
MIT License
Copyright (c) 2022 Bartłomiej Maryńczak
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+1 -5
View File
File diff suppressed because one or more lines are too long
+1 -7
View File
@@ -60,14 +60,8 @@ winresource = "0.1"
# kAEOpenDocuments Apple event, which winit doesn't handle (#27).
craft = { workspace = true, features = ["platform-apple-events", "menu"] }
[target.'cfg(all(unix, not(any(target_os = "macos", target_os = "linux"))))'.dependencies]
winit = { version = "0.30", default-features = false, features = ["x11"] }
[target.'cfg(target_os = "linux")'.dependencies]
# Retain X11 fallback; draw Wayland client-side controls without bundled title fonts.
winit = { version = "0.30", default-features = false, features = ["x11", "wayland-csd-adwaita-notitle"] }
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
winit = { version = "0.30", default-features = false, features = ["x11"] }
# Check that the libraries winit's X11 backend opens are installed before choosing XWayland (see
# `x11_libraries` in main.rs). Both are already in the build through winit's `x11` feature, at
# these versions and with this feature.
@@ -1,167 +0,0 @@
//! Integration test for Linux Wayland client-side window decoration controls (#5814, #5375).
//!
//! Ensures that on Linux, client-side window controls use font-free Adwaita vector paths
//! so the close button is rendered as a clean vector cross rather than a square fallback,
//! and that sctk-adwaita has proper license attribution in NOTICE without bundling font files.
use std::path::Path;
/// Strips an unquoted TOML `#` comment from a single line.
fn strip_toml_comment(line: &str) -> &str {
let mut in_double = false;
let mut in_single = false;
for (idx, ch) in line.char_indices() {
match ch {
'"' if !in_single => in_double = !in_double,
'\'' if !in_double => in_single = !in_single,
'#' if !in_double && !in_single => return &line[..idx],
_ => {}
}
}
line
}
/// Extracts the comment-stripped body of a TOML table section by exact `[header]`.
fn toml_section(content: &str, header: &str) -> String {
let mut in_section = false;
let mut out = String::new();
for raw_line in content.lines() {
let line = strip_toml_comment(raw_line).trim();
if line.starts_with('[') && line.ends_with(']') {
if in_section {
break;
}
in_section = line == header;
continue;
}
if in_section && !line.is_empty() {
out.push_str(line);
out.push('\n');
}
}
assert!(in_section, "expected target section {header} in apps/wordcraft/Cargo.toml");
out
}
/// Parses the `features = [...]` string array from the `winit = { ... }` dependency entry in a TOML section.
fn winit_features(section: &str) -> Vec<&str> {
let winit_start = section.find("winit").expect("target section must declare a winit dependency");
let after_winit = &section[winit_start..];
let table_end = after_winit.find('}').expect("winit inline table must close with '}'");
let winit_table = &after_winit[..=table_end];
let features_start = winit_table.find("features").expect("winit dependency must declare features");
let after_features = &winit_table[features_start..];
let open_bracket = after_features.find('[').expect("winit features must open with '['");
let after_open = &after_features[open_bracket + 1..];
let close_bracket = after_open.find(']').expect("winit features must close with ']'");
let array_body = &after_open[..close_bracket];
array_body.split(',').map(|item| item.trim().trim_matches('"')).filter(|item| !item.is_empty()).collect()
}
/// Verifies that `apps/wordcraft/Cargo.toml` enables `wayland-csd-adwaita-notitle` for Linux.
#[test]
fn linux_manifest_enables_wayland_csd_adwaita_notitle() {
let cargo_toml = Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
let content = std::fs::read_to_string(&cargo_toml).expect("read apps/wordcraft/Cargo.toml");
let linux_section = toml_section(&content, "[target.'cfg(target_os = \"linux\")'.dependencies]");
let linux_features = winit_features(&linux_section);
assert!(
linux_features.contains(&"x11") && linux_features.contains(&"wayland-csd-adwaita-notitle"),
"Linux winit dependency must enable x11 and wayland-csd-adwaita-notitle, got: {linux_features:?}"
);
let other_unix_section = toml_section(&content, "[target.'cfg(all(unix, not(any(target_os = \"macos\", target_os = \"linux\"))))'.dependencies]");
let other_unix_features = winit_features(&other_unix_section);
assert!(
other_unix_features.contains(&"x11") && !other_unix_features.contains(&"wayland-csd-adwaita-notitle"),
"Non-Linux Unix winit dependency must enable x11 without wayland-csd-adwaita-notitle, got: {other_unix_features:?}"
);
}
/// Verifies that `NOTICE` documents sctk-adwaita and its MIT licence.
#[test]
fn notice_documents_sctk_adwaita_attribution() {
let workspace_root = Path::new(env!("CARGO_MANIFEST_DIR")).parent().and_then(Path::parent).expect("workspace root");
let notice = std::fs::read_to_string(workspace_root.join("NOTICE")).expect("read NOTICE");
assert!(notice.contains("Linux Wayland window decorations"), "NOTICE must include 'Linux Wayland window decorations'");
assert!(notice.contains("sctk-adwaita"), "NOTICE must document sctk-adwaita");
assert!(notice.contains("Bartłomiej Maryńczak"), "NOTICE must retain sctk-adwaita's author copyright");
}
/// Parses `[[package]]` entries from `Cargo.lock` as `(name, version, dependencies)`.
fn parse_lockfile_packages(lockfile: &str) -> Vec<(&str, &str, Vec<&str>)> {
lockfile
.split("[[package]]")
.skip(1)
.filter_map(|chunk| {
let mut name = None;
let mut version = None;
let mut deps = Vec::new();
let mut in_deps = false;
for raw_line in chunk.lines() {
let line = raw_line.trim();
if in_deps {
if line == "]" {
in_deps = false;
continue;
}
let dep = line.trim_end_matches(',').trim().trim_matches('"');
if !dep.is_empty() {
deps.push(dep);
}
continue;
}
if let Some(rest) = line.strip_prefix("name = ") {
name = Some(rest.trim_matches('"'));
} else if let Some(rest) = line.strip_prefix("version = ") {
version = Some(rest.trim_matches('"'));
} else if line == "dependencies = [" {
in_deps = true;
}
}
Some((name?, version?, deps))
})
.collect()
}
/// Verifies that WordCraft's resolved Linux `winit` -> `sctk-adwaita` dependency path in
/// `Cargo.lock` does not pull in any title-font renderer crates.
#[test]
fn cargo_lock_contains_font_free_sctk_adwaita() {
use std::collections::{HashSet, VecDeque};
let workspace_root = Path::new(env!("CARGO_MANIFEST_DIR")).parent().and_then(Path::parent).expect("workspace root");
let lockfile = std::fs::read_to_string(workspace_root.join("Cargo.lock")).expect("read Cargo.lock");
let packages = parse_lockfile_packages(&lockfile);
let has_dep = |pkg_name: &str, target: &str| {
packages.iter().any(|(name, _, deps)| *name == pkg_name && deps.iter().any(|spec| spec.split_whitespace().next() == Some(target)))
};
assert!(has_dep("winit", "sctk-adwaita"), "winit in Cargo.lock must depend on sctk-adwaita");
let mut queue = VecDeque::new();
let mut visited = HashSet::new();
for (idx, (name, _, _)) in packages.iter().enumerate() {
if *name == "sctk-adwaita" && visited.insert(idx) {
queue.push_back(idx);
}
}
assert!(!queue.is_empty(), "Cargo.lock must include sctk-adwaita");
let forbidden = ["fontdue", "ab_glyph", "cosmic-text", "crossfont"];
while let Some(idx) = queue.pop_front() {
let (name, _, deps) = &packages[idx];
assert!(!forbidden.contains(name), "sctk-adwaita's resolved dependency path must not include title-font renderer {name}");
for spec in deps {
let mut parts = spec.split_whitespace();
let dep_name = parts.next().expect("dependency name");
let dep_ver = parts.next();
for (next_idx, (cand_name, cand_ver, _)) in packages.iter().enumerate() {
if *cand_name == dep_name && dep_ver.is_none_or(|v| v == *cand_ver) && visited.insert(next_idx) {
queue.push_back(next_idx);
}
}
}
}
}
-2
View File
@@ -2,7 +2,5 @@
mod appimage_env;
mod control_arg;
mod help;
#[cfg(target_os = "linux")]
mod linux_decorations;
#[cfg(unix)]
mod non_utf8_args;
+7 -26
View File
@@ -703,44 +703,25 @@ impl Document {
}
/// A drawing id no shape uses yet (for gluing a connector to a shape that has none).
///
/// Returns one past the largest in-use shape id across the body, all secondary parts, and
/// footnote/endnote separator stories (walking nested groups and tables); if `u32::MAX` is
/// already in use, falls back via [`free_id`] to the smallest unused non-zero id (or `0` only
/// if every non-zero `u32` id is taken).
pub fn next_shape_id(&self) -> u32 {
let mut largest: Option<u32> = None;
let mut used: Vec<u32> = Vec::new();
let mut record = |id: u32| {
if id != 0 {
largest = largest.max(Some(id));
used.push(id);
}
};
let mut max = 0u32;
let mut see = |o: &InlineObject| match o {
InlineObject::Shape { extra, .. } => record(extra.id),
InlineObject::Shape { extra, .. } => max = max.max(extra.id),
InlineObject::Group { children, .. } => {
let mut todo: Vec<&InlineObject> = children.iter().map(|c| &c.obj).collect();
while let Some(obj) = todo.pop() {
match obj {
InlineObject::Shape { extra, .. } => record(extra.id),
InlineObject::Group { children, .. } => todo.extend(children.iter().map(|c| &c.obj)),
_ => {}
for c in children {
if let InlineObject::Shape { extra, .. } = &c.obj {
max = max.max(extra.id);
}
}
}
_ => {}
};
let sep_stories = [&self.footnote_separators, &self.endnote_separators]
.into_iter()
.flat_map(|s| [&s.separator, &s.continuation_separator, &s.continuation_notice])
.flatten();
for blocks in std::iter::once(&self.body).chain(self.parts.values().map(|p| &p.blocks)).chain(sep_stories) {
for blocks in std::iter::once(&self.body).chain(self.parts.values().map(|p| &p.blocks)) {
for b in blocks {
edit::each_para(b, 0, &mut |p| p.objects.iter().for_each(&mut see));
}
}
free_id(largest, used.into_iter(), 1).unwrap_or(0)
max.saturating_add(1).max(1)
}
/// Change every inline object in every story (paragraphs inside tables too), copying only
+10 -32
View File
@@ -291,47 +291,25 @@ impl InlineObject {
_ => None,
}
}
/// The text box stories this object shows: a text box's, or its group members' (nested groups
/// included, in member order).
/// The text box stories this object shows: a text box's, or its group members'.
pub fn text_boxes(&self) -> Vec<u32> {
match self {
InlineObject::Shape { story: Some(id), .. } => vec![*id],
InlineObject::Group { children, .. } => {
let mut out = Vec::new();
let mut todo: Vec<&InlineObject> = children.iter().rev().map(|c| &c.obj).collect();
while let Some(obj) = todo.pop() {
match obj {
InlineObject::Shape { story: Some(id), .. } => out.push(*id),
InlineObject::Group { children, .. } => {
todo.extend(children.iter().rev().map(|c| &c.obj));
}
_ => {}
}
}
out
}
InlineObject::Group { children, .. } => children.iter().filter_map(|c| c.obj.text_box()).collect(),
_ => Vec::new(),
}
}
/// The text box story slots of this object and its group members (nested groups included, in
/// member order), to repoint.
/// The text box story slots of this object and its group members, to repoint.
pub fn text_box_slots(&mut self) -> Vec<&mut Option<u32>> {
match self {
InlineObject::Shape { story, .. } => vec![story],
InlineObject::Group { children, .. } => {
let mut out = Vec::new();
let mut todo: Vec<&mut InlineObject> = children.iter_mut().rev().map(|c| &mut c.obj).collect();
while let Some(obj) = todo.pop() {
match obj {
InlineObject::Shape { story, .. } => out.push(story),
InlineObject::Group { children, .. } => {
todo.extend(children.iter_mut().rev().map(|c| &mut c.obj));
}
_ => {}
}
}
out
}
InlineObject::Group { children, .. } => children
.iter_mut()
.filter_map(|c| match &mut c.obj {
InlineObject::Shape { story, .. } => Some(story),
_ => None,
})
.collect(),
_ => Vec::new(),
}
}
+1 -17
View File
@@ -42,27 +42,11 @@ pub struct Revision {
/// insertion or deletion.
#[serde(skip_serializing_if = "Option::is_none")]
pub move_name: Option<String>,
/// The change's UTC timestamp: from the file (`w16du:dateUtc`, where `date` is the local time
/// Word writes in `w:date`), or the time WordCraft stamped the change with. `None` when the
/// file doesn't give it.
#[serde(skip_serializing_if = "Option::is_none")]
pub date_utc: Option<String>,
}
impl Revision {
pub fn new(kind: RevisionKind, author: impl Into<String>, date: impl Into<String>) -> Revision {
Revision { kind, author: author.into(), date: date.into(), move_name: None, date_utc: None }
}
/// A change made here: `date` is the local wall-clock time it was made at, as Word writes
/// `w:date`, and `date_utc` the same instant in UTC.
pub fn made_at(kind: RevisionKind, author: impl Into<String>, date: impl Into<String>, utc: impl Into<String>) -> Revision {
Revision { kind, author: author.into(), date: date.into(), move_name: None, date_utc: Some(utc.into()) }
}
/// The instant changes are grouped by: the UTC time when it is known, else `date`.
pub fn instant(&self) -> &str {
self.date_utc.as_deref().unwrap_or(&self.date)
Revision { kind, author: author.into(), date: date.into(), move_name: None }
}
}
-272
View File
@@ -440,116 +440,6 @@ fn prune_text_boxes_drops_only_unshown_ones() {
assert_eq!(d.prune_text_boxes(), 0);
}
/// A text-box shape (`story: Some(id)`) or plain shape (`story: None`) for nested-group tests.
fn test_shape(story: Option<u32>) -> InlineObject {
InlineObject::Shape {
kind: para::ShapeKind::TextBox,
w: 50.0,
h: 20.0,
fill: None,
stroke: None,
stroke_width: 0.0,
float: Default::default(),
story,
freeform: None,
effects: Default::default(),
extra: Default::default(),
}
}
/// A group holding `children`.
fn test_group(children: Vec<InlineObject>) -> InlineObject {
InlineObject::Group {
w: 100.0,
h: 100.0,
float: Default::default(),
ch_w: 100.0,
ch_h: 100.0,
children: children.into_iter().map(|obj| para::GroupChild { x: 0.0, y: 0.0, obj }).collect(),
canvas: None,
}
}
/// `obj` wrapped inside `levels` nested [`InlineObject::Group`]s.
fn nested_group(levels: usize, obj: InlineObject) -> InlineObject {
(0..levels).fold(obj, |inner, _| test_group(vec![inner]))
}
#[test]
fn nested_group_text_boxes_are_collected_and_slots_repointed_in_order() {
let mut outer = test_group(vec![
test_shape(Some(1)),
test_shape(None),
nested_group(1, test_shape(Some(2))), // depth 2 from outer
test_group(vec![nested_group(1, test_shape(Some(3))), test_shape(Some(4))]), // depth 3 and depth 2
nested_group(39, test_shape(Some(5))), // depth 40 from outer
]);
assert_eq!(outer.text_boxes(), vec![1, 2, 3, 4, 5]);
let slots = outer.text_box_slots();
assert_eq!(slots.len(), 6);
for id in slots.into_iter().flatten() {
*id += 100;
}
assert_eq!(outer.text_boxes(), vec![101, 102, 103, 104, 105]);
}
#[test]
fn prune_text_boxes_keeps_nested_group_boxes_and_drops_unreachable() {
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
let mut d = Document::from_text("body");
let depth2 = d.add_part(PartKind::TextBox, para_of("depth 2"));
let depth3 = d.add_part(PartKind::TextBox, para_of("depth 3"));
let deep = d.add_part(PartKind::TextBox, para_of("depth 40"));
let linked_live = d.add_part(PartKind::TextBox, para_of("linked follower"));
let orphan = d.add_part(PartKind::TextBox, para_of("unreachable"));
let orphan_nested = d.add_part(PartKind::TextBox, para_of("inside unreachable"));
// Live link between two nested-group boxes and a dangling link to an unreachable box.
d.parts.get_mut(&depth2).unwrap().body.next = Some(linked_live);
d.parts.get_mut(&depth3).unwrap().body.next = Some(orphan);
d.insert_object(&Pos::body(0, 0), nested_group(2, test_shape(Some(depth2))), &CharProps::default()).unwrap();
d.insert_object(&Pos::body(0, 0), nested_group(3, test_shape(Some(depth3))), &CharProps::default()).unwrap();
d.insert_object(&Pos::body(0, 0), nested_group(40, test_shape(Some(deep))), &CharProps::default()).unwrap();
d.insert_object(&Pos::body(0, 0), nested_group(2, test_shape(Some(linked_live))), &CharProps::default()).unwrap();
let at_orphan = Pos { story: StoryRef::Part(orphan), path: Path::top(0), off: 0 };
d.insert_object(&at_orphan, nested_group(2, test_shape(Some(orphan_nested))), &CharProps::default()).unwrap();
assert_eq!(d.prune_text_boxes(), 2);
let kept: Vec<u32> = d.parts.keys().copied().collect();
assert_eq!(kept, vec![depth2, depth3, deep, linked_live]);
assert_eq!(d.plain_text(StoryRef::Part(depth2)), "depth 2");
assert_eq!(d.plain_text(StoryRef::Part(depth3)), "depth 3");
assert_eq!(d.plain_text(StoryRef::Part(deep)), "depth 40");
assert_eq!(d.parts.get(&depth2).unwrap().body.next, Some(linked_live), "live chain link stays");
assert_eq!(d.parts.get(&depth3).unwrap().body.next, None, "dangling chain link is cleared");
assert_eq!(d.prune_text_boxes(), 0);
}
#[test]
fn prune_text_boxes_terminates_on_cyclic_nested_group_stories() {
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
let mut d = Document::from_text("body");
let a = d.add_part(PartKind::TextBox, para_of("a"));
let b = d.add_part(PartKind::TextBox, para_of("b"));
let dead_c = d.add_part(PartKind::TextBox, para_of("dead c"));
let dead_d = d.add_part(PartKind::TextBox, para_of("dead d"));
let at = |id| Pos { story: StoryRef::Part(id), path: Path::top(0), off: 0 };
// Reachable cycle: body -> nested group -> a -> nested group -> b -> nested group -> (a, b).
d.insert_object(&Pos::body(0, 0), nested_group(2, test_shape(Some(a))), &CharProps::default()).unwrap();
d.insert_object(&at(a), nested_group(2, test_shape(Some(b))), &CharProps::default()).unwrap();
d.insert_object(&at(b), nested_group(2, test_group(vec![test_shape(Some(a)), test_shape(Some(b))])), &CharProps::default()).unwrap();
// Unreachable cycle: dead_c <-> dead_d through nested groups.
d.insert_object(&at(dead_c), nested_group(2, test_shape(Some(dead_d))), &CharProps::default()).unwrap();
d.insert_object(&at(dead_d), nested_group(2, test_shape(Some(dead_c))), &CharProps::default()).unwrap();
assert_eq!(d.prune_text_boxes(), 2);
let kept: Vec<u32> = d.parts.keys().copied().collect();
assert_eq!(kept, vec![a, b]);
assert_eq!(d.counted_stories(), vec![StoryRef::Body, StoryRef::Part(a), StoryRef::Part(b)]);
}
/// `blocks` in the only cell of `levels` tables, each nested in the next.
fn nested_tables(levels: usize, blocks: Blocks) -> Blocks {
(0..levels).fold(blocks, |inner, _| {
@@ -928,165 +818,3 @@ fn missing_pictures_are_capped_deduplicated_and_not_content() {
assert!(!serde_json::to_string(&d).unwrap().contains("p0"));
assert_eq!(MissingPictureReason::ExternalTarget.label(), "external target");
}
fn shape_with_id(id: u32, story: Option<u32>) -> InlineObject {
InlineObject::Shape {
kind: para::ShapeKind::Rectangle,
w: 50.0,
h: 20.0,
fill: None,
stroke: None,
stroke_width: 0.0,
float: Default::default(),
story,
freeform: None,
effects: Default::default(),
extra: connector::ShapeExtra { id, ..Default::default() },
}
}
fn group_of(children: Vec<InlineObject>) -> InlineObject {
InlineObject::Group {
w: 100.0,
h: 100.0,
float: Default::default(),
ch_w: 100.0,
ch_h: 100.0,
children: children.into_iter().map(|obj| para::GroupChild { x: 0.0, y: 0.0, obj }).collect(),
canvas: None,
}
}
fn nested_group_of(depth: usize, leaf: InlineObject) -> InlineObject {
(0..depth).fold(leaf, |inner, _| group_of(vec![inner]))
}
#[test]
fn next_shape_id_accounts_for_shapes_in_nested_groups() {
// Doubly-nested group carrying shape id 1: must not reissue id 1.
let mut d = Document::from_text("body");
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(1, None)), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 2);
// Deeper nesting (5-level and 40-level groups) with mixed siblings.
d.insert_object(
&Pos::body(0, 0),
nested_group_of(5, group_of(vec![shape_with_id(42, None), nested_group_of(35, shape_with_id(99, None))])),
&CharProps::default(),
)
.unwrap();
assert_eq!(d.next_shape_id(), 100);
// Nested group inside a secondary story (part).
let hdr = d.add_part(PartKind::Header, vec![para_block(Paragraph::with_text("hdr", CharProps::default()))]);
let at_hdr = Pos { story: StoryRef::Part(hdr), path: Path::top(0), off: 0 };
d.insert_object(&at_hdr, nested_group_of(3, shape_with_id(150, None)), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 151);
}
#[test]
fn next_shape_id_preserves_flat_group_and_ungrouped_allocation() {
let mut d = Document::from_text("body");
assert_eq!(d.next_shape_id(), 1);
// Ungrouped shapes (including id 0).
d.insert_object(&Pos::body(0, 0), shape_with_id(0, None), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 1);
d.insert_object(&Pos::body(0, 0), shape_with_id(3, None), &CharProps::default()).unwrap();
d.insert_object(&Pos::body(0, 0), shape_with_id(7, None), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 8);
// Flat (1-level) group.
d.insert_object(&Pos::body(0, 0), group_of(vec![shape_with_id(12, None), shape_with_id(4, None)]), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 13);
// At u32::MAX, overflow falls back to an unused non-zero id rather than reissuing u32::MAX.
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(u32::MAX, None)), &CharProps::default()).unwrap();
let id = d.next_shape_id();
assert_ne!(id, 0);
for used in [3, 4, 7, 12, u32::MAX] {
assert_ne!(id, used);
}
assert_eq!(id, 1);
}
#[test]
fn next_shape_id_avoids_reissuing_u32_max_on_overflow() {
// Non-overflow boundary: u32::MAX - 1 still advances to u32::MAX.
let mut d = Document::from_text("body");
d.insert_object(&Pos::body(0, 0), shape_with_id(u32::MAX - 1, None), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), u32::MAX);
// Once u32::MAX is in use inside a nested group, allocator must not reissue any in-use id.
let hdr = d.add_part(PartKind::Header, vec![para_block(Paragraph::with_text("hdr", CharProps::default()))]);
let at_hdr = Pos { story: StoryRef::Part(hdr), path: Path::top(0), off: 0 };
d.insert_object(&Pos::body(0, 0), shape_with_id(1, None), &CharProps::default()).unwrap();
d.insert_object(&at_hdr, nested_group_of(2, shape_with_id(2, None)), &CharProps::default()).unwrap();
d.insert_object(&Pos::body(0, 0), nested_group_of(3, shape_with_id(u32::MAX, None)), &CharProps::default()).unwrap();
let in_use = [1, 2, u32::MAX - 1, u32::MAX];
let first = d.next_shape_id();
assert_ne!(first, 0);
assert!(!in_use.contains(&first), "reissued in-use shape id {first}");
assert_eq!(first, 3);
// Using the returned id advances to the next unused id rather than repeating it.
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(first, None)), &CharProps::default()).unwrap();
let second = d.next_shape_id();
assert_ne!(second, 0);
assert_ne!(second, first);
assert!(!in_use.contains(&second), "reissued in-use shape id {second}");
assert_eq!(second, 4);
}
#[test]
fn next_shape_id_terminates_on_cyclic_nested_group_stories() {
// InlineObject::Group owns Vec<GroupChild> by value (and unsafe is forbidden), so a cyclic
// in-memory Group tree cannot be constructed in safe Rust; mirror #8068 by constructing a
// cyclic text-box story graph through nested groups instead.
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
let mut d = Document::from_text("body");
let a = d.add_part(PartKind::TextBox, para_of("a"));
let b = d.add_part(PartKind::TextBox, para_of("b"));
let at = |id| Pos { story: StoryRef::Part(id), path: Path::top(0), off: 0 };
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(5, Some(a))), &CharProps::default()).unwrap();
d.insert_object(&at(a), nested_group_of(2, shape_with_id(10, Some(b))), &CharProps::default()).unwrap();
d.insert_object(&at(b), nested_group_of(2, shape_with_id(25, Some(a))), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 26);
}
#[test]
fn next_shape_id_accounts_for_shapes_in_note_separators() {
let blocks_with = |obj: InlineObject| -> Blocks {
let mut p = Paragraph::with_text("sep", CharProps::default());
p.insert_object(0, obj, &CharProps::default()).unwrap();
vec![para_block(p)]
};
// A shape ID used only in a footnote separator story must not be reissued.
let mut d = Document::from_text("body");
d.footnote_separators.separator = Some(blocks_with(shape_with_id(1, None)));
assert_eq!(d.next_shape_id(), 2);
// Every footnote and endnote separator slot is walked, including nested groups and tables.
d.footnote_separators.continuation_separator = Some(blocks_with(nested_group_of(2, shape_with_id(2, None))));
d.footnote_separators.continuation_notice = Some(nested_tables(1, blocks_with(shape_with_id(5, None))));
assert_eq!(d.next_shape_id(), 6);
d.endnote_separators.separator = Some(blocks_with(shape_with_id(9, None)));
assert_eq!(d.next_shape_id(), 10);
d.endnote_separators.continuation_separator = Some(blocks_with(nested_group_of(3, shape_with_id(14, None))));
assert_eq!(d.next_shape_id(), 15);
// Overflow fallback also respects IDs held exclusively in note-separator stories.
d.endnote_separators.continuation_notice = Some(blocks_with(nested_group_of(2, shape_with_id(u32::MAX, None))));
let allocated = d.next_shape_id();
assert_ne!(allocated, 0);
for used in [1, 2, 5, 9, 14, u32::MAX] {
assert_ne!(allocated, used);
}
assert_eq!(allocated, 3);
}
+10 -64
View File
@@ -316,13 +316,7 @@ fn styles_and_lists_round_trip() {
#[test]
fn tracked_style_definition_change_round_trips() {
let mut d = Document::new();
d.revisions.push(Revision {
kind: RevisionKind::Format,
author: "Ana".into(),
date: "2026-10-17T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision { kind: RevisionKind::Format, author: "Ana".into(), date: "2026-10-17T10:00:00Z".into(), move_name: None });
std::sync::Arc::make_mut(&mut d.styles).upsert(Style {
id: "Mine".into(),
name: "Mine".into(),
@@ -1011,20 +1005,8 @@ fn toc_field_skips_nested_stories() {
#[test]
fn tracked_changes_round_trip() {
let mut d = Document::new();
d.revisions.push(Revision {
kind: RevisionKind::Insert,
author: "Alice".into(),
date: "2026-05-01T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision {
kind: RevisionKind::Delete,
author: "Bob".into(),
date: "2026-05-02T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
d.settings.track_changes = true;
let ins = CharProps { ins: Some(0), ..Default::default() };
let del = CharProps { del: Some(1), bold: Some(true), ..Default::default() };
@@ -1052,20 +1034,8 @@ fn tracked_changes_round_trip() {
fn tracked_equations_round_trip() {
// Issue #6011: equations saved with tracked revision marks (w:ins / w:del) around math.
let mut d = Document::new();
d.revisions.push(Revision {
kind: RevisionKind::Insert,
author: "Alice".into(),
date: "2026-05-01T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision {
kind: RevisionKind::Delete,
author: "Bob".into(),
date: "2026-05-02T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
d.settings.track_changes = true;
let ins = CharProps { ins: Some(0), ..Default::default() };
let del = CharProps { del: Some(1), ..Default::default() };
@@ -1119,20 +1089,8 @@ fn tracked_equations_round_trip() {
fn nested_omath_para_revisions_read() {
// Defensive reader check: w:ins and w:del nested inside m:oMathPara.
let mut d = Document::new();
d.revisions.push(Revision {
kind: RevisionKind::Insert,
author: "Ada".into(),
date: "2026-05-01T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision {
kind: RevisionKind::Delete,
author: "Charles".into(),
date: "2026-05-02T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Charles".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
let doc_xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"><w:body><w:p><m:oMathPara><w:ins w:id="1" w:author="Ada" w:date="2026-05-01T10:00:00Z"><m:oMath><m:r><m:t>x+1</m:t></m:r></m:oMath></w:ins><w:del w:id="2" w:author="Charles" w:date="2026-05-02T10:00:00Z"><m:oMath><m:r><m:t>y-1</m:t></m:r></m:oMath></w:del></m:oMathPara></w:p></w:body></w:document>"#;
let base = wordcraft_docx::write(&d).unwrap();
let bytes = replace_part(&base, "word/document.xml", doc_xml.as_bytes());
@@ -1150,20 +1108,8 @@ fn tracked_paragraph_marks_round_trip() {
// Issue #229: an inserted / deleted paragraph mark is `w:ins` / `w:del` in the mark's
// `w:rPr` (ECMA-376 §17.13.5.16, §17.13.5.15), alone or with mark formatting.
let mut d = Document::new();
d.revisions.push(Revision {
kind: RevisionKind::Insert,
author: "Alice".into(),
date: "2026-05-01T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision {
kind: RevisionKind::Delete,
author: "Bob".into(),
date: "2026-05-02T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
let mut split = Paragraph::with_text("Owned ALPHA ", CharProps::default());
split.mark.ins = Some(0);
let mut joined = Paragraph::with_text("Owned BETA", CharProps::default());
@@ -1917,7 +1863,7 @@ fn kitchen_sink() -> Document {
let f = d.add_part(PartKind::Footnote, vec![para_block(Paragraph::with_text("Note", CharProps::default()))]);
let c = d.add_part(PartKind::Comment, vec![para_block(Paragraph::with_text("Comment", CharProps::default()))]);
d.comments.insert(3, Comment { author: "X".into(), part: c, ..Default::default() });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "A".into(), date: String::new(), move_name: None, date_utc: None });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "A".into(), date: String::new(), move_name: None });
d.last_section.headers.default = Some(h);
let mut blocks: Blocks = Vec::new();
let mut p = para_runs(&[
+1 -1
View File
@@ -41,7 +41,7 @@ fn sample() -> Document {
let foot = d.add_part(PartKind::Footnote, vec![para_block(Paragraph::with_text("Sown in May.", CharProps::default()))]);
let com = d.add_part(PartKind::Comment, vec![para_block(Paragraph::with_text("Too short?", CharProps::default()))]);
d.comments.insert(3, Comment { author: "Bo".into(), part: com, ..Default::default() });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None });
d.last_section.headers.default = Some(head);
let mut p = Paragraph::new();
-2
View File
@@ -298,8 +298,6 @@ Review|Language|Translate|review.translate
Review|Language|Language|review.language
Review|Comments|New Comment|review.newComment
Review|Comments|Delete|review.deleteComment
Review|Comments|Delete All Comments in Document|review.deleteComment
Review|Comments|Delete All Resolved Comments|review.deleteComment
Review|Comments|Previous|review.previousComment
Review|Comments|Next|review.nextComment
Review|Comments|Show Comments|review.comments
+2 -27
View File
@@ -210,21 +210,14 @@ pub fn new_revision(s: &mut Session, kind: RevisionKind) -> u32 {
.iter()
.enumerate()
.rev()
.find(|(i, r)| r.kind == kind && r.author == s.author && r.instant() == date && r.move_name.is_none() && held != Some(*i as u32))
.find(|(i, r)| r.kind == kind && r.author == s.author && r.date == date && r.move_name.is_none() && held != Some(*i as u32))
{
return i as u32;
}
s.doc.revisions.push(made_revision(kind, s.author.clone(), date));
s.doc.revisions.push(Revision { kind, author: s.author.clone(), date, move_name: None });
(s.doc.revisions.len() - 1) as u32
}
/// A revision record for a change made at `utc` (ISO 8601, UTC): dated in local wall-clock time,
/// as Word writes `w:date`, with the UTC time beside it, so a save writes it as it is (#6851).
pub fn made_revision(kind: RevisionKind, author: String, utc: String) -> Revision {
let date = crate::io_ext::word_date(&utc, local_offset_secs).unwrap_or_else(|| utc.clone());
Revision::made_at(kind, author, date, utc)
}
/// Whether the paragraph at `path` is followed by another paragraph in the same container (so
/// its paragraph mark can be removed by joining the two).
pub fn has_next_para(s: &Session, story: StoryRef, path: &wordcraft_doc::Path) -> bool {
@@ -563,10 +556,6 @@ pub fn iso_from_unix_secs(secs: u64) -> String {
/// Seconds since the Unix epoch (UTC): the system clock, or the browser's on the web.
pub fn now_unix() -> u64 {
#[cfg(test)]
if let Some(now) = TEST_NOW.with(std::cell::Cell::get) {
return now;
}
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
{
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
@@ -588,23 +577,9 @@ pub fn now_iso() -> String {
/// The local time zone's offset from UTC in seconds (east positive) at `unix`, daylight saving
/// included: the system's zone, or the browser's on the web. 0 (UTC) when it can't be found.
pub fn local_offset_secs(unix: u64) -> i64 {
#[cfg(test)]
if let Some(zone) = TEST_ZONE.with(std::cell::Cell::get) {
return zone(unix);
}
system_offset_secs(unix).clamp(-26 * 3600, 26 * 3600)
}
#[cfg(test)]
thread_local! {
/// The clock [`now_unix`] reads on this thread in place of the system's, so a test can make
/// edits at the instants it needs.
pub static TEST_NOW: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
/// The zone [`local_offset_secs`] gives on this thread in place of the system's. CI runs on
/// UTC, where local time is UTC, so a test sets a zone that isn't to tell them apart.
pub static TEST_ZONE: std::cell::Cell<Option<fn(u64) -> i64>> = const { std::cell::Cell::new(None) };
}
#[cfg(not(target_arch = "wasm32"))]
fn system_offset_secs(unix: u64) -> i64 {
use chrono::Offset;
+1 -1
View File
@@ -35,7 +35,7 @@ pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("references.sources", "Manage Sources", "References › Citations & Bibliography", sources)
.params(r#"{"add"?: Source, "remove"?: tag, "import"?: path (a Word bibliography file, `b:Sources` / `Sources.xml`)} → list"#),
CommandSpec::new("references.citation", "Insert Citation", "References › Citations & Bibliography", citation).params(r#"{"tag"?: string, "source"?: Source (added, or edited when its tag exists, and cited when no tag is given), "pages"?: string}"#),
CommandSpec::new("references.citation", "Insert Citation", "References › Citations & Bibliography", citation).params(r#"{"tag"?: string, "source"?: Source (added if new), "pages"?: string}"#),
CommandSpec::new("references.citationStyle", "Style", "References › Citations & Bibliography", |s, v| {
let st = p::str(v, "style").unwrap_or("APA");
let st = find_style(st).ok_or_else(|| {
+25 -33
View File
@@ -37,7 +37,22 @@ fn auto_tag_base(src: &Source) -> String {
/// document's sources. `import` reads a Word bibliography file (`b:Sources`, #2640).
pub(super) fn sources(s: &mut Session, v: &Value) -> CmdResult {
if let Some(a) = v.get("add") {
add_source(s, a)?;
let mut src: Source = serde_json::from_value(a.clone()).map_err(|e| CmdError::Params(e.to_string()))?;
// A new source's tag is made from its author and year; an edit keeps the tag it has.
if src.tag.is_empty() {
src.tag = auto_tag(&s.doc, &src);
}
// Edit Source keeps the source's place in the list and refreshes its citations.
match s.doc.sources.iter().position(|x| x.tag == src.tag) {
Some(i) => {
if let Some(x) = s.doc.sources.get_mut(i) {
*x = src;
}
update_citations(s)?;
}
None => s.doc.sources.push(src),
}
s.touch();
}
if let Some(t) = p::str(v, "remove") {
s.doc.sources.retain(|x| x.tag != t);
@@ -48,28 +63,6 @@ pub(super) fn sources(s: &mut Session, v: &Value) -> CmdResult {
Ok(serde_json::to_value(&s.doc.sources).unwrap_or(Value::Null))
}
/// Adds a source, or edits the one with its tag, and returns that tag (#7443).
fn add_source(s: &mut Session, a: &Value) -> Result<String, CmdError> {
let mut src: Source = serde_json::from_value(a.clone()).map_err(|e| CmdError::Params(e.to_string()))?;
// A new source's tag is made from its author and year; an edit keeps the tag it has.
if src.tag.is_empty() {
src.tag = auto_tag(&s.doc, &src);
}
let tag = src.tag.clone();
// Edit Source keeps the source's place in the list and refreshes its citations.
match s.doc.sources.iter().position(|x| x.tag == src.tag) {
Some(i) => {
if let Some(x) = s.doc.sources.get_mut(i) {
*x = src;
}
update_citations(s)?;
}
None => s.doc.sources.push(src),
}
s.touch();
Ok(tag)
}
/// The largest bibliography sources file imported from disk.
#[cfg(not(target_arch = "wasm32"))]
const MAX_SOURCES_FILE: u64 = 32 << 20;
@@ -133,16 +126,15 @@ fn import_sources(s: &mut Session, path: &str) -> Result<(), CmdError> {
}
pub(super) fn citation(s: &mut Session, v: &Value) -> CmdResult {
// The source just added or edited is the one cited when no `tag` is given, wherever it sits
// in the list (#7443).
let added = match v.get("source") {
Some(a) => Some(add_source(s, a)?),
None => None,
};
let tag = match (p::str(v, "tag"), added) {
(Some(t), _) => t.to_string(),
(None, Some(t)) => t,
(None, None) => return Err(CmdError::Params("give `tag` or `source`".into())),
if v.get("source").is_some() {
sources(s, &json!({"add": v.get("source")}))?;
}
let tag = match p::str(v, "tag") {
Some(t) => t.to_string(),
None => match v.get("source") {
Some(_) => s.doc.sources.last().map(|x| x.tag.clone()).unwrap_or_default(),
None => return Err(CmdError::Params("give `tag` or `source`".into())),
},
};
let src = s.doc.sources.iter().find(|x| x.tag == tag).cloned().ok_or_else(|| CmdError::Params(format!("no source `{tag}`")))?;
let pages = p::str(v, "pages").unwrap_or("").to_string();
-16
View File
@@ -597,22 +597,6 @@ fn editing_author_and_year_keeps_the_tag_and_updates_the_citation_text() {
assert!(f[0].1.contains("Jones") && f[0].1.contains("2021"), "{:?}", f[0].1);
}
#[test]
fn citing_an_edited_source_that_is_not_last_cites_that_source() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("references.sources", &json!({"add": src_of("Alice, Ann", "2000")})).unwrap();
s.run("references.sources", &json!({"add": src_of("Bob, Ben", "2001")})).unwrap();
let mut edited = src_of("Alice Edited, Ann", "2000");
edited["tag"] = json!("Ali00");
let r = s.run("references.citation", &json!({"source": edited})).unwrap();
assert_eq!(r["tag"], "Ali00");
let tags: Vec<_> = s.doc.sources.iter().map(|x| x.tag.as_str()).collect();
assert_eq!(tags, ["Ali00", "Bob01"]);
let f = fields(&s);
assert_eq!(f[0].0, "CITATION Ali00");
assert!(f[0].1.contains("Alice Edited") && f[0].1.contains("2000"), "{:?}", f[0].1);
}
#[test]
fn a_new_sources_tag_is_three_letters_and_two_year_digits() {
let mut s = Session::new(wordcraft_doc::Document::new());
+2 -2
View File
@@ -53,11 +53,11 @@ impl Recorder<'_> {
if let Some(r) = self.rid {
return r;
}
let found = self.revisions.iter().rposition(|r| r.kind == RevisionKind::Format && r.author == self.author && r.instant() == self.date);
let found = self.revisions.iter().rposition(|r| r.kind == RevisionKind::Format && r.author == self.author && r.date == self.date);
let r = match found {
Some(i) => i as u32,
None => {
self.revisions.push(crate::cmd::made_revision(RevisionKind::Format, self.author.clone(), self.date.clone()));
self.revisions.push(Revision { kind: RevisionKind::Format, author: self.author.clone(), date: self.date.clone(), move_name: None });
self.revisions.len().saturating_sub(1) as u32
}
};
-196
View File
@@ -27,7 +27,6 @@ pub fn specs() -> Vec<CommandSpec> {
r#"{"type"?: "indented|runIn", "columns"?: 1-4, "rightAlign"?: bool, "tabLeader"?: "dot|hyphen|underscore|none", "headings"?: bool (letter headings)} (replaces an existing index's settings)"#,
),
CommandSpec::new("references.updateIndex", "Update Index", "References › Index", |s, _| {
check_index_reachable(s)?;
super::citations::update_generated(s)?;
sel_result(s)
}),
@@ -136,63 +135,8 @@ fn index_field(s: &Session) -> Option<(usize, String)> {
})
}
/// Whether an INDEX field (a plain one or a range field, as Word files hold it) sits in the main
/// text's own paragraphs (`main`), or anywhere else a reader sees: a table cell, a text box, a
/// header or a footer in use. Stored headers and footers no page shows (a first-page header
/// while Different First Page is off) don't count. Only an index in the main text is rebuilt.
fn has_index(s: &Session, main: bool) -> bool {
s.doc.shown_stories().into_iter().any(|story| {
s.doc
.para_paths(story)
.iter()
.filter(|path| (story == StoryRef::Body && path.depth() == 0) == main)
.filter_map(|path| s.doc.para(story, path))
.any(|p| {
p.objects.iter().any(|o| {
matches!(o, InlineObject::Field { instr, .. } | InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX")
})
})
})
}
/// Refuses Insert and Update Index when the document has an index they can't rebuild, even beside
/// one in the main text, rather than adding a second index or reporting an update that left it
/// unchanged.
fn check_index_reachable(s: &Session) -> Result<(), CmdError> {
if has_index(s, false) {
return Err(CmdError::Failed(
"the index is in a table, text box, header or footer, where it can't be updated; move it into the main text, then use Update Index"
.into(),
));
}
// A range-field index after text in its paragraph is not rebuilt either: Update Index only
// takes one that starts its paragraph.
if range_index_after_text(s) {
return Err(CmdError::Failed(
"the index follows text in its paragraph, where it can't be updated; put it at the start of its own paragraph in the main text".into(),
));
}
Ok(())
}
/// Whether a main-text range-field INDEX has text before it in its paragraph.
fn range_index_after_text(s: &Session) -> bool {
s.doc.body.iter().filter_map(|b| b.as_para()).any(|p| {
p.objects_with_offsets().any(|(off, o)| {
matches!(o, InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX")
&& !p.text.get(..off).is_some_and(|t| t.chars().all(|c| c.is_whitespace() || c == wordcraft_doc::para::OBJ))
})
})
}
fn insert_index(s: &mut Session, v: &Value) -> CmdResult {
let instr = index_instr(v);
check_index_reachable(s)?;
// An index Word wrote as a range field is rebuilt by Update Index; Insert Index would add a
// second one beside it (#8034).
if index_field(s).is_none() && has_index(s, true) {
return Err(CmdError::Failed("the document already has an index; use Update Index to rebuild it".into()));
}
match index_field(s) {
Some((i, _)) => {
// Settings for the index that is there: a new field code, then rebuild it.
@@ -540,144 +484,4 @@ mod tests {
let (i, _) = index_field(&s).unwrap();
assert_eq!(s.doc.body[i + 2].as_para().unwrap().props.tabs.as_ref().unwrap()[0].leader, TabLeader::Hyphen);
}
/// #3670: an index in a table cell or a text box (as imported documents have it) can't be
/// rebuilt where it is, so Insert and Update Index say so, and Insert Index doesn't add a
/// second index at the caret.
#[test]
fn an_index_outside_the_main_text_is_refused_not_doubled() {
let indexes = |s: &Session| {
std::iter::once(StoryRef::Body)
.chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k)))
.flat_map(|story| s.doc.para_paths(story).into_iter().filter_map(move |path| s.doc.para(story, &path).cloned()))
.flat_map(|p| p.objects)
.filter(|o| matches!(o, InlineObject::Field { instr, .. } | InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX"))
.count()
};
for in_box in [false, true] {
let mut s = Session::new(wordcraft_doc::Document::from_text(
"Kilns are hot.
End.",
));
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
s.run("references.markEntry", &json!({})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
let at = if in_box {
s.run("insert.textBox", &json!({"text": "Box"})).unwrap();
let id = s.doc.parts.iter().find(|(_, p)| p.kind == wordcraft_doc::PartKind::TextBox).map(|(id, _)| *id).unwrap();
Pos { story: StoryRef::Part(id), path: Path::top(0), off: 0 }
} else {
s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap();
let cell = s.doc.para_paths(StoryRef::Body).into_iter().find(|path| path.depth() > 0).unwrap();
Pos { story: StoryRef::Body, path: cell, off: 0 }
};
// A range field, as a Word file holds its index.
let p = s.doc.para_mut(at.story, &at.path).unwrap();
p.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
p.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
.unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
let r = s.run("references.index", &json!({"columns": 2}));
assert!(r.is_err(), "Insert Index with the index in a {}: {r:?}", if in_box { "text box" } else { "table" });
assert_eq!(indexes(&s), 1, "INDEX fields after Insert Index");
assert!(s.run("references.updateIndex", &json!({})).is_err(), "Update Index reports the index it can't rebuild");
}
}
/// #3670: an index in a table is refused even when the main text also has one, so the update
/// can't report success and leave the table's index as it was.
#[test]
fn an_index_in_a_table_is_refused_beside_one_in_the_main_text() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns are hot."));
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
s.run("references.markEntry", &json!({})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
s.run("references.index", &json!({})).unwrap();
s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap();
let cell = s.doc.para_paths(StoryRef::Body).into_iter().find(|path| path.depth() > 0).unwrap();
let p = s.doc.para_mut(StoryRef::Body, &cell).unwrap();
p.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
p.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default()).unwrap();
assert!(s.run("references.index", &json!({"columns": 2})).is_err());
assert!(s.run("references.updateIndex", &json!({})).is_err());
}
/// #3670: only the headers a page shows count. An INDEX in a first-page header is out of
/// reach while Different First Page is on, and doesn't block Insert Index while it is off.
#[test]
fn an_index_in_a_header_blocks_insert_only_while_the_header_is_shown() {
let with_header_index = |first: bool, title_page: bool| {
let mut d = wordcraft_doc::Document::from_text("Kilns are hot.");
let mut p = wordcraft_doc::Paragraph::new();
p.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
p.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
.unwrap();
let id = d.add_part(wordcraft_doc::PartKind::Header, vec![std::sync::Arc::new(wordcraft_doc::Block::Para(p))]);
if first {
d.last_section.headers.first = Some(id);
} else {
d.last_section.headers.default = Some(id);
}
d.last_section.title_page = title_page;
let mut s = Session::new(d);
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
s.run("references.markEntry", &json!({})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
s
};
let body_has_index = |s: &Session| index_field(s).is_some();
// Linked (default) header: shown, so Insert Index is refused.
let mut s = with_header_index(false, false);
assert!(s.run("references.index", &json!({})).is_err());
assert!(!body_has_index(&s));
// First-page header with Different First Page off: hidden, so the body gets its index.
let mut s = with_header_index(true, false);
s.run("references.index", &json!({})).unwrap();
assert!(body_has_index(&s));
// The same header with Different First Page on is shown again.
let mut s = with_header_index(true, true);
assert!(s.run("references.index", &json!({})).is_err());
assert!(!body_has_index(&s));
}
/// An index Word wrote as a range field in the main text is rebuilt by Update Index; Insert
/// Index says so instead of adding a second one (#8034).
#[test]
fn insert_index_leaves_a_range_field_index_in_the_main_text_to_update_index() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns are hot."));
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
s.run("references.markEntry", &json!({})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
let at = s.doc.body.len();
let mut para = wordcraft_doc::para::Paragraph::new();
para.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
para.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
.unwrap();
s.doc.insert_block(StoryRef::Body, &Path::top(at), wordcraft_doc::Block::Para(para)).unwrap();
let before = s.doc.body.len();
assert!(s.run("references.index", &json!({})).is_err());
assert_eq!(s.doc.body.len(), before, "no second index was added");
s.run("references.updateIndex", &json!({})).unwrap();
let text: String =
s.doc.body.iter().filter_map(|b| b.as_para()).map(|p| p.text.replace(wordcraft_doc::para::OBJ, "")).collect::<Vec<_>>().join(
"
",
);
assert!(text.contains("Kilns are hot."), "the text before the index survives: {text:?}");
assert!(text.contains("Kilns, 1"), "Update Index generated an entry: {text:?}");
}
#[test]
fn a_range_field_index_after_text_is_refused_not_reported_updated() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns are hot."));
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
s.run("references.markEntry", &json!({})).unwrap();
let p = s.doc.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
let end = p.len();
p.insert_object(end, InlineObject::FieldEnd, &CharProps::default()).unwrap();
p.insert_object(end, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
.unwrap();
assert!(s.run("references.updateIndex", &json!({})).is_err());
assert!(s.run("references.index", &json!({})).is_err());
}
}
+3 -3
View File
@@ -56,7 +56,7 @@ pub fn cut_tracked(s: &mut Session) -> Result<bool, CmdError> {
if !s.doc.settings.track_changes || !s.doc.settings.track_moves || a == b || a.story != b.story || !move_sized(&s.clipboard_text) {
return Ok(false);
}
s.doc.revisions.push(crate::cmd::made_revision(RevisionKind::Delete, s.author.clone(), now_iso()));
s.doc.revisions.push(Revision::new(RevisionKind::Delete, s.author.clone(), now_iso()));
let rid = (s.doc.revisions.len() - 1) as u32;
let at = track_delete_as(s, &a, &b, rid)?.at;
s.sel = Selection::caret(at);
@@ -75,13 +75,13 @@ pub fn take_paste(s: &mut Session, frag: &Fragment) -> Option<u32> {
return None;
}
let src = s.doc.revisions.get(m.rev as usize).filter(|r| r.kind == RevisionKind::Delete && r.move_name.is_none())?;
let (date, date_utc) = (src.date.clone(), src.date_utc.clone());
let date = src.date.clone();
let taken: BTreeSet<&str> = s.doc.revisions.iter().filter_map(|r| r.move_name.as_deref()).collect();
let name = (1..).map(|n: u64| format!("move{n}")).find(|n| !taken.contains(n.as_str()))?;
if let Some(r) = s.doc.revisions.get_mut(m.rev as usize) {
r.move_name = Some(name.clone());
}
s.doc.revisions.push(Revision { kind: RevisionKind::Insert, author: s.author.clone(), date, move_name: Some(name), date_utc });
s.doc.revisions.push(Revision { kind: RevisionKind::Insert, author: s.author.clone(), date, move_name: Some(name) });
Some((s.doc.revisions.len() - 1) as u32)
}
+1 -1
View File
@@ -200,7 +200,7 @@ pub fn specs() -> Vec<CommandSpec> {
r#"{"color": "RRGGBB" | null, "paragraph"?: bool} (text selected inside one paragraph is shaded itself, as in Word; `paragraph: true` shades the paragraphs instead, as Borders and Shading › Apply to: Paragraph)"#,
),
CommandSpec::new("para.borders", "Borders", "Home › Paragraph", borders).params(
r#"{"kind": "bottom|top|left|right|none|all|outside|inside|horizontalLine", "width"?: pt, "color"?: "RRGGBB", "style"?: "single|double|dotted|dashed|thick|triple|dotDash|wave", "sides"?: Sides} where Sides = {"top"|"left"|"bottom"|"right"|"between": {"style"?, "width"?: pt, "color"?: "RRGGBB"} | null}: exactly these sides (others off), instead of `kind` (with whole table cells selected, `kind` borders the cells as a block instead of their paragraphs)"#,
r#"{"kind": "bottom|top|left|right|none|all|outside|inside|horizontalLine", "width"?: pt, "color"?: "RRGGBB", "style"?: "single|double|dotted|dashed|thick|triple|dotDash|wave", "sides"?: Sides} where Sides = {"top"|"left"|"bottom"|"right"|"between": {"style"?, "width"?: pt, "color"?: "RRGGBB"} | null}: exactly these sides (others off), instead of `kind`"#,
),
CommandSpec::new("para.sort", "Sort", "Home › Paragraph", sort).params(r#"{"descending"?: bool}"#),
CommandSpec::new("para.keepNext", "Keep with Next", "Home › Paragraph › Line and Page Breaks", |s, v| tog(s, v, |p| p.keep_next, |p, b| p.keep_next = Some(b)))
@@ -102,10 +102,6 @@ pub(super) fn borders(s: &mut Session, v: &Value) -> CmdResult {
// A paragraph with a bottom border, like Word's Horizontal Line.
return fmt(s, &|p| p.borders = Some(Borders { bottom: Some(Border { width: 1.5, ..b }), ..Default::default() }));
}
// Whole table cells selected: the border goes on the cells, not their paragraphs (#7874).
if let Some(range) = s.cell_range().cloned() {
return crate::cmd::table::cell_block_borders(s, &range, kind, b);
}
fmt(s, &|p| {
let mut cur = p.borders.unwrap_or_default();
match kind {
+1 -3
View File
@@ -33,9 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("review.editComment", "Edit Comment", "Review › Comments", edit_comment)
.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 32-bit JSON integer (omit to use the caret), "all"?: bool (every comment), "resolved"?: bool (every resolved comment, with its replies; wins over all)}"#,
),
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()))?;
+1 -2
View File
@@ -608,11 +608,10 @@ pub(super) fn list_changes(s: &mut Session, _: &Value) -> CmdResult {
list.iter()
.map(|c| {
let rev = c.rev.and_then(|r| s.doc.revisions.get(r as usize));
// The date in UTC when it is known; a file's `w:date` without it is as read.
let mut v = json!({
"kind": c.kind, "start": pos_json(&c.a), "end": pos_json(&c.b),
"text": s.doc.copy_range(&c.a, &c.b).plain_text(),
"author": rev.map(|r| r.author.clone()), "date": rev.map(|r| r.instant().to_string()),
"author": rev.map(|r| r.author.clone()), "date": rev.map(|r| r.date.clone()),
});
if c.kind == "format" {
v["description"] = json!(fmt_revisions::describe(&c.props));
+7 -11
View File
@@ -163,17 +163,17 @@ fn remove_anchors(s: &mut Session, ids: &BTreeSet<u32>) -> Result<(), CmdError>
Ok(())
}
/// The comments and every reply below them, replies to replies included (#1345), each once. A
/// parent cycle from a hostile file ends the walk instead of looping.
fn threads_of(s: &Session, roots: impl IntoIterator<Item = u32>) -> Vec<u32> {
/// The comment and every reply below it, replies to replies included (#1345). A parent cycle
/// from a hostile file ends the walk instead of looping.
fn thread_of(s: &Session, id: u32) -> Vec<u32> {
let mut children: BTreeMap<u32, Vec<u32>> = BTreeMap::new();
for (k, c) in &s.doc.comments {
if let Some(parent) = c.parent {
children.entry(parent).or_default().push(*k);
}
}
let mut seen = BTreeSet::new();
let mut ids: Vec<u32> = roots.into_iter().filter(|id| seen.insert(*id)).collect();
let mut seen = BTreeSet::from([id]);
let mut ids = vec![id];
let mut i = 0;
while let Some(&at) = ids.get(i) {
for k in children.get(&at).into_iter().flatten() {
@@ -188,15 +188,11 @@ fn threads_of(s: &Session, roots: impl IntoIterator<Item = u32>) -> Vec<u32> {
pub(super) fn delete_comment(s: &mut Session, v: &Value) -> CmdResult {
validate_comment_id(v)?;
let ids: Vec<u32> = if p::bool(v, "resolved").unwrap_or(false) {
// Delete All Resolved Comments (#7818): each resolved comment goes with its replies.
let resolved: Vec<u32> = s.doc.comments.iter().filter(|(_, c)| c.resolved).map(|(k, _)| *k).collect();
threads_of(s, resolved)
} else if p::bool(v, "all").unwrap_or(false) {
let ids: Vec<u32> = if p::bool(v, "all").unwrap_or(false) {
s.doc.comments.keys().copied().collect()
} else {
let id = p::u64(v, "id").map(|x| x as u32).or_else(|| comment_at_caret(s)).ok_or_else(|| CmdError::Params("no comment here".into()))?;
threads_of(s, [id])
thread_of(s, id)
};
remove_anchors(s, &ids.iter().copied().collect())?;
for id in &ids {
-200
View File
@@ -549,135 +549,6 @@ fn selected(s: &Session) -> (usize, usize) {
(a.off, b.off)
}
/// Two edits an hour apart in the repeated hour as daylight saving time ends are two changes,
/// though both were made at 01:30 local time: each keeps its UTC time (#6851). Rejecting one at
/// the caret leaves the other pending. Saved as DOCX or Word XML, both are dated 01:30, as Word
/// dates them, with their UTC times beside it (`w16du:dateUtc`), so they reopen as two changes,
/// and a second save writes them as read.
#[test]
fn edits_in_the_repeated_hour_stay_separate_changes() {
use crate::cmd::{TEST_NOW, TEST_ZONE};
struct Reset;
impl Drop for Reset {
fn drop(&mut self) {
TEST_NOW.with(|c| c.set(None));
TEST_ZONE.with(|z| z.set(None));
}
}
let _reset = Reset;
TEST_ZONE.with(|z| z.set(Some(crate::io_ext::tests::new_york)));
let mut s = Session::new(Document::new());
s.view.proofing = false;
s.run("document.setText", &json!({"text": "Draft."})).unwrap();
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
// 1 November 2026, 01:30 EDT (05:30 UTC) and then 01:30 EST (06:30 UTC).
for (now, text) in [(1_793_511_000, " One"), (1_793_514_600, " Two")] {
TEST_NOW.with(|c| c.set(Some(now)));
s.run("text.insert", &json!({"text": text})).unwrap();
}
assert_eq!(change_spans(&mut s), [("insert".into(), 6, 10), ("insert".into(), 10, 14)]);
let utc = ["2026-11-01T05:30:00Z", "2026-11-01T06:30:00Z"];
let instants = |d: &Document| d.revisions.iter().map(|r| r.instant().to_string()).collect::<Vec<_>>();
assert_eq!(instants(&s.doc), utc);
let listed = s.run("review.changes", &json!({})).unwrap();
assert_eq!(listed.as_array().map(|l| l.iter().map(|c| c["date"].clone()).collect::<Vec<_>>()), Some(vec![json!(utc[0]), json!(utc[1])]));
let local = |d: &Document| d.revisions.iter().map(|r| r.date.clone()).collect::<Vec<_>>();
for name in ["repeated.docx", "repeated.xml"] {
let bytes = crate::io::save_bytes(name, &s.doc).unwrap();
let read = |bytes: &[u8]| if name.ends_with(".xml") { wordcraft_docx::read_xml(bytes) } else { wordcraft_docx::read(bytes) }.unwrap();
let written = read(&bytes);
assert_eq!(local(&written), ["2026-11-01T01:30:00Z"; 2], "{name}");
assert_eq!(instants(&written), utc, "{name}");
let mut opened = Session::new(crate::io::open_bytes(name, &bytes).unwrap());
opened.view.proofing = false;
assert_eq!(change_spans(&mut opened), [("insert".into(), 6, 10), ("insert".into(), 10, 14)], "{name}");
// Saved again, the changes are written as read: their local time doesn't move.
let again = read(&crate::io::save_bytes(name, &opened.doc).unwrap());
assert_eq!((local(&again), instants(&again)), (local(&written), instants(&written)), "{name}");
opened.run("caret.set", &json!({"pos": {"block": 0, "off": 12}})).unwrap();
opened.run("review.reject", &json!({})).unwrap();
assert_eq!(opened.doc.plain_text(wordcraft_doc::StoryRef::Body), "Draft. One", "{name}");
assert_eq!(change_spans(&mut opened), [("insert".into(), 6, 10)], "{name}: the earlier insertion is still pending");
}
assert_eq!(instants(&s.doc), utc, "saving leaves the session's changes as they were");
s.run("caret.set", &json!({"pos": {"block": 0, "off": 12}})).unwrap();
s.run("review.reject", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(wordcraft_doc::StoryRef::Body), "Draft. One");
assert_eq!(change_spans(&mut s), [("insert".into(), 6, 10)], "the earlier insertion is still pending");
}
/// A change made at 08:33 UTC at UTC+8 is dated 16:33 in a Word file, as Word dates it, and 08:33
/// UTC in an OpenDocument file, whose `dc:date` is an instant (#6851).
#[test]
fn a_new_change_is_dated_in_utc_in_opendocument() {
use crate::cmd::{TEST_NOW, TEST_ZONE};
struct Reset;
impl Drop for Reset {
fn drop(&mut self) {
TEST_NOW.with(|c| c.set(None));
TEST_ZONE.with(|z| z.set(None));
}
}
let _reset = Reset;
TEST_ZONE.with(|z| z.set(Some(|_| 8 * 3600)));
TEST_NOW.with(|c| c.set(Some(1_794_818_004)));
let mut s = Session::new(Document::new());
s.view.proofing = false;
s.run("document.setText", &json!({"text": "Draft."})).unwrap();
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
s.run("text.insert", &json!({"text": " One"})).unwrap();
let utc = "2026-11-16T08:33:24Z";
let dates = |d: &Document| d.revisions.iter().map(|r| r.date.clone()).collect::<Vec<_>>();
for (name, date) in [("new.odt", utc), ("new.fodt", utc), ("new.docx", "2026-11-16T16:33:24Z"), ("new.xml", "2026-11-16T16:33:24Z")] {
let opened = crate::io::open_bytes(name, &crate::io::save_bytes(name, &s.doc).unwrap()).unwrap();
assert_eq!(dates(&opened), [date], "{name}");
assert!(opened.revisions.iter().all(|r| r.instant() == utc), "{name}: {:?}", opened.revisions);
}
}
/// A tracked change read from a file keeps its `w:date` and `w16du:dateUtc` as read through open
/// and save in another zone (#6851): one without a UTC time (an older Word, another program), whose
/// zone WordCraft doesn't guess, and one written in UTC, where the two are the same.
#[test]
fn a_file_date_is_written_as_read() {
use crate::cmd::TEST_ZONE;
struct Reset;
impl Drop for Reset {
fn drop(&mut self) {
TEST_ZONE.with(|z| z.set(None));
}
}
let _reset = Reset;
TEST_ZONE.with(|z| z.set(Some(|_| 8 * 3600)));
let date = "2026-11-16T08:33:24Z";
for utc in [None, Some(date)] {
let mut doc = Document::from_text("Draft.");
let mut rev = wordcraft_doc::Revision::new(wordcraft_doc::RevisionKind::Insert, "Ada", date);
rev.date_utc = utc.map(String::from);
doc.revisions.push(rev);
doc.para_mut(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().mark.ins = Some(0);
let dates = |d: &Document| d.revisions.iter().map(|r| (r.date.clone(), r.date_utc.clone())).collect::<Vec<_>>();
let want = vec![(date.to_string(), utc.map(String::from))];
for name in ["file.docx", "file.xml"] {
let bytes = crate::io::save_bytes(name, &doc).unwrap();
let opened = crate::io::open_bytes(name, &bytes).unwrap();
assert_eq!(dates(&opened), want, "{name} {utc:?}: opened");
let saved = crate::io::save_bytes(name, &opened).unwrap();
let again = if name.ends_with(".xml") { wordcraft_docx::read_xml(&saved) } else { wordcraft_docx::read(&saved) }.unwrap();
assert_eq!(dates(&again), want, "{name} {utc:?}: saved again");
}
}
}
/// Accept and Move to Next, Reject and Move to Next: the change at the caret is resolved and
/// the next one is selected; without `next` the caret stays where the change was.
#[test]
@@ -925,77 +796,6 @@ fn deleting_a_comment_in_a_parent_cycle_ends() {
assert!(s.doc.comments.is_empty());
}
/// Comments on "one", "two" and "three" with a reply on the first; the ids, in that order.
fn three_commented_words(s: &mut Session) -> [u64; 4] {
s.view.proofing = false;
s.run("document.setText", &json!({"text": "one two three"})).unwrap();
let on = |s: &mut Session, word: &str| {
s.run("select.text", &json!({"text": word})).unwrap();
s.run("review.newComment", &json!({"text": word})).unwrap()["id"].as_u64().unwrap()
};
let (one, two, three) = (on(s, "one"), on(s, "two"), on(s, "three"));
let reply = s.run("review.reply", &json!({"id": one, "text": "reply"})).unwrap()["id"].as_u64().unwrap();
[one, reply, two, three]
}
/// #7818: Review › Delete › Delete All Resolved Comments deletes each resolved comment with its
/// replies and their text, and keeps the open ones with their anchors; Undo brings them back.
#[test]
fn delete_all_resolved_comments_keeps_the_open_ones() {
let mut s = Session::new(Document::new());
let [one, reply, two, three] = three_commented_words(&mut s);
for id in [one, three] {
s.run("review.resolveComment", &json!({"id": id, "value": true})).unwrap();
}
let part = |s: &Session, id: u64| s.doc.comments[&(id as u32)].part;
let kept_part = part(&s, two);
let gone_parts: Vec<u32> = [one, reply, three].iter().map(|id| part(&s, *id)).collect();
// The caret sits in the open comment, which Delete alone would take.
s.run("select.text", &json!({"text": "two"})).unwrap();
let depth = s.undo_depth();
let out = s.run("review.deleteComment", &json!({"resolved": true})).unwrap();
let mut deleted: Vec<u64> = out["deleted"].as_array().unwrap().iter().filter_map(|v| v.as_u64()).collect();
let mut want = vec![one, reply, three];
deleted.sort_unstable();
want.sort_unstable();
assert_eq!(deleted, want, "the resolved comments and the reply below one of them");
assert_eq!(s.doc.comments.keys().map(|k| u64::from(*k)).collect::<Vec<_>>(), vec![two], "the open comment stays");
assert!(s.doc.parts.contains_key(&kept_part));
assert!(gone_parts.iter().all(|p| !s.doc.parts.contains_key(p)), "the deleted comments' text parts are gone");
assert_eq!(anchors(&s), vec![(wordcraft_doc::StoryRef::Body, two as u32); 2], "only the open comment's anchors are left");
assert_eq!(s.undo_depth(), depth + 1, "one undo step");
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc.comments.len(), 4);
assert_eq!(anchors(&s).len(), 6);
}
/// #7818: with nothing resolved, Delete All Resolved Comments leaves every comment.
#[test]
fn delete_all_resolved_comments_without_resolved_ones_keeps_all() {
let mut s = Session::new(Document::new());
three_commented_words(&mut s);
let out = s.run("review.deleteComment", &json!({"resolved": true})).unwrap();
assert_eq!(out["deleted"], json!([]));
assert_eq!(s.doc.comments.len(), 4);
assert_eq!(anchors(&s).len(), 6);
}
/// #7818: Review › Delete › Delete All Comments in Document deletes every comment, reply and
/// anchor, resolved or not.
#[test]
fn delete_all_comments_in_document_deletes_every_comment() {
let mut s = Session::new(Document::new());
let [one, ..] = three_commented_words(&mut s);
s.run("review.resolveComment", &json!({"id": one, "value": true})).unwrap();
s.run("review.deleteComment", &json!({"all": true})).unwrap();
assert!(s.doc.comments.is_empty());
assert!(s.doc.parts.is_empty(), "no comment text is left: {:?}", s.doc.parts.keys());
assert!(anchors(&s).is_empty());
}
/// A very long reply chain (as a hostile file could hold) is deleted in one pass over the
/// comments, not one pass per reply: 50,000 replies would otherwise freeze the app.
#[test]
+1 -1
View File
@@ -26,7 +26,7 @@ use clear::{cell_prefix, guard_delete, text_spans};
use convert::{formula, from_text, quick_table, sort_table, to_text};
pub use convert::{text_table_cells, text_table_lines};
use layout::{autofit, borders, fix_caret, properties, set_column_widths};
pub(crate) use layout::{cell_block_borders, sync_cell_widths, text_direction, touch_cells};
pub(crate) use layout::{sync_cell_widths, text_direction, touch_cells};
pub(crate) use select::{extend_selection, grow_select_all, select_cell_first, select_range};
use select::{select_cells, select_column};
pub use structure::split_targets;
-182
View File
@@ -279,185 +279,3 @@ pub(super) fn borders(s: &mut Session, v: &Value) -> CmdResult {
}
})
}
/// Home › Paragraph › Borders with whole cells selected (the table, rows, columns or a block of
/// cells): the border goes on the cells as one block, as in Word, not on the paragraphs in them
/// (#7874). `all` borders every cell, `outside` the block's edges, `inside` the lines between its
/// cells, `none` clears every side, and one side toggles along that edge of the block. Other kinds
/// change nothing.
pub(crate) fn cell_block_borders(s: &mut Session, range: &crate::CellRange, kind: &str, b: Border) -> CmdResult {
let nil = Border { style: BorderStyle::None, width: 0.0, color: None, space: 0.0 };
let b = Border { space: 0.0, ..b };
let one_side = ["top", "left", "bottom", "right"].iter().position(|k| *k == kind);
if one_side.is_none() && !matches!(kind, "all" | "none" | "outside" | "inside") {
return sel_result(s);
}
let t = s.doc.table(range.story, &range.table).ok_or_else(|| CmdError::Disabled("the selection isn't in a table".into()))?;
let (g0, g1) = range.cols;
let picked = with_merge_runs(t, range.cells(t));
// The selected cells' grid columns, row by row from the block's first row.
let r0 = picked.iter().map(|&(r, _)| r).min().unwrap_or(range.rows.0);
let mut spans: Vec<Vec<(usize, usize)>> = Vec::new();
for &(r, c) in &picked {
let i = r.saturating_sub(r0);
if spans.len() <= i {
spans.resize_with(i + 1, Vec::new);
}
spans[i].push(super::grid_cols(t, r, c));
}
// Whether a selected cell in row `r` covers any of grid columns `a..=z`.
let picked_in = |r: Option<usize>, (a, z): (usize, usize)| {
r.and_then(|r| r.checked_sub(r0)).and_then(|i| spans.get(i)).is_some_and(|row| row.iter().any(|&(sa, sz)| sa <= z && sz >= a))
};
// Each selected cell, and which of its sides (top, left, bottom, right) are on the block's edge:
// above and below, where no selected cell lies across that side (a row that skips the selected
// grid columns with `w:gridBefore` leaves a gap in the block). A row's first and last cells are
// on it too when the row skips grid columns (`w:gridBefore`, `w:gridAfter`): the layout draws
// those as the table's outer edge.
let cells: Vec<(usize, usize, [bool; 4])> = picked
.iter()
.map(|&(r, c)| {
let (a, z) = super::grid_cols(t, r, c);
let last = t.rows.get(r).map_or(0, |row| row.cells.len().saturating_sub(1));
(r, c, [!picked_in(r.checked_sub(1), (a, z)), a <= g0 || c == 0, !picked_in(Some(r + 1), (a, z)), z >= g1 || c >= last])
})
.collect();
// Whether cell (`r`, `c`) draws a line on side `i`, its own or one the table or its style gives it.
let resolved = wordcraft_layout::CellBorders::new(&s.doc, t);
let draws = |r: usize, c: usize, i: usize| side(&resolved.of(r, c), i).is_some_and(|x| x.is_visible());
// One side is taken off when a line already shows all along that edge, drawn by the cells
// there or by cells beyond them that span the whole side, as the button toggles.
let shown = one_side.is_some_and(|i| {
cells.iter().filter(|(_, _, edge)| edge[i]).all(|&(r, c, _)| {
if draws(r, c, i) {
return true;
}
let across = beside(t, r, c, i, (g0, g1));
if matches!(i, 1 | 3) {
// The cell beside it in the row has the same height.
return !across.is_empty() && across.into_iter().all(|(nr, nc)| draws(nr, nc, (i + 2) % 4));
}
// Above or below: the cells drawing the facing line must cover the side's grid
// columns within the block, so a row that skips columns there leaves it uncovered.
let (a, z) = super::grid_cols(t, r, c);
let drawing = across.into_iter().filter(|&(nr, nc)| draws(nr, nc, (i + 2) % 4)).map(|(nr, nc)| super::grid_cols(t, nr, nc));
covers(drawing.collect(), (a.max(g0), z.min(g1)))
})
});
// The sides to set: (row, cell, side, border).
let mut writes: Vec<(usize, usize, usize, Border)> = Vec::new();
for (r, c, edge) in cells {
for (i, on_edge) in edge.into_iter().enumerate() {
let new = match kind {
"all" => Some(b),
"none" => Some(nil),
"outside" if on_edge => Some(b),
"inside" if !on_edge => Some(b),
_ if one_side == Some(i) && on_edge => Some(if shown { nil } else { b }),
_ => None,
};
let Some(new) = new else { continue };
writes.push((r, c, i, new));
// Each cell draws its own sides, so a line on the block's edge is also the facing
// side of the cell beyond it: that gets the same border, or No Border would leave
// the neighbour's line showing.
if on_edge {
writes.extend(beside(t, r, c, i, (g0, g1)).into_iter().map(|(nr, nc)| (nr, nc, (i + 2) % 4, new)));
}
}
}
let t = s.doc.table_mut(range.story, &range.table)?;
for (r, c, i, new) in writes {
let Some(cl) = t.rows.get_mut(r).and_then(|row| row.cells.get_mut(c)) else { continue };
let mut cur = cl.props.borders.unwrap_or_default();
*side_mut(&mut cur, i) = Some(new);
cl.props.borders = Some(cur);
}
touch_cells(s, &range.table)?;
sel_result(s)
}
/// Whether the grid column spans `parts` (first, last) cover every column of `a..=z`.
fn covers(mut parts: Vec<(usize, usize)>, (a, z): (usize, usize)) -> bool {
parts.sort_unstable();
let mut next = a;
for (pa, pz) in parts {
if pa > next {
break;
}
next = next.max(pz + 1);
}
next > z
}
/// `cells` with the rest of each vertically merged cell's run: the merged cell is one cell over
/// its rows, though selecting it from its first row takes in only that row.
fn with_merge_runs(t: &Table, mut cells: Vec<(usize, usize)>) -> Vec<(usize, usize)> {
// The cell starting at grid column `g` of row `r`, when there is one.
let at = |r: usize, g: usize| t.cell_at_grid(r, g).filter(|&c| t.grid_col(r, c) == g);
let continues =
|r: usize, c: usize| t.rows.get(r).and_then(|row| row.cells.get(c)).is_some_and(|x| x.props.vmerge == wordcraft_doc::props::VMerge::Continue);
let mut seen: std::collections::HashSet<(usize, usize)> = cells.iter().copied().collect();
let mut i = 0;
while let Some(&(r, c)) = cells.get(i) {
i += 1;
let g = t.grid_col(r, c);
let below = at(r + 1, g).filter(|&nc| continues(r + 1, nc)).map(|nc| (r + 1, nc));
let above = r.checked_sub(1).filter(|_| continues(r, c)).and_then(|pr| at(pr, g).map(|pc| (pr, pc)));
for next in [below, above].into_iter().flatten() {
if seen.insert(next) {
cells.push(next);
}
}
}
cells
}
/// The cells across side `i` (top, left, bottom, right) of cell (`r`, `c`) whose facing edge lies
/// wholly on that line. Above and below, only cells within grid columns `cols` (the selected
/// block's), so a wider cell's edge beyond the block keeps its line.
fn beside(t: &Table, r: usize, c: usize, i: usize, (g0, g1): (usize, usize)) -> Vec<(usize, usize)> {
let Some(row) = t.rows.get(r) else { return Vec::new() };
match i {
1 => c.checked_sub(1).map(|p| vec![(r, p)]).unwrap_or_default(),
3 => {
if c + 1 < row.cells.len() {
vec![(r, c + 1)]
} else {
Vec::new()
}
}
_ => {
let nr = if i == 0 { r.checked_sub(1) } else { Some(r + 1) };
let Some((nr, next)) = nr.and_then(|nr| t.rows.get(nr).map(|x| (nr, x))) else { return Vec::new() };
let (a, z) = super::grid_cols(t, r, c);
(0..next.cells.len())
.filter(|&nc| {
let (na, nz) = super::grid_cols(t, nr, nc);
na <= z && nz >= a && na >= g0 && nz <= g1
})
.map(|nc| (nr, nc))
.collect()
}
}
}
/// Side `i` of `b`: top, left, bottom, right.
fn side(b: &Borders, i: usize) -> Option<Border> {
match i {
0 => b.top,
1 => b.left,
2 => b.bottom,
_ => b.right,
}
}
/// Side `i` of `b` to set: top, left, bottom, right.
fn side_mut(b: &mut Borders, i: usize) -> &mut Option<Border> {
match i {
0 => &mut b.top,
1 => &mut b.left,
2 => &mut b.bottom,
_ => &mut b.right,
}
}
+4 -4
View File
@@ -116,9 +116,9 @@ pub(super) fn compare(s: &mut Session, v: &Value) -> CmdResult {
}
std::mem::take(&mut revised.body)
};
s.doc.revisions.push(crate::cmd::made_revision(RevisionKind::Insert, author.clone(), date.clone()));
s.doc.revisions.push(wordcraft_doc::Revision { kind: RevisionKind::Insert, author: author.clone(), date: date.clone(), move_name: None });
let ins = (s.doc.revisions.len() - 1) as u32;
s.doc.revisions.push(crate::cmd::made_revision(RevisionKind::Delete, author.clone(), date.clone()));
s.doc.revisions.push(wordcraft_doc::Revision { kind: RevisionKind::Delete, author: author.clone(), date: date.clone(), move_name: None });
let del = (s.doc.revisions.len() - 1) as u32;
let mut char_fallbacks = 0usize;
let mut table_fallbacks = 0usize;
@@ -1437,10 +1437,10 @@ fn diff_table(
/// Find or create the formatting revision entry for `author` and `date`.
fn format_revision(doc: &mut Document, author: &str, date: &str) -> u32 {
if let Some(i) = doc.revisions.iter().rposition(|r| r.kind == RevisionKind::Format && r.author == author && r.instant() == date) {
if let Some(i) = doc.revisions.iter().rposition(|r| r.kind == RevisionKind::Format && r.author == author && r.date == date) {
return u32::try_from(i).unwrap_or(u32::MAX);
}
doc.revisions.push(crate::cmd::made_revision(RevisionKind::Format, author.to_string(), date.to_string()));
doc.revisions.push(wordcraft_doc::Revision { kind: RevisionKind::Format, author: author.to_string(), date: date.to_string(), move_name: None });
u32::try_from(doc.revisions.len().saturating_sub(1)).unwrap_or(u32::MAX)
}
-1
View File
@@ -2775,7 +2775,6 @@ fn compare_strips_source_revisions_from_adopted_notes() {
author: "Other".into(),
date: "2026-01-01T00:00:00Z".into(),
move_name: None,
date_utc: None,
});
for part in rev.doc.parts.values_mut() {
if part.kind == wordcraft_doc::PartKind::Footnote
+1 -46
View File
@@ -98,15 +98,6 @@ pub fn save(ext: &str, doc: &Document, opts: &crate::io::ExportOptions) -> Optio
}
}
/// A UTC date and time (a `Z` or an offset) as Word writes `w:date`: the wall-clock time in the
/// zone `zone` gives for an instant (seconds east of UTC), with a `Z` Word writes but doesn't
/// mean. Word read the UTC dates WordCraft wrote as local time, shifted by the user's offset from
/// UTC (#6851). None for anything else (no zone or no time of day, before 1970, unreadable).
pub(crate) fn word_date(date: &str, zone: impl Fn(u64) -> i64) -> Option<String> {
let utc = u64::try_from(chrono::DateTime::parse_from_rfc3339(date.trim()).ok()?.timestamp()).ok()?;
Some(crate::cmd::iso_from_unix_secs(utc.checked_add_signed(zone(utc))?))
}
/// How a page image is drawn: the printed page, headers and footers at full strength, tracked
/// changes marked as Track Changes Options mark them. One place for `file.exportPng`,
/// `file.strictReport`'s page check and a downloaded page image.
@@ -143,45 +134,9 @@ pub fn render_png(doc: &Document, page: usize, scale: f32, opts: &crate::io::Exp
}
#[cfg(test)]
pub(crate) mod tests {
mod tests {
use super::*;
/// New York in 2026: daylight saving time from 8 March 07:00 UTC to 1 November 06:00 UTC.
pub(crate) fn new_york(t: u64) -> i64 {
if (1_772_953_200..1_793_512_800).contains(&t) { -4 * 3600 } else { -5 * 3600 }
}
/// Word dates `w:date` in local wall-clock time with a `Z`; the change keeps UTC (#6851).
#[test]
fn word_dates_tracked_changes_in_local_time() {
let plus8 = |_| 8 * 3600;
// The issue's edit: 08:33:24 UTC at UTC+8, which Word showed as 8:33 AM.
assert_eq!(word_date("2026-11-16T08:33:24Z", plus8).as_deref(), Some("2026-11-16T16:33:24Z"));
// A date naming its offset is that instant, whatever the zone.
assert_eq!(word_date("2026-11-16T16:33:24+08:00", plus8).as_deref(), Some("2026-11-16T16:33:24Z"));
// West of UTC, the date can go back a day.
assert_eq!(word_date("2026-01-01T03:00:00Z", new_york).as_deref(), Some("2025-12-31T22:00:00Z"));
// The repeated hour: 05:30 and 06:30 UTC are both 01:30 in New York; `dateUtc` keeps them
// apart. Either side of a change of offset takes the offset at that instant.
assert_eq!(word_date("2026-11-01T05:30:00Z", new_york).as_deref(), Some("2026-11-01T01:30:00Z"));
assert_eq!(word_date("2026-11-01T06:30:00Z", new_york).as_deref(), Some("2026-11-01T01:30:00Z"));
assert_eq!(word_date("2026-11-01T04:30:00Z", new_york).as_deref(), Some("2026-11-01T00:30:00Z"));
assert_eq!(word_date("2026-11-01T07:30:00Z", new_york).as_deref(), Some("2026-11-01T02:30:00Z"));
assert_eq!(word_date("2026-03-08T06:30:00Z", new_york).as_deref(), Some("2026-03-08T01:30:00Z"));
assert_eq!(word_date("2026-03-08T07:30:00Z", new_york).as_deref(), Some("2026-03-08T03:30:00Z"));
// Anything else is left as it is: no zone, no time of day, before 1970, not a date.
for date in ["", "2026-11-16T08:33:24", "2026-11-16", "1969-12-31T23:00:00Z", "yesterday", "2026-13-01T00:00:00Z"] {
assert_eq!(word_date(date, plus8), None, "{date:?}");
}
// A hostile zone or a far date doesn't overflow.
for zone in [i64::MAX, i64::MIN] {
let _ = word_date("2026-11-16T08:33:24Z", |_| zone);
}
assert!(word_date("9999-12-31T23:59:59Z", plus8).is_some());
}
/// A page image is the printed page: headers and footers draw at full strength (#6267).
#[test]
fn a_page_image_draws_headers_at_full_strength() {
+1 -62
View File
@@ -17,7 +17,6 @@ mod find_apostrophes;
mod fit_one_page;
mod font_sizes;
mod fonts;
mod home_borders_cells;
mod ime_noop;
mod page_number_formats_in_lists;
mod para_tools;
@@ -15447,7 +15446,7 @@ fn sectioned_revision(delete: bool) -> Session {
run(&mut s, "caret.set", json!({"pos": {"block": 2, "off": 0}}));
run(&mut s, "para.style", json!({"style": "Heading1"}));
let kind = if delete { RevisionKind::Delete } else { RevisionKind::Insert };
s.doc.revisions.push(Revision { kind, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
s.doc.revisions.push(Revision { kind, author: "Ada".into(), date: String::new(), move_name: None });
s.doc.last_section.margin_left = 72.0;
let mut sect = s.doc.last_section.clone();
sect.margin_left = 144.0;
@@ -15652,63 +15651,3 @@ fn a_range_paste_formatting_keeps_the_targets_link_and_tracked_marks() {
assert!(c.ins.is_some(), "Paste Formatting kept the insertion mark");
assert_eq!(c.bold, Some(true));
}
/// #8068: A text box reachable only inside nested shape groups survives mutating Session commands
/// (which call `prune_text_boxes`) and copy/paste adoption, while an unreachable box is pruned.
#[test]
fn nested_group_text_box_survives_mutating_session_commands() {
use wordcraft_doc::para::{GroupChild, InlineObject, ShapeKind};
use wordcraft_doc::{CharProps, Document, Paragraph, PartKind, Path, para_block};
let mut d = Document::from_text("body");
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
let nested_tb = d.add_part(PartKind::TextBox, para_of("nested group box"));
let orphan_tb = d.add_part(PartKind::TextBox, para_of("orphan box"));
let shape = InlineObject::Shape {
kind: ShapeKind::TextBox,
w: 50.0,
h: 20.0,
fill: None,
stroke: None,
stroke_width: 0.0,
float: Default::default(),
story: Some(nested_tb),
freeform: None,
effects: Default::default(),
extra: Default::default(),
};
let group = |obj: InlineObject| InlineObject::Group {
w: 100.0,
h: 100.0,
float: Default::default(),
ch_w: 100.0,
ch_h: 100.0,
children: vec![GroupChild { x: 0.0, y: 0.0, obj }],
canvas: None,
};
d.insert_object(&Pos::body(0, 0), group(group(shape)), &CharProps::default()).unwrap();
let mut s = Session::new(d);
run(&mut s, "caret.docEnd", json!({}));
run(&mut s, "text.insert", json!({"text": " edited"}));
assert!(s.doc.parts.contains_key(&nested_tb), "nested group text box must survive prune");
assert!(!s.doc.parts.contains_key(&orphan_tb), "unreachable text box must still be pruned");
assert_eq!(s.doc.plain_text(StoryRef::Part(nested_tb)), "nested group box");
let objs = &s.doc.para(StoryRef::Body, &Path::top(0)).unwrap().objects;
assert_eq!(objs.len(), 1);
assert_eq!(objs[0].text_boxes(), vec![nested_tb]);
// Copy/paste adopts the nested-group text box into a fresh story via text_box_slots() and survives prune.
run(&mut s, "select.all", json!({}));
run(&mut s, "edit.copy", json!({}));
run(&mut s, "caret.docEnd", json!({}));
run(&mut s, "edit.paste", json!({}));
let ids: Vec<u32> = s.doc.para(StoryRef::Body, &Path::top(0)).unwrap().objects.iter().flat_map(InlineObject::text_boxes).collect();
assert_eq!(ids.len(), 2, "original and pasted nested groups each hold a text box");
assert_ne!(ids[0], ids[1], "pasted nested group box gets its own story id");
for id in ids {
assert_eq!(s.doc.plain_text(StoryRef::Part(id)), "nested group box");
}
}
@@ -1,259 +0,0 @@
//! #7874: Home › Paragraph › Borders with whole table cells selected borders the cells as a
//! block, as Word does, instead of each paragraph in them.
use std::sync::Arc;
use serde_json::json;
use wordcraft_doc::props::{Border, Borders};
use wordcraft_doc::{Block, Cell, Document, Paragraph, Path, Pos, StoryRef, Table, para_block};
use crate::{Selection, Session};
/// A document of a 3 x 3 table with text in every cell, the caret in the first cell.
fn doc() -> Session {
let mut t = Table::new(3, 3, 300.0);
for (r, row) in t.rows.iter_mut().enumerate() {
for (c, cell) in row.cells.iter_mut().enumerate() {
cell.blocks = Cell::with_text(&format!("c{r}{c}")).blocks;
}
}
let mut d = Document::new();
d.body = vec![Arc::new(Block::Table(t)), para_block(Paragraph::new())];
let mut s = Session::new(d);
s.sel = Selection::caret(Pos::new(StoryRef::Body, Path(vec![0, 0, 0, 0]), 0));
s
}
fn table(s: &Session) -> &Table {
s.doc.body.iter().find_map(|b| b.as_table()).unwrap()
}
fn cell_borders(s: &Session, r: usize, c: usize) -> Borders {
table(s).rows[r].cells[c].props.borders.unwrap_or_default()
}
/// Which sides of cell (`r`, `c`) the layout draws a line on, the table style's lines included:
/// top, left, bottom, right.
fn drawn(s: &Session, r: usize, c: usize) -> [bool; 4] {
let b = wordcraft_layout::cell_borders(&s.doc, table(s), r, c);
[b.top, b.left, b.bottom, b.right].map(|x| x.is_some_and(|x| x.is_visible()))
}
/// Which sides of cell (`r`, `c`) show a line: top, left, bottom, right.
fn shown(s: &Session, r: usize, c: usize) -> [bool; 4] {
let b = cell_borders(s, r, c);
[b.top, b.left, b.bottom, b.right].map(|x| x.is_some_and(|x| x.is_visible()))
}
/// Whether any paragraph in the table has borders of its own.
fn para_borders(s: &Session) -> bool {
table(s).rows.iter().flat_map(|r| &r.cells).flat_map(|c| &c.blocks).filter_map(|b| b.as_para()).any(|p| p.props.borders.is_some())
}
fn borders(s: &mut Session, kind: &str) {
s.run("para.borders", &json!({"kind": kind})).unwrap();
}
/// Select whole cells: rows `rows` and grid columns `cols` of the table.
fn select(s: &mut Session, rows: (usize, usize), cols: (usize, usize)) {
crate::cmd::table::select_range(s, StoryRef::Body, &Path(vec![0]), rows, cols).unwrap();
}
#[test]
fn all_borders_on_a_selected_table_borders_every_cell() {
let mut s = doc();
s.run("table.selectTable", &json!({})).unwrap();
borders(&mut s, "all");
for r in 0..3 {
for c in 0..3 {
assert_eq!(shown(&s, r, c), [true; 4], "cell ({r}, {c}) has a line on every side");
}
}
assert!(!para_borders(&s), "the paragraphs in the cells get no borders of their own");
// The line is the one asked for, with no paragraph spacing.
let top = cell_borders(&s, 1, 1).top.unwrap();
assert_eq!((top.width, top.space), (0.5, 0.0));
}
#[test]
fn outside_and_inside_borders_follow_the_selected_block() {
let mut s = doc();
// The top-left 2 x 2 cells.
select(&mut s, (0, 1), (0, 1));
borders(&mut s, "outside");
assert_eq!(shown(&s, 0, 0), [true, true, false, false]);
assert_eq!(shown(&s, 0, 1), [true, false, false, true]);
assert_eq!(shown(&s, 1, 0), [false, true, true, false]);
assert_eq!(shown(&s, 1, 1), [false, false, true, true]);
assert_eq!(table(&s).rows[2].cells[2].props.borders, None, "a cell outside the selection is left alone");
// The cells beyond the block share its edge lines: their facing sides get the same line.
assert_eq!(shown(&s, 0, 2), [false, true, false, false]);
assert_eq!(shown(&s, 2, 0), [true, false, false, false]);
borders(&mut s, "inside");
assert_eq!(shown(&s, 0, 0), [true; 4]);
assert_eq!(shown(&s, 1, 1), [true; 4]);
assert_eq!(shown(&s, 0, 2), [false, true, false, false], "Inside leaves the cells beyond the block alone");
assert!(!para_borders(&s));
}
#[test]
fn no_border_on_a_row_clears_the_lines_it_shares_with_the_rows_around_it() {
let mut s = doc();
s.run("table.selectTable", &json!({})).unwrap();
borders(&mut s, "all");
select(&mut s, (1, 1), (0, 2));
borders(&mut s, "none");
for c in 0..3 {
// Each cell draws its own sides, so the rows above and below must not keep the lines.
assert_eq!(shown(&s, 0, c), [true, true, false, true], "the row above keeps its other lines, cell (0, {c})");
assert_eq!(shown(&s, 1, c), [false; 4], "cell (1, {c})");
assert_eq!(shown(&s, 2, c), [false, true, true, true], "the row below keeps its other lines, cell (2, {c})");
}
}
#[test]
fn a_row_that_skips_grid_columns_has_its_first_cell_on_the_outside() {
let mut s = doc();
// The middle row starts at grid column 1 (`w:gridBefore`): two cells.
let tb = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
tb.rows[1].cells.remove(0);
tb.rows[1].props.grid_before = 1;
s.run("table.selectTable", &json!({})).unwrap();
borders(&mut s, "none");
borders(&mut s, "outside");
assert_eq!(shown(&s, 1, 0), [false, true, false, false], "the row's first cell is on the table's left edge");
assert_eq!(shown(&s, 1, 1), [false, false, false, true]);
borders(&mut s, "none");
borders(&mut s, "inside");
assert_eq!(shown(&s, 1, 0), [true, false, true, true], "Inside leaves the row's outer edge without a line");
}
#[test]
fn one_side_toggles_along_the_block_edge_and_no_border_clears_the_cells() {
let mut s = doc();
// The middle row, with no line on it or around it.
select(&mut s, (1, 1), (0, 2));
borders(&mut s, "none");
borders(&mut s, "bottom");
for c in 0..3 {
assert_eq!(shown(&s, 1, c), [false, false, true, false], "cell (1, {c})");
}
borders(&mut s, "bottom");
for c in 0..3 {
assert_eq!(shown(&s, 1, c), [false; 4], "the second press takes the bottom line off cell (1, {c})");
}
borders(&mut s, "all");
borders(&mut s, "none");
let nil = |x: Option<Border>| x.is_some_and(|x| !x.is_visible());
for c in 0..3 {
let b = cell_borders(&s, 1, c);
assert!(
nil(b.top) && nil(b.left) && nil(b.bottom) && nil(b.right),
"No Border writes no line on every side of cell (1, {c}), over the table's own borders"
);
}
}
#[test]
fn a_caret_in_a_cell_still_borders_its_paragraph() {
let mut s = doc();
borders(&mut s, "all");
assert!(para_borders(&s), "without whole cells selected, the paragraph is bordered as before");
assert_eq!(table(&s).rows[0].cells[0].props.borders, None);
}
/// A line the table's style draws counts as shown: the first press of one side takes it off,
/// from the cells along the edge and the ones beyond it, and the second puts it back.
#[test]
fn one_side_takes_off_a_line_the_table_style_draws() {
let mut s = doc();
assert!(table(&s).rows[1].cells.iter().all(|c| c.props.borders.is_none()), "no cell has borders of its own");
assert!((0..3).all(|c| drawn(&s, 1, c)[2]), "Table Grid draws the middle row's bottom line");
select(&mut s, (1, 1), (0, 2));
borders(&mut s, "bottom");
for c in 0..3 {
assert!(!drawn(&s, 1, c)[2] && !drawn(&s, 2, c)[0], "the first press takes the line off cell (1, {c})");
assert!(drawn(&s, 1, c)[0], "the other sides keep the style's lines, cell (1, {c})");
}
borders(&mut s, "bottom");
assert!((0..3).all(|c| drawn(&s, 1, c)[2]), "the second press puts it back");
}
/// A column whose middle row skips it (`w:gridBefore`) is two blocks of cells: the cells above
/// and below the gap face it with an outer edge, not an inside one.
#[test]
fn a_column_with_a_skipped_middle_cell_has_outer_edges_at_the_gap() {
let mut s = doc();
let tb = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
tb.rows[1].cells.remove(0);
tb.rows[1].props.grid_before = 1;
s.run("table.selectTable", &json!({})).unwrap();
borders(&mut s, "none");
// The first grid column: cells (0, 0) and (2, 0); the middle row has no cell there.
select(&mut s, (0, 2), (0, 0));
borders(&mut s, "outside");
assert_eq!(shown(&s, 0, 0), [true; 4], "Outside draws the bottom of the cell above the gap");
assert_eq!(shown(&s, 2, 0), [true; 4], "and the top of the cell below it");
borders(&mut s, "none");
borders(&mut s, "inside");
assert_eq!(shown(&s, 0, 0), [false; 4], "Inside has no line between cells that don't meet");
assert_eq!(shown(&s, 2, 0), [false; 4]);
}
/// A line drawn along only part of an edge isn't shown along it: the press completes it. Here
/// the selected cell spans the three cells below it, and only the first of them draws its top.
#[test]
fn one_side_completes_a_line_drawn_along_part_of_the_edge() {
let mut s = doc();
let nil = Border { style: wordcraft_doc::props::BorderStyle::None, width: 0.0, color: None, space: 0.0 };
let line = Border { style: wordcraft_doc::props::BorderStyle::Single, width: 0.5, color: None, space: 0.0 };
let tb = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
tb.rows[0].cells.truncate(1);
tb.rows[0].cells[0].props.span = 3;
tb.rows[0].cells[0].props.borders = Some(Borders { bottom: Some(nil), ..Default::default() });
for (c, cell) in tb.rows[1].cells.iter_mut().enumerate() {
cell.props.borders = Some(Borders { top: Some(if c == 0 { line } else { nil }), ..Default::default() });
}
select(&mut s, (0, 0), (0, 2));
borders(&mut s, "bottom");
assert!(drawn(&s, 0, 0)[2], "the line goes all along the selected cell's bottom");
assert!((0..3).all(|c| drawn(&s, 1, c)[0]), "and along the tops of the cells below");
}
/// A cell merged over two rows is one cell: selected from its first row, No Border clears its
/// outline in the second row too.
#[test]
fn no_border_clears_all_of_a_vertically_merged_cell() {
use wordcraft_doc::props::VMerge;
let mut s = doc();
let tb = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
tb.rows[0].cells[1].props.vmerge = VMerge::Restart;
tb.rows[1].cells[1].props.vmerge = VMerge::Continue;
s.run("table.selectTable", &json!({})).unwrap();
borders(&mut s, "all");
// The merged cell, as selecting it from its first row selects it.
select(&mut s, (0, 0), (1, 1));
borders(&mut s, "none");
assert_eq!(shown(&s, 0, 1), [false; 4]);
assert_eq!(shown(&s, 1, 1), [false; 4], "the merged cell's second row keeps no line");
assert!(shown(&s, 1, 0)[1] && shown(&s, 2, 1)[2], "the cells around it keep their other lines");
}
/// The cells below draw a line along only part of the edge when their row skips the rest of its
/// columns (`w:gridAfter`): the press completes it.
#[test]
fn one_side_completes_a_line_over_a_row_that_skips_columns() {
let mut s = doc();
let nil = Border { style: wordcraft_doc::props::BorderStyle::None, width: 0.0, color: None, space: 0.0 };
let line = Border { style: wordcraft_doc::props::BorderStyle::Single, width: 0.5, color: None, space: 0.0 };
let tb = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
tb.rows[0].cells.truncate(1);
tb.rows[0].cells[0].props.span = 3;
tb.rows[0].cells[0].props.borders = Some(Borders { bottom: Some(nil), ..Default::default() });
tb.rows[1].cells.truncate(1);
tb.rows[1].props.grid_after = 2;
tb.rows[1].cells[0].props.borders = Some(Borders { top: Some(line), ..Default::default() });
select(&mut s, (0, 0), (0, 2));
borders(&mut s, "bottom");
assert!(drawn(&s, 0, 0)[2], "the selected cell's bottom gets the line all along it");
}
@@ -429,7 +429,6 @@ fn tracked_separator_session(slot: Slot) -> Session {
author: "Alice".into(),
date: String::new(),
move_name: None,
date_utc: None,
});
let props = wordcraft_doc::CharProps { ins: Some(0), ..Default::default() };
let p = wordcraft_doc::Paragraph::with_text("SEP", props);
+6 -16
View File
@@ -30,27 +30,17 @@ pub fn import_flat_on(bytes: &[u8], page: &SectionProps) -> Result<Document, Str
wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())
}
/// The shared model an OpenDocument file is written from. ODF's `dc:date` is an instant (a `Z`
/// means UTC), so a tracked change is dated by its UTC time where it is known: its `date` is the
/// local wall-clock time Word writes in `w:date` (#6851).
fn odf_model(doc: &Document) -> Result<craft_wordmodel::Document, String> {
let mut shared = wordcraft_docx::to_shared_model(doc).map_err(|e| e.to_string())?;
for r in &mut shared.revisions {
if let Some(utc) = &r.date_utc {
r.date = utc.clone();
}
}
Ok(shared)
}
pub fn export(doc: &Document) -> Result<Vec<u8>, String> {
craft_odf::text::export(&odf_model(doc)?)
let shared = wordcraft_docx::to_shared_model(doc).map_err(|e| e.to_string())?;
craft_odf::text::export(&shared)
}
pub fn export_template(doc: &Document) -> Result<Vec<u8>, String> {
craft_odf::text::export_template(&odf_model(doc)?)
let shared = wordcraft_docx::to_shared_model(doc).map_err(|e| e.to_string())?;
craft_odf::text::export_template(&shared)
}
pub fn export_flat(doc: &Document) -> Result<Vec<u8>, String> {
craft_odf::text::export_flat(&odf_model(doc)?)
let shared = wordcraft_docx::to_shared_model(doc).map_err(|e| e.to_string())?;
craft_odf::text::export_flat(&shared)
}
+1 -1
View File
@@ -51,7 +51,7 @@ pub use fields::FieldCtx;
pub use hit::VisualStep;
pub use missing::{MetafileTextLayout, layout_metafile_text};
pub use para::{LineEnd, ParaLayout};
pub use table::{CellBorders, autofit_widths, cell_borders, cell_margins, measure_table_columns};
pub use table::{autofit_widths, cell_margins, measure_table_columns};
mod boxes;
mod cache;
+39 -92
View File
@@ -350,95 +350,6 @@ fn region_borders(parts: &[(TablePart, Borders)], rows: (usize, usize), edges: (
wordcraft_doc::styles::part_borders(parts, rows, edges)
}
/// The table's outer and inside borders: the style's, overlaid by the table's own side by side.
fn table_borders(t: &Table, style: Option<&TableStyleProps>) -> Borders {
let mut tborders = style.and_then(|s| s.parts.borders).unwrap_or_default();
if let Some(own) = t.props.borders {
tborders.overlay(&own);
}
tborders
}
/// The borders the layout draws for cell `ci` of row `ri`, before a right-to-left table mirrors
/// them: the cell's own, then its row's table property exceptions, then the table style's
/// conditional parts it is in, then the table's outer or inside borders. Home › Borders toggles
/// on these, so a line the table style shows counts as shown (#7874). For many cells of one
/// table, [`CellBorders`] resolves the table's part once.
pub fn cell_borders(doc: &wordcraft_doc::Document, t: &Table, ri: usize, ci: usize) -> Borders {
CellBorders::new(doc, t).of(ri, ci)
}
/// [`cell_borders`] for the cells of one table: its style, borders and grid width resolved once.
pub struct CellBorders<'a> {
t: &'a Table,
style: Option<TableStyleProps>,
tborders: Borders,
ncols: usize,
}
impl<'a> CellBorders<'a> {
pub fn new(doc: &wordcraft_doc::Document, t: &'a Table) -> Self {
let style = t.props.style.as_deref().and_then(|id| doc.styles.table_style(id));
let tborders = table_borders(t, style.as_ref());
CellBorders { t, style, tborders, ncols: grid_cols(t).max(1) }
}
/// The borders cell `ci` of row `ri` draws, as [`cell_borders`] gives them.
pub fn of(&self, ri: usize, ci: usize) -> Borders {
let t = self.t;
let Some(cell) = t.rows.get(ri).and_then(|row| row.cells.get(ci)) else { return Borders::default() };
let (g, span) = (t.grid_col(ri, ci), cell.span());
let look = self.style.as_ref().map(|st| region_look(st, region_of(t, Some(st), ri, g, span, self.ncols)));
resolved_cell_borders(t, ri, ci, (g, span, self.ncols), look.as_ref().map(|l| l.borders.as_slice()), self.tborders)
}
}
/// [`cell_borders`] for cell `ci` of row `ri`, which starts at grid column `g` and is `span`
/// columns wide in a table of `ncols`, given its style `parts` and the table borders `tb`.
fn resolved_cell_borders(
t: &Table,
ri: usize,
ci: usize,
(g, span, ncols): (usize, usize, usize),
parts: Option<&[(TablePart, Borders)]>,
tb: Borders,
) -> Borders {
let nrows = t.rows.len();
let Some(row) = t.rows.get(ri) else { return Borders::default() };
// Effective borders: cell > table (outer vs inside).
let edge = |own: Option<Border>, outer: bool, outer_b: Option<Border>, inner_b: Option<Border>| own.or(if outer { outer_b } else { inner_b });
let cb = row.cells.get(ci).and_then(|c| c.props.borders).unwrap_or_default();
// A row's table property exceptions (`w:tblPrEx`) override the table's borders for its cells.
let row_borders = row.props.exceptions.as_ref().and_then(|e| e.borders).unwrap_or_default();
// A row that skips grid columns (`w:gridBefore`/`w:gridAfter`) has its edge at its own
// first and last cell.
let (first_g, last_g) = (g == row.first_grid(), g + span >= ncols.saturating_sub(row.grid_after()));
let rb = parts.map(|p| region_borders(p, (ri, nrows), (first_g, last_g))).unwrap_or_default();
Borders {
top: edge(cb.top.or(if ri == 0 { row_borders.top } else { row_borders.between }).or(rb.top), ri == 0, tb.top, tb.between),
bottom: edge(
cb.bottom.or(if ri + 1 == nrows { row_borders.bottom } else { row_borders.between }).or(rb.bottom),
ri + 1 == nrows,
tb.bottom,
tb.between,
),
left: edge(
cb.left.or(if first_g { row_borders.left } else { row_borders.inside_v }).or(if first_g { rb.left } else { rb.inside_v }),
first_g,
tb.left,
tb.inside_v,
),
right: edge(
cb.right.or(if last_g { row_borders.right } else { row_borders.inside_v }).or(if last_g { rb.right } else { rb.inside_v }),
last_g,
tb.right,
tb.inside_v,
),
between: None,
inside_v: None,
}
}
struct CellBox {
items: Vec<Placed>,
h: f32,
@@ -553,7 +464,11 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
// indent); earlier modes line the first cell's text up with it instead.
let margins_def = default_margins(t, style);
let indent = t.props.indent.unwrap_or(0.0);
let tborders = table_borders(t, style);
// The style's borders, overlaid by the table's own side by side.
let mut tborders = style.and_then(|s| s.parts.borders).unwrap_or_default();
if let Some(own) = t.props.borders {
tborders.overlay(&own);
}
let first_cell = t.rows.first().and_then(|r| r.cells.first());
// A right-to-left table (`w:bidiVisual`) mirrors: its first column stands at the right, its
// start alignment and indent are measured from the right margin, and each cell's start
@@ -649,8 +564,40 @@ pub fn layout_table(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], ava
let mut cpath = path.to_vec();
cpath.push(ri as u32);
cpath.push(ci as u32);
let parts = look.map(|l| l.borders.as_slice());
let mut borders = resolved_cell_borders(t, ri, ci, (g, span, ncols), parts, tborders);
// Effective borders: cell > table (outer vs inside).
let tb = tborders;
let edge =
|own: Option<Border>, outer: bool, outer_b: Option<Border>, inner_b: Option<Border>| own.or(if outer { outer_b } else { inner_b });
let cb = cell.props.borders.unwrap_or_default();
// A row's table property exceptions (`w:tblPrEx`) override the table's borders for its cells.
let row_borders = row.props.exceptions.as_ref().and_then(|e| e.borders).unwrap_or_default();
// A row that skips grid columns (`w:gridBefore`/`w:gridAfter`) has its edge at its own
// first and last cell.
let (first_g, last_g) = (g == row.first_grid(), g + span >= ncols.saturating_sub(row.grid_after()));
let rb = look.map(|l| region_borders(&l.borders, (ri, nrows), (first_g, last_g))).unwrap_or_default();
let mut borders = Borders {
top: edge(cb.top.or(if ri == 0 { row_borders.top } else { row_borders.between }).or(rb.top), ri == 0, tb.top, tb.between),
bottom: edge(
cb.bottom.or(if ri + 1 == nrows { row_borders.bottom } else { row_borders.between }).or(rb.bottom),
ri + 1 == nrows,
tb.bottom,
tb.between,
),
left: edge(
cb.left.or(if first_g { row_borders.left } else { row_borders.inside_v }).or(if first_g { rb.left } else { rb.inside_v }),
first_g,
tb.left,
tb.inside_v,
),
right: edge(
cb.right.or(if last_g { row_borders.right } else { row_borders.inside_v }).or(if last_g { rb.right } else { rb.inside_v }),
last_g,
tb.right,
tb.inside_v,
),
between: None,
inside_v: None,
};
// The logical start (left) and end (right) borders, drawn mirrored in an RTL table.
if rtl {
std::mem::swap(&mut borders.left, &mut borders.right);
-2
View File
@@ -2129,7 +2129,6 @@ fn a_deleted_list_items_number_is_drawn_as_deleted_text() {
author: "Ana".into(),
date: String::new(),
move_name: None,
date_utc: 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();
@@ -3956,7 +3955,6 @@ fn a_tracked_paragraph_mark_shows_in_its_authors_colour() {
author: "Ana".into(),
date: String::new(),
move_name: None,
date_utc: None,
});
d.para_mut(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().mark.ins = Some(0);
let l = lay(&d);
+1 -1
View File
@@ -426,7 +426,7 @@ mod tests {
use wordcraft_doc::props::TextDirection;
use wordcraft_doc::{CharProps, Document, Paragraph, Revision, RevisionKind, para_block};
let mut d = Document::new();
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None });
let cp = CharProps { outline: Some(true), size: Some(20.0), ins: Some(0), ..Default::default() };
d.body = vec![para_block(Paragraph::with_text("Inserted", cp))];
let mut opts = DisplayOptions { markup: true, ..Default::default() };
+7 -7
View File
@@ -337,8 +337,8 @@ fn hostile_documents_export() {
fn tracked_deletions_are_left_out_without_markup() {
use wordcraft_doc::{Revision, RevisionKind};
let mut d = Document::new();
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Ada".into(), date: String::new(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None });
let mut p = Paragraph::with_text("Keep ", CharProps::default());
let n = p.len();
p.insert_text(n, "DELETEDTEXT ", &CharProps { del: Some(0), ..Default::default() }).unwrap();
@@ -360,8 +360,8 @@ fn markup_takes_the_track_changes_option_colours() {
use wordcraft_doc::props::Rgb;
use wordcraft_doc::{Revision, RevisionKind};
let mut d = Document::new();
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Ada".into(), date: String::new(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None });
let mut p = Paragraph::with_text("Keep ", CharProps::default());
let n = p.len();
p.insert_text(n, "Kansas ", &CharProps { del: Some(0), ..Default::default() }).unwrap();
@@ -411,8 +411,8 @@ fn markup_takes_the_track_changes_option_colours() {
fn hidden_deletions_stay_out_of_markup_pdf() {
use wordcraft_doc::{Revision, RevisionKind};
let mut d = Document::new();
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Ada".into(), date: String::new(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None });
let mut p = Paragraph::with_text("Keep ", CharProps::default());
let n = p.len();
p.insert_text(n, "Kansas ", &CharProps { del: Some(0), ..Default::default() }).unwrap();
@@ -440,7 +440,7 @@ fn hidden_deletions_stay_out_of_markup_pdf() {
fn deleted_heading_text_stays_out_of_bookmarks_and_tags() {
use wordcraft_doc::{Revision, RevisionKind};
let mut d = Document::new();
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Ada".into(), date: String::new(), move_name: None });
let del = CharProps { del: Some(0), ..Default::default() };
// "Intro SECRET Part" with "SECRET " deleted, then a heading deleted as a whole.
let mut h = Paragraph::with_text("Intro ", CharProps::default()).styled("Heading1");
-2
View File
@@ -10,7 +10,6 @@ use craft::ui::menu::search::{HelpEntry, SearchIndex, SearchWords, Synonyms};
use craft::ui::patterns::panels::{CommandPalette, PaletteFace};
use craft::ui::runtime::env::{Env, EnvView, Label, WordTemplate};
use craft::ui::runtime::inspect;
use craft::ui::style::FieldLook;
use egui::Ui;
use serde_json::json;
@@ -102,7 +101,6 @@ pub(super) fn show(app: &mut WordApp, ui: &mut Ui, compact: bool) -> egui::Rect
let cache = SearchCache::for_pass(kept, commands, &view);
let out = CommandPalette::new(name.clone(), &cache.entries, &cache.index, Bind::bound(&mut open))
.face(if compact { PaletteFace::Dialog } else { PaletteFace::InPlace })
.look(FieldLook::Quiet)
.placeholder(Label::from(name.clone()))
.suggested((Label::from(tl!("Suggested").to_string()), suggested))
.fallback(WordTemplate::new(tl!("Find “{text}” in the document")))
+8 -10
View File
@@ -13,7 +13,7 @@ use craft::ui::runtime::env::{Env, Label};
use serde::{Deserialize, Serialize};
use wordcraft_render::icon_lib::{self, Category};
use super::host::{Asks, DialogHooks, Settle, WordForm, captioned, open_form, open_with};
use super::host::{Asks, DialogHooks, Settle, WordForm, open_form, open_with};
use super::{Value, WordApp};
use egui::Ui;
use serde_json::json;
@@ -113,15 +113,13 @@ impl StackDialog for BookmarkDialog {
.name_box(Bind::bound(name))
.name_check(|n| wordcraft_engine::cmd::insert::bookmark_name_ok(n.trim()))
.under_list(move |ui| {
captioned(ui, Label::from(tl!("Sort by:")), |name, ui| {
RadioGroup::new(name, Bind::bound(&mut *by_location)).show(ui, |ui, _| {
Stack::new().show(ui, |ui, cx| {
for (at, (value, label)) in [(false, "Name"), (true, "Location")].into_iter().enumerate() {
let side = SideLabel::new().layout(FieldLayout::After);
cx.labelled(ui, at, Label::from(tl!(label)), side, Radio::new(value));
}
});
})
RadioGroup::new(Label::from(tl!("Sort by:")), Bind::bound(&mut *by_location)).show(ui, |ui, _| {
Stack::new().show(ui, |ui, cx| {
for (at, (value, label)) in [(false, "Name"), (true, "Location")].into_iter().enumerate() {
let side = SideLabel::new().layout(FieldLayout::After);
cx.labelled(ui, at, Label::from(tl!(label)), side, Radio::new(value));
}
});
});
Checkbox::new(Bind::bound(&mut *hidden)).label(Label::from(tl!("Hidden bookmarks"))).show(ui);
});
+4 -4
View File
@@ -256,10 +256,10 @@ impl RibbonDialog {
let source = TreeSource(&self.tree);
let mut selection = Selection::single(self.selected.clone());
let renamable: Vec<TreeItem> = self.tree.iter().filter(|row| self.renamable(&row.item)).map(|row| row.item.clone()).collect();
let columns = vec![
ColumnSpec::toggle(SHOWN, word("Show"), ToggleColumn::default()),
ColumnSpec::new(ColumnKey::new("name"), word("Ribbon tabs"), ColumnWidth::fill(1.0)),
];
let mut show = ColumnSpec::toggle(SHOWN, word("Show"), ToggleColumn::default());
// As wide as its header, not just its check box: "Show" read "S…".
show.width = ColumnWidth::Content;
let columns = vec![show, ColumnSpec::new(ColumnKey::new("name"), word("Ribbon tabs"), ColumnWidth::fill(1.0))];
let rows = &self.tree;
let out = List::new(word("Ribbon tabs"))
.id(self.tree_id(ui))
+5 -16
View File
@@ -56,22 +56,11 @@ pub(super) fn review(row: &mut RibbonRow<'_>, app: &mut WordApp) {
.arrangement(Arrangement::Stacked)
.show(ui);
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
SplitButton::<u8>::command(
CommandRef::new("review.deleteComment"),
SplitMenu::Body(Box::new(|ui, _| {
MenuItem::command(CommandRef::new("review.deleteComment")).label(tl!("Delete").to_string()).show(ui);
MenuItem::command(CommandRef::with_params("review.deleteComment", json!({"all": true})))
.label(tl!("Delete All Comments in Document").to_string())
.show(ui);
MenuItem::command(CommandRef::with_params("review.deleteComment", json!({"resolved": true})))
.label(tl!("Delete All Resolved Comments").to_string())
.show(ui);
})),
)
.label(tl!("Delete").to_string())
.tooltip(tl!("Delete Comment").to_string())
.icon(IconId::new("deleteComment"))
.show(ui);
Button::command(CommandRef::new("review.deleteComment"))
.label(tl!("Delete").to_string())
.tooltip(tl!("Delete Comment").to_string())
.icon(IconId::new("deleteComment"))
.show(ui);
Button::command(CommandRef::new("review.previousComment"))
.label(tl!("Previous").to_string())
.tooltip(tl!("Previous Comment").to_string())
+5 -7
View File
@@ -123,9 +123,9 @@ Recorded reader pairs (exact shapes in the policy):
| lib.rs::report_dups | ID-BOOKMARK-DUP,ID-DOCPR-DUP,ID-REVISION-DUP | type.HashMap*2,type.HashSet*2 | intentional package-wide reductions for counts and document-wide duplicates, including unreached stories; definition duplicates remain per definition part | source unavailable or malformed; XML event/depth budget; category allocation cap | retain count/duplicate evidence from observed prefixes; loss remains recorded at each source; owner-local joins assemble their own scope | independent |
| lib.rs::report_missing | ID-COMMENT-REF | access.missing*1,type.CompleteSet*1,type.HashSet*2 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | ID-COMMENT-REF |
| lib.rs::report_missing_note | REF-NOTE | access.missing*1,type.CompleteSet*1,type.HashSet*2 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | REF-NOTE |
| lib.rs::check_media | MEDIA-MAGIC | access.missing*1,field.bytes*1,field.content_types*1,field.entries*1,type.Vec*6 | existing media candidates and signatures; prove non-consumption from drawing-reference coverage or verify alternate raster bytes with the shared bounded decoder | incomplete relationship or reference discovery, unsupported alternate encoding, or decode budget | retain the signature Error when neither basis for a Warning is established and explain decoder budget loss, incomplete TIFF directories, or skipped assessment of a recognized encoding | independent |
| lib.rs::check_media | MEDIA-MAGIC | access.missing*1,field.bytes*1,field.content_types*1,field.entries*1,type.Vec*1 | existing media candidates and signatures; prove non-consumption from drawing-reference coverage or verify alternate raster bytes with the shared bounded decoder | incomplete relationship or reference discovery, unsupported alternate encoding, or decode budget | retain the signature Error when neither basis for a Warning is established and explain decoder budget loss, incomplete TIFF directories, or skipped assessment of a recognized encoding | independent |
| lib.rs::possible_drawing_targets | - | access.into_complete_set*2,access.is_complete*1,access.missing*1,access.prefix*1,field.collapsed_names*1,field.entries*1,field.parts*1,field.references*2,field.rels*2,type.CompleteSet*1,type.HashMap*2,type.HashSet*1,type.Observed*2 | package relationship targets possibly consumed by drawings; join complete per-story reference sets by owning relationship part | package relationship discovery incomplete; source missing or unexamined, duplicate owner identity, skipped markup, unmodeled relationship attributes, or reference budget | unknown owner usage leaves every internal target of its declarations possible; incomplete package discovery withholds non-consumption entirely | independent |
| lib.rs::decode_alternate_image_step | - | type.Vec*1 | the admitted TIFF directory graph's main chain, within the part byte and metadata limits | directory walk incomplete, or the alternate image decode budget | leave the image unassessed | independent |
| lib.rs::decode_alternate_image | - | type.Vec*1 | the admitted TIFF directory graph's main chain, within the part byte and metadata limits | directory walk incomplete, or the alternate image decode budget | leave the image unassessed | independent |
| lib.rs::probe_alternate_tiff | - | field.first*1,type.Vec*1 | the admitted TIFF directory graph's main chain against the codec's own page listing | a main-chain directory the codec did not list | leave the image unassessed | independent |
| lib.rs::relationship_targets | - | field.rels*2,type.HashSet*2 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| observed.rs::default | - | - | private Observed/CompleteSet representation provider; signature and footprint pinned in observations/representation-contracts.json | local completeness and allocation budgets carried by the typed representation | retain prefix; incomplete observations cannot construct CompleteSet; fixtures check semantics | independent |
@@ -267,12 +267,10 @@ Recorded reader pairs (exact shapes in the policy):
| scan.rs::parse_comments_ids | COMMENTEX-LINK | parser.parse_comments_ids*1,type.Vec*3 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::push_comment_id | - | type.Vec*1 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| scan.rs::attrs_of | - | type.Vec*2 | source-local bounded extraction; no implicit document owner | source unavailable or malformed; XML event/depth budget; category allocation cap | retain proven prefix presence and duplicates; return loss to the caller; no negative membership from an incomplete set | independent |
| tiff_admission.rs::init_walk | - | type.HashMap*6,type.HashSet*3 | the TIFF directory graph within the part byte and metadata limits | header failure, malformed directory or metadata budget | leave the image unassessed | independent |
| tiff_admission.rs::establish_chain_role | - | field.chain_next*1,field.parsed*1,field.pending_chain_members*2 | chain edges of already-examined TIFF directories whose chain role is established | unexamined targets remain outside the established subgraph | leave unexamined targets pending for bounded examination | independent |
| tiff_admission.rs::run_phase1 | - | field.children_of*1,field.nearest*1,field.pending_chain_members*1,field.queue*7,field.visited*1 | the TIFF directory graph within the directory, entry, depth and work bounds | directory cycle, malformed directory or metadata budget | leave the image unassessed | independent |
| tiff_admission.rs::finish_phase2 | - | field.bytes*2,field.chain_next*2,field.children_of*1,field.parsed*1,type.HashMap*2,type.Vec*1 | the examined TIFF directory subgraph and its main chain | directory cycle, malformed directory or metadata budget | leave the image unassessed | independent |
| tiff_admission.rs::payload | - | type.HashMap*2,type.Vec*1 | the TIFF directory graph within the part byte and metadata limits | header failure, malformed directory or metadata budget | leave the image unassessed | independent |
| tiff_admission.rs::offset | - | field.bytes*2 | one classic TIFF or BigTIFF offset field | offset bytes outside the payload | return no offset | independent |
| tiff_admission.rs::directory | - | field.bytes*2,field.declared*5,field.entries*3,field.examined_dirs*2,field.failed_dirs*8,field.parsed*2,field.value_spans*1,type.BTreeMap*2 | TIFF directory table and physical value spans, bounded before directory or decoder allocations | malformed directory, incomplete value or pointer, directory cycle, work/byte budget | do not assess pixels from an incomplete preflight | independent |
| tiff_admission.rs::admit | - | field.parsed*1,type.HashMap*8,type.HashSet*1,type.Vec*3 | the TIFF directory graph within the directory, entry, depth and work bounds | directory cycle, malformed directory or metadata budget | leave the image unassessed | independent |
| tiff_admission.rs::directory | - | field.bytes*2,field.declared*5,field.entries*3,field.parsed*3,field.value_spans*1,type.BTreeMap*2 | TIFF directory table and physical value spans, bounded before directory or decoder allocations | malformed directory, incomplete value or pointer, directory cycle, work/byte budget | do not assess pixels from an incomplete preflight | independent |
| tiff_admission.rs::record_image_data | - | type.BTreeMap*1 | ranges named by the directory’s checked offset and length tables | work budget or unreadable range | preserve decoder handling of truncated image data | independent |
| tiff_admission.rs::children | - | type.BTreeMap*1,type.Vec*2 | SubIFD, Exif, GPS and Interop pointers under directory, depth and work bounds | unreadable child pointer or incomplete child directory | withhold the complete directory inventory | independent |
| tiff_admission.rs::uint | - | field.bytes*1 | one checked unsigned value from a TIFF tag span | unreadable value or incompatible TIFF field type | return no value | independent |
+34 -1113
View File
File diff suppressed because it is too large Load Diff
+125 -641
View File
@@ -6,92 +6,19 @@ use craft_image_codecs::CodecError;
use craft_tiff::{ByteOrder, EntrySpan, FieldType, ParseOptions, Tiff, directory_entries, entry_span, tags};
/// A bound of the validator's own admission (depth, directory count, entry count) was reached: the graph was not
/// fully assessed, which is no evidence that it is malformed, so alone it is a lost assessment (`Limited`), never a grade.
fn bound_reason(what: &str) -> String {
format!("TIFF directory {what} bound")
}
/// Outcome of bounded TIFF directory-graph admission.
pub(crate) enum Admission<'a> {
/// Complete acyclic directory graph within all bounds: payload slice and main-chain IFD offsets.
Admitted(&'a [u8], Vec<u64>),
/// A decisive defect (cycle or malformed directory/pointer) was established within the examined
/// subgraph. If a traversal bound was also hit on an unexplored branch, the payload names it so the
/// caller can disclose lost coverage without withdrawing the established defect.
MalformedOrCyclic(Option<String>),
/// No decisive defect was established within the examined subgraph, and a traversal bound
/// stopped further exploration.
Limited(String),
}
/// Outcome of starting a bounded TIFF directory-graph admission walk.
pub(crate) enum AdmissionStep<'a> {
/// Admission completed within its initial pass.
Done(Admission<'a>),
/// The walk reached a continuation point (a malformed directory/pointer or per-branch bound)
/// while more queued directories remain. Callers assessing a multi-part package can defer
/// continuation until neighbouring parts finish their initial assessments so extra walk work
/// cannot starve unaffected parts of the package-wide decode budget.
Paused(Box<PausedWalk<'a>>),
}
/// Resumable state of a TIFF directory-graph walk paused at a continuation point.
pub(crate) struct PausedWalk<'a> {
walk: DirectoryWalk<'a>,
root_offset: u64,
queue: VecDeque<(u64, bool, usize)>,
visited: HashSet<(u64, bool)>,
nearest: HashMap<u64, usize>,
children_of: HashMap<u64, Vec<u64>>,
pending_chain_members: HashSet<u64>,
chain_next: HashMap<u64, u64>,
malformed: bool,
bound_hit: Option<String>,
}
enum DirOutcome<T> {
Ok(T),
Malformed,
/// A per-branch bound (such as one directory's entry limit) stopped this directory without
/// exhausting the global walk budgets; other queued branches may still be examined.
BranchBound(String),
/// A global bound (directory count, total entries, or work/byte budget) stopped further parsing.
GlobalBound(String),
}
enum ChildrenStatus {
Complete,
Malformed,
Limited(String),
}
enum FailedDir {
Malformed,
BranchBound(String),
/// assessed, which is no evidence that it is malformed, so it is a lost assessment (`LimitExceeded`), never a grade.
fn bound(what: &str) -> CodecError {
CodecError::LimitExceeded(format!("TIFF directory {what} bound"))
}
/// What the codec will read for a complete TIFF: everything up to its last referenced byte (bytes after that are
/// padding of any content and any length), with the directories of its main chain in order: the first directory and
/// each `next` target. This is the ONE authority for which directories are main-chain pages; the page the validator
/// assesses is chosen from it (a directory first reached as a SubIFD stays a main-chain page).
pub(crate) fn payload(bytes: &[u8], mut reserve: impl FnMut(u64) -> Result<(), CodecError>) -> Result<Admission<'_>, CodecError> {
let mut state = init_walk(bytes, ParseOptions::default())?;
state.run_phase1(&mut reserve, false)?;
Ok(state.finish_phase2())
}
/// Begin bounded TIFF directory-graph admission, pausing at the first continuation point if other
/// queued branches remain so multi-part callers can finish initial assessments of neighbouring
/// parts before spending shared budget on continuation work.
pub(crate) fn start<'a>(bytes: &'a [u8], reserve: &mut impl FnMut(u64) -> Result<(), CodecError>) -> Result<AdmissionStep<'a>, CodecError> {
let mut state = init_walk(bytes, ParseOptions::default())?;
if state.run_phase1(reserve, true)? { Ok(AdmissionStep::Paused(Box::new(state))) } else { Ok(AdmissionStep::Done(state.finish_phase2())) }
}
fn init_walk(bytes: &[u8], limits: ParseOptions) -> Result<PausedWalk<'_>, CodecError> {
pub(crate) fn payload(bytes: &[u8], mut reserve: impl FnMut(u64) -> Result<(), CodecError>) -> Result<Option<(&[u8], Vec<u64>)>, CodecError> {
observation_contract! {
rules: "-";
collections: "type.HashMap*6,type.HashSet*3";
collections: "type.HashMap*2,type.Vec*1";
scope: "the TIFF directory graph within the part byte and metadata limits";
loss: "header failure, malformed directory or metadata budget";
fallback: "leave the image unassessed";
@@ -101,249 +28,43 @@ fn init_walk(bytes: &[u8], limits: ParseOptions) -> Result<PausedWalk<'_>, Codec
let Some((order, big)) = Tiff::sniff(bytes) else {
return Err(CodecError::Malformed { format: craft_image_codecs::Format::Tiff, message: "not a TIFF or BigTIFF header".into() });
};
let walk = DirectoryWalk {
let mut walk = DirectoryWalk {
bytes,
order,
big,
limits,
limits: ParseOptions::default(),
parsed: HashMap::new(),
examined_dirs: HashSet::new(),
failed_dirs: HashMap::new(),
value_spans: HashMap::new(),
entries: 0,
end: if big { 16 } else { 8 },
reserve: &mut reserve,
};
let malformed_root =
|| CodecError::Malformed { format: craft_image_codecs::Format::Tiff, message: "the first TIFF directory is missing or cut off".into() };
let root_offset = walk.offset(if big { 8 } else { 4 }).filter(|&offset| offset != 0).ok_or_else(malformed_root)?;
directory_entries(bytes, root_offset, order, big, walk.limits.max_entries).map_err(|_| malformed_root())?;
Ok(PausedWalk {
walk,
root_offset,
queue: VecDeque::from([(root_offset, true, 0usize)]),
visited: HashSet::new(),
nearest: HashMap::new(),
children_of: HashMap::new(),
pending_chain_members: HashSet::new(),
chain_next: HashMap::new(),
malformed: false,
bound_hit: None,
})
let first = walk.offset(if big { 8 } else { 4 }).filter(|&offset| offset != 0).ok_or_else(malformed_root)?;
directory_entries(bytes, first, order, big, walk.limits.max_entries).map_err(|_| malformed_root())?;
let Some(main_chain) = walk.admit(first)? else {
return Ok(None);
};
// Every range the codec reads is named by the walk, so what follows its end is padding of any content.
let end = usize::try_from(walk.end).unwrap_or(usize::MAX).min(bytes.len());
Ok(bytes.get(..end).map(|payload| (payload, main_chain)))
}
impl<'a> PausedWalk<'a> {
/// Whether this paused walk has already established a malformed defect before pausing.
pub(crate) fn has_established_defect(&self) -> bool {
self.malformed
}
/// Resume a paused walk to completion using the caller's remaining reservation budget.
pub(crate) fn resume(mut self, reserve: &mut impl FnMut(u64) -> Result<(), CodecError>) -> Result<Admission<'a>, CodecError> {
self.run_phase1(reserve, false)?;
Ok(self.finish_phase2())
}
/// Record that a decoded pointer has established `offset` as a chain member, and immediately
/// install `chain_next` edges across any already-examined directories reachable through its
/// cached `next` links so a later global stop cannot drop an already-established cycle.
fn establish_chain_role(&mut self, mut offset: u64) {
observation_contract! {
rules: "-";
collections: "field.chain_next*1,field.parsed*1,field.pending_chain_members*2";
scope: "chain edges of already-examined TIFF directories whose chain role is established";
loss: "unexamined targets remain outside the established subgraph";
fallback: "leave unexamined targets pending for bounded examination";
package_loss: "independent";
}
loop {
let Some(&(_, next)) = self.walk.parsed.get(&offset) else {
self.pending_chain_members.insert(offset);
break;
};
self.pending_chain_members.remove(&offset);
if next == 0 || self.chain_next.insert(offset, next).is_some() {
break;
}
offset = next;
}
}
/// Phase 1: reach every directory once per role (chain member or single), nearest first.
/// `next` keeps the depth (a chain is one level); a pointer to a child adds one.
/// Returns `Ok(true)` when paused at a continuation point with queued work remaining.
fn run_phase1(&mut self, reserve: &mut impl FnMut(u64) -> Result<(), CodecError>, pause_on_continuation: bool) -> Result<bool, CodecError> {
observation_contract! {
rules: "-";
collections: "field.children_of*1,field.nearest*1,field.pending_chain_members*1,field.queue*7,field.visited*1";
scope: "the TIFF directory graph within the directory, entry, depth and work bounds";
loss: "directory cycle, malformed directory or metadata budget";
fallback: "leave the image unassessed";
package_loss: "independent";
}
while let Some((offset, chain, depth)) = self.queue.pop_front() {
if !self.visited.insert((offset, chain)) {
continue;
}
if *self.nearest.entry(offset).or_insert(depth) > self.walk.limits.max_depth {
self.bound_hit.get_or_insert_with(|| bound_reason("depth"));
if pause_on_continuation && !self.queue.is_empty() {
return Ok(true);
}
continue;
}
let (tags, next) = match self.walk.directory(offset, reserve)? {
DirOutcome::Ok(dir) => dir,
DirOutcome::Malformed => {
self.malformed = true;
if pause_on_continuation && !self.queue.is_empty() {
return Ok(true);
}
continue;
}
DirOutcome::BranchBound(reason) => {
self.bound_hit.get_or_insert(reason);
if pause_on_continuation && !self.queue.is_empty() {
return Ok(true);
}
continue;
}
DirOutcome::GlobalBound(reason) => {
self.bound_hit.get_or_insert(reason);
break;
}
};
// Preserve any established chain edge immediately so a later budget stop cannot erase it.
if chain || self.pending_chain_members.remove(&offset) {
self.establish_chain_role(offset);
}
if chain && next != 0 {
self.queue.push_front((next, true, depth));
}
if let Entry::Vacant(slot) = self.children_of.entry(offset) {
match self.walk.record_image_data(&tags, reserve) {
Ok(()) => {}
Err(CodecError::LimitExceeded(reason)) => {
self.bound_hit.get_or_insert(reason);
break;
}
Err(err) => return Err(err),
}
let (children, status) = self.walk.children(&tags, reserve)?;
slot.insert(children.iter().map(|&(child, _)| child).collect());
// A decoded SubIFD pointer establishes its target's chain role immediately; install
// the cached `next` edge for any already-examined target before queue order or a
// later global stop can exit the walk.
for &(child, child_chain) in &children {
if child_chain {
self.establish_chain_role(child);
}
}
match status {
ChildrenStatus::Complete => {
self.queue.extend(children.into_iter().map(|(child, chain)| (child, chain, depth + 1)));
}
ChildrenStatus::Malformed => {
self.malformed = true;
if pause_on_continuation && !self.queue.is_empty() {
return Ok(true);
}
}
ChildrenStatus::Limited(reason) => {
self.bound_hit.get_or_insert(reason);
break;
}
}
}
}
Ok(false)
}
/// Phase 2: a directory with a path back to itself in the examined subgraph is a cycle
/// (depth-first, three colours). Runs even when a traversal bound stopped unexplored branches
/// so an established cycle is never withdrawn by an unrelated bound hit.
///
/// This is the ONLY cycle computation. The graph's edges are every SubIFD, Exif, GPS and Interop
/// pointer, and the `next` pointer of every directory that is read as a chain member (the first
/// directory, a `next` target or a SubIFD target; Exif, GPS and Interop directories are single
/// directories whose `next` nothing follows). Reaching a directory again is free whatever route
/// it took, deeper routes included; only a directory that reaches itself rejects.
fn finish_phase2(self) -> Admission<'a> {
observation_contract! {
rules: "-";
collections: "field.bytes*2,field.chain_next*2,field.children_of*1,field.parsed*1,type.HashMap*2,type.Vec*1";
scope: "the examined TIFF directory subgraph and its main chain";
loss: "directory cycle, malformed directory or metadata budget";
fallback: "leave the image unassessed";
package_loss: "independent";
}
let mut cyclic = false;
let successors = |offset: u64| -> Vec<u64> {
self.children_of.get(&offset).into_iter().flatten().copied().chain(self.chain_next.get(&offset).copied()).collect()
};
// `false`: open on the current path; `true`: finished, with no path back to itself.
let mut colour: HashMap<u64, bool> = HashMap::from([(self.root_offset, false)]);
let mut stack = vec![(self.root_offset, successors(self.root_offset).into_iter())];
while let Some((offset, rest)) = stack.last_mut() {
let offset = *offset;
match rest.next().map(|target| (target, colour.get(&target).copied())) {
Some((_, Some(false))) => {
cyclic = true;
break;
}
Some((target, None)) => {
colour.insert(target, false);
stack.push((target, successors(target).into_iter()));
}
Some(_) => {}
None => {
colour.insert(offset, true);
stack.pop();
}
}
}
if self.malformed || cyclic {
return Admission::MalformedOrCyclic(self.bound_hit);
}
if let Some(reason) = self.bound_hit {
return Admission::Limited(reason);
}
// The main chain: the first directory and each `next` target. The graph is acyclic here.
let mut main_chain = vec![self.root_offset];
while let Some(&next) = main_chain.last().and_then(|at| self.chain_next.get(at)) {
if main_chain.len() > self.walk.parsed.len() {
break;
}
main_chain.push(next);
}
// Every range the codec reads is named by the walk, so what follows its end is padding of any content.
let end = usize::try_from(self.walk.end).unwrap_or(usize::MAX).min(self.walk.bytes.len());
match self.walk.bytes.get(..end) {
Some(payload) => Admission::Admitted(payload, main_chain),
None => Admission::MalformedOrCyclic(None),
}
}
}
struct DirectoryWalk<'a> {
struct DirectoryWalk<'a, R> {
bytes: &'a [u8],
order: ByteOrder,
big: bool,
limits: ParseOptions,
/// Directories already read and charged, with their tables and next pointers.
parsed: HashMap<u64, (BTreeMap<u16, EntrySpan>, u64)>,
/// Distinct in-range directories whose examination has started, independent of cache success.
examined_dirs: HashSet<u64>,
/// Cached non-Ok outcomes so revisiting an offset in another role does not re-charge budgets.
failed_dirs: HashMap<u64, FailedDir>,
value_spans: HashMap<u64, u64>,
entries: usize,
end: u64,
reserve: &'a mut R,
}
impl DirectoryWalk<'_> {
impl<R: FnMut(u64) -> Result<(), CodecError>> DirectoryWalk<'_, R> {
fn offset(&self, at: usize) -> Option<u64> {
observation_contract! {
rules: "-";
@@ -357,14 +78,90 @@ impl DirectoryWalk<'_> {
if self.big { self.order.read_u64(self.bytes, at) } else { self.order.read_u32(self.bytes, at).map(u64::from) }
}
fn directory(
&mut self,
offset: u64,
reserve: &mut impl FnMut(u64) -> Result<(), CodecError>,
) -> Result<DirOutcome<(BTreeMap<u16, EntrySpan>, u64)>, CodecError> {
/// The main chain of the directory graph reachable from `first` when it can be admitted: every directory reads,
/// the directory, entry and depth budgets hold, and no directory is reachable from itself. `None` when the graph is
/// malformed or cyclic; a budget that does not hold is `Err(LimitExceeded)`, a lost assessment.
///
/// This is the ONLY cycle computation. The graph's edges are every SubIFD, Exif, GPS and Interop
/// pointer, and the `next` pointer of every directory that is read as a chain member (the first
/// directory, a `next` target or a SubIFD target; Exif, GPS and Interop directories are single
/// directories whose `next` nothing follows). Reaching a directory again is free whatever route
/// it took, deeper routes included; only a directory that reaches itself rejects. Reachability is explored first, so
/// the verdict depends on the graph and not on the order its edges are visited in.
fn admit(&mut self, first: u64) -> Result<Option<Vec<u64>>, CodecError> {
observation_contract! {
rules: "-";
collections: "field.bytes*2,field.declared*5,field.entries*3,field.examined_dirs*2,field.failed_dirs*8,field.parsed*2,field.value_spans*1,type.BTreeMap*2";
collections: "field.parsed*1,type.HashMap*8,type.HashSet*1,type.Vec*3";
scope: "the TIFF directory graph within the directory, entry, depth and work bounds";
loss: "directory cycle, malformed directory or metadata budget";
fallback: "leave the image unassessed";
package_loss: "independent";
}
// Phase 1: reach every directory once per role (chain member or single), nearest first.
// `next` keeps the depth (a chain is one level); a pointer to a child adds one.
let mut queue = VecDeque::from([(first, true, 0usize)]);
let mut visited = HashSet::new();
// The depth at which each directory was first reached in any role: the queue pops nearest first, so it is
// the directory's minimum depth, and the depth bound is decided on that alone.
let mut nearest: HashMap<u64, usize> = HashMap::new();
let mut children_of: HashMap<u64, Vec<u64>> = HashMap::new();
let mut chain_next: HashMap<u64, u64> = HashMap::new();
while let Some((offset, chain, depth)) = queue.pop_front() {
if !visited.insert((offset, chain)) {
continue;
}
if *nearest.entry(offset).or_insert(depth) > self.limits.max_depth {
return Err(bound("depth"));
}
let Some((tags, next)) = self.directory(offset)? else { return Ok(None) };
if let Entry::Vacant(slot) = children_of.entry(offset) {
self.record_image_data(&tags)?;
let Some(children) = self.children(&tags)? else { return Ok(None) };
slot.insert(children.iter().map(|&(child, _)| child).collect());
queue.extend(children.into_iter().map(|(child, chain)| (child, chain, depth + 1)));
}
if chain && next != 0 {
chain_next.insert(offset, next);
queue.push_front((next, true, depth));
}
}
// Phase 2: a directory with a path back to itself is a cycle (depth-first, three colours).
let successors =
|offset: u64| -> Vec<u64> { children_of.get(&offset).into_iter().flatten().copied().chain(chain_next.get(&offset).copied()).collect() };
// `false`: open on the current path; `true`: finished, with no path back to itself.
let mut colour: HashMap<u64, bool> = HashMap::from([(first, false)]);
let mut stack = vec![(first, successors(first).into_iter())];
while let Some((offset, rest)) = stack.last_mut() {
let offset = *offset;
match rest.next().map(|target| (target, colour.get(&target).copied())) {
Some((_, Some(false))) => return Ok(None),
Some((target, None)) => {
colour.insert(target, false);
stack.push((target, successors(target).into_iter()));
}
Some(_) => {}
None => {
colour.insert(offset, true);
stack.pop();
}
}
}
// The main chain: the first directory and each `next` target. The graph is acyclic here.
let mut main_chain = vec![first];
while let Some(&next) = main_chain.last().and_then(|at| chain_next.get(at)) {
if main_chain.len() > self.parsed.len() {
break;
}
main_chain.push(next);
}
Ok(Some(main_chain))
}
fn directory(&mut self, offset: u64) -> Result<Option<(BTreeMap<u16, EntrySpan>, u64)>, CodecError> {
observation_contract! {
rules: "-";
collections: "field.bytes*2,field.declared*5,field.entries*3,field.parsed*3,field.value_spans*1,type.BTreeMap*2";
scope: "TIFF directory table and physical value spans, bounded before directory or decoder allocations";
loss: "malformed directory, incomplete value or pointer, directory cycle, work/byte budget";
fallback: "do not assess pixels from an incomplete preflight";
@@ -372,65 +169,33 @@ impl DirectoryWalk<'_> {
}
if let Some(known) = self.parsed.get(&offset) {
return Ok(DirOutcome::Ok(known.clone()));
return Ok(Some(known.clone()));
}
if let Some(failed) = self.failed_dirs.get(&offset) {
return Ok(match failed {
FailedDir::Malformed => DirOutcome::Malformed,
FailedDir::BranchBound(reason) => DirOutcome::BranchBound(reason.clone()),
});
if self.parsed.len() >= self.limits.max_ifds {
return Err(bound("count"));
}
if self.examined_dirs.len() >= self.limits.max_ifds {
return Ok(DirOutcome::GlobalBound(bound_reason("count")));
}
self.examined_dirs.insert(offset);
match reserve(512) {
Ok(()) => {}
Err(CodecError::LimitExceeded(reason)) => return Ok(DirOutcome::GlobalBound(reason)),
Err(err) => return Err(err),
}
let Ok(dir) = directory_entries(self.bytes, offset, self.order, self.big, self.limits.max_entries) else {
self.failed_dirs.insert(offset, FailedDir::Malformed);
return Ok(DirOutcome::Malformed);
};
(self.reserve)(512)?;
let Ok(dir) = directory_entries(self.bytes, offset, self.order, self.big, self.limits.max_entries) else { return Ok(None) };
self.entries = self.entries.saturating_add(dir.read());
if self.entries > self.limits.max_entries_total {
return Ok(DirOutcome::GlobalBound(bound_reason("entry")));
}
if dir.read() >= self.limits.max_entries && dir.declared() > dir.read() as u64 {
let reason = bound_reason("entry");
self.failed_dirs.insert(offset, FailedDir::BranchBound(reason.clone()));
return Ok(DirOutcome::BranchBound(reason));
if self.entries > self.limits.max_entries_total || (dir.read() >= self.limits.max_entries && dir.declared() > dir.read() as u64) {
return Err(bound("entry"));
}
if dir.declared() != dir.read() as u64 {
self.failed_dirs.insert(offset, FailedDir::Malformed);
return Ok(DirOutcome::Malformed);
return Ok(None);
}
// Bound the indexes here and the directory inventory in the codec. Use actual
// directory and entry counts, including overlaps, independently of payload size.
match reserve(160 * dir.declared()) {
Ok(()) => {}
Err(CodecError::LimitExceeded(reason)) => return Ok(DirOutcome::GlobalBound(reason)),
Err(err) => return Err(err),
}
(self.reserve)(160 * dir.declared())?;
let mut tags = BTreeMap::new();
for pos in dir.positions() {
let Some(value) = entry_span(self.bytes, pos, self.order, self.big, 0) else {
self.failed_dirs.insert(offset, FailedDir::Malformed);
return Ok(DirOutcome::Malformed);
};
let Some(value) = entry_span(self.bytes, pos, self.order, self.big, 0) else { return Ok(None) };
if tags.insert(value.tag, value).is_some() {
self.failed_dirs.insert(offset, FailedDir::Malformed);
return Ok(DirOutcome::Malformed);
return Ok(None);
}
let held = self.value_spans.entry(value.start).or_default();
// Alias ranges with the same origin share physical bytes. A wider view
// extends the reservation by just the bytes not seen at that offset.
match reserve(value.len.saturating_sub(*held).saturating_mul(8)) {
Ok(()) => {}
Err(CodecError::LimitExceeded(reason)) => return Ok(DirOutcome::GlobalBound(reason)),
Err(err) => return Err(err),
}
(self.reserve)(value.len.saturating_sub(*held).saturating_mul(8))?;
*held = (*held).max(value.len);
self.end = self.end.max(value.start.saturating_add(value.len));
}
@@ -438,31 +203,17 @@ impl DirectoryWalk<'_> {
// The codec describes each page separately and materializes its ExtraSamples.
// Charge those vectors per page when several pages alias the same value bytes.
let samples = tags.get(&tags::SAMPLES_PER_PIXEL).and_then(|span| self.uint(*span, 0)).unwrap_or(1).min(u64::from(u16::MAX));
match reserve(16 * extra.count.min(samples)) {
Ok(()) => {}
Err(CodecError::LimitExceeded(reason)) => return Ok(DirOutcome::GlobalBound(reason)),
Err(err) => return Err(err),
}
(self.reserve)(16 * extra.count.min(samples))?;
}
let table = if self.big { 8 + 20 * dir.declared() } else { 2 + 12 * dir.declared() };
let Some(next_at) = offset.checked_add(table) else {
self.failed_dirs.insert(offset, FailedDir::Malformed);
return Ok(DirOutcome::Malformed);
};
let Some(next) = usize::try_from(next_at).ok().and_then(|at| self.offset(at)) else {
self.failed_dirs.insert(offset, FailedDir::Malformed);
return Ok(DirOutcome::Malformed);
};
let Some(next_at) = offset.checked_add(table) else { return Ok(None) };
let Some(next) = usize::try_from(next_at).ok().and_then(|at| self.offset(at)) else { return Ok(None) };
self.end = self.end.max(next_at.saturating_add(if self.big { 8 } else { 4 }));
self.parsed.insert(offset, (tags.clone(), next));
Ok(DirOutcome::Ok((tags, next)))
Ok(Some((tags, next)))
}
fn record_image_data(
&mut self,
tags: &BTreeMap<u16, EntrySpan>,
reserve: &mut impl FnMut(u64) -> Result<(), CodecError>,
) -> Result<(), CodecError> {
fn record_image_data(&mut self, tags: &BTreeMap<u16, EntrySpan>) -> Result<(), CodecError> {
observation_contract! {
rules: "-";
collections: "type.BTreeMap*1";
@@ -480,7 +231,7 @@ impl DirectoryWalk<'_> {
] {
let (Some(offsets), Some(sizes)) = (tags.get(&offsets), tags.get(&sizes)) else { continue };
let chunks = offsets.count.min(sizes.count);
reserve(chunks.saturating_mul(8))?;
(self.reserve)(chunks.saturating_mul(8))?;
for index in 0..chunks {
if let (Some(start), Some(len)) = (self.uint(*offsets, index), self.uint(*sizes, index))
&& len > 0
@@ -495,13 +246,8 @@ impl DirectoryWalk<'_> {
}
/// The directories a directory points at, each with whether it is read as a chain (SubIFD) or as a
/// single directory (Exif, GPS, Interop). Preserves any decoded prefix even if a later child tag
/// is malformed or exceeds the reservation budget.
fn children(
&mut self,
tags: &BTreeMap<u16, EntrySpan>,
reserve: &mut impl FnMut(u64) -> Result<(), CodecError>,
) -> Result<(Vec<(u64, bool)>, ChildrenStatus), CodecError> {
/// single directory (Exif, GPS, Interop). `None` when a pointer is unreadable or malformed.
fn children(&mut self, tags: &BTreeMap<u16, EntrySpan>) -> Result<Option<Vec<(u64, bool)>>, CodecError> {
observation_contract! {
rules: "-";
collections: "type.BTreeMap*1,type.Vec*2";
@@ -515,23 +261,17 @@ impl DirectoryWalk<'_> {
for tag in [tags::SUB_IFDS, tags::EXIF_IFD, tags::GPS_IFD, tags::INTEROP_IFD] {
let Some(children) = tags.get(&tag) else { continue };
if tag != tags::SUB_IFDS && children.count != 1 {
return Ok((out, ChildrenStatus::Malformed));
}
match reserve(children.count.saturating_mul(8)) {
Ok(()) => {}
Err(CodecError::LimitExceeded(reason)) => return Ok((out, ChildrenStatus::Limited(reason))),
Err(err) => return Err(err),
return Ok(None);
}
(self.reserve)(children.count.saturating_mul(8))?;
for index in 0..children.count {
let Some(child) = self.uint(*children, index) else {
return Ok((out, ChildrenStatus::Malformed));
};
let Some(child) = self.uint(*children, index) else { return Ok(None) };
if child != 0 {
out.push((child, tag == tags::SUB_IFDS));
}
}
}
Ok((out, ChildrenStatus::Complete))
Ok(Some(out))
}
fn uint(&self, span: EntrySpan, index: u64) -> Option<u64> {
@@ -651,259 +391,3 @@ pub(crate) fn worker_open_bytes(bytes: &[u8], page: &craft_image_codecs::TiffPag
}
total
}
#[cfg(test)]
mod tests {
use super::*;
/// Finding 2 (exact two-directory allowance shape): a directory that hits its per-directory
/// entry cap counts against `max_ifds`, so a third distinct table beyond the allowance cannot
/// be examined or change `Limited` into `MalformedOrCyclic`.
#[test]
fn directory_count_charges_entry_capped_directory_under_two_directory_allowance() {
// Layout:
// D0 at 8: 2 entries (SubIFD count=2 -> out-of-line [D1, D2], plus one dummy tag)
// D1 at 38: 5 entries (exceeds max_entries=4 -> per-directory BranchBound)
// D2 at 104: 2 entries (duplicate tag 40000 -> Malformed if examined)
// SubIFD array at 134: [D1, D2]
let d0_off = 8u32;
let d1_off = d0_off + 2 + 2 * 12 + 4; // 38
let d2_off = d1_off + 2 + 5 * 12 + 4; // 104
let sub_arr_off = d2_off + 2 + 2 * 12 + 4; // 134
let build = |duplicate_in_third: bool| {
let mut bytes = b"II*\0\x08\0\0\0".to_vec();
let push_dir = |buf: &mut Vec<u8>, entries: &[(u16, u16, u32, u32)]| {
buf.extend((entries.len() as u16).to_le_bytes());
for &(tag, ty, count, val) in entries {
buf.extend(tag.to_le_bytes());
buf.extend(ty.to_le_bytes());
buf.extend(count.to_le_bytes());
buf.extend(val.to_le_bytes());
}
buf.extend(0u32.to_le_bytes());
};
push_dir(&mut bytes, &[(330, 4, 2, sub_arr_off), (40001, 4, 1, 0)]);
assert_eq!(bytes.len() as u32, d1_off);
push_dir(&mut bytes, &[(40010, 4, 1, 0), (40011, 4, 1, 1), (40012, 4, 1, 2), (40013, 4, 1, 3), (40014, 4, 1, 4)]);
assert_eq!(bytes.len() as u32, d2_off);
let third_tag2 = if duplicate_in_third { 40000 } else { 40002 };
push_dir(&mut bytes, &[(40000, 4, 1, 1), (third_tag2, 4, 1, 2)]);
assert_eq!(bytes.len() as u32, sub_arr_off);
bytes.extend(d1_off.to_le_bytes());
bytes.extend(d2_off.to_le_bytes());
bytes
};
fn run(bytes: &[u8], max_ifds: usize) -> Admission<'_> {
let limits = ParseOptions { max_ifds, max_entries: 4, ..ParseOptions::default() };
let mut state = init_walk(bytes, limits).unwrap();
let mut reserve = |_: u64| Ok(());
state.run_phase1(&mut reserve, false).unwrap();
state.finish_phase2()
}
// Under a 2-directory allowance, D0 + entry-capped D1 exhaust `max_ifds`; D2 must stay
// unexamined whether or not it carries a duplicate tag.
let malformed_third = build(true);
let clean_third = build(false);
assert!(matches!(run(&malformed_third, 2), Admission::Limited(_)));
assert!(matches!(run(&clean_third, 2), Admission::Limited(_)));
// Under a 3-directory allowance, D2 IS within budget and its duplicate tag grades MalformedOrCyclic.
assert!(matches!(run(&malformed_third, 3), Admission::MalformedOrCyclic(Some(_))));
assert!(matches!(run(&clean_third, 3), Admission::Limited(_)));
}
/// Build a classic little-endian TIFF from `(subifds, exif, next, duplicate_tag)`.
fn build_test_graph(nodes: &[(Vec<usize>, Option<usize>, Option<usize>, bool)]) -> Vec<u8> {
let mut offsets = Vec::with_capacity(nodes.len());
let mut cursor = 8u32;
for (subs, exif, _, dup) in nodes {
offsets.push(cursor);
let count = 1u32 + u32::from(*dup) + u32::from(!subs.is_empty()) + u32::from(exif.is_some());
cursor += 2 + count * 12 + 4;
}
let mut sub_arrays = Vec::with_capacity(nodes.len());
for (subs, _, _, _) in nodes {
if subs.len() > 1 {
sub_arrays.push(Some(cursor));
cursor += (subs.len() as u32) * 4;
} else {
sub_arrays.push(None);
}
}
let mut bytes = b"II*\0\x08\0\0\0".to_vec();
for (idx, (subs, exif, next, dup)) in nodes.iter().enumerate() {
let mut entries: Vec<(u16, u16, u32, u32)> = Vec::new();
if !subs.is_empty() {
let val = if subs.len() == 1 { offsets[subs[0]] } else { sub_arrays[idx].unwrap() };
entries.push((tags::SUB_IFDS, 4, subs.len() as u32, val));
}
if let Some(ex) = *exif {
entries.push((tags::EXIF_IFD, 4, 1, offsets[ex]));
}
entries.push((40000, 4, 1, idx as u32));
if *dup {
entries.push((40000, 4, 1, idx as u32 + 1));
}
entries.sort_by_key(|e| e.0);
bytes.extend((entries.len() as u16).to_le_bytes());
for (tag, ty, cnt, val) in entries {
bytes.extend(tag.to_le_bytes());
bytes.extend(ty.to_le_bytes());
bytes.extend(cnt.to_le_bytes());
bytes.extend(val.to_le_bytes());
}
bytes.extend(next.map_or(0u32, |n| offsets[n]).to_le_bytes());
}
for (subs, _, _, _) in nodes {
if subs.len() > 1 {
for &child in subs {
bytes.extend(offsets[child].to_le_bytes());
}
}
}
assert_eq!(bytes.len() as u32, cursor);
bytes
}
/// Round-2 Item 1 (Astra's Exif-to-SubIFD graph under global stops): when a decoded SubIFD
/// pointer establishes a chain role for an already-examined Exif directory, its cached `next`
/// edge must be installed immediately so a subsequent global stop (directory count or byte
/// reservation) on an independent sibling cannot drop the established cycle in either sibling
/// order — while an unexamined malformed sibling still stays outside the allowance.
#[test]
fn cached_chain_role_installs_edge_before_global_stop_in_both_sibling_orders() {
// Astra's exact Exif/SubIFD graph:
// 0 = D0: SubIFD [B1], Exif X
// 1 = X: next -> D0 (when cyclic) or None (acyclic control)
// 2..=11 = B1..B10 (chain of SubIFDs); B10 has SubIFD [X, B11] or [B11, X]
// 12 = B11: independent sibling (duplicate tag in acyclic control to prove it stays unexamined)
let build_astra_graph = |x_first: bool, cyclic: bool, b11_malformed: bool| -> Vec<u8> {
let mut nodes = vec![(vec![2], Some(1), None, false), (vec![], None, cyclic.then_some(0), false)];
for step in 0..10 {
let subs = if step < 9 {
vec![3 + step]
} else if x_first {
vec![1, 12]
} else {
vec![12, 1]
};
nodes.push((subs, None, None, false));
}
nodes.push((vec![], None, None, b11_malformed));
build_test_graph(&nodes)
};
// Measure the exact byte reservation right before B11's examination begins (12 tables cached).
let probe_bytes = build_astra_graph(false, false, false);
let mut reservations = Vec::new();
{
let limits = ParseOptions { max_depth: 11, max_ifds: 12, ..ParseOptions::default() };
let mut state = init_walk(&probe_bytes, limits).unwrap();
let mut reserve = |cost: u64| {
reservations.push(cost);
Ok(())
};
state.run_phase1(&mut reserve, false).unwrap();
assert_eq!(state.walk.parsed.len(), 12);
assert!(matches!(state.finish_phase2(), Admission::Limited(_)));
}
let exact_12_tables_budget: u64 = reservations.iter().sum();
fn run_count(bytes: &[u8]) -> (usize, Admission<'_>) {
let limits = ParseOptions { max_depth: 11, max_ifds: 12, ..ParseOptions::default() };
let mut state = init_walk(bytes, limits).unwrap();
let mut reserve = |_: u64| Ok(());
state.run_phase1(&mut reserve, false).unwrap();
let cached = state.walk.parsed.len();
(cached, state.finish_phase2())
}
fn run_bytes(bytes: &[u8], budget: u64) -> (usize, Admission<'_>) {
let limits = ParseOptions { max_depth: 11, ..ParseOptions::default() };
let mut state = init_walk(bytes, limits).unwrap();
let mut rem = budget;
let mut reserve = |cost: u64| {
if cost > rem {
return Err(CodecError::LimitExceeded("alternate image decode budget".into()));
}
rem -= cost;
Ok(())
};
state.run_phase1(&mut reserve, false).unwrap();
let cached = state.walk.parsed.len();
(cached, state.finish_phase2())
}
for x_first in [false, true] {
let cyclic = build_astra_graph(x_first, true, false);
let acyclic_malformed_sibling = build_astra_graph(x_first, false, true);
let (cached, outcome) = run_count(&cyclic);
assert_eq!(cached, 12, "x_first={x_first}");
assert!(
matches!(outcome, Admission::MalformedOrCyclic(Some(ref r)) if r.contains("TIFF directory count bound")),
"count stop cyclic x_first={x_first}"
);
let (cached, outcome) = run_count(&acyclic_malformed_sibling);
assert_eq!(cached, 12, "x_first={x_first}");
assert!(
matches!(outcome, Admission::Limited(ref r) if r.contains("TIFF directory count bound")),
"count stop acyclic x_first={x_first}: B11 must stay unexamined"
);
let (cached, outcome) = run_bytes(&cyclic, exact_12_tables_budget);
assert_eq!(cached, 12, "x_first={x_first}");
assert!(
matches!(outcome, Admission::MalformedOrCyclic(Some(ref r)) if r.contains("alternate image decode budget")),
"byte stop cyclic x_first={x_first}"
);
let (cached, outcome) = run_bytes(&acyclic_malformed_sibling, exact_12_tables_budget);
assert_eq!(cached, 12, "x_first={x_first}");
assert!(
matches!(outcome, Admission::Limited(ref r) if r.contains("alternate image decode budget")),
"byte stop acyclic x_first={x_first}: B11 must stay unexamined"
);
}
}
/// Reversed discovery order: a SubIFD pointer to X is decoded (from A at depth 1) BEFORE X is
/// examined as Exif (depth 1), and sibling B hits `max_ifds = 3` before `(X, true, 2)` is popped.
#[test]
fn cached_chain_role_installs_edge_in_reversed_discovery_order() {
for x_first in [false, true] {
let subs_a = if x_first { vec![2, 3] } else { vec![3, 2] };
// 0 = D0 (SubIFD A, Exif X), 1 = A (SubIFD [X, B] or [B, X]), 2 = X (next D0), 3 = B
let cyclic = build_test_graph(&[
(vec![1], Some(2), None, false),
(subs_a.clone(), None, None, false),
(vec![], None, Some(0), false),
(vec![], None, None, false),
]);
let acyclic = build_test_graph(&[
(vec![1], Some(2), None, false),
(subs_a, None, None, false),
(vec![], None, None, false),
(vec![], None, None, true),
]);
for (is_cyclic, bytes) in [(true, &cyclic), (false, &acyclic)] {
let limits = ParseOptions { max_ifds: 3, ..ParseOptions::default() };
let mut state = init_walk(bytes, limits).unwrap();
let mut reserve = |_: u64| Ok(());
state.run_phase1(&mut reserve, false).unwrap();
let outcome = state.finish_phase2();
if is_cyclic {
assert!(
matches!(outcome, Admission::MalformedOrCyclic(Some(ref r)) if r.contains("TIFF directory count bound")),
"reversed discovery cyclic x_first={x_first}"
);
} else {
assert!(
matches!(outcome, Admission::Limited(ref r) if r.contains("TIFF directory count bound")),
"reversed discovery acyclic x_first={x_first}"
);
}
}
}
}
}
File diff suppressed because one or more lines are too long
+3 -3
View File
@@ -2,7 +2,7 @@
Generated by `cargo xtask parity` (`wordcraft-cli parity --markdown`): the word-processor feature catalog (`crates/engine/src/catalog.rs`) compared with the live command registry.
**512 of 524 catalog features have commands (97.7%).**
**510 of 522 catalog features have commands (97.7%).**
| Tab | Live | Total |
|---|---|---|
@@ -16,7 +16,7 @@ Generated by `cargo xtask parity` (`wordcraft-cli parity --markdown`): the word-
| Layout | 23 | 23 |
| References | 25 | 25 |
| Mailings | 23 | 23 |
| Review | 31 | 33 |
| Review | 29 | 31 |
| View | 29 | 29 |
| Read Mode | 2 | 3 |
| Developer | 11 | 11 |
@@ -32,7 +32,7 @@ Generated by `cargo xtask parity` (`wordcraft-cli parity --markdown`): the word-
| Editing | 41 | 41 |
| Tools | 7 | 7 |
**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 512 yes, 12 no (window 3, os 8, engine-gap 1), 0 partial, 0 unknown.** A feature is `headless: yes` when its command is in the engine registry that `wordcraft-cli` and the MCP server load, so every live feature above is `yes`; the missing ones carry the hand mark from `HEADLESS` in `crates/engine/src/catalog.rs`, or `unknown`.
**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 510 yes, 12 no (window 3, os 8, engine-gap 1), 0 partial, 0 unknown.** A feature is `headless: yes` when its command is in the engine registry that `wordcraft-cli` and the MCP server load, so every live feature above is `yes`; the missing ones carry the hand mark from `HEADLESS` in `crates/engine/src/catalog.rs`, or `unknown`.
## Missing
+1 -2
View File
File diff suppressed because one or more lines are too long