DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge PR #797
Brandon Thomas0923c8247a4c
diff --cc ROADMAP.mdindex c4483f3c9,bb66401f1..7781c8edb--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -131,66 -127,10 +131,67 @@@ list) · [roadmap.md](docs/roadmap.md)## Progress log+- **2026-10-13** · Switching between document and parent pages refreshes the canvas immediately, preventing black parent pages and stale document objects when the zoom stays the same. Ordinary edits retain partial repainting. No readiness percentage change.+Newest first.+- **2026-10-14** · The Type tool draws a new text frame over a locked empty frame, as InDesign does, instead of turning the locked frame into a text frame. No readiness percentage change.+- **2026-10-14** · 100% black shows as pure black on screen by default, as InDesign's Appearance of Black does out of the box (Display All Blacks as Rich Black); Preferences › Appearance of Black › Display All Blacks Accurately still shows it as the dark grey it prints, and a saved choice is kept. No readiness percentage change.+- **2026-10-14** · Pathfinder keeps the frontmost object, as InDesign does: a photo placed over shapes and intersected with them shows through the shapes (it was dropped, and the shapes kept their black fill); Add, Exclude Overlap and Minus Back take the front object's fill too, Subtract still keeps the back one. No readiness percentage change.+- **2026-10-14** · The Color panel's Tint field keeps what is typed while it has focus and applies it on Enter or when it loses focus, clamped to 0–100 %. Typing 60 over 100 % no longer snaps back to 100 after the first digit (10060), and a typed tint is no longer ignored. No readiness percentage change.+- **2026-10-15** · IDML: ruler guides import and export (they were dropped). Each page's guides come in measured from the document's ruler origin (spread, page or spine), with Fit to Page, Locked and their layer, parent pages' included, and go out again under their pages. No readiness percentage change.+- **2026-10-15** · Find Font no longer reports a style missing when it differs from the installed one only in spacing or case (InDesign files can name `Regular ` with a trailing space); the text was already drawn in the right face. No readiness percentage change.+- **2026-10-15** · A line of text is set when its baseline fits in the frame, as in InDesign: descenders may hang below the frame's bottom. A frame sized to the cap height of a big heading (103 pt in a 2.77 cm frame, as Zero2Graphic's magazine tutorial draws them) no longer oversets. No readiness percentage change.+- **2026-10-15** · A story that ends with a return is no longer overset when only its empty last paragraph doesn't fit, as in InDesign (Preflight said "Overset text: 0 characters" for a caption InDesign shows with no errors). No readiness percentage change.+- **2026-10-13** · Object › Fitting has InDesign's shortcuts: Fill Frame Proportionally ⌘⌥⇧C, Fit Content Proportionally ⌘⌥⇧E, Fit Frame to Content ⌘⌥C, Fit Content to Frame ⌘⌥E, Center Content ⌘⇧E. No readiness percentage change.+- **2026-10-13** · Gradients between process colours blend as inks, as InDesign shows them: magenta to cyan passes through C 50 M 50 (a light lilac) on screen instead of the darker RGB mix, and a midpoint between CMYK or grey stops no longer turns the PDF shading RGB. No readiness percentage change.+- **2026-10-14** · The Swatches panel has InDesign's header: a Fill/Stroke proxy, Formatting Affects Container/Text and the Tint of the colour in front (a tint alone keeps each object's own swatch). Clicking a swatch applies it to the fill or stroke in front (of the text, when formatting affects text), and the bottom row has New Color Group, New Swatch and Delete Swatch. No readiness percentage change.+- **2026-10-14** · With the Page tool, the Control panel shows the page as InDesign's does: W/H from a reference point, page-size preset (US Business Card added), orientation, Liquid Page Rule (now with Controlled by Parent) and Show Parent Page Overlay, which draws the parent page's size over a resized page. No readiness percentage change.+- **2026-10-14** · On an object-based page the Page tool shows a selected object's liquid pins and resize locks as InDesign does: a click pins a side to the page edge or locks the width or height, with InDesign's tooltips. No readiness percentage change.+- **2026-10-14** · The Liquid Layout panel follows InDesign's: Liquid Page Rule with the page number, Content › Auto-Fit, and Object Constraints › Resize with Page and Pin for the selected object on an object-based page; Create Alternate Layout moved to the Layout menu. No readiness percentage change.+- **2026-10-14** · With the Page tool, the Control panel shows the page as InDesign's does: W/H from a reference point, page-size preset (US Business Card added), orientation, Liquid Page Rule (now with Controlled by Parent) and Show Parent Page Overlay, which draws the parent page's size over a resized page. No readiness percentage change.+- **2026-10-14** · With the Page tool, the Control panel shows the page as InDesign's does: W/H from a reference point, page-size preset (US Business Card added), orientation, Liquid Page Rule and Show Parent Page Overlay, which draws the parent page's size over a resized page. No readiness percentage change.+- **2026-10-14** · The Page tool works as InDesign's: a click selects a page and shows its handles and liquid page rule; dragging a handle previews the rule and springs back, Alt-drag resizes the page from the opposite edge, Shift keeps proportions, with a W/H readout. No readiness percentage change.+- **2026-10-14** · With the Page tool, a guide dragged from a ruler is a liquid guide (dashed), as in InDesign; guide-based pages stretch the objects it crosses. No readiness percentage change.+- **2026-10-14** · The Pages panel menu follows InDesign's order: Insert Pages…, Move Pages…, Duplicate Spread (and at End of Document), Delete Page/Spread, New Parent…, Apply Parent to Pages, Override All Parent Page Items, Parent Pages, Create Alternate Layout…, Numbering & Section Options…, Allow Selected Spread to Shuffle. No readiness percentage change.+- **2026-10-14** · Pages panel: Alt-drag copies a page, a page dropped on Create new page is duplicated at the end, Edit page size offers the presets and Custom Page Size…; duplicated pages keep their own size, rule and guides; thumbnails of pages of their own size stay in their rows. No readiness percentage change.+- **2026-10-12 (PDFW)** · PDF, booklet and book composition share guarded writing, metadata and font preparation through craft-pdf. Layout, shaping, placed graphics, colour policy, tagging and PDF/X postprocessing remain in DesignCraft. Failed native drawing returns an export error; failed writer cleanup cannot serialize an incomplete document. No readiness percentage change.++- **2026-10-13** · Copy with a placed graphic selected (Direct Selection) copies just the graphic, uncropped, where it sits on the page and without the frame's stroke, so Paste Into puts the whole image in place; Cut and Delete then remove only the graphic and leave its frame empty. Nested selections copy in their spread coordinates. No readiness percentage change.+- **2026-10-13** · Object effects (Basic Feather, Inner Glow, shadows, glows, bevel, satin, directional and gradient feathers) apply to frames with pasted-in content, on screen and in image exports: the frame, its clipped content and its stroke are one object to the effect. PDF export still has no soft effects for any object. No readiness percentage change.+- **2026-10-13** · Links rows show their source paths; selecting a link shows its full path wrapped inside the panel, so same-named files from different folders can be distinguished. No readiness percentage change.+- **2026-10-13** · The Text Wrap panel is laid out as InDesign's: the wrap buttons with Invert, and the four offsets (Top, Left, Bottom, Right) showing the object's values, with the link button that sets them all the same. It used to show a single offset, always 0. No readiness percentage change.+- **2026-10-13** · Radial gradients stretch with the object's box, as InDesign draws them: by default an ellipse reaching the frame's sides (it was a circle reaching only the longer side), and a Gradient Swatch tool drag keeps the box's proportions; on screen and in PDF. No readiness percentage change.+- **2026-10-13** · The Window menu follows InDesign's order (Arrange, Workspace, then the panels alphabetically with Color, Editorial, Object & Layout, Styles… submenus), and Window › Workspace lists the workspaces as InDesign does, now with Essentials Classic: the Control panel and an icon column of named panel groups. No readiness percentage change.+- **2026-10-14** · In a facing document, pages take their side from their section's page numbers, as InDesign shuffles them: a section that starts at 1 on a left page moves it to the right and the pages after it follow, with their objects. No readiness percentage change.+- **2026-10-14** · The Type menu follows InDesign's order (Size, Character ⌘T, Paragraph ⌥⌘T, Glyphs, the style panels, Notes, footnotes and endnotes, then the insert submenus and Show Hidden Characters); Current Page Number has ⌥⇧⌘N. No readiness percentage change.+- **2026-10-14** · Colour parameters: a bare `{c,m,y,k}` is always read as 0..100, so C 1 is a 1 % tint and no longer+ solid cyan; fractions take the colour's own `{model: "cmyk", …}` form (#910). No readiness percentage change.+- **2026-10-14** · The Tools panel follows InDesign's: Gradient Swatch and Gradient Feather are tools of their own; in two columns Content Collector and Placer, Apply Color / Gradient / None and Normal / Preview each get a button; View Options holds Frame Edges, Rulers, Guides, Smart Guides, Baseline Grid and Hidden Characters; Apply Color (,) and Apply Gradient (.) reuse the last colour and gradient. No readiness percentage change.+- **2026-10-12** · Text threads by hand: click a selected text frame's in or out port to load+ the text cursor, then click a frame to thread it, click empty space for a column-wide frame or+ drag one (it snaps like frame drawing); Shift-click autoflows, Alt-click stays loaded on the+ frame just added; click the linked frame or double-click a port to break the thread.+ `text.thread`, `text.unthread`, `text.removeFromThread` with undo; locked frames and layers+ refuse threads. The alpha gate now waits only on the Primary Text Frame page fixes (#165). No+ readiness percentage change.+- **2026-10-14** · Georgian interface (`ka`, Edit ▸ Interface Language ▸ ქართული): every catalog key+ translated, count captions as `noun: n`.+- **2026-10-13** · Layout ▸ Table of Contents opens a real dialog: title and title style, Include Paragraph Styles and Other Styles lists with Add and Remove, and per style its entry style, page number position (after, before, none), separator and level. Replace Existing regenerates the current table of contents in place; otherwise OK makes a new frame on the page in view. IDML export writes the definition as a TOC style that import reads back, so Update works after a round trip. No readiness percentage change.+- **2026-10-13** · Control-channel clicks and drags validate positive counts and the complete pending-event budget before queuing input (#732). Oversized requests leave pending gestures intact, preventing unbounded click-count allocation. No readiness percentage change.+- **2026-10-13** · Backspace between two consecutive tables, pasting a table next to a table anchor, and pasting several paragraphs right before one keep every table on its own anchor paragraph. Previously a table was dropped or left without its anchor, and the saved file failed to reopen. No readiness percentage change.+- **2026-10-13** · Dialogs and the About window move when you drag their title row, so the page behind them can be seen. A dragged dialog may go partly off-screen, but its title row stays reachable; each dialog opens centred, and again after the window is resized. No readiness percentage change.+- **2026-10-13** · Command scripts look up only a well-formed `$N.path` / `$last.path` reference; other strings starting with `$`, such as a GREP replacement of `$1` and a nonbreaking space, stay as written, and `$$` writes a literal `$` (#749). No readiness percentage change.+- **2026-10-13** · An explicit recovery folder (`file.recovery.save` with `dir`) never overwrites or deletes another running app's checkpoints. Document uids start at 1 in every process, so two apps saving recovery to one chosen folder replaced or removed each other's `<uid>.designcraft`. A run replaces or removes only the entries it wrote or recovered there, refuses an occupied uid, and refuses a folder whose run lock another app holds. No readiness percentage change.+- **2026-10-13** · Path edits (`path.setAnchor`, `path.moveAnchors`, `path.appendAnchor`, `path.reverse`, `path.close`, anchor add/delete/convert, Erase, Smooth and Scissors) refuse a path that is locked, sits in a locked group or on a locked layer (#735). Properties links to the Stroke, Character, Paragraph, Effects, Text Wrap and Info panels open them in a customized panel layout too (#736). No readiness percentage change.+- **2026-10-13** · IDML export keeps parent item overrides: each page lists its overridden parent items and the local copy keeps its link to the parent item, so a reopened IDML file shows only the local copy (#725). No readiness percentage change.+- **2026-10-13** · macOS: a command chosen with the mouse in the menu bar runs at once. It used to wait for the next mouse move or key press over the window, so File › Open, Place and Save As seemed to take 10–20 seconds to open their dialogs. No readiness percentage change.+- **2026-10-13** · Text recomposes when the document baseline grid changes, when a layer holding a text-wrap object is shown or hidden, or when a section's start number, numbering style, prefix or marker changes; the composition cache keyed only on the section count and item identities and kept the old layout. No readiness percentage change.+- **2026-10-13** · Reflowable EPUB and HTML export include tables (header and footer rows, merged cells), footnotes (a linked note after the paragraph that refers to it) and endnotes (a linked section at the end of the book). No readiness percentage change.+ - **2026-10-13** · Word import: table cells read text by the same rules as body text, so deleted text, moved-away text and field codes stay out (#721). Word's Normal comes in as its own paragraph style "Normal" over the document defaults, so text formatted only by Normal keeps its look; it conflicts only with a document's own Normal, and the style map can send it to [Basic Paragraph] (#722). No readiness percentage change.- **2026-10-12** · macOS Dock Quit uses the same unsaved-document prompts as window and menu Quit. Repeated requests keep the current answers; Cancel retains every tab and unsaved recovery checkpoint, and completed Save/Don't Save answers exit through the ordinary event loop. No readiness percentage change.+- **2026-10-12** · Text strokes can sit behind the fill: the stroke lies wholly outside the letters at its full weight on screen, in PNG and in PDF, set from the Properties panel or Character Style Options. IDML `StrokeAlignment` on text imports and exports as this setting, so imported text with outside-aligned strokes keeps its letter shapes (#619). No readiness percentage change.+- **2026-10-12** · Placed Word documents keep their bullets and numbering (#626): `numbering.xml` levels become bullet or numbered paragraphs with Word's number formats, label text, start numbers, restarts and list indents, also when a paragraph style carries the list. No readiness percentage change.- **2026-10-12** · Orderly native exit writes the latest recovery state after finalizing current quit approvals; incomplete or stale plans keep their documents, and Undo to the saved state clears stale recovery. Unavailable or failed recovery is reported. Cancelable macOS Dock Quit remains open (#544). No readiness percentage change.- **2026-10-12** · Recovered documents keep a checkpoint until saved, closed or reverted, including a second crash before autosave. Restarted document IDs and explicit recovery folders preserve other snapshots; failed republishing retains the original. No readiness percentage change.- **2026-10-12** · Book numbering and style updates prepare every chapter before saving. Only closed native chapters are changed; imported IDML remains a read-only style/PDF source. If a later disk write fails, the error names the completed chapters; the batch is not a whole-book transaction. No readiness percentage change.diff --cc crates/textimport/src/docx.rsindex 327979191,e9ecf808c..20101f824--- a/crates/textimport/src/docx.rs+++ b/crates/textimport/src/docx.rs@@@ -221,12 -216,8 +221,14 @@@ struct Ctxfootnotes: HashMap<String, El>,warnings: Vec<String>,next_table: u64,+ numbering: Numbering,+ /// A paragraph style's list (`w:numPr` numId and ilvl, through `w:basedOn`), by style id.+ style_lists: HashMap<String, (Option<String>, Option<String>)>,+ /// The number the model's own list counter is at (it restarts after a paragraph that isn't+ /// in a list), to tell where a numbered paragraph needs an explicit Start At.+ model_counter: u32,+ /// The style of paragraphs without `w:pStyle` (Word's default paragraph style, usually Normal).+ default_para: String,}impl Ctx {@@@ -258,21 -242,18 +260,21 @@@let at = st.len();st.format_paras(at..at, |f| *f = ParaFormat { style: style.clone(), para: attrs.clone(), ..Default::default() });self.inline(e, st, allow_notes);+ if let Some(n) = self.start_at(list.as_ref(), st.len() == at) {+ st.format_paras(at..at, |f| f.para.start_at = Some(Some(n)));+ }}"tbl" => {- let rows: Vec<Vec<String>> = e- .els()- .filter(|r| r.name == "tr")- .map(|r| {- r.els()- .filter(|c| c.name == "tc")- .map(|c| c.els().filter(|p| p.name == "p").map(|p| p.text()).collect::<Vec<_>>().join("\n"))- .collect()- })- .collect();+ let mut rows: Vec<Vec<String>> = Vec::new();+ for r in e.els().filter(|r| r.name == "tr") {+ let mut row = Vec::new();+ for c in r.els().filter(|c| c.name == "tc") {+ let mut paras = Vec::new();+ self.cell_paras(c, &mut paras);+ row.push(paras.join("\n"));+ }+ rows.push(row);+ }if rows.is_empty() {continue;}@@@ -292,35 -273,27 +294,56 @@@}}+ /// The list a paragraph is in (its own `w:numPr`, else its style's), counting it.+ fn list(&mut self, ppr: Option<&El>) -> Option<ListPara> {+ let direct = ppr.and_then(|p| p.child("numPr"));+ let style = ppr.and_then(|p| p.val("pStyle")).and_then(|id| self.style_lists.get(&id));+ let num_id = direct.and_then(|n| n.val("numId")).or_else(|| style.and_then(|s| s.0.clone()))?;+ let ilvl = direct.and_then(|n| n.val("ilvl")).or_else(|| style.and_then(|s| s.1.clone()));+ // A level that isn't a small number is no list.+ let ilvl = ilvl.map_or(Some(0), |l| l.trim().parse::<u32>().ok())?;+ self.numbering.next(num_id.trim(), ilvl)+ }++ /// Start At for a paragraph, so that the model numbers it as Word does: only where the+ /// model's counter (which follows the previous numbered paragraph, and restarts after one+ /// that isn't in a list) would give a different number.+ fn start_at(&mut self, list: Option<&ListPara>, empty: bool) -> Option<u32> {+ let Some(l) = list else {+ self.model_counter = 0;+ return None;+ };+ // Bullets and empty paragraphs leave the counter alone (they show no number).+ if l.attrs.list_type != Some(ListType::Numbers) || empty {+ return None;+ }+ let want = l.number.max(1);+ let next = self.model_counter.saturating_add(1);+ self.model_counter = want;+ (want != next).then_some(want)+ }++ /// The text of each paragraph in a table cell, read by the same run rules as body text.+ /// Cells are plain text, so a page or column break in a cell ends its paragraph.+ fn cell_paras(&mut self, el: &El, out: &mut Vec<String>) {+ for e in el.els() {+ match e.name.as_str() {+ "p" => {+ let mut st = Story::new(StoryId(0));+ self.inline(e, &mut st, false);+ let is_break = |c: char| matches!(c, designcraft_doc::PAGE_BREAK | designcraft_doc::COLUMN_BREAK);+ out.push(st.text.chars().map(|c| if is_break(c) { '\n' } else { c }).collect());+ }+ "sdt" => {+ if let Some(c) = e.child("sdtContent") {+ self.cell_paras(c, out);+ }+ }+ _ => {}+ }+ }+ }+/// Runs (and hyperlinks, fields' results) of a paragraph.fn inline(&mut self, p: &El, st: &mut Story, allow_notes: bool) {for e in p.els() {@@@ -421,22 -362,27 +444,37 @@@ pub fn import(bytes: &[u8]) -> Result<Ifootnotes: HashMap::new(),warnings: vec![],next_table: 0,+ numbering: Numbering::default(),+ style_lists: HashMap::new(),+ model_counter: 0,+ default_para: BASIC_PARAGRAPH.into(),};+ // Lists that can't be read leave plain paragraphs, not a failed import.+ match part_capped(&mut zip, "word/numbering.xml", NUMBERING_LIMIT).and_then(|s| s.map(|s| parse(&s)).transpose()) {+ Ok(Some(n)) => ctx.numbering = Numbering::parse(&n),+ Ok(None) => {}+ Err(_) => ctx.warnings.push("The Word file's list definitions could not be read: lists were imported as plain paragraphs.".into()),+ }let mut para_styles = Vec::new();let mut char_styles = Vec::new();if let Some(styles) = part(&mut zip, "word/styles.xml")?.map(|s| parse(&s)).transpose()? {let ids: HashMap<String, String> =styles.els().filter(|s| s.name == "style").filter_map(|s| Some((s.attr("styleId")?.to_string(), s.val("name")?))).collect();+ ctx.style_lists = style_lists(&styles);+ // Word's document defaults sit beneath every paragraph style that isn't based on another.+ let defaults = styles.child("docDefaults");+ let default_para = para_attrs(defaults.and_then(|d| d.child("pPrDefault")).and_then(|d| d.child("pPr")));+ let default_chars = run_attrs(defaults.and_then(|d| d.child("rPrDefault")).and_then(|d| d.child("rPr")));+ let is_para = |s: &&El| s.name == "style" && s.attr("type").unwrap_or("paragraph") == "paragraph";+ let default_id = styles+ .els()+ .filter(is_para)+ .find(|s| matches!(s.attr("default"), Some("1" | "true" | "on")))+ .or_else(|| styles.els().filter(is_para).find(|s| s.attr("styleId") == Some("Normal")))+ .and_then(|s| s.attr("styleId"));+ if let Some(name) = default_id.and_then(|id| ids.get(id)) {+ ctx.default_para = name.clone();+ }for s in styles.els().filter(|s| s.name == "style") {let (Some(id), Some(name)) = (s.attr("styleId"), s.val("name")) else { continue };let kind = s.attr("type").unwrap_or("paragraph");@@@ -614,200 -560,44 +657,241 @@@ mod testsassert_eq!(i.story.text, "Kept text. MOVED HERE. Plain INSERTED\nEnd.");}+ /// A paragraph in a Word list: `w:numPr` with `numId` and, unless `None`, `ilvl`.+ fn list_p(num_id: &str, ilvl: Option<&str>, text: &str) -> String {+ let ilvl = ilvl.map(|l| format!(r#"<w:ilvl w:val="{l}"/>"#)).unwrap_or_default();+ format!(r#"<w:p><w:pPr><w:numPr>{ilvl}<w:numId w:val="{num_id}"/></w:numPr></w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#)+ }++ fn plain_p(text: &str) -> String {+ format!(r#"<w:p><w:r><w:t>{text}</w:t></w:r></w:p>"#)+ }++ fn lists_docx(numbering: &str, styles: &str, body: &[String]) -> Imported {+ let document = format!(r#"<w:document {W}><w:body>{}</w:body></w:document>"#, body.concat());+ let i = import(&docx_parts(&[("word/document.xml", &document), ("word/styles.xml", styles), ("word/numbering.xml", numbering)])).unwrap();+ i.story.check().unwrap();+ i+ }++ /// The label the model gives paragraph `i` when its number is `n`.+ fn label(st: &Story, i: usize, n: u32) -> String {+ let mut p = designcraft_doc::ParaProps::default();+ p.apply(&st.paras[i].para);+ match p.list_type {+ ListType::Numbers => p.number_label(n),+ ListType::Bullets => p.bullet_label(),+ ListType::None => String::new(),+ }+ }++ /// Regression (#626): pandoc's Markdown list example lost its bullets and numbers.+ #[test]+ fn bullets_and_numbers_from_numbering_xml() {+ let numbering = format!(+ r#"<w:numbering {W}>+ <w:abstractNum w:abstractNumId="990"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="bullet"/><w:lvlText w:val="•"/>+ <w:pPr><w:ind w:left="480" w:hanging="480"/></w:pPr></w:lvl></w:abstractNum>+ <w:abstractNum w:abstractNumId="991"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/>+ <w:pPr><w:ind w:left="480" w:hanging="480"/></w:pPr></w:lvl></w:abstractNum>+ <w:num w:numId="1000"><w:abstractNumId w:val="990"/></w:num>+ <w:num w:numId="1001"><w:abstractNumId w:val="991"/><w:lvlOverride w:ilvl="0"><w:startOverride w:val="1"/></w:lvlOverride></w:num>+ </w:numbering>"#+ );+ let body = [+ plain_p("Intro paragraph."),+ list_p("1000", Some("0"), "first item"),+ list_p("1000", Some("0"), "second item"),+ list_p("1001", Some("0"), "step one"),+ list_p("1001", Some("0"), "step two"),+ ];+ let st = lists_docx(&numbering, "", &body).story;+ let types: Vec<Option<ListType>> = st.paras.iter().map(|p| p.para.list_type).collect();+ assert_eq!(types, [None, Some(ListType::Bullets), Some(ListType::Bullets), Some(ListType::Numbers), Some(ListType::Numbers)]);+ assert_eq!(label(&st, 1, 1), "•\t");+ assert_eq!(st.paras[3].para.number_style, Some(designcraft_doc::NumberStyle::Arabic));+ assert_eq!((label(&st, 3, 1), label(&st, 4, 2)), ("1.\t".to_string(), "2.\t".to_string()));+ // The model's own counter already starts at 1 and carries on: no Start At needed.+ assert_eq!((st.paras[3].para.start_at, st.paras[4].para.start_at), (None, None));+ assert_eq!((st.paras[1].para.left_indent, st.paras[1].para.first_line_indent), (Some(24.0), Some(-24.0)));+ }++ /// Level 1 inside level 0, parent numbers in a label, numbering that carries on past a plain+ /// paragraph, and a `num` with a start override restarting.+ #[test]+ fn nested_levels_and_restarts() {+ let numbering = format!(+ r#"<w:numbering {W}>+ <w:abstractNum w:abstractNumId="1">+ <w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/></w:lvl>+ <w:lvl w:ilvl="1"><w:start w:val="1"/><w:numFmt w:val="lowerLetter"/><w:lvlText w:val="%2)"/><w:suff w:val="space"/>+ <w:pPr><w:ind w:left="1440" w:hanging="360"/></w:pPr></w:lvl>+ <w:lvl w:ilvl="2"><w:start w:val="1"/><w:numFmt w:val="upperRoman"/><w:lvlText w:val="%1.%2.%3"/></w:lvl>+ </w:abstractNum>+ <w:num w:numId="1"><w:abstractNumId w:val="1"/></w:num>+ <w:num w:numId="2"><w:abstractNumId w:val="1"/><w:lvlOverride w:ilvl="0"><w:startOverride w:val="1"/></w:lvlOverride></w:num>+ <w:num w:numId="3"><w:abstractNumId w:val="1"/></w:num>+ </w:numbering>"#+ );+ let body = [+ list_p("1", None, "A"),+ list_p("1", Some("1"), "B"),+ list_p("1", Some("1"), "C"),+ list_p("1", Some("2"), "D"),+ list_p("1", Some("0"), "E"),+ plain_p("Between"),+ list_p("1", Some("0"), "F"),+ list_p("2", Some("0"), "G"),+ list_p("3", Some("0"), "H"),+ ];+ let st = lists_docx(&numbering, "", &body).story;+ let start: Vec<Option<Option<u32>>> = st.paras.iter().map(|p| p.para.start_at).collect();+ // Word's numbers: 1, a, b, 1.b.I, 2, –, 3, 1 (own counter), 4 (shares numId 1's). E's 2+ // follows the model's counter (1 after D).+ assert_eq!(start, [None, Some(Some(1)), None, Some(Some(1)), None, None, Some(Some(3)), Some(Some(1)), Some(Some(4))]);+ assert_eq!(label(&st, 1, 1), "a) ");+ assert_eq!(label(&st, 3, 1), "1.b.I\t");+ assert_eq!(st.paras[1].para.left_indent, Some(72.0));+ assert_eq!(st.paras[1].para.first_line_indent, Some(-18.0));+ }++ /// A paragraph style's `w:numPr` (inherited through `w:basedOn`) makes its paragraphs a list;+ /// numId 0 on a paragraph takes it out of the list.+ #[test]+ fn style_lists_and_num_id_zero() {+ let numbering = format!(+ r#"<w:numbering {W}>+ <w:abstractNum w:abstractNumId="7">+ <w:lvl w:ilvl="0"><w:numFmt w:val="bullet"/><w:lvlText w:val=""/><w:rPr><w:rFonts w:ascii="Symbol" w:hAnsi="Symbol"/></w:rPr></w:lvl>+ <w:lvl w:ilvl="1"><w:numFmt w:val="bullet"/><w:lvlText w:val="o"/><w:rPr><w:rFonts w:ascii="Courier New"/></w:rPr></w:lvl>+ </w:abstractNum>+ <w:num w:numId="5"><w:abstractNumId w:val="7"/></w:num>+ </w:numbering>"#+ );+ let styles = format!(+ r#"<w:styles {W}>+ <w:style w:type="paragraph" w:styleId="ListBullet"><w:name w:val="List Bullet"/><w:pPr><w:numPr><w:numId w:val="5"/></w:numPr></w:pPr></w:style>+ <w:style w:type="paragraph" w:styleId="ListBullet2"><w:name w:val="List Bullet 2"/><w:basedOn w:val="ListBullet"/>+ <w:pPr><w:numPr><w:ilvl w:val="1"/></w:numPr></w:pPr></w:style>+ </w:styles>"#+ );+ let styled =+ |id: &str, extra: &str, text: &str| format!(r#"<w:p><w:pPr><w:pStyle w:val="{id}"/>{extra}</w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#);+ let body = [+ styled("ListBullet", "", "one"),+ styled("ListBullet2", "", "two"),+ styled("ListBullet", r#"<w:numPr><w:ilvl w:val="0"/><w:numId w:val="0"/></w:numPr>"#, "not a list"),+ ];+ let st = lists_docx(&numbering, &styles, &body).story;+ assert_eq!(label(&st, 0, 1), "•\t");+ assert_eq!(label(&st, 1, 1), "◦\t");+ assert_eq!(st.paras[2].para.list_type, None);+ assert_eq!(st.paras[2].style, "List Bullet");+ }++ /// Hostile list definitions: missing abstractNums and levels, huge or negative levels and+ /// starts, a long label, a `w:basedOn` cycle. No panic; what can't be a list is plain.+ #[test]+ fn hostile_numbering_falls_back_to_plain_paragraphs() {+ let long = "x".repeat(10_000);+ let numbering = format!(+ r#"<w:numbering {W}>+ <w:abstractNum w:abstractNumId="1">+ <w:lvl w:ilvl="0"><w:start w:val="99999999999999"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1{long}%9%"/></w:lvl>+ <w:lvl w:ilvl="99999999999999"><w:numFmt w:val="decimal"/></w:lvl>+ <w:lvl w:ilvl="-1"><w:numFmt w:val="decimal"/></w:lvl>+ <w:lvl w:ilvl="3"><w:start w:val="-5"/><w:numFmt w:val="ordinalText"/><w:lvlText w:val="%4^"/><w:lvlRestart w:val="99"/></w:lvl>+ </w:abstractNum>+ <w:num w:numId="1"><w:abstractNumId w:val="1"/></w:num>+ <w:num w:numId="2"><w:abstractNumId w:val="404"/></w:num>+ <w:num w:numId="3"/>+ <w:num><w:abstractNumId w:val="1"/></w:num>+ </w:numbering>"#+ );+ let styles = format!(+ r#"<w:styles {W}>+ <w:style w:type="paragraph" w:styleId="A"><w:name w:val="A"/><w:basedOn w:val="B"/></w:style>+ <w:style w:type="paragraph" w:styleId="B"><w:name w:val="B"/><w:basedOn w:val="A"/></w:style>+ </w:styles>"#+ );+ let body = [+ list_p("2", None, "missing abstractNum"),+ list_p("3", None, "num without abstractNum"),+ list_p("404", None, "unknown numId"),+ list_p("1", Some("99999999999999"), "huge level"),+ list_p("1", Some("9"), "level 9"),+ list_p("1", Some("-1"), "negative level"),+ list_p("1", Some("1"), "undefined level"),+ r#"<w:p><w:pPr><w:pStyle w:val="A"/><w:numPr><w:ilvl w:val="0"/></w:numPr></w:pPr><w:r><w:t>cycle</w:t></w:r></w:p>"#.to_string(),+ list_p("1", None, "huge start"),+ list_p("1", Some("3"), "negative start"),+ ];+ let st = lists_docx(&numbering, &styles, &body).story;+ assert!(st.paras[..8].iter().all(|p| p.para.list_type.is_none()), "{:?}", st.paras);+ assert_eq!(st.paras[8].para.start_at, Some(Some(u32::MAX)));+ let expr = st.paras[8].para.number_expression.clone().unwrap_or_default();+ assert!(expr.starts_with("^#x") && expr.chars().count() < 80, "{expr}");+ // A start below 0 counts from 0, which the model shows as 1; `^` in a label is literal.+ assert_eq!(label(&st, 9, 1), "1^\t");+ // Unreadable list definitions leave plain paragraphs and a warning, not a failed import.+ let document = format!(r#"<w:document {W}><w:body>{}</w:body></w:document>"#, list_p("1", None, "x"));+ let i = import(&docx_parts(&[("word/document.xml", &document), ("word/numbering.xml", "<w:numbering></w:num>")])).unwrap();+ assert_eq!(i.story.paras[0].para.list_type, None);+ assert_eq!(i.warnings.len(), 1);+ }++ #[test]+ fn an_element_with_many_attributes_parses_in_linear_time() {+ // RUSTSEC-2026-0194: before quick-xml 0.41 the duplicate-attribute check compared each name with every+ // earlier one on the element, so a crafted .docx/.xlsx with one huge tag hung the import (O(N²)).+ let attrs: String = (0..100_000).map(|i| format!(" w:a{i}=\"{i}\"")).collect();+ let xml = format!("<w:document><w:body><w:p{attrs}/></w:body></w:document>");+ let started = std::time::Instant::now();+ let doc = parse(&xml).unwrap();+ assert!(started.elapsed() < std::time::Duration::from_secs(5), "parse took {:?}", started.elapsed());+ let p = doc.child("body").and_then(|b| b.child("p")).unwrap();+ assert_eq!(p.attr("a0"), Some("0"));+ assert_eq!(p.attr("a99999"), Some("99999"));+ }+++ #[test]+ fn table_cells_read_text_like_body_paragraphs() {+ // Regression (#721): cells took every text node, so deleted text, move sources and field+ // instructions showed up in the table.+ let para = r#"<w:p><w:r><w:t xml:space="preserve">kept </w:t></w:r>+ <w:del w:id="1" w:author="A"><w:r><w:delText>GONE</w:delText></w:r></w:del>+ <w:moveFrom w:id="2" w:author="A"><w:r><w:t>MOVED AWAY</w:t></w:r></w:moveFrom>+ <w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> PAGE </w:instrText></w:r>+ <w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>7</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>"#;+ let document = format!(r#"<w:document {W}><w:body>{para}<w:tbl><w:tr><w:tc>{para}<w:p/></w:tc></w:tr></w:tbl></w:body></w:document>"#);+ let i = import(&docx(&document, "", "")).unwrap();+ assert!(i.story.text.starts_with("kept 7"), "{:?}", i.story.text);+ let cell = &i.story.tables.values().next().unwrap().cell(0, 0).unwrap().text;+ assert_eq!(cell.text, "kept 7\n");+ }++ #[test]+ fn normal_is_its_own_style_over_the_document_defaults() {+ // Regression (#722): text formatted only by Normal and the document defaults lost it.+ let styles = format!(+ r#"<w:styles {W}><w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val="22"/></w:rPr></w:rPrDefault>+ <w:pPrDefault><w:pPr><w:spacing w:after="160"/></w:pPr></w:pPrDefault></w:docDefaults>+ <w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:rPr><w:rFonts w:ascii="Georgia"/><w:sz w:val="26"/></w:rPr></w:style>+ <w:style w:type="paragraph" w:styleId="Quote"><w:name w:val="Quote"/><w:basedOn w:val="Normal"/><w:rPr><w:i/></w:rPr></w:style>+ </w:styles>"#+ );+ let document = format!(+ r#"<w:document {W}><w:body><w:p><w:r><w:t>Plain</w:t></w:r></w:p>+ <w:p><w:pPr><w:pStyle w:val="Quote"/></w:pPr><w:r><w:t>Quoted</w:t></w:r></w:p></w:body></w:document>"#+ );+ let i = import(&docx(&document, &styles, "")).unwrap();+ assert_eq!(i.story.paras[0].style, "Normal");+ let normal = i.para_styles.iter().find(|s| s.name == "Normal").unwrap();+ assert_eq!(normal.chars.size, Some(13.0), "Normal's size wins over the default");+ assert_eq!(normal.chars.font_family.as_deref(), Some("Georgia"));+ assert_eq!(normal.para.space_after, Some(8.0), "from the document defaults");+ let quote = i.para_styles.iter().find(|s| s.name == "Quote").unwrap();+ assert_eq!(quote.based_on.as_deref(), Some("Normal"));+ assert_eq!(quote.chars.size, None, "inherited from Normal, not copied");+ }}