From c20635aacfcbb9c628630a065e5b8e7917aede30 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Wed, 14 Oct 2026 12:22:11 +0200 Subject: [PATCH 0001/1349] Pages panel: spread labels and section markers as InDesign's; it follows the page in view MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Chris Nielsen's "Numbering Page Sections" reads the Pages panel all along: InDesign labels each spread ("2–3", "2, 1" where a section starts inside it, "8, A", "ii–iii"), puts a small triangle over each section's first page, and the panel scrolls to the page selected ("the pages panel jumps down there", 6:46). DesignCraft named each page under it ("2 1") and drew its triangle over the spread in view. - One label per spread (spread_label): a range with an en dash for pages numbered on in one section, the names apart when a section starts inside it. Positions under absolute numbering. A blue badge marks the spread in view; a click on the label goes to the spread. - A triangle above every page that starts a section (page 1 included). - The panel scrolls to the spread of the page in view when that page changes. - Page thumbnails are named for screen readers ("Page 1"). Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 1 + crates/ui-egui/src/panels/pages.rs | 130 +++++++++++++++++++++++++---- 2 files changed, 117 insertions(+), 14 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index c60a04107..4db547830 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -128,6 +128,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-10-14** · The Pages panel labels spreads as InDesign does ("2–3", "2, 1" across a section start, "8, A"), marks each section's first page with a triangle, and scrolls to the page in view. 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 diff --git a/crates/ui-egui/src/panels/pages.rs b/crates/ui-egui/src/panels/pages.rs index ae323225b..2fa04b9ff 100644 --- a/crates/ui-egui/src/panels/pages.rs +++ b/crates/ui-egui/src/panels/pages.rs @@ -51,6 +51,25 @@ enum PageDrag { Parent(Option), } +/// A spread's label under its thumbnails, as InDesign's: one name for a single page, "2–3" for +/// pages numbered on in one section (an en dash), and the names apart ("2, 1", "8, A") when a section starts +/// inside the spread. +pub(crate) fn spread_label(app: &DesignApp, doc: &designcraft_doc::Document, first: usize, n: usize) -> String { + let names: Vec = (first..first + n).map(|abs| app.session.page_label(abs)).collect(); + let starts = |abs: usize| abs == 0 || doc.sections.iter().any(|s| s.start == abs); + match (names.first(), names.last()) { + (Some(a), Some(b)) if names.len() > 1 => { + if !app.session.prefs.absolute_page_numbers && (first + 1..first + n).any(starts) { + names.join(", ") + } else { + format!("{a}\u{2013}{b}") + } + } + (Some(a), _) => a.clone(), + _ => String::new(), + } +} + /// Selected-page tint (multiplied over the thumbnail). const SELECTED_TINT: Color32 = Color32::from_rgb(0x88, 0xc7, 0xfb); /// Page-number badge of the selected page. @@ -112,18 +131,19 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { // ---- Document spreads. let cur = crate::canvas::current_page(app).unwrap_or(0); let cur_spread = doc.page_loc(cur).map(|l| l.0); + let followed_id = egui::Id::new("pages_panel_followed"); let center = ui.available_width() / 2.0; let dragging = egui::DragAndDrop::has_any_payload(ui.ctx()); for (si, sp) in doc.spreads.iter().enumerate() { let first = doc.first_page_of_spread(si); let scale = THUMB_H / doc.settings.page_height.max(1.0) as f32; let spine = sp.spine_x() as f32; - let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), 8.0 + THUMB_H + 22.0), Sense::hover()); + let (row, row_resp) = ui.allocate_exact_size(vec2(ui.available_width(), 8.0 + THUMB_H + 22.0), Sense::hover()); let top = row.min.y + 8.0; - // Marker above the current spread. - if cur_spread == Some(si) && !editing_parents { - let c = egui::pos2(row.min.x + center, row.min.y + 3.5); - ui.painter().add(egui::Shape::convex_polygon(vec![c + vec2(-5.0, -3.0), c + vec2(5.0, -3.0), c + vec2(0.0, 3.0)], t.icon, Stroke::NONE)); + // The panel follows the page in view (InDesign scrolls to the selected page). + if cur_spread == Some(si) && !editing_parents && ui.data(|d| d.get_temp::(followed_id)) != Some(cur) { + row_resp.scroll_to_me(None); + ui.data_mut(|d| d.insert_temp(followed_id, cur)); } for (pi, p) in sp.pages.iter().enumerate() { let abs = first + pi; @@ -138,6 +158,22 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { ui.painter().rect_filled(pr, 0.0, tint); } ui.painter().rect_stroke(pr, 0.0, Stroke::new(0.5, Color32::from_gray(0x4a)), StrokeKind::Outside); + // A section starts here: InDesign's small triangle above the page. + if abs == 0 || doc.sections.iter().any(|s| s.start == abs) { + let c = egui::pos2(pr.center().x, row.min.y + 4.0); + ui.painter().add(egui::Shape::convex_polygon( + vec![c + vec2(-4.5, -3.0), c + vec2(4.5, -3.0), c + vec2(0.0, 3.0)], + t.icon, + Stroke::NONE, + )); + } + resp.widget_info(|| { + egui::WidgetInfo::labeled( + egui::WidgetType::Button, + true, + format!("{} {}", crate::i18n::tr(&app.ui.language, "Page"), app.session.page_label(abs)), + ) + }); // Parent prefix in the outer top corner (black on white). if let Some(pid) = p.parent && let Some(pp) = doc.parents.iter().find(|x| x.id == pid) @@ -172,15 +208,20 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { crate::canvas::go_to_page(app, abs); } resp.context_menu(|ui| page_menu(app, ui, &doc, abs, si)); - // Page number under the page: white on a blue badge when selected. - let name = app.session.page_label(abs); - let g = ui.painter().layout_no_wrap(name, crate::theme::semibold(11.0), Color32::WHITE); - let c = egui::pos2(pr.center().x, pr.max.y + 11.0); - if selected { - let br = egui::Rect::from_center_size(c, vec2(g.size().x.max(7.0) + 7.0, 12.5)); - ui.painter().rect_filled(br, 0.0, BADGE); - } - ui.painter().galley(c - g.size() / 2.0, g, Color32::WHITE); + } + // The spread's label under its pages: white on a blue badge when it holds the page in view. + let label = spread_label(app, &doc, first, sp.pages.len()); + let g = ui.painter().layout_no_wrap(label.clone(), crate::theme::semibold(11.0), Color32::WHITE); + let c = egui::pos2(row.min.x + center, top + THUMB_H + 11.0); + let br = egui::Rect::from_center_size(c, vec2(g.size().x.max(7.0) + 7.0, 12.5)); + if cur_spread == Some(si) && !editing_parents { + ui.painter().rect_filled(br, 0.0, BADGE); + } + ui.painter().galley(c - g.size() / 2.0, g, Color32::WHITE); + let lr = ui.interact(br, ui.id().with(("spread_label", si)), Sense::click()); + lr.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, &label)); + if lr.clicked() { + crate::canvas::go_to_page(app, first); } } ui.add_space(6.0); @@ -289,3 +330,64 @@ fn drag_ghost(ui: &egui::Ui, label: &str, t: &Tokens) { painter.rect(r, 2.0, t.panel_darker, Stroke::new(1.0, t.field_border), StrokeKind::Inside); painter.galley(r.min + vec2(5.0, 3.0), g, t.text_strong); } + +#[cfg(test)] +mod spread_label_tests { + use egui_kittest::{Harness, kittest::Queryable}; + use serde_json::json; + + use super::*; + + fn app() -> DesignApp { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"facingPages": true, "pages": 9})).unwrap(); + app + } + + fn labels(app: &DesignApp) -> Vec { + let doc = app.session.doc().unwrap().doc.clone(); + (0..doc.spreads.len()).map(|si| spread_label(app, &doc, doc.first_page_of_spread(si), doc.spreads[si].pages.len())).collect() + } + + #[test] + fn spreads_are_labelled_as_indesign_labels_them() { + // Chris Nielsen's "Numbering Page Sections": sections starting at 1 on pages 3 and 7, + // the second in letters, label their spreads "2, 1" and "6, A". + let mut app = app(); + assert_eq!(labels(&app), ["1", "2–3", "4–5", "6–7", "8–9"]); + app.run("layout.section", json!({"page": 3, "startNumber": 1})).unwrap(); + app.run("layout.section", json!({"page": 7, "startNumber": 1, "style": "upperLetters"})).unwrap(); + assert_eq!(labels(&app), ["1", "2, 1", "2–3", "4, A", "B–C"]); + // Absolute numbering: positions, always a range. + app.session.prefs.absolute_page_numbers = true; + assert_eq!(labels(&app), ["1", "2–3", "4–5", "6–7", "8–9"]); + } + + #[test] + fn the_panel_shows_spread_labels_and_a_click_on_one_goes_to_its_spread() { + let mut app = app(); + app.run("layout.section", json!({"page": 3, "startNumber": 1})).unwrap(); + // The canvas the panel's clicks move (not drawn here). + app.canvas_rect = Some(egui::Rect::from_min_size(egui::pos2(0.0, 0.0), vec2(1000.0, 800.0))); + let mut h = Harness::builder().with_size(vec2(260.0, 900.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let key = egui::Id::new("test_fonts"); + if ui.data(|d| d.get_temp::(key)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(key, true)); + return; + } + egui::ScrollArea::vertical().show(ui, |ui| show(app, ui)); + }, + app, + ); + h.run_steps(3); + let _ = h.get_by_label("2, 1"); + assert!(h.query_by_label("2 1").is_none()); + // Each page is named for screen readers: two pages are numbered 1. + assert_eq!(h.query_all_by_label("Page 1").count(), 2); + h.get_by_label("2–3").click(); + h.run_steps(3); + assert_eq!(h.state().session.doc().unwrap().doc.page_loc(crate::canvas::current_page(h.state()).unwrap()).unwrap().0, 2); + } +} From be0fbb75c047bb3579a90625456aa29919df314b Mon Sep 17 00:00:00 2001 From: moppeeer Date: Wed, 14 Oct 2026 12:32:25 +0200 Subject: [PATCH 0002/1349] Numbering & Section Options opens as New Section on a page without one, as InDesign's Chris Nielsen's "Numbering Page Sections" (4:43): with page 3 selected, the Pages panel menu's Numbering & Section Options opens InDesign's New Section window: Start Section checked, Automatic Page Numbering chosen and 1 offered in Start Page Numbering at, which stays editable. The window here was titled Numbering & Section Options, Start Section was off and the field showed the page's current number, greyed out. - Opened on a page that doesn't start a section, the window is New Section: Start Section on and 1 offered; on a section's first page it is Numbering & Section Options, as before. - Start Page Numbering at and Start Chapter Numbering at stay editable; typing a number chooses that option. - "New Section" translated. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 1 + crates/ui-egui/src/dialogs.rs | 50 +++++++++++++++++++++++++++ crates/ui-egui/src/i18n.rs | 1 + crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/uk.rs | 1 + crates/ui-egui/src/section_options.rs | 24 ++++++++++--- 9 files changed, 76 insertions(+), 5 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 805dfeb6c..f9dfe361a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -129,6 +129,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-10-14** · Numbering & Section Options opened on a page that doesn't start a section is New Section, as in InDesign: Start Section on, 1 offered, and the start numbers stay editable (typing one chooses it). 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** · 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. diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index c56bf267e..26c339e72 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1130,6 +1130,8 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { "insertTable" => crate::i18n::tr(&app.ui.language, "Create Table"), "textFrameOptions" => crate::i18n::tr(&app.ui.language, "Text Frame Options"), "documentSetup" => crate::i18n::tr(&app.ui.language, "Document Setup"), + // On a page that doesn't start a section yet, InDesign titles it New Section. + "numberingSection" if d.b("newSection") => crate::i18n::tr(&app.ui.language, "New Section"), "numberingSection" => crate::i18n::tr(&app.ui.language, "Numbering & Section Options…").trim_end_matches('…'), "findChange" => crate::i18n::tr(&app.ui.language, "Find/Change"), "paragraphStyleOptions" => crate::i18n::tr(&app.ui.language, "Paragraph Style Options"), @@ -4156,6 +4158,54 @@ mod tests { } } + #[test] + fn on_a_page_without_a_section_the_window_is_new_section() { + // Chris Nielsen's "Numbering Page Sections" (4:43): page 3 selected, the Pages panel menu's + // Numbering & Section Options opens New Section with Start Section on and 1 offered. + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 6, "facingPages": true})).unwrap(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 800.0))); + crate::canvas::go_to_page(&mut app, 2); + crate::menus::activate(&mut app, "layout.section", &Value::Null); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!( + (d.n("page"), d.b("newSection"), d.b("startSection"), d.b("automatic"), d.s("startNumber")), + (Some(3.0), true, true, true, "1".into()) + ); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0)); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + visible_label(&labels, screen, "New Section"); + // Typing a number in the field chooses Start Page Numbering at; OK: page 3 is page 2. + let field = visible_label(&labels, screen, "1"); + click_dialog(&mut app, &ctx, screen, field.center()); + dialog_frame( + &mut app, + &ctx, + screen, + vec![ + egui::Event::Key { key: egui::Key::End, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }, + egui::Event::Key { key: egui::Key::Backspace, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }, + egui::Event::Text("2".into()), + ], + ); + assert!(!app.ui.dialog.as_ref().unwrap().b("automatic"), "typing chose Start Page Numbering at"); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "OK").center()); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.active().unwrap().doc.page_name(2), "2"); + // Opened again on that page, it is Numbering & Section Options, showing the section. + crate::menus::activate(&mut app, "layout.section", &Value::Null); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.b("newSection"), d.b("startSection"), d.b("automatic"), d.s("startNumber")), (false, true, false, "2".into())); + let labels = (0..4).map(|_| dialog_frame(&mut app, &ctx, screen, vec![])).last().unwrap(); + visible_label(&labels, screen, "Numbering & Section Options"); + assert!(!labels.iter().any(|(t, _, _)| t == "New Section")); + } + #[test] fn preferences_sidebar_scroll_keeps_selected_options_visible() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index bff4e0bd8..2d715ffbe 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -55,6 +55,7 @@ const TABLE: &[(&str, [&str; 5])] = &[ ("Cut", ["Ausschneiden", "Couper", "Cortar", "カット", "剪切"]), ("Copy", ["Kopieren", "Copier", "Copiar", "コピー", "复制"]), ("Paste", ["Einfügen", "Coller", "Pegar", "ペースト", "粘贴"]), + ("New Section", ["Neuer Abschnitt", "Nouvelle section", "Nueva sección", "新規セクション", "新建章节"]), ("Reverse Path", ["Pfadrichtung umkehren", "Inverser le tracé", "Invertir trazado", "パスの方向反転", "反转路径"]), ("Set Anchor", ["Ankerpunkt festlegen", "Définir le point d’ancrage", "Definir punto de ancla", "アンカーポイントを設定", "设置锚点"]), ("Clear", ["Löschen", "Effacer", "Borrar", "消去", "清除"]), diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index a182d09ec..f40ed5518 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -30,6 +30,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "قص"), ("Copy", "نسخ"), ("Paste", "لصق"), + ("New Section", "قسم جديد"), ("Reverse Path", "عكس المسار"), ("Set Anchor", "تعيين نقطة الارتساء"), ("Clear", "مسح"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index aa8963f2c..f96181b3b 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -28,6 +28,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Taglia"), ("Copy", "Copia"), ("Paste", "Incolla"), + ("New Section", "Nuova sezione"), ("Reverse Path", "Inverti tracciato"), ("Set Anchor", "Imposta ancoraggio"), ("Clear", "Cancella"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 642b4a4c0..fdfcf0534 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -30,6 +30,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "カット"), ("Copy", "コピー"), ("Paste", "ペースト"), + ("New Section", "新規セクション"), ("Reverse Path", "パスの方向反転"), ("Set Anchor", "アンカーポイントを設定"), ("Clear", "消去"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 982dfb20d..f144bbf2a 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -31,6 +31,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Recortar"), ("Copy", "Copiar"), ("Paste", "Colar"), + ("New Section", "Nova seção"), ("Reverse Path", "Inverter demarcador"), ("Set Anchor", "Definir ponto de ancoragem"), ("Clear", "Limpar"), diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index f3bc8fb35..a133bd753 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -31,6 +31,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Вирізати"), ("Copy", "Копіювати"), ("Paste", "Вставити"), + ("New Section", "Новий розділ"), ("Reverse Path", "Розвернути контур"), ("Set Anchor", "Задати прив’язку"), ("Clear", "Очистити"), diff --git a/crates/ui-egui/src/section_options.rs b/crates/ui-egui/src/section_options.rs index 899b9fbed..428f60828 100644 --- a/crates/ui-egui/src/section_options.rs +++ b/crates/ui-egui/src/section_options.rs @@ -36,13 +36,17 @@ pub(crate) fn open(app: &mut DesignApp) { let doc = &st.doc; let page = current.min(doc.page_count().saturating_sub(1)); let own = doc.sections.iter().find(|s| s.start == page); - // A new section starts from the one the page is in. + // A new section starts from the one the page is in. As in InDesign, the window opened on a + // page that doesn't start a section is New Section: Start Section checked, Start Page + // Numbering at offering 1, Automatic Page Numbering chosen. let base = own.or_else(|| doc.section_of(page)); + let new = page != 0 && own.is_none(); let fields = json!({ "page": page + 1, - "startSection": page == 0 || own.is_some(), + "newSection": new, + "startSection": true, "automatic": own.is_none_or(|s| s.start_number.is_none()), - "startNumber": doc.page_number(page).to_string(), + "startNumber": if new { "1".to_string() } else { doc.page_number(page).to_string() }, "prefix": base.map(|s| s.prefix.clone()).unwrap_or_default(), "style": base.map(|s| s.style).unwrap_or_default(), "marker": base.map(|s| s.marker.clone()).unwrap_or_default(), @@ -160,7 +164,12 @@ pub(crate) fn body(app: &DesignApp, ui: &mut Ui, d: &mut Dialog) { if ui.radio(!automatic, crate::rtl::widget(ui, tr("Start Page Numbering at:"))).clicked() { d.fields.insert("automatic".into(), json!(false)); } - ui.add_enabled_ui(!automatic, |ui| text(ui, d, "startNumber", FIELD_W)); + // As in InDesign, the number stays editable; typing one chooses Start Page Numbering at. + let mut n = d.s("startNumber"); + if ui.add(egui::TextEdit::singleline(&mut n).desired_width(FIELD_W)).changed() { + d.fields.insert("startNumber".into(), Value::String(n)); + d.fields.insert("automatic".into(), json!(false)); + } }); ui.add_space(4.0); group(ui, rtl, tr("Page Numbering"), |ui| { @@ -200,7 +209,12 @@ pub(crate) fn body(app: &DesignApp, ui: &mut Ui, d: &mut Dialog) { } }); if value == ChapterSource::UserDefined { - ui.add_enabled_ui(source == value, |ui| text(ui, d, "chapterStart", FIELD_W)); + // Editable whichever is chosen, as in InDesign; typing a number chooses it. + let mut n = d.s("chapterStart"); + if ui.add(egui::TextEdit::singleline(&mut n).desired_width(FIELD_W)).changed() { + d.fields.insert("chapterStart".into(), Value::String(n)); + d.fields.insert("chapterSource".into(), json!(value)); + } } }); } From d70093244692d55e57cecbb46dddf9835dfb5162 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Wed, 14 Oct 2026 14:07:17 +0200 Subject: [PATCH 0003/1349] New Section test: start page 3 at 5, an odd number, so it holds with #889's facing-page sides Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 26c339e72..a289d4005 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -4179,7 +4179,8 @@ mod tests { } let labels = dialog_frame(&mut app, &ctx, screen, vec![]); visible_label(&labels, screen, "New Section"); - // Typing a number in the field chooses Start Page Numbering at; OK: page 3 is page 2. + // Typing a number in the field chooses Start Page Numbering at; OK: page 3 is page 5 (odd, + // so a facing page stays on the right). let field = visible_label(&labels, screen, "1"); click_dialog(&mut app, &ctx, screen, field.center()); dialog_frame( @@ -4189,18 +4190,18 @@ mod tests { vec![ egui::Event::Key { key: egui::Key::End, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }, egui::Event::Key { key: egui::Key::Backspace, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }, - egui::Event::Text("2".into()), + egui::Event::Text("5".into()), ], ); assert!(!app.ui.dialog.as_ref().unwrap().b("automatic"), "typing chose Start Page Numbering at"); let labels = dialog_frame(&mut app, &ctx, screen, vec![]); click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "OK").center()); assert!(app.ui.dialog.is_none()); - assert_eq!(app.session.active().unwrap().doc.page_name(2), "2"); + assert_eq!(app.session.active().unwrap().doc.page_name(2), "5"); // Opened again on that page, it is Numbering & Section Options, showing the section. crate::menus::activate(&mut app, "layout.section", &Value::Null); let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.b("newSection"), d.b("startSection"), d.b("automatic"), d.s("startNumber")), (false, true, false, "2".into())); + assert_eq!((d.b("newSection"), d.b("startSection"), d.b("automatic"), d.s("startNumber")), (false, true, false, "5".into())); let labels = (0..4).map(|_| dialog_frame(&mut app, &ctx, screen, vec![])).last().unwrap(); visible_label(&labels, screen, "Numbering & Section Options"); assert!(!labels.iter().any(|(t, _, _)| t == "New Section")); From bf2cf8842bc28e4fcef146bcd9f7a73b77afbbdb Mon Sep 17 00:00:00 2001 From: moppeeer Date: Wed, 14 Oct 2026 14:53:40 +0200 Subject: [PATCH 0004/1349] Direct Selection: pressing on a corner of an unselected object pulls just that corner Chris Nielsen's "The Adobe InDesign Toolbox" (10:10): with the White Arrow he clicks outside, then presses on a frame's corner and pulls it up, turning the rectangle into a lopsided triangle. DesignCraft only looked for anchors on objects already selected, so the press fell through to moving the whole frame. The Direct Selection tool now also looks at the anchors of the object under the pointer: on one, it selects the object and drags that point, in one undo step. Elsewhere on the object it still drags it whole; Shift- click still toggles the selection. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 1 + crates/engine/src/tests.rs | 42 ++++++++++++++++++++++++++++++++++++++ crates/tools/src/select.rs | 13 ++++++++++++ 3 files changed, 56 insertions(+) diff --git a/ROADMAP.md b/ROADMAP.md index c60a04107..0473076a4 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -128,6 +128,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-10-14** · The Direct Selection tool pressed on a corner or anchor of an object that isn't selected selects it and pulls just that point, as in InDesign (it moved the whole object). 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 diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 9d6308983..e40174c48 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -669,3 +669,45 @@ fn type_tool_frames_snap_to_the_margins() { assert!((r.x0 - margin.x0).abs() < 1e-6 && (r.y0 - margin.y0).abs() < 1e-6, "press point {r:?} vs {margin:?}"); assert!((r.x1 - margin.x1).abs() < 1e-6, "right edge {} vs {}", r.x1, margin.x1); } + +#[test] +fn direct_selection_pulls_one_corner_of_an_unselected_frame() { + // Chris Nielsen's "The Adobe InDesign Toolbox" (10:10): with the White Arrow, click outside, + // then press on a frame's corner and pull it: only that corner moves (a triangle, nearly). + use designcraft_tools::{PointerEvent, PointerKind, SnapView}; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 612, "height": 792, "facingPages": false})).unwrap(); + let id = s.execute("frame.create", &json!({"rect": [156, 219, 455, 569], "content": "graphic"})).unwrap()["id"].as_u64().unwrap(); + s.execute("edit.deselectAll", &json!({})).unwrap(); + let corners = |s: &Session| { + let d = &s.doc().unwrap().doc; + let it = d.item(designcraft_doc::ItemId(id)).unwrap(); + it.path.subpaths[0].anchors.iter().map(|a| it.xf * a.p).collect::>() + }; + let before = corners(&s); + s.set_tool("directSelection"); + let v = ViewInfo { snap: SnapView::OFF, ..ViewInfo::at_zoom(1.0) }; + let layout = s.layout(); + let at = |x: f64, y: f64| layout.to_canvas(designcraft_doc::SpreadRef::Doc(0), designcraft_geom::Point::new(x, y)); + let (a, b) = (at(455.0, 219.0), at(455.0, 150.0)); + s.pointer(&PointerEvent::new(PointerKind::Down, a.x, a.y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, a.x, a.y - 30.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, b.x, b.y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, b.x, b.y), v).unwrap(); + let after = corners(&s); + let moved: Vec<_> = before.iter().zip(&after).filter(|(p, q)| (**p - **q).hypot() > 1e-6).collect(); + assert_eq!(moved.len(), 1, "one corner moved: {before:?} → {after:?}"); + assert!((*moved[0].1 - designcraft_geom::Point::new(455.0, 150.0)).hypot() < 1e-6, "{after:?}"); + assert_eq!(s.doc().unwrap().selection.items, [designcraft_doc::ItemId(id)], "the frame is selected"); + // One undo step puts the corner back. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(corners(&s), before); + // Away from its corners, the White Arrow still drags the whole unselected frame. + s.execute("edit.deselectAll", &json!({})).unwrap(); + let (c, d) = (at(300.0, 219.0), at(300.0, 269.0)); + s.pointer(&PointerEvent::new(PointerKind::Down, c.x, c.y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, c.x, c.y + 20.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, d.x, d.y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, d.x, d.y), v).unwrap(); + assert!(corners(&s).iter().zip(&before).all(|(p, q)| (p.y - q.y - 50.0).abs() < 1e-6), "{:?}", corners(&s)); +} diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index b2ac97731..5dab5c128 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -507,6 +507,19 @@ impl Tool for SelectionTool { self.drag = Drag::Anchor { id, si, ai, handle, start: p, at }; return vec![Action::Begin(if handle.is_some() { "Move Direction Handle".into() } else { "Move Anchor".into() })]; } + // As in InDesign, the Direct Selection tool pressed on a corner or anchor of an object + // that isn't selected selects it and moves just that point (Chris Nielsen's "The + // InDesign Toolbox", 10:10: click outside, then pull a frame's corner). + if self.direct + && !ev.mods.shift + && let Some((_, hit)) = cx.hit(p) + && !cx.selection.contains(hit) + && let Some((id, si, ai, None)) = anchor_at_in(cx, &[hit], p) + { + let at = anchor_spread_point(cx, id, si, ai); + self.drag = Drag::Anchor { id, si, ai, handle: None, start: p, at }; + return vec![Action::Exec("selection.set".into(), json!({"ids": [id], "content": true})), Action::Begin("Move Anchor".into())]; + } if !self.direct && handle_at(cx, p).is_none() && let Some(center) = rotate_zone(cx, p) From 0c4fc4c0c5ddd48436dd32544ec24d6fef5a8d79 Mon Sep 17 00:00:00 2001 From: midasmatterhorn <248507632+midasmatterhorn@users.noreply.github.com> Date: Thu, 15 Oct 2026 15:57:28 +0300 Subject: [PATCH 0005/1349] images: the DOS EPS TIFF preview is read where the spec puts it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The EPSF binary header is 22 bytes (magic, psStart, psLength, tiffStart, tiffLength, checksum), so the TIFF section is at 12/16 — not at 20/24, which is the checksum plus the first two bytes of the PostScript section and always lands past the end of a real file. A legacy DOS EPS therefore never showed its preview: it fell back to drawn rectangles or the grey placeholder. The old fixture encoded the same wrong layout, so it could not catch it. Read tiffStart/tiffLength at 12/16, document the header, and rebuild the fixture on the real layout. Regression: the fixture test fails on main (pixel_size 201x101 — the stand-in) and passes with the fix (10x5 — the preview). --- crates/images/src/eps.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/images/src/eps.rs b/crates/images/src/eps.rs index d7c1f81dd..394e7aeaa 100644 --- a/crates/images/src/eps.rs +++ b/crates/images/src/eps.rs @@ -14,10 +14,13 @@ fn u32le(b: &[u8], at: usize) -> Option { } /// The PostScript section and the TIFF preview (DOS EPS). +/// +/// The binary header is 22 bytes: the magic (0xC5D0, 0xD3C6), `psStart`, `psLength`, +/// `tiffStart`, `tiffLength`, then a two-byte checksum. fn sections(bytes: &[u8]) -> (&[u8], Option<&[u8]>) { if bytes.starts_with(&[0xC5, 0xD0, 0xD3, 0xC6]) { let ps = u32le(bytes, 4).zip(u32le(bytes, 8)).and_then(|(o, l)| bytes.get(o..o.checked_add(l)?)).unwrap_or(&[]); - let tiff = u32le(bytes, 20).zip(u32le(bytes, 24)).filter(|(o, l)| *o > 0 && *l > 0).and_then(|(o, l)| bytes.get(o..o.checked_add(l)?)); + let tiff = u32le(bytes, 12).zip(u32le(bytes, 16)).filter(|(o, l)| *o > 0 && *l > 0).and_then(|(o, l)| bytes.get(o..o.checked_add(l)?)); return (ps, tiff); } (bytes, None) @@ -224,15 +227,16 @@ mod tests { let (png, size) = eps_proxy(eps).unwrap(); assert_eq!(size, (100.5, 50.25)); assert_eq!(crate::pixel_size(&png), Some((201, 101))); - // DOS EPS with a TIFF preview: the preview is the proxy. + // DOS EPS with a TIFF preview: the preview is the proxy. The binary header is 22 bytes: + // the magic, psStart, psLength, tiffStart, tiffLength, then a two-byte checksum. let mut tiff = Vec::new(); image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(10, 5, image::Rgba([255, 0, 0, 255]))) .write_to(&mut std::io::Cursor::new(&mut tiff), image::ImageFormat::Tiff) .unwrap(); let mut dos = vec![0xC5, 0xD0, 0xD3, 0xC6]; - let ps_off = 30usize; + let ps_off = 22usize; let tiff_off = ps_off + eps.len(); - for v in [ps_off, eps.len(), 0, 0, tiff_off, tiff.len()] { + for v in [ps_off, eps.len(), tiff_off, tiff.len()] { dos.extend((v as u32).to_le_bytes()); } dos.extend([0xFF, 0xFF]); From b642cec8cbcff5cf51869aca728d915e4499606c Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 15 Oct 2026 15:32:19 +0200 Subject: [PATCH 0006/1349] Anchored objects wrap their own story as their anchor lines are set #563 composed the story again with its objects where the previous pass put them, up to four times. In a long story whose objects move between frames from one pass to the next (Learn Skills Daily's 03_HP_LongDoc_Class, 79 pages), that never settled: stale wrap areas pushed headings into the next frame. Now the composer places a custom or above-line object when its anchor line is set and the lines after it wrap it in the same pass, as in InDesign. Co-Authored-By: Claude Opus 5.5 --- crates/compose/src/lib.rs | 131 +++++++++++++++++++++++++------------ crates/compose/src/wrap.rs | 41 ++---------- 2 files changed, 94 insertions(+), 78 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 5689ced9f..7bebaf9a5 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -514,6 +514,9 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C let mut out = ComposedStory { story: story.id, rev: story.rev, text_len: story.text.len(), ..Default::default() }; let mut styles_tab: Vec = Vec::new(); let mut missing_fonts: HashMap = HashMap::new(); + // The wrap of the story's own custom and above-line anchored objects, per frame, added as + // their anchor lines are set (see `own_wrap`). + let mut own_ex: Vec> = vec![Vec::new(); frames.len()]; let cols: Vec> = frames .iter() .map(|f| { @@ -986,7 +989,16 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C para_box_decos(&mut out, pi, &pp); break 'paras; } - let f = &frames[cur.fi]; + let merged; + let f = match own_ex.get(cur.fi).filter(|e| !e.is_empty()) { + Some(extra) => { + let mut spec = frames[cur.fi].clone(); + spec.exclusions.extend(extra.iter().cloned()); + merged = spec; + &merged + } + None => &frames[cur.fi], + }; let base = cols[cur.fi][cur.col.min(cols[cur.fi].len() - 1)]; let col = cur.clip(base); // A spanning paragraph isn't held to the balanced bottom of the columns above it. @@ -1232,16 +1244,32 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C continue 'paras; } } + let mut wraps_below = false; if !sub_objects.is_empty() { let ft = &mut out.frames[cur.fi]; let li = ft.lines.len() - 1; let text_ascent = line_glyphs.iter().filter(|g| g.ch != designcraft_doc::OBJECT_MARK).map(|g| g.ascent).fold(0.0, f64::max); let text_ascent = if text_ascent > 0.0 { text_ascent } else { base_chars.size * 0.75 }; + let first = ft.objects.len(); for g in ft.lines[li].glyphs.iter().filter(|g| g.len > 0) { if let Some(o) = sub_objects.get(&g.byte) { ft.objects.push(PlacedObject { index: o.index, origin: Point::ZERO, size: (o.w, o.h), line: li, x: g.x, text_ascent }); } } + // Custom and above-line objects anchored here wrap the lines after this one. + for o in ft.objects.get(first..).unwrap_or_default() { + if let (Some(l), Some(obj)) = (ft.lines.get(li), story.objects.get(o.index)) + && let Some(ex) = own_wrap(story, obj, o, l, &ft.columns, f) + { + for e in &mut own_ex { + e.retain(|x| x.after != ex.after); + } + wraps_below |= ex.rect.x0 < col.x1 && ex.rect.x1 > col.x0 && ex.rect.y1 > baseline && ex.rect.y0 < col.y1; + if let Some(e) = own_ex.get_mut(cur.fi) { + e.push(ex); + } + } + } } cur.last_baseline = Some(baseline); cur.last_reference = reference; @@ -1263,6 +1291,11 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C } // An own-story anchored object anchored in this line wraps the lines after it, // which were broken without it: break them again. + if k + 1 < breaks.len() && wraps_below { + g0 += b.next; + moved = true; + break; + } if k + 1 < breaks.len() && f.exclusions.iter().any(|ex| { ex.after.is_some_and(|a| (range_start..range_end).contains(&a)) @@ -1404,47 +1437,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C for o in &mut ft.objects { let Some(l) = ft.lines.get(o.line) else { continue }; let Some(obj) = story.objects.get(o.index) else { continue }; - let (w, h) = o.size; - o.origin = match &obj.position { - designcraft_doc::AnchorPosition::Inline { y_offset } => Point::new(o.x, l.baseline - y_offset - h), - designcraft_doc::AnchorPosition::AboveLine { align, space_after, .. } => { - let x = match align { - designcraft_doc::anchored::AnchorAlign::Left => l.x0, - designcraft_doc::anchored::AnchorAlign::Center => (l.x0 + l.x1 - w) / 2.0, - designcraft_doc::anchored::AnchorAlign::Right => l.x1 - w, - }; - Point::new(x, l.baseline - o.text_ascent - space_after - h) - } - designcraft_doc::AnchorPosition::Custom { - x_relative, - y_relative, - x_offset, - y_offset, - object_point, - ref_point, - keep_within_column, - } => { - use designcraft_doc::anchored::AnchorRelative as R; - let col = ft.columns.get(l.column as usize).copied().unwrap_or(f.area); - let area = |r: R| match r { - R::Anchor => None, - R::TextFrame => Some(f.area), - R::ColumnEdge => Some(col), - R::PageMargin => Some(f.page_rect.map_or(f.area, |p| p.1)), - R::PageEdge => Some(f.page_rect.map_or(f.area, |p| p.0)), - }; - let frac = |i: u8| ([0.0, 0.5, 1.0][(i % 3) as usize], [0.0, 0.5, 1.0][(i / 3).min(2) as usize]); - let (rfx, rfy) = frac(*ref_point); - let (ofx, ofy) = frac(*object_point); - let rx = area(*x_relative).map_or(o.x, |a| a.x0 + a.width() * rfx); - let ry = area(*y_relative).map_or(l.baseline, |a| a.y0 + a.height() * rfy); - let mut y = ry + y_offset - h * ofy; - if *keep_within_column { - y = y.clamp(col.y0, (col.y1 - h).max(col.y0)); - } - Point::new(rx + x_offset - w * ofx, y) - } - }; + o.origin = object_origin(obj, o, l, &ft.columns, f); } } } @@ -1471,6 +1464,60 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C out } +/// The wrap of a custom or above-line anchored object `obj` of `story`, placed as `o` on line `l` +/// of a frame (`columns`, spec `f`), in the frame's inner space: it wraps the lines of the story +/// that start after its anchor. None for inline objects (they sit in their line) and objects +/// without text wrap. +fn own_wrap(story: &Story, obj: &designcraft_doc::AnchoredObject, o: &PlacedObject, l: &Line, columns: &[Rect], f: &FrameSpec) -> Option { + if obj.item.wrap.mode == WrapMode::None || obj.item.hidden || matches!(obj.position, designcraft_doc::AnchorPosition::Inline { .. }) { + return None; + } + let anchor = story.text.match_indices(designcraft_doc::OBJECT_MARK).nth(o.index).map(|(i, _)| i)?; + let origin = object_origin(obj, o, l, columns, f); + let w = obj.item.wrap.offsets; + let b = obj.item.bounds(); + let rect = Rect::new(b.x0 - w[1], b.y0 - w[0], b.x1 + w[3], b.y1 + w[2]) + origin.to_vec2(); + rect.is_finite().then_some(Exclusion { rect, mode: obj.item.wrap.mode, after: Some(anchor) }) +} + +/// Where anchored object `obj`, placed as `o` on line `l` of a frame (`columns`, spec `f`), has its +/// top-left, in the frame's inner space. +fn object_origin(obj: &designcraft_doc::AnchoredObject, o: &PlacedObject, l: &Line, columns: &[Rect], f: &FrameSpec) -> Point { + let (w, h) = o.size; + match &obj.position { + designcraft_doc::AnchorPosition::Inline { y_offset } => Point::new(o.x, l.baseline - y_offset - h), + designcraft_doc::AnchorPosition::AboveLine { align, space_after, .. } => { + let x = match align { + designcraft_doc::anchored::AnchorAlign::Left => l.x0, + designcraft_doc::anchored::AnchorAlign::Center => (l.x0 + l.x1 - w) / 2.0, + designcraft_doc::anchored::AnchorAlign::Right => l.x1 - w, + }; + Point::new(x, l.baseline - o.text_ascent - space_after - h) + } + designcraft_doc::AnchorPosition::Custom { x_relative, y_relative, x_offset, y_offset, object_point, ref_point, keep_within_column } => { + use designcraft_doc::anchored::AnchorRelative as R; + let col = columns.get(l.column as usize).copied().unwrap_or(f.area); + let area = |r: R| match r { + R::Anchor => None, + R::TextFrame => Some(f.area), + R::ColumnEdge => Some(col), + R::PageMargin => Some(f.page_rect.map_or(f.area, |p| p.1)), + R::PageEdge => Some(f.page_rect.map_or(f.area, |p| p.0)), + }; + let frac = |i: u8| ([0.0, 0.5, 1.0][(i % 3) as usize], [0.0, 0.5, 1.0][(i / 3).min(2) as usize]); + let (rfx, rfy) = frac(*ref_point); + let (ofx, ofy) = frac(*object_point); + let rx = area(*x_relative).map_or(o.x, |a| a.x0 + a.width() * rfx); + let ry = area(*y_relative).map_or(l.baseline, |a| a.y0 + a.height() * rfy); + let mut y = ry + y_offset - h * ofy; + if *keep_within_column { + y = y.clamp(col.y0, (col.y1 - h).max(col.y0)); + } + Point::new(rx + x_offset - w * ofx, y) + } + } +} + /// The columns a spanning paragraph is set across, from `col`'s top to its bottom. fn span_rect(cols: &[Rect], col: Rect, span: SpanColumns) -> Rect { let SpanColumns::Span(n) = span else { return col }; diff --git a/crates/compose/src/wrap.rs b/crates/compose/src/wrap.rs index 31ec719d6..9962e1a70 100644 --- a/crates/compose/src/wrap.rs +++ b/crates/compose/src/wrap.rs @@ -10,22 +10,16 @@ //! other's text don't depend on each other in a cycle. //! - **Its own story.** A custom or above-line anchored object wraps the lines of its own story //! that come after the line holding its anchor; that line and the lines before it are never -//! wrapped by it (an inline object sits in its line and wraps none of its own story). The story -//! is composed again with the objects where the previous pass placed them until they stop -//! moving, at most [`MAX_PASSES`] more times. +//! wrapped by it (an inline object sits in its line and wraps none of its own story). As in +//! InDesign, the object is placed when its anchor line is set and wraps the text that follows +//! in the same composition (`own_wrap` in the composer), so the layout doesn't depend on where +//! an earlier composition put the objects. use designcraft_doc::{AnchorPosition, AnchoredObject, Document, OBJECT_MARK, SpreadRef, Story, StoryId, WrapMode}; use designcraft_geom::{Affine, Rect}; use crate::{ComposeOptions, ComposedStory, Exclusion, FrameSpec}; -/// Extra compositions of a story with its own anchored objects' wrap; a layout that keeps moving -/// its objects (keep options, vertical justification) stops here. -pub(crate) const MAX_PASSES: usize = 4; - -/// How far an obstacle may move between passes and still count as settled (points). -const SETTLED: f64 = 0.01; - /// A wrapping anchored object where its story's composition placed it. #[derive(Clone, Debug)] pub(crate) struct Obstacle { @@ -161,18 +155,6 @@ fn with_exclusions(specs: &[FrameSpec], added: &[Vec]) -> Vec], b: &[Vec]) -> bool { - let near = |x: &Exclusion, y: &Exclusion| { - x.mode == y.mode - && x.after == y.after - && (x.rect.x0 - y.rect.x0).abs() <= SETTLED - && (x.rect.y0 - y.rect.y0).abs() <= SETTLED - && (x.rect.x1 - y.rect.x1).abs() <= SETTLED - && (x.rect.y1 - y.rect.y1).abs() <= SETTLED - }; - a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.len() == y.len() && x.iter().zip(y).all(|(p, q)| near(p, q))) -} - /// Compose story `sid` with the wrapping anchored objects of `others` (compositions of its /// [`neighbours`]) and of its own. pub(crate) fn compose_among(doc: &Document, sid: StoryId, opts: &ComposeOptions, others: &[&ComposedStory]) -> ComposedStory { @@ -190,18 +172,5 @@ pub(crate) fn compose_among(doc: &Document, sid: StoryId, opts: &ComposeOptions, specs = with_exclusions(&specs, &added); } } - let mut out = crate::compose(doc, st, &specs, opts); - if !has_wrapping_objects(st) { - return out; - } - let mut prev = vec![Vec::new(); specs.len()]; - for _ in 0..MAX_PASSES { - let added = exclusions(doc, &specs, &obstacles(doc, st, &out, true)); - if settled(&added, &prev) { - break; - } - out = crate::compose(doc, st, &with_exclusions(&specs, &added), opts); - prev = added; - } - out + crate::compose(doc, st, &specs, opts) } From 56cef8aeeeb1eeea2927c17af840e90c9d43f87f Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 15 Oct 2026 16:07:17 +0200 Subject: [PATCH 0007/1349] Test and ROADMAP: an object wraps the frame its anchor lands in Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 1 + crates/compose/src/tests.rs | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/ROADMAP.md b/ROADMAP.md index 8f8523f0b..4b7faf5eb 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -347,6 +347,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-10-15** · Anchored objects wrap their own story as their anchor lines are set, as in InDesign: the layout no longer depends on where an earlier composition put them (a long story whose pictures moved between frames from pass to pass never settled). No readiness percentage change. - **2026-10-12** · Anchored objects with text wrap push text aside: other stories' text under them and the lines of their own story after the anchor's line (#557). No readiness percentage change. - **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. diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 1f01498f9..2dc339697 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -4569,3 +4569,40 @@ fn anchored_wrap_that_moves_its_own_anchor_terminates() { assert!(cs.line_count() > 0); assert_eq!(cs.frames[0].objects.len(), 1); } + +/// An object's wrap pushes the text so that a later object's anchor goes on into the next frame +/// (Learn Skills Daily's long-document exercise: pictures anchored in headings through a 79-page +/// story). Each object is placed when its anchor line is set and wraps only the lines after it, +/// in the frame its anchor lands in: the layout doesn't depend on where an earlier composition put +/// the objects, and composing again gives the same lines. +#[test] +fn an_object_wraps_the_frame_its_anchor_lands_in_after_an_earlier_object_pushed_it_on() { + let text = [LOREM; 6].join(" "); + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let (a, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 300.0, 300.0), lid, &text, ParaFormat::default()).unwrap(); + let (b, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(320.0, 0.0, 620.0, 300.0), lid, "", ParaFormat::default()).unwrap(); + d.thread(a, b).unwrap(); + let plain = compose_story(&d, sid, &ComposeOptions::default()); + // The second object's anchor sits near the end of the first frame without wrap. + let late = plain.frames[0].lines.iter().rev().nth(2).unwrap().range.start + 2; + anchor_box(&mut d, sid, late, 0.0, 0.0, true, WrapMode::BoundingBox); + // The first, early in the first frame: 60 pt over its whole width pushes the later anchor on. + let early = plain.frames[0].lines[1].range.start + 2; + anchor_box(&mut d, sid, early, 0.0, 0.0, true, WrapMode::JumpObject); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let late = late + OBJECT_LEN; + let anchor_frame = cs.frames.iter().position(|f| f.range.contains(&late) || f.range.end == late).unwrap(); + assert_eq!(anchor_frame, 1, "the later anchor went on into the second frame"); + // The first frame's lines under the first object's band keep the full measure (the second + // object is in the other frame); in the second frame, the lines under its object move right. + let left = cs.frames[0].lines[0].x0; + assert!(cs.frames[0].lines.iter().all(|l| (l.x0 - left).abs() < 1e-6)); + let f1 = &cs.frames[1]; + let (li, line) = f1.lines.iter().enumerate().find(|(_, l)| l.range.contains(&late)).unwrap(); + let under: Vec<_> = f1.lines[li + 1..].iter().filter(|l| l.baseline - l.ascent < line.baseline + 60.0).collect(); + assert!(!under.is_empty() && under.iter().all(|l| l.x0 >= f1.lines[0].x0 + 100.0 - 1e-6)); + assert_eq!(f1.objects.len(), 1); + // Deterministic: the same lines again. + assert_eq!(line_layout(&compose_story(&d, sid, &ComposeOptions::default())), line_layout(&cs)); +} From 2a7f4d95059006d20f559b841ba4fae8cd276dcb Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 15 Oct 2026 21:58:30 +0200 Subject: [PATCH 0008/1349] Color Picker: laid out as InDesign's, with a component field and slider, every space's values and Add CMYK Swatch Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 1 + crates/ui-egui/src/dialogs.rs | 431 ++++++++++++++++++++++++++++--- crates/ui-egui/src/i18n.rs | 22 ++ crates/ui-egui/src/i18n/ar.rs | 4 + crates/ui-egui/src/i18n/de.rs | 4 + crates/ui-egui/src/i18n/it.rs | 4 + crates/ui-egui/src/i18n/ja.rs | 4 + crates/ui-egui/src/i18n/ka.rs | 4 + crates/ui-egui/src/i18n/pt_br.rs | 4 + crates/ui-egui/src/i18n/uk.rs | 4 + 10 files changed, 450 insertions(+), 32 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index d60a6bf49..87ad24136 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -347,6 +347,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- 2026-10-15: The Color Picker is laid out as InDesign's: a field of two components and a slider for the third (H, S, B, L, a, b, R, G or B by radio button; RGB or Lab Color Space View), the new colour over the old one, H/S/B, L/a/b, R/G/B and C/M/Y/K values, the hex code, and Add CMYK Swatch. - **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. diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 7d02776a2..262a48b60 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1828,7 +1828,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { } "insertXref" => insert_xref(app, ui, &mut d), "findFont" => find_font(app, ui, &mut d), - "colorPicker" => color_picker(ui, &mut d), + "colorPicker" => color_picker(app, ui, &mut d), "preferences" => preferences(app, ui, &mut d, body_height), "print" => print_dialog(app, ui, &mut d), "pdfImport" => { @@ -4710,44 +4710,356 @@ fn insert_xref(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { } } -/// Color Picker: saturation/brightness field and hue slider, with RGB, CMYK and hex fields. -fn color_picker(ui: &mut egui::Ui, d: &mut Dialog) { - let hex = d.s("hex"); - let mut c = designcraft_color::Color::from_hex(&hex).map(|c| c.to_rgb()).map_or(egui::Color32::BLACK, |[r, g, b]| { - egui::Color32::from_rgb((r * 255.0).round() as u8, (g * 255.0).round() as u8, (b * 255.0).round() as u8) - }); - let before = c; +/// The Color Picker's components: the one picked runs along the slider, the other two of its +/// space across the field (InDesign's, as Photoshop's: R puts B across and G up). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PickComp { + H, + S, + Br, + L, + A, + Lb, + R, + G, + Bl, +} + +impl PickComp { + const ALL: [PickComp; 9] = + [PickComp::H, PickComp::S, PickComp::Br, PickComp::L, PickComp::A, PickComp::Lb, PickComp::R, PickComp::G, PickComp::Bl]; + + fn key(self) -> &'static str { + match self { + PickComp::H => "h", + PickComp::S => "s", + PickComp::Br => "b", + PickComp::L => "l", + PickComp::A => "la", + PickComp::Lb => "lb", + PickComp::R => "r", + PickComp::G => "g", + PickComp::Bl => "bl", + } + } + + fn from_key(k: &str) -> PickComp { + PickComp::ALL.into_iter().find(|c| c.key() == k).unwrap_or(PickComp::R) + } + + fn lab(self) -> bool { + matches!(self, PickComp::L | PickComp::A | PickComp::Lb) + } +} + +/// The colour the picker shows, in each of its spaces (HSB keeps its hue through greys). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Picked { + pub rgb: [f32; 3], + pub hsb: [f32; 3], + pub lab: [f32; 3], +} + +impl Picked { + pub fn from_rgb(rgb: [f32; 3], hue: f32) -> Picked { + let rgb = rgb.map(|v| v.clamp(0.0, 1.0)); + let c = designcraft_color::Color::Rgb { r: rgb[0], g: rgb[1], b: rgb[2] }; + let mut hsb = c.to_hsb(); + if hsb[1] <= 1e-4 || hsb[2] <= 1e-4 { + hsb[0] = hue; + } + let l = designcraft_color::cms::lab::srgb_to_lab(rgb); + Picked { rgb, hsb, lab: [l.l, l.a, l.b] } + } + + fn from_hsb(hsb: [f32; 3]) -> Picked { + let hsb = [hsb[0].rem_euclid(360.0), hsb[1].clamp(0.0, 1.0), hsb[2].clamp(0.0, 1.0)]; + let mut p = Picked::from_rgb(designcraft_color::Color::from_hsb(hsb[0], hsb[1], hsb[2]).to_rgb_uncalibrated(), hsb[0]); + p.hsb = hsb; + p + } + + fn from_lab(lab: [f32; 3], hue: f32) -> Picked { + let lab = [lab[0].clamp(0.0, 100.0), lab[1].clamp(-128.0, 127.0), lab[2].clamp(-128.0, 127.0)]; + let mut p = Picked::from_rgb(designcraft_color::cms::lab::lab_to_srgb(designcraft_color::cms::Lab::new(lab[0], lab[1], lab[2])), hue); + p.lab = lab; + p + } + + /// (slider, across, up), each 0..1, for component `c`. + pub fn coords(&self, c: PickComp) -> (f32, f32, f32) { + let [r, g, b] = self.rgb; + let [h, s, v] = self.hsb; + let [l, la, lb] = self.lab; + let (a, bb) = ((la + 128.0) / 255.0, (lb + 128.0) / 255.0); + match c { + PickComp::R => (r, b, g), + PickComp::G => (g, b, r), + PickComp::Bl => (b, r, g), + PickComp::H => (h / 360.0, s, v), + PickComp::S => (s, h / 360.0, v), + PickComp::Br => (v, h / 360.0, s), + PickComp::L => (l / 100.0, a, bb), + PickComp::A => (a, bb, l / 100.0), + PickComp::Lb => (bb, a, l / 100.0), + } + } + + /// The colour at (slider `t`, across `u`, up `v`) for component `c`. + pub fn at(&self, c: PickComp, t: f32, u: f32, v: f32) -> Picked { + let hue = self.hsb[0]; + let ab = |x: f32| x * 255.0 - 128.0; + match c { + PickComp::R => Picked::from_rgb([t, v, u], hue), + PickComp::G => Picked::from_rgb([v, t, u], hue), + PickComp::Bl => Picked::from_rgb([u, v, t], hue), + PickComp::H => Picked::from_hsb([t * 360.0, u, v]), + PickComp::S => Picked::from_hsb([u * 360.0, t, v]), + PickComp::Br => Picked::from_hsb([u * 360.0, v, t]), + PickComp::L => Picked::from_lab([t * 100.0, ab(u), ab(v)], hue), + PickComp::A => Picked::from_lab([v * 100.0, ab(t), ab(u)], hue), + PickComp::Lb => Picked::from_lab([v * 100.0, ab(u), ab(t)], hue), + } + } + + /// The slider's colour at `t`: the hue slider shows pure hues, the others this colour with + /// the component at `t`. + fn slider_at(&self, c: PickComp, t: f32) -> [f32; 3] { + if c == PickComp::H { + return designcraft_color::Color::from_hsb(t * 360.0, 1.0, 1.0).to_rgb_uncalibrated(); + } + let (_, u, v) = self.coords(c); + self.at(c, t, u, v).rgb + } + + pub fn hex(&self) -> String { + let q = |x: f32| (x.clamp(0.0, 1.0) * 255.0).round() as u8; + format!("#{:02x}{:02x}{:02x}", q(self.rgb[0]), q(self.rgb[1]), q(self.rgb[2])) + } +} + +fn color32(rgb: [f32; 3]) -> egui::Color32 { + let q = |x: f32| (x.clamp(0.0, 1.0) * 255.0).round() as u8; + egui::Color32::from_rgb(q(rgb[0]), q(rgb[1]), q(rgb[2])) +} + +/// A `cols` × `rows` grid of quads over `r`, coloured at each vertex by `f(x, y)` (0..1, y up). +fn gradient_mesh(painter: &egui::Painter, r: egui::Rect, cols: usize, rows: usize, f: impl Fn(f32, f32) -> [f32; 3]) { + let mut mesh = egui::Mesh::default(); + for j in 0..=rows { + for i in 0..=cols { + let (x, y) = (i as f32 / cols as f32, j as f32 / rows as f32); + mesh.colored_vertex(egui::pos2(r.left() + x * r.width(), r.bottom() - y * r.height()), color32(f(x, y))); + } + } + let w = (cols + 1) as u32; + for j in 0..rows as u32 { + for i in 0..cols as u32 { + let a = j * w + i; + mesh.add_triangle(a, a + 1, a + w); + mesh.add_triangle(a + 1, a + w + 1, a + w); + } + } + painter.add(egui::Shape::mesh(mesh)); +} + +/// `n` numbers from an array field. +fn nums(d: &Dialog, key: &str) -> Option<[f64; N]> { + let a = d.fields.get(key)?.as_array()?; + let mut out = [0.0; N]; + for (o, v) in out.iter_mut().zip(a) { + *o = v.as_f64().filter(|v| v.is_finite())?; + } + (a.len() == N).then_some(out) +} + +/// The colour in the dialog's fields: `hex`, with the HSB hue and the Lab values kept while +/// they round-trip (`_hsb`, `_lab`). +fn picked_of(d: &Dialog) -> Picked { + let rgb = designcraft_color::Color::from_hex(&d.s("hex")).map_or([0.0; 3], |c| c.to_rgb_uncalibrated()); + let hue = nums::<3>(d, "_hsb").map_or(0.0, |h| h[0] as f32); + let mut p = Picked::from_rgb(rgb, hue); + // The exact values the picker last set, while they still give this colour. + if let Some(h) = nums::<3>(d, "_hsb").map(|h| h.map(|v| v as f32)) + && Picked::from_hsb(h).hex() == p.hex() + { + p.hsb = h; + } + if let Some(l) = nums::<3>(d, "_lab").map(|l| l.map(|v| v as f32)) + && Picked::from_lab(l, p.hsb[0]).hex() == p.hex() + { + p.lab = l; + } + p +} + +fn store_picked(d: &mut Dialog, p: &Picked) { + d.fields.insert("hex".into(), json!(p.hex())); + d.fields.insert("_hsb".into(), json!(p.hsb)); + d.fields.insert("_lab".into(), json!(p.lab)); +} + +/// The Color Picker, laid out as InDesign's: the field of two components and the slider of the +/// third (the one whose radio button is on, R at first), the new colour over the one it replaces, +/// H/S/B, L/a/b, R/G/B and C/M/Y/K values, the hex code, and Add CMYK Swatch. +fn color_picker(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { + let lang = app.ui.language.clone(); + let tr = |s: &str| crate::i18n::tr(&lang, s).to_string(); + if !d.fields.contains_key("old") { + let old = d.s("hex"); + d.fields.insert("old".into(), json!(old)); + } + let comp = PickComp::from_key(&d.s("component")); + let mut p = picked_of(d); + let before = p; + let t = crate::theme::Tokens::get(ui.ctx()); ui.horizontal_top(|ui| { - egui::color_picker::color_picker_color32(ui, &mut c, egui::color_picker::Alpha::Opaque); + // The field and the slider. ui.vertical(|ui| { - let mut rgb = [c.r() as f32, c.g() as f32, c.b() as f32]; - egui::Grid::new("cp_rgb").num_columns(2).spacing([6.0, 4.0]).show(ui, |ui| { - for (k, l) in ["R", "G", "B"].iter().enumerate() { - ui.label(*l); - ui.add(egui::DragValue::new(&mut rgb[k]).range(0.0..=255.0)); - ui.end_row(); + crate::rtl::label(ui, egui::RichText::new(tr(if comp.lab() { "Lab Color Space View" } else { "RGB Color Space View" })).size(11.5)); + ui.add_space(4.0); + ui.horizontal_top(|ui| { + let (fr, fresp) = ui.allocate_exact_size(egui::vec2(190.0, 200.0), egui::Sense::click_and_drag()); + let (tv, _, _) = p.coords(comp); + let cells = if matches!(comp, PickComp::R | PickComp::G | PickComp::Bl | PickComp::H) { 2 } else { 24 }; + gradient_mesh(ui.painter(), fr, cells, cells, |x, y| p.at(comp, tv, x, y).rgb); + ui.painter().rect_stroke(fr, 0.0, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Outside); + fresp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Other, true, "Color field")); + if let Some(pos) = fresp.interact_pointer_pos().filter(|_| fresp.is_pointer_button_down_on() || fresp.clicked()) { + let u = ((pos.x - fr.left()) / fr.width()).clamp(0.0, 1.0); + let v = ((fr.bottom() - pos.y) / fr.height()).clamp(0.0, 1.0); + p = p.at(comp, tv, u, v); } - }); - c = egui::Color32::from_rgb(rgb[0] as u8, rgb[1] as u8, rgb[2] as u8); - let col = designcraft_color::Color::rgb8(c.r(), c.g(), c.b()); - let [cc, m, y, k] = col.to_cmyk(); - ui.add_space(6.0); - ui.label(format!("C {:.0}% M {:.0}% Y {:.0}% K {:.0}%", cc * 100.0, m * 100.0, y * 100.0, k * 100.0)); - ui.add_space(6.0); - ui.horizontal(|ui| { - ui.label("#"); - let mut h = format!("{:02x}{:02x}{:02x}", c.r(), c.g(), c.b()); - if ui.add(egui::TextEdit::singleline(&mut h).desired_width(70.0)).changed() - && let Some(n) = designcraft_color::Color::from_hex(&h) - { - let [r, g, b] = n.to_rgb(); - c = egui::Color32::from_rgb((r * 255.0).round() as u8, (g * 255.0).round() as u8, (b * 255.0).round() as u8); + let (_, u, v) = p.coords(comp); + let mark = egui::pos2(fr.left() + u * fr.width(), fr.bottom() - v * fr.height()); + ui.painter().circle_stroke(mark, 5.0, egui::Stroke::new(1.5, egui::Color32::WHITE)); + ui.painter().circle_stroke(mark, 6.0, egui::Stroke::new(1.0, egui::Color32::BLACK)); + ui.add_space(6.0); + let (sr, sresp) = ui.allocate_exact_size(egui::vec2(14.0, 200.0), egui::Sense::click_and_drag()); + gradient_mesh(ui.painter(), sr, 1, 48, |_, y| p.slider_at(comp, y)); + ui.painter().rect_stroke(sr, 0.0, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Outside); + sresp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Slider, true, "Color slider")); + if let Some(pos) = sresp.interact_pointer_pos().filter(|_| sresp.is_pointer_button_down_on() || sresp.clicked()) { + let tn = ((sr.bottom() - pos.y) / sr.height()).clamp(0.0, 1.0); + let (_, u, v) = p.coords(comp); + p = p.at(comp, tn, u, v); + } + let (tn, _, _) = p.coords(comp); + let y = sr.bottom() - tn * sr.height(); + for (x, dir) in [(sr.left() - 1.0, 1.0), (sr.right() + 1.0, -1.0)] { + ui.painter().add(egui::Shape::convex_polygon( + vec![egui::pos2(x, y), egui::pos2(x - 5.0 * dir, y - 4.0), egui::pos2(x - 5.0 * dir, y + 4.0)], + t.text_strong, + egui::Stroke::NONE, + )); } }); }); + ui.add_space(10.0); + ui.vertical(|ui| { + // The new colour over the one it replaces. + let (pr, _) = ui.allocate_exact_size(egui::vec2(60.0, 60.0), egui::Sense::hover()); + let old = designcraft_color::Color::from_hex(&d.s("old")).map_or([0.0; 3], |c| c.to_rgb_uncalibrated()); + ui.painter().rect_filled(egui::Rect::from_min_max(pr.min, egui::pos2(pr.max.x, pr.center().y)), 0.0, color32(p.rgb)); + ui.painter().rect_filled(egui::Rect::from_min_max(egui::pos2(pr.min.x, pr.center().y), pr.max), 0.0, color32(old)); + ui.painter().rect_stroke(pr, 0.0, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Outside); + ui.add_space(10.0); + let mut comp_now = comp; + let mut edited: Option = None; + let [cc, cm, cy, ck] = designcraft_color::Color::Rgb { r: p.rgb[0], g: p.rgb[1], b: p.rgb[2] } + .to_cmyk_managed(designcraft_color::cms::active_settings().intent) + .map(|v| v * 100.0); + let mut cmyk = [cc, cm, cy, ck]; + egui::Grid::new("cp_values").num_columns(6).spacing([4.0, 4.0]).show(ui, |ui| { + let mut field = + |ui: &mut egui::Ui, c: Option, label: &str, v: &mut f32, range: std::ops::RangeInclusive, suffix: &str| -> bool { + match c { + Some(c) => { + ui.radio_value(&mut comp_now, c, ""); + } + None => { + ui.label(""); + } + } + ui.label(label); + ui.add(egui::DragValue::new(v).range(range).max_decimals(0).suffix(suffix)).changed() + }; + let (mut h, mut s, mut b) = (p.hsb[0], p.hsb[1] * 100.0, p.hsb[2] * 100.0); + let (mut l, mut la, mut lb) = (p.lab[0], p.lab[1], p.lab[2]); + let (mut r, mut g, mut bl) = (p.rgb[0] * 255.0, p.rgb[1] * 255.0, p.rgb[2] * 255.0); + // Rows as InDesign's: H S B beside L a b, R G B beside C M Y K. + let hsb_changed = + field(ui, Some(PickComp::H), "H:", &mut h, 0.0..=360.0, "°") | field(ui, Some(PickComp::L), "L:", &mut l, 0.0..=100.0, ""); + ui.end_row(); + let hsb_changed2 = + field(ui, Some(PickComp::S), "S:", &mut s, 0.0..=100.0, "%") | field(ui, Some(PickComp::A), "a:", &mut la, -128.0..=127.0, ""); + ui.end_row(); + let hsb_changed3 = + field(ui, Some(PickComp::Br), "B:", &mut b, 0.0..=100.0, "%") | field(ui, Some(PickComp::Lb), "b:", &mut lb, -128.0..=127.0, ""); + ui.end_row(); + if hsb_changed || hsb_changed2 || hsb_changed3 { + // Whichever space changed wins: HSB if its values moved, else Lab. + edited = Some(if (h, s, b) != (p.hsb[0], p.hsb[1] * 100.0, p.hsb[2] * 100.0) { + Picked::from_hsb([h, s / 100.0, b / 100.0]) + } else { + Picked::from_lab([l, la, lb], p.hsb[0]) + }); + } + let rgb_changed = field(ui, Some(PickComp::R), "R:", &mut r, 0.0..=255.0, ""); + let c1 = field(ui, None, "C:", &mut cmyk[0], 0.0..=100.0, "%"); + ui.end_row(); + let rgb_changed2 = field(ui, Some(PickComp::G), "G:", &mut g, 0.0..=255.0, ""); + let c2 = field(ui, None, "M:", &mut cmyk[1], 0.0..=100.0, "%"); + ui.end_row(); + let rgb_changed3 = field(ui, Some(PickComp::Bl), "B:", &mut bl, 0.0..=255.0, ""); + let c3 = field(ui, None, "Y:", &mut cmyk[2], 0.0..=100.0, "%"); + ui.end_row(); + ui.label(""); + ui.label(""); + ui.label(""); + let c4 = field(ui, None, "K:", &mut cmyk[3], 0.0..=100.0, "%"); + ui.end_row(); + if rgb_changed || rgb_changed2 || rgb_changed3 { + edited = Some(Picked::from_rgb([r / 255.0, g / 255.0, bl / 255.0], p.hsb[0])); + } + if c1 || c2 || c3 || c4 { + let [c, m, y, k] = cmyk.map(|v| v / 100.0); + edited = Some(Picked::from_rgb(designcraft_color::Color::Cmyk { c, m, y, k }.to_rgb(), p.hsb[0])); + } + }); + if let Some(e) = edited { + p = e; + } + if comp_now != comp { + d.fields.insert("component".into(), json!(comp_now.key())); + } + ui.add_space(4.0); + ui.horizontal(|ui| { + ui.label("#"); + let id = egui::Id::new("color_picker_hex"); + let editing = ui.memory(|m| m.has_focus(id)); + let mut h = if editing { d.s("_hexEdit") } else { p.hex().trim_start_matches('#').to_string() }; + if ui.add(egui::TextEdit::singleline(&mut h).id(id).desired_width(70.0)).changed() + && let Some(c) = designcraft_color::Color::from_hex(&h) + { + p = Picked::from_rgb(c.to_rgb_uncalibrated(), p.hsb[0]); + } + d.fields.insert("_hexEdit".into(), json!(h)); + }); + ui.add_space(8.0); + if ui.button(crate::rtl::widget(ui, tr("Add CMYK Swatch"))).clicked() { + let [c, m, y, k] = designcraft_color::Color::Rgb { r: p.rgb[0], g: p.rgb[1], b: p.rgb[2] } + .to_cmyk_managed(designcraft_color::cms::active_settings().intent) + .map(|v| (v * 100.0).round()); + match app.run("swatch.create", json!({"color": {"c": c, "m": m, "y": y, "k": k}})) { + Ok(r) => app.status(format!("{} {}", tr("Added swatch"), r["name"].as_str().unwrap_or(""))), + Err(e) => app.status(e), + } + } + }); }); - if c != before { - d.fields.insert("hex".into(), json!(format!("#{:02x}{:02x}{:02x}", c.r(), c.g(), c.b()))); + if p != before { + store_picked(d, &p); } } @@ -6794,6 +7106,61 @@ mod tests { (0..doc.page_count()).map(|abs| doc.page(abs).unwrap().guides.len()).collect() } + /// The Color Picker laid out as InDesign's: a field and a slider for the component whose radio + /// is on, the new colour over the old one, and the values in every space. + #[test] + fn the_color_picker_picks_on_its_field_and_slider_and_adds_a_cmyk_swatch() { + use egui_kittest::kittest::Queryable; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("frame.create", json!({"rect": [72, 72, 200, 200], "shape": "rectangle"})).unwrap(); + app.ui.dialog = Some(Dialog::new("colorPicker", json!({"target": "fill", "hex": "#7c1315", "text": false}))); + let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); + h.run_steps(3); + // R at first: R up the slider, B across and G up the field. + let _ = h.get_by_label("RGB Color Space View"); + let field = h.get_by_label("Color field").rect(); + crate::test_window::click_at(&mut h, egui::pos2(field.right() - 1.0, field.top() + 1.0)); + h.run_steps(2); + let p = picked_of(h.state().app.ui.dialog.as_ref().unwrap()); + assert!((p.rgb[0] - 124.0 / 255.0).abs() < 0.01 && p.rgb[1] > 0.97 && p.rgb[2] > 0.97, "{p:?}: R kept, G and B full"); + // The slider sets R alone. + let slider = h.get_by_label("Color slider").rect(); + crate::test_window::click_at(&mut h, egui::pos2(slider.center().x, slider.bottom() - 1.0)); + h.run_steps(2); + let p = picked_of(h.state().app.ui.dialog.as_ref().unwrap()); + assert!(p.rgb[0] < 0.02 && p.rgb[1] > 0.97, "{p:?}"); + // Hue on the slider: the field is saturation across, brightness up. + h.state_mut().app.ui.dialog.as_mut().unwrap().fields.insert("hex".into(), json!("#7c1315")); + h.state_mut().app.ui.dialog.as_mut().unwrap().fields.insert("component".into(), json!("h")); + h.run_steps(2); + crate::test_window::click_at(&mut h, egui::pos2(field.left() + 1.0, field.top() + 1.0)); + h.run_steps(2); + let p = picked_of(h.state().app.ui.dialog.as_ref().unwrap()); + assert!(p.hsb[1] < 0.02 && p.hsb[2] > 0.98 && (p.hsb[0] - 359.0).abs() < 2.0, "{p:?}: no saturation, full brightness, the hue kept"); + // Lab shows its own view. + h.state_mut().app.ui.dialog.as_mut().unwrap().fields.insert("component".into(), json!("l")); + h.run_steps(2); + let _ = h.get_by_label("Lab Color Space View"); + // Add CMYK Swatch adds the colour as a CMYK swatch; OK applies it. + h.state_mut().app.ui.dialog.as_mut().unwrap().fields.insert("hex".into(), json!("#7c1315")); + h.run_steps(2); + let before = h.state().app.session.active().unwrap().doc.swatches.len(); + h.get_by_label("Add CMYK Swatch").click(); + h.run_steps(3); + let doc = &h.state().app.session.active().unwrap().doc; + assert_eq!(doc.swatches.len(), before + 1); + assert!(matches!( + doc.swatches.last().unwrap().value, + designcraft_color::swatch::SwatchValue::Color { color: designcraft_color::Color::Cmyk { .. }, .. } + )); + confirm(&mut h.state_mut().app).unwrap(); + let st = h.state().app.session.active().unwrap(); + let id = st.selection.items[0]; + let fill = st.doc.item(id).unwrap().fill.swatch.clone(); + assert_eq!(st.doc.resolve_color(&fill, 1.0).unwrap().to_hex(), "#7c1315"); + } + #[test] fn create_guides_dialog_targets_the_page_in_view() { let mut app = facing_app(6); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 245a6e287..87a3eda7b 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -58,6 +58,28 @@ const TABLE: &[(&str, [&str; 5])] = &[ ("Cut", ["Ausschneiden", "Couper", "Cortar", "カット", "剪切"]), ("Copy", ["Kopieren", "Copier", "Copiar", "コピー", "复制"]), ("Paste", ["Einfügen", "Coller", "Pegar", "ペースト", "粘贴"]), + ( + "RGB Color Space View", + [ + "RGB-Farbraumansicht", + "Affichage de l’espace colorimétrique RVB", + "Vista de espacio de color RGB", + "RGB カラースペース表示", + "RGB 色彩空间视图", + ], + ), + ( + "Lab Color Space View", + [ + "Lab-Farbraumansicht", + "Affichage de l’espace colorimétrique Lab", + "Vista de espacio de color Lab", + "Lab カラースペース表示", + "Lab 色彩空间视图", + ], + ), + ("Add CMYK Swatch", ["CMYK-Farbfeld hinzufügen", "Ajouter une nuance CMJN", "Añadir muestra CMYK", "CMYK スウォッチを追加", "添加 CMYK 色板"]), + ("Added swatch", ["Farbfeld hinzugefügt", "Nuance ajoutée", "Muestra añadida", "スウォッチを追加しました", "已添加色板"]), ( "Bulleted & Numbered Lists", [ diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index d1dcb7acf..29a703d35 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -30,6 +30,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "قص"), ("Copy", "نسخ"), ("Paste", "لصق"), + ("RGB Color Space View", "عرض مساحة ألوان RGB"), + ("Lab Color Space View", "عرض مساحة ألوان Lab"), + ("Add CMYK Swatch", "إضافة حامل ألوان CMYK"), + ("Added swatch", "تمت إضافة حامل الألوان"), ("Bulleted & Numbered Lists", "القوائم ذات التعداد النقطي والرقمي"), ("Current Page Number", "رقم الصفحة الحالية"), ("Apply Color (,)", "تطبيق اللون (,)"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 0f55578b5..d9eb9b272 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -30,6 +30,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Ausschneiden"), ("Copy", "Kopieren"), ("Paste", "Einfügen"), + ("RGB Color Space View", "RGB-Farbraumansicht"), + ("Lab Color Space View", "Lab-Farbraumansicht"), + ("Add CMYK Swatch", "CMYK-Farbfeld hinzufügen"), + ("Added swatch", "Farbfeld hinzugefügt"), ("Clear", "Löschen"), ("Duplicate", "Duplizieren"), ("Select All", "Alles auswählen"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 00328ac9f..1da1642d3 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -28,6 +28,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Taglia"), ("Copy", "Copia"), ("Paste", "Incolla"), + ("RGB Color Space View", "Vista spazio colore RGB"), + ("Lab Color Space View", "Vista spazio colore Lab"), + ("Add CMYK Swatch", "Aggiungi campione CMYK"), + ("Added swatch", "Campione aggiunto"), ("Bulleted & Numbered Lists", "Elenchi puntati e numerati"), ("Current Page Number", "Numero di pagina corrente"), ("Apply Color (,)", "Applica colore (,)"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index fe9e213e7..dd848f64b 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -30,6 +30,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "カット"), ("Copy", "コピー"), ("Paste", "ペースト"), + ("RGB Color Space View", "RGB カラースペース表示"), + ("Lab Color Space View", "Lab カラースペース表示"), + ("Add CMYK Swatch", "CMYK スウォッチを追加"), + ("Added swatch", "スウォッチを追加しました"), ("Bulleted & Numbered Lists", "箇条書き"), ("Apply Color (,)", "カラーを適用 (,)"), ("Apply Gradient (.)", "グラデーションを適用 (.)"), diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index b3379c6d7..12d4b0b8a 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -31,6 +31,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "ამოჭრა"), ("Copy", "კოპირება"), ("Paste", "ჩასმა"), + ("RGB Color Space View", "RGB ფერთა სივრცის ხედი"), + ("Lab Color Space View", "Lab ფერთა სივრცის ხედი"), + ("Add CMYK Swatch", "CMYK ნიმუშის დამატება"), + ("Added swatch", "ნიმუში დაემატა"), ("Reverse Path", "ტრაექტორიის შებრუნება"), ("Set Anchor", "საყრდენი წერტილის დაყენება"), ("Clear", "გასუფთავება"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 0675a2f66..76ca36985 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -31,6 +31,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Recortar"), ("Copy", "Copiar"), ("Paste", "Colar"), + ("RGB Color Space View", "Exibição do espaço de cores RGB"), + ("Lab Color Space View", "Exibição do espaço de cores Lab"), + ("Add CMYK Swatch", "Adicionar amostra CMYK"), + ("Added swatch", "Amostra adicionada"), ("Bulleted & Numbered Lists", "Listas com marcadores e numeradas"), ("Show Hidden Characters", "Mostrar caracteres ocultos"), ("Current Page Number", "Número da página atual"), diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 8f1d27f84..32d637087 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -31,6 +31,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Вирізати"), ("Copy", "Копіювати"), ("Paste", "Вставити"), + ("RGB Color Space View", "Подання колірного простору RGB"), + ("Lab Color Space View", "Подання колірного простору Lab"), + ("Add CMYK Swatch", "Додати зразок CMYK"), + ("Added swatch", "Додано зразок"), ("Bulleted & Numbered Lists", "Марковані й нумеровані списки"), ("Current Page Number", "Номер поточної сторінки"), ("Apply Color (,)", "Застосувати колір (,)"), From 7cf1e30acb7beed0127899549902191c41e0601d Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 15 Oct 2026 22:57:35 +0200 Subject: [PATCH 0009/1349] Color Picker: InDesign's layout at the app's density, its own OK / Cancel / Add CMYK Swatch at the top right Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 401 ++++++++++++++++++++++------------ 1 file changed, 256 insertions(+), 145 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 262a48b60..6e8fe34b5 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1538,6 +1538,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { let preferred_width: f32 = match d.id.as_str() { "alert" => 440.0, "closeDocument" | "updateLink" => 380.0, + "colorPicker" => 580.0, "newDocument" if crate::i18n::is_rtl(&app.ui.language) => 380.0, _ => 640.0, }; @@ -2201,6 +2202,15 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { } _ => {} }); + // The Color Picker has its own OK and Cancel, at the top right as InDesign's. + if d.id == "colorPicker" { + match d.fields.remove("_close").as_ref().and_then(Value::as_str) { + Some("ok") => result = Some(true), + Some("cancel") => result = Some(false), + _ => {} + } + return; + } ui.add_space(12.0); let ok_label = match d.id.as_str() { "closeDocument" => " Save ", @@ -4899,10 +4909,63 @@ fn store_picked(d: &mut Dialog, p: &Picked) { d.fields.insert("_lab".into(), json!(p.lab)); } -/// The Color Picker, laid out as InDesign's: the field of two components and the slider of the -/// third (the one whose radio button is on, R at first), the new colour over the one it replaces, -/// H/S/B, L/a/b, R/G/B and C/M/Y/K values, the hex code, and Add CMYK Swatch. +/// The Color Picker's place in the dialog, as InDesign's (points from the body's top-left). +mod picker_layout { + use egui::{Rect, pos2, vec2}; + // InDesign's proportions at this app's density (its 30 px fields are 21 pt here). + pub const SIZE: egui::Vec2 = vec2(566.0, 334.0); + pub fn field() -> Rect { + Rect::from_min_size(pos2(2.0, 31.0), vec2(265.0, 287.0)) + } + pub fn slider() -> Rect { + Rect::from_min_size(pos2(285.0, 32.0), vec2(19.0, 282.0)) + } + pub fn swatch() -> Rect { + Rect::from_min_size(pos2(319.0, 0.0), vec2(71.0, 90.0)) + } + /// OK, Cancel, Add … Swatch. + pub fn button(i: usize) -> Rect { + Rect::from_min_size(pos2(433.0, [0.0, 39.0, 78.0][i.min(2)]), vec2(132.0, 25.0)) + } + /// Row centres: H/L, S/a, B/b, (gap), R/C, G/M, B/Y, K, #. + pub const ROWS: [f32; 8] = [129.0, 157.0, 185.0, 224.0, 252.0, 280.0, 308.0, 320.0]; + /// The radio buttons' columns. + pub const LEFT: f32 = 326.0; + pub const RIGHT: f32 = 457.0; +} + +/// A value field: the text typed stays while it has the focus; a number that parses applies. +fn picker_field(ui: &mut egui::Ui, d: &mut Dialog, r: egui::Rect, key: &str, value: f32, range: (f32, f32)) -> Option { + let id = egui::Id::new(("color_picker_field", key)); + let editing = ui.memory(|m| m.has_focus(id)); + let shown = format!("{}", value.round() as i64); + let edit_key = format!("_edit_{key}"); + let mut text = if editing { d.fields.get(&edit_key).and_then(Value::as_str).map(str::to_string).unwrap_or(shown) } else { shown }; + let resp = ui.put( + r, + egui::TextEdit::singleline(&mut text) + .id(id) + .font(egui::FontId::proportional(11.5)) + .vertical_align(egui::Align::Center) + .margin(egui::Margin::symmetric(4, 2)), + ); + let mut out = None; + if resp.changed() + && let Ok(v) = text.trim().parse::() + && v.is_finite() + { + out = Some(v.clamp(range.0, range.1)); + } + d.fields.insert(edit_key, json!(text)); + out +} + +/// The Color Picker, laid out as InDesign's: the colour space view (a field of two components, +/// a slider for the third: the one whose radio button is on, R at first), the new colour over the +/// one it replaces, OK / Cancel / Add CMYK Swatch at the top right, H/S/B beside L/a/b, R/G/B +/// beside C/M/Y/K, and the hex code. Its buttons replace the dialog's own. fn color_picker(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { + use picker_layout as at; let lang = app.ui.language.clone(); let tr = |s: &str| crate::i18n::tr(&lang, s).to_string(); if !d.fields.contains_key("old") { @@ -4913,151 +4976,196 @@ fn color_picker(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { let mut p = picked_of(d); let before = p; let t = crate::theme::Tokens::get(ui.ctx()); - ui.horizontal_top(|ui| { - // The field and the slider. - ui.vertical(|ui| { - crate::rtl::label(ui, egui::RichText::new(tr(if comp.lab() { "Lab Color Space View" } else { "RGB Color Space View" })).size(11.5)); - ui.add_space(4.0); - ui.horizontal_top(|ui| { - let (fr, fresp) = ui.allocate_exact_size(egui::vec2(190.0, 200.0), egui::Sense::click_and_drag()); - let (tv, _, _) = p.coords(comp); - let cells = if matches!(comp, PickComp::R | PickComp::G | PickComp::Bl | PickComp::H) { 2 } else { 24 }; - gradient_mesh(ui.painter(), fr, cells, cells, |x, y| p.at(comp, tv, x, y).rgb); - ui.painter().rect_stroke(fr, 0.0, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Outside); - fresp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Other, true, "Color field")); - if let Some(pos) = fresp.interact_pointer_pos().filter(|_| fresp.is_pointer_button_down_on() || fresp.clicked()) { - let u = ((pos.x - fr.left()) / fr.width()).clamp(0.0, 1.0); - let v = ((fr.bottom() - pos.y) / fr.height()).clamp(0.0, 1.0); - p = p.at(comp, tv, u, v); + let (area, _) = ui.allocate_exact_size(at::SIZE, egui::Sense::hover()); + let o = area.min.to_vec2(); + let put = |r: egui::Rect| r.translate(o); + let font = egui::FontId::proportional(11.5); + let text = |ui: &egui::Ui, pos: egui::Pos2, align: egui::Align2, s: &str| { + ui.painter().text(pos, align, s, egui::FontId::proportional(11.5), t.text_strong); + }; + // The colour space view (a label, so screen readers hear which). + ui.scope_builder( + egui::UiBuilder::new() + .max_rect(egui::Rect::from_min_size(area.min, egui::vec2(260.0, 24.0))) + .layout(egui::Layout::left_to_right(egui::Align::Center)), + |ui| { + ui.label( + egui::RichText::new(tr(if comp.lab() { "Lab Color Space View" } else { "RGB Color Space View" })).size(11.5).color(t.text_strong), + ); + }, + ); + let fr = put(at::field()); + let fresp = ui.interact(fr, ui.id().with("cp_field"), egui::Sense::click_and_drag()); + let (tv, _, _) = p.coords(comp); + let cells = if matches!(comp, PickComp::R | PickComp::G | PickComp::Bl | PickComp::H) { 2 } else { 24 }; + gradient_mesh(ui.painter(), fr, cells, cells, |x, y| p.at(comp, tv, x, y).rgb); + fresp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Other, true, "Color field")); + if let Some(pos) = fresp.interact_pointer_pos().filter(|_| fresp.is_pointer_button_down_on() || fresp.clicked()) { + let u = ((pos.x - fr.left()) / fr.width()).clamp(0.0, 1.0); + let v = ((fr.bottom() - pos.y) / fr.height()).clamp(0.0, 1.0); + p = p.at(comp, tv, u, v); + } + // The marker: a cross with an open centre, white over black. + let (_, u, v) = p.coords(comp); + let m = egui::pos2(fr.left() + u * fr.width(), fr.bottom() - v * fr.height()); + let painter = ui.painter().with_clip_rect(fr); + for (dx, dy) in [(1.0, 0.0), (-1.0, 0.0), (0.0, 1.0), (0.0, -1.0)] { + let (a, b) = (m + egui::vec2(dx * 3.0, dy * 3.0), m + egui::vec2(dx * 10.0, dy * 10.0)); + let side = egui::vec2(dy, dx) * 1.2; + painter.line_segment([a + side, b + side], egui::Stroke::new(1.0, egui::Color32::BLACK)); + painter.line_segment([a - side, b - side], egui::Stroke::new(1.0, egui::Color32::BLACK)); + painter.line_segment([a, b], egui::Stroke::new(1.5, egui::Color32::WHITE)); + } + // The slider, with a marker on each side. + let sr = put(at::slider()); + let sresp = ui.interact(sr.expand2(egui::vec2(6.0, 0.0)), ui.id().with("cp_slider"), egui::Sense::click_and_drag()); + gradient_mesh(ui.painter(), sr, 1, 48, |_, y| p.slider_at(comp, y)); + sresp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Slider, true, "Color slider")); + if let Some(pos) = sresp.interact_pointer_pos().filter(|_| sresp.is_pointer_button_down_on() || sresp.clicked()) { + let tn = ((sr.bottom() - pos.y) / sr.height()).clamp(0.0, 1.0); + let (_, u, v) = p.coords(comp); + p = p.at(comp, tn, u, v); + } + let (tn, _, _) = p.coords(comp); + let y = sr.bottom() - tn * sr.height(); + for (x, dir) in [(sr.left(), 1.0), (sr.right(), -1.0)] { + let pts = vec![ + egui::pos2(x - 5.0 * dir, y - 4.5), + egui::pos2(x, y - 4.5), + egui::pos2(x + 3.5 * dir, y), + egui::pos2(x, y + 4.5), + egui::pos2(x - 5.0 * dir, y + 4.5), + ]; + ui.painter().add(egui::Shape::convex_polygon(pts, egui::Color32::WHITE, egui::Stroke::new(1.0, egui::Color32::from_gray(40)))); + } + // The new colour over the one it replaces. + let pr = put(at::swatch()); + let old = designcraft_color::Color::from_hex(&d.s("old")).map_or([0.0; 3], |c| c.to_rgb_uncalibrated()); + ui.painter().rect_filled(egui::Rect::from_min_max(pr.min, egui::pos2(pr.max.x, pr.center().y)), 0.0, color32(p.rgb)); + ui.painter().rect_filled(egui::Rect::from_min_max(egui::pos2(pr.min.x, pr.center().y), pr.max), 0.0, color32(old)); + ui.painter().rect_stroke(pr, 0.0, egui::Stroke::new(1.0, egui::Color32::from_gray(80)), egui::StrokeKind::Inside); + // OK, Cancel, Add CMYK Swatch: rounded, OK filled. + let pill = |ui: &mut egui::Ui, i: usize, label: &str, primary: bool| -> bool { + let r = put(at::button(i)); + let resp = ui.interact(r, ui.id().with(("cp_button", i)), egui::Sense::click()); + let (fill, fg, stroke) = if primary { + (t.accent_strong, egui::Color32::WHITE, egui::Stroke::NONE) + } else { + (if resp.hovered() { t.hover } else { egui::Color32::TRANSPARENT }, t.text_strong, egui::Stroke::new(1.0, t.text_dim)) + }; + ui.painter().rect(r, r.height() / 2.0, fill, stroke, egui::StrokeKind::Inside); + ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, label, egui::FontId::proportional(12.0), fg); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label)); + resp.clicked() + }; + if pill(ui, 0, &tr("OK"), true) || ui.input(|i| i.key_pressed(egui::Key::Enter)) { + d.fields.insert("_close".into(), json!("ok")); + } + if pill(ui, 1, &tr("Cancel"), false) || ui.input(|i| i.key_pressed(egui::Key::Escape)) { + d.fields.insert("_close".into(), json!("cancel")); + } + if pill(ui, 2, &tr("Add CMYK Swatch"), false) { + let [c, m, y, k] = designcraft_color::Color::Rgb { r: p.rgb[0], g: p.rgb[1], b: p.rgb[2] } + .to_cmyk_managed(designcraft_color::cms::active_settings().intent) + .map(|v| (v * 100.0).round()); + match app.run("swatch.create", json!({"color": {"c": c, "m": m, "y": y, "k": k}})) { + Ok(r) => app.status(format!("{} {}", tr("Added swatch"), r["name"].as_str().unwrap_or(""))), + Err(e) => app.status(e), + } + } + // The values: a radio button, a label, the field, a unit. + let mut comp_now = comp; + let mut edited: Option = None; + let cmyk = designcraft_color::Color::Rgb { r: p.rgb[0], g: p.rgb[1], b: p.rgb[2] } + .to_cmyk_managed(designcraft_color::cms::active_settings().intent) + .map(|v| v * 100.0); + // (column x of the radio, row, component, label, key, value, range, unit) + let rows: [(f32, usize, Option, &str, &str, f32, (f32, f32), &str); 13] = [ + (at::LEFT, 0, Some(PickComp::H), "H:", "h", p.hsb[0], (0.0, 360.0), "°"), + (at::LEFT, 1, Some(PickComp::S), "S:", "s", p.hsb[1] * 100.0, (0.0, 100.0), "%"), + (at::LEFT, 2, Some(PickComp::Br), "B:", "b", p.hsb[2] * 100.0, (0.0, 100.0), "%"), + (at::RIGHT, 0, Some(PickComp::L), "L:", "l", p.lab[0], (0.0, 100.0), ""), + (at::RIGHT, 1, Some(PickComp::A), "a:", "la", p.lab[1], (-128.0, 127.0), ""), + (at::RIGHT, 2, Some(PickComp::Lb), "b:", "lb", p.lab[2], (-128.0, 127.0), ""), + (at::LEFT, 3, Some(PickComp::R), "R:", "r", p.rgb[0] * 255.0, (0.0, 255.0), ""), + (at::LEFT, 4, Some(PickComp::G), "G:", "g", p.rgb[1] * 255.0, (0.0, 255.0), ""), + (at::LEFT, 5, Some(PickComp::Bl), "B:", "bl", p.rgb[2] * 255.0, (0.0, 255.0), ""), + (at::RIGHT, 3, None, "C:", "c", cmyk[0], (0.0, 100.0), "%"), + (at::RIGHT, 4, None, "M:", "m", cmyk[1], (0.0, 100.0), "%"), + (at::RIGHT, 5, None, "Y:", "y", cmyk[2], (0.0, 100.0), "%"), + (at::RIGHT, 6, None, "K:", "k", cmyk[3], (0.0, 100.0), "%"), + ]; + for (x, row, c, label, key, value, range, unit) in rows { + let cy = area.min.y + at::ROWS[row]; + let x = area.min.x + x; + match c { + Some(c) => { + let rr = egui::Rect::from_center_size(egui::pos2(x, cy), egui::vec2(14.0, 14.0)); + let resp = ui.interact(rr, ui.id().with(("cp_radio", key)), egui::Sense::click()); + ui.painter().circle(rr.center(), 6.0, t.input, egui::Stroke::new(1.0, t.text_dim)); + if comp_now == c { + ui.painter().circle_filled(rr.center(), 2.6, t.text_strong); } - let (_, u, v) = p.coords(comp); - let mark = egui::pos2(fr.left() + u * fr.width(), fr.bottom() - v * fr.height()); - ui.painter().circle_stroke(mark, 5.0, egui::Stroke::new(1.5, egui::Color32::WHITE)); - ui.painter().circle_stroke(mark, 6.0, egui::Stroke::new(1.0, egui::Color32::BLACK)); - ui.add_space(6.0); - let (sr, sresp) = ui.allocate_exact_size(egui::vec2(14.0, 200.0), egui::Sense::click_and_drag()); - gradient_mesh(ui.painter(), sr, 1, 48, |_, y| p.slider_at(comp, y)); - ui.painter().rect_stroke(sr, 0.0, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Outside); - sresp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Slider, true, "Color slider")); - if let Some(pos) = sresp.interact_pointer_pos().filter(|_| sresp.is_pointer_button_down_on() || sresp.clicked()) { - let tn = ((sr.bottom() - pos.y) / sr.height()).clamp(0.0, 1.0); - let (_, u, v) = p.coords(comp); - p = p.at(comp, tn, u, v); + resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::RadioButton, true, comp_now == c, label)); + if resp.clicked() { + comp_now = c; } - let (tn, _, _) = p.coords(comp); - let y = sr.bottom() - tn * sr.height(); - for (x, dir) in [(sr.left() - 1.0, 1.0), (sr.right() + 1.0, -1.0)] { - ui.painter().add(egui::Shape::convex_polygon( - vec![egui::pos2(x, y), egui::pos2(x - 5.0 * dir, y - 4.0), egui::pos2(x - 5.0 * dir, y + 4.0)], - t.text_strong, - egui::Stroke::NONE, - )); + text(ui, egui::pos2(x + 11.0, cy), egui::Align2::LEFT_CENTER, label); + } + // C/M/Y/K have no radio button: their labels end at the field. + None => text(ui, egui::pos2(x + 28.0, cy), egui::Align2::RIGHT_CENTER, label), + } + let fr = egui::Rect::from_min_size(egui::pos2(x + 35.0, cy - 10.5), egui::vec2(44.0, 21.0)); + if let Some(v) = picker_field(ui, d, fr, key, value, range) { + edited = Some(match key { + "h" => Picked::from_hsb([v, p.hsb[1], p.hsb[2]]), + "s" => Picked::from_hsb([p.hsb[0], v / 100.0, p.hsb[2]]), + "b" => Picked::from_hsb([p.hsb[0], p.hsb[1], v / 100.0]), + "l" => Picked::from_lab([v, p.lab[1], p.lab[2]], p.hsb[0]), + "la" => Picked::from_lab([p.lab[0], v, p.lab[2]], p.hsb[0]), + "lb" => Picked::from_lab([p.lab[0], p.lab[1], v], p.hsb[0]), + "r" => Picked::from_rgb([v / 255.0, p.rgb[1], p.rgb[2]], p.hsb[0]), + "g" => Picked::from_rgb([p.rgb[0], v / 255.0, p.rgb[2]], p.hsb[0]), + "bl" => Picked::from_rgb([p.rgb[0], p.rgb[1], v / 255.0], p.hsb[0]), + _ => { + let mut c = cmyk; + c[["c", "m", "y", "k"].iter().position(|k| *k == key).unwrap_or(0)] = v; + let [c, m, y, k] = c.map(|x| x / 100.0); + Picked::from_rgb(designcraft_color::Color::Cmyk { c, m, y, k }.to_rgb(), p.hsb[0]) } }); - }); - ui.add_space(10.0); - ui.vertical(|ui| { - // The new colour over the one it replaces. - let (pr, _) = ui.allocate_exact_size(egui::vec2(60.0, 60.0), egui::Sense::hover()); - let old = designcraft_color::Color::from_hex(&d.s("old")).map_or([0.0; 3], |c| c.to_rgb_uncalibrated()); - ui.painter().rect_filled(egui::Rect::from_min_max(pr.min, egui::pos2(pr.max.x, pr.center().y)), 0.0, color32(p.rgb)); - ui.painter().rect_filled(egui::Rect::from_min_max(egui::pos2(pr.min.x, pr.center().y), pr.max), 0.0, color32(old)); - ui.painter().rect_stroke(pr, 0.0, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Outside); - ui.add_space(10.0); - let mut comp_now = comp; - let mut edited: Option = None; - let [cc, cm, cy, ck] = designcraft_color::Color::Rgb { r: p.rgb[0], g: p.rgb[1], b: p.rgb[2] } - .to_cmyk_managed(designcraft_color::cms::active_settings().intent) - .map(|v| v * 100.0); - let mut cmyk = [cc, cm, cy, ck]; - egui::Grid::new("cp_values").num_columns(6).spacing([4.0, 4.0]).show(ui, |ui| { - let mut field = - |ui: &mut egui::Ui, c: Option, label: &str, v: &mut f32, range: std::ops::RangeInclusive, suffix: &str| -> bool { - match c { - Some(c) => { - ui.radio_value(&mut comp_now, c, ""); - } - None => { - ui.label(""); - } - } - ui.label(label); - ui.add(egui::DragValue::new(v).range(range).max_decimals(0).suffix(suffix)).changed() - }; - let (mut h, mut s, mut b) = (p.hsb[0], p.hsb[1] * 100.0, p.hsb[2] * 100.0); - let (mut l, mut la, mut lb) = (p.lab[0], p.lab[1], p.lab[2]); - let (mut r, mut g, mut bl) = (p.rgb[0] * 255.0, p.rgb[1] * 255.0, p.rgb[2] * 255.0); - // Rows as InDesign's: H S B beside L a b, R G B beside C M Y K. - let hsb_changed = - field(ui, Some(PickComp::H), "H:", &mut h, 0.0..=360.0, "°") | field(ui, Some(PickComp::L), "L:", &mut l, 0.0..=100.0, ""); - ui.end_row(); - let hsb_changed2 = - field(ui, Some(PickComp::S), "S:", &mut s, 0.0..=100.0, "%") | field(ui, Some(PickComp::A), "a:", &mut la, -128.0..=127.0, ""); - ui.end_row(); - let hsb_changed3 = - field(ui, Some(PickComp::Br), "B:", &mut b, 0.0..=100.0, "%") | field(ui, Some(PickComp::Lb), "b:", &mut lb, -128.0..=127.0, ""); - ui.end_row(); - if hsb_changed || hsb_changed2 || hsb_changed3 { - // Whichever space changed wins: HSB if its values moved, else Lab. - edited = Some(if (h, s, b) != (p.hsb[0], p.hsb[1] * 100.0, p.hsb[2] * 100.0) { - Picked::from_hsb([h, s / 100.0, b / 100.0]) - } else { - Picked::from_lab([l, la, lb], p.hsb[0]) - }); - } - let rgb_changed = field(ui, Some(PickComp::R), "R:", &mut r, 0.0..=255.0, ""); - let c1 = field(ui, None, "C:", &mut cmyk[0], 0.0..=100.0, "%"); - ui.end_row(); - let rgb_changed2 = field(ui, Some(PickComp::G), "G:", &mut g, 0.0..=255.0, ""); - let c2 = field(ui, None, "M:", &mut cmyk[1], 0.0..=100.0, "%"); - ui.end_row(); - let rgb_changed3 = field(ui, Some(PickComp::Bl), "B:", &mut bl, 0.0..=255.0, ""); - let c3 = field(ui, None, "Y:", &mut cmyk[2], 0.0..=100.0, "%"); - ui.end_row(); - ui.label(""); - ui.label(""); - ui.label(""); - let c4 = field(ui, None, "K:", &mut cmyk[3], 0.0..=100.0, "%"); - ui.end_row(); - if rgb_changed || rgb_changed2 || rgb_changed3 { - edited = Some(Picked::from_rgb([r / 255.0, g / 255.0, bl / 255.0], p.hsb[0])); - } - if c1 || c2 || c3 || c4 { - let [c, m, y, k] = cmyk.map(|v| v / 100.0); - edited = Some(Picked::from_rgb(designcraft_color::Color::Cmyk { c, m, y, k }.to_rgb(), p.hsb[0])); - } - }); - if let Some(e) = edited { - p = e; - } - if comp_now != comp { - d.fields.insert("component".into(), json!(comp_now.key())); - } - ui.add_space(4.0); - ui.horizontal(|ui| { - ui.label("#"); - let id = egui::Id::new("color_picker_hex"); - let editing = ui.memory(|m| m.has_focus(id)); - let mut h = if editing { d.s("_hexEdit") } else { p.hex().trim_start_matches('#').to_string() }; - if ui.add(egui::TextEdit::singleline(&mut h).id(id).desired_width(70.0)).changed() - && let Some(c) = designcraft_color::Color::from_hex(&h) - { - p = Picked::from_rgb(c.to_rgb_uncalibrated(), p.hsb[0]); - } - d.fields.insert("_hexEdit".into(), json!(h)); - }); - ui.add_space(8.0); - if ui.button(crate::rtl::widget(ui, tr("Add CMYK Swatch"))).clicked() { - let [c, m, y, k] = designcraft_color::Color::Rgb { r: p.rgb[0], g: p.rgb[1], b: p.rgb[2] } - .to_cmyk_managed(designcraft_color::cms::active_settings().intent) - .map(|v| (v * 100.0).round()); - match app.run("swatch.create", json!({"color": {"c": c, "m": m, "y": y, "k": k}})) { - Ok(r) => app.status(format!("{} {}", tr("Added swatch"), r["name"].as_str().unwrap_or(""))), - Err(e) => app.status(e), - } - } - }); - }); + } + if !unit.is_empty() { + text(ui, egui::pos2(fr.right() + 8.0, cy), egui::Align2::LEFT_CENTER, unit); + } + } + if let Some(e) = edited { + p = e; + } + if comp_now != comp { + d.fields.insert("component".into(), json!(comp_now.key())); + } + // The hex code, and the eyedropper's mark beside it. + let cy = area.min.y + at::ROWS[7]; + text(ui, egui::pos2(area.min.x + 321.0, cy), egui::Align2::LEFT_CENTER, "#:"); + let hr = egui::Rect::from_min_size(egui::pos2(area.min.x + 341.0, cy - 10.5), egui::vec2(64.0, 21.0)); + let id = egui::Id::new("color_picker_hex"); + let editing = ui.memory(|m| m.has_focus(id)); + let mut h = if editing { d.s("_hexEdit") } else { p.hex().trim_start_matches('#').to_string() }; + if ui + .put(hr, egui::TextEdit::singleline(&mut h).id(id).font(font).vertical_align(egui::Align::Center).margin(egui::Margin::symmetric(4, 2))) + .changed() + && let Some(c) = designcraft_color::Color::from_hex(&h) + { + p = Picked::from_rgb(c.to_rgb_uncalibrated(), p.hsb[0]); + } + d.fields.insert("_hexEdit".into(), json!(h)); + crate::icons::paint( + ui.painter(), + egui::Rect::from_center_size(egui::pos2(hr.right() + 16.0, cy), egui::vec2(15.0, 15.0)), + "tool-eyedropper", + t.icon, + ); if p != before { store_picked(d, &p); } @@ -7154,7 +7262,10 @@ mod tests { doc.swatches.last().unwrap().value, designcraft_color::swatch::SwatchValue::Color { color: designcraft_color::Color::Cmyk { .. }, .. } )); - confirm(&mut h.state_mut().app).unwrap(); + // Its own OK, at the top right, applies it. + h.get_by_label("OK").click(); + h.run_steps(3); + assert!(h.state().app.ui.dialog.is_none(), "OK closes it"); let st = h.state().app.session.active().unwrap(); let id = st.selection.items[0]; let fill = st.doc.item(id).unwrap().fill.swatch.clone(); From a97bd20a688f12c7107f239608f6d5ef76b7a4c1 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 16 Oct 2026 09:05:01 +0200 Subject: [PATCH 0010/1349] Cargo.lock: main's, with #500's designcraft-images dependency of idml --- Cargo.lock | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.lock b/Cargo.lock index afd57fddd..90c55cc62 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -997,6 +997,7 @@ dependencies = [ "log", "quick-xml", "regex", + "same-file", "serde", "serde_json", "tempfile", From c708b080333751bb5711638caa8f2a319394f81f Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 16 Oct 2026 09:47:56 +0200 Subject: [PATCH 0011/1349] Compose: a line past the breaker's estimated wrap segments is re-broken for its segment On narrow segments beside an object, the breaker's estimate of the segments ran out; the lines after it were set for the whole column and placed in one segment, running across the object. Co-Authored-By: Claude Opus 5.5 --- crates/compose/src/lib.rs | 4 +++- crates/engine/src/tests.rs | 25 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index afabb6fad..bdec0b163 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -1268,7 +1268,9 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C // paragraph from here, starting with this line's segments as they are. A pass // re-breaks at its first line only for a new line, whose segments it carries, so // every re-break makes progress; their number is capped too. - if (k > 0 || !continues) && rebreaks < 256 && slots.get(k).is_some_and(|&(a, b)| ((b - a) - (x1 - x0)).abs() > 0.5) { + // Past the estimated slots the breaker set the line for the whole column. + let (sa, sb) = slots.get(k).copied().unwrap_or((col.x0, col.x1)); + if (k > 0 || !continues) && rebreaks < 256 && ((sb - sa) - (x1 - x0)).abs() > 0.5 { rebreaks += 1; carry.insert(0, (x0, x1)); if !continues { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index dd038caa5..8e1999ddd 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1155,3 +1155,28 @@ fn a_line_fits_when_its_baseline_does() { assert!(!overset(&mut s, 78.5), "the line is set; its descenders hang below the frame"); assert!(overset(&mut s, 50.0), "a baseline below the frame still oversets the line"); } + + +/// Beside an object with text on both sides, every line stays within its segment, however many +/// lines the paragraph needs (the breaker's segment estimate can run out on narrow segments; a +/// line it set for the whole column ran across the object). +#[test] +fn every_line_beside_a_wrap_stays_within_its_segment() { + let mut s = Session::new(); + s.execute("file.new", &json!({"facingPages": false})).unwrap(); + // Placeholder text: paragraphs of a few sentences, some of them starting beside the object. + let t = s.execute("frame.create", &json!({"rect": [36, 36, 576, 756], "content": "text", "text": ""})).unwrap(); + s.execute("type.fillWithPlaceholder", &json!({})).unwrap(); + s.execute("selection.set", &json!({"ids": []})).unwrap(); + s.execute("frame.create", &json!({"rect": [196, 160, 416, 490]})).unwrap(); + s.execute("object.textWrap", &json!({"mode": "boundingBox", "offset": 6})).unwrap(); + let d = &s.doc().unwrap().doc; + let c = s.cache.get(d, designcraft_doc::StoryId(t["story"].as_u64().unwrap()), None); + let mut beside = 0; + for l in c.frames.iter().flat_map(|f| &f.lines) { + let end = l.glyphs.iter().filter(|g| g.visible).map(|g| g.x + g.adv).fold(l.x0, f64::max); + assert!(end <= l.x1 + 0.5, "line at {} runs to {end}, past its segment {}..{}", l.baseline, l.x0, l.x1); + beside += usize::from(l.x1 < 400.0 || l.x0 > 400.0); + } + assert!(beside > 20, "lines on both sides of the object: {beside}"); +} From afa015f113239a61e83ad09266ca8d2f38051ec2 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 16 Oct 2026 09:53:40 +0200 Subject: [PATCH 0012/1349] Text wrap: Alpha Channel contour traced from the image, holes with Include Inside Edges, open gaps kept Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 1 + crates/compose/src/lib.rs | 184 ++++++++++++--- crates/compose/src/tests.rs | 27 +++ crates/doc/src/build.rs | 1 + crates/doc/src/item.rs | 26 ++- crates/doc/src/lib.rs | 23 ++ crates/engine/src/cmd/alpha_wrap.rs | 285 ++++++++++++++++++++++++ crates/engine/src/cmd/mod.rs | 1 + crates/engine/src/cmd/object.rs | 24 +- crates/engine/src/lib.rs | 5 +- crates/engine/src/tests.rs | 1 - crates/idml/src/export.rs | 6 +- crates/idml/src/import.rs | 2 + crates/idml/src/tests.rs | 7 + crates/render/src/blendspace.rs | 3 + crates/ui-egui/src/i18n.rs | 5 + crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/it.rs | 2 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ka.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 2 + crates/ui-egui/src/i18n/uk.rs | 2 + crates/ui-egui/src/panels/mod.rs | 3 + crates/ui-egui/src/panels/properties.rs | 19 +- 25 files changed, 584 insertions(+), 49 deletions(-) create mode 100644 crates/engine/src/cmd/alpha_wrap.rs diff --git a/ROADMAP.md b/ROADMAP.md index 2aacdaf9b..739e9bb17 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -347,6 +347,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- 2026-10-16: Text Wrap › Contour › Alpha Channel follows a placed image's transparency, as InDesign's: the outline is traced from the image and follows it when it moves or is refitted; text keeps the open gaps between its parts, and enters enclosed holes with Include Inside Edges. - **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. diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index bdec0b163..eda488d83 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -369,6 +369,96 @@ impl Contour { } (lo <= hi).then_some((lo - self.offset, hi + self.offset)) } + + /// Occupied intervals across the whole line band, preserving gaps between parts of a + /// concave or compound outline. Project boundary edges and the filled middle slice: any + /// area that starts or ends inside the band is bounded by those projected edges. + fn band_spans(&self, y0: f64, y1: f64) -> Vec<(f64, f64)> { + let (low, high) = (y0 - self.offset, y1 + self.offset); + if !low.is_finite() || !high.is_finite() || high < low { + return self.band_extent(y0, y1).into_iter().collect(); + } + let mut spans = rings_band_spans(&self.rings, low, high); + // Extremely fragmented imported paths use the conservative outer extent, bounding the + // work of subtracting intervals from every line. A traced 128-column mask stays below it. + if spans.len() > 128 { + return self.band_extent(y0, y1).into_iter().collect(); + } + if !self.clip.is_empty() { + let clip = rings_band_spans(&self.clip, low, high); + let mut cut = Vec::new(); + let (mut i, mut j) = (0, 0); + while let (Some(&(a, b)), Some(&(c, d))) = (spans.get(i), clip.get(j)) { + if a.max(c) < b.min(d) { + cut.push((a.max(c), b.min(d))); + } + if b < d { + i += 1; + } else { + j += 1; + } + } + spans = cut; + } + merge_spans(spans.into_iter().map(|(a, b)| (a - self.offset, b + self.offset)).collect()) + } +} + +fn merge_spans(mut spans: Vec<(f64, f64)>) -> Vec<(f64, f64)> { + spans.retain(|(a, b)| a.is_finite() && b.is_finite() && b - a > 1e-9); + spans.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut out: Vec<(f64, f64)> = Vec::new(); + for (a, b) in spans { + if let Some(last) = out.last_mut().filter(|last| a <= last.1 + 1e-9) { + last.1 = last.1.max(b); + } else { + out.push((a, b)); + } + } + out +} + +fn rings_band_spans(rings: &[Vec], y0: f64, y1: f64) -> Vec<(f64, f64)> { + let mut spans = Vec::new(); + let mut crossings = Vec::new(); + let middle = y0 * 0.5 + y1 * 0.5; + for ring in rings { + let Some(&last) = ring.last() else { continue }; + let mut a = last; + for &b in ring { + let dy = b.y - a.y; + if a.y.max(b.y) >= y0 && a.y.min(b.y) <= y1 { + let (t0, t1) = if dy.abs() < 1e-12 { + (0.0, 1.0) + } else { + let (u, v) = ((y0 - a.y) / dy, (y1 - a.y) / dy); + (u.min(v).clamp(0.0, 1.0), u.max(v).clamp(0.0, 1.0)) + }; + let (x0, x1) = (a.x + t0 * (b.x - a.x), a.x + t1 * (b.x - a.x)); + spans.push((x0.min(x1), x0.max(x1))); + } + if (a.y <= middle && middle < b.y) || (b.y <= middle && middle < a.y) { + let x = a.x + (middle - a.y) / dy * (b.x - a.x); + if x.is_finite() { + crossings.push((x, if dy > 0.0 { 1i32 } else { -1 })); + } + } + a = b; + } + } + crossings.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut winding = 0i32; + let mut previous = None; + for (x, delta) in crossings { + if winding != 0 + && let Some(start) = previous + { + spans.push((start, x)); + } + winding += delta; + previous = Some(x); + } + merge_spans(spans) } /// The closed polylines of `path` (after `to_inner`), flattened; None if it is empty or too detailed. @@ -431,7 +521,13 @@ fn rings_band_extent(rings: &[Vec], y0: f64, y1: f64) -> Option<(f64, f64 /// The wrap exclusion of `other` (an item whose inner space maps to the spread by `xf`) for a /// frame whose inner space is reached from the spread by `inv`. `left_page` places the object on /// a left page (for the spine sides). -pub fn exclusion(other: &designcraft_doc::Item, xf: designcraft_geom::Affine, inv: designcraft_geom::Affine, left_page: bool) -> Exclusion { +pub fn exclusion( + doc: &Document, + other: &designcraft_doc::Item, + xf: designcraft_geom::Affine, + inv: designcraft_geom::Affine, + left_page: bool, +) -> Exclusion { let o = other.wrap.offsets; let b = if other.shape == designcraft_doc::Shape::Group { (xf * other.xf.inverse()).transform_rect_bbox(other.bounds()) @@ -452,7 +548,7 @@ pub fn exclusion(other: &designcraft_doc::Item, xf: designcraft_geom::Affine, in let contour = matches!(other.wrap.mode, WrapMode::BoundingBox | WrapMode::Contour).then_some(custom); return Exclusion { rect, mode: other.wrap.mode, side, contour }; } - let contour = (other.wrap.mode == WrapMode::Contour && other.shape != designcraft_doc::Shape::Group).then(|| contour_path(other)).and_then( + let contour = (other.wrap.mode == WrapMode::Contour && other.shape != designcraft_doc::Shape::Group).then(|| contour_path(doc, other)).and_then( |(path, frame)| { let c = Contour::of(&path, inv * xf, other.wrap.offsets[0])?; Some(match frame { @@ -466,11 +562,26 @@ pub fn exclusion(other: &designcraft_doc::Item, xf: designcraft_geom::Affine, in } /// The outline a contour wrap follows, in the item's inner space, and for an outline taken from -/// the placed graphic, the frame path that clips it. Graphic frames follow their contour type; -/// detected edges, alpha channels and image paths need the image, so they follow the frame's path -/// (as other frames do). -fn contour_path(it: &designcraft_doc::Item) -> (designcraft_geom::BezPath, Option) { +/// the placed graphic, the frame path that clips it. Graphic frames follow their contour type. An +/// alpha channel follows the image's traced outline, placed where the graphic is now (so it +/// follows the image when it moves or is refitted); its transparent holes count only with Include +/// Inside Edges. Detected edges and image paths, and an alpha channel not traced (yet), follow the +/// frame's path (as other frames do). +fn contour_path(doc: &Document, it: &designcraft_doc::Item) -> (designcraft_geom::BezPath, Option) { let frame = designcraft_geom::corners::apply(&it.path, &it.corners); + if it.wrap.contour == designcraft_doc::ContourType::AlphaChannel + && let Some(g) = it.graphic() + && let Some(o) = doc.alpha_outline(g.asset, it.wrap.alpha_threshold) + && o.width > 0 + && o.height > 0 + { + let to_graphic = designcraft_geom::Affine::scale_non_uniform(g.size.0 / f64::from(o.width), g.size.1 / f64::from(o.height)); + let mut path = o.outer.to_bezpath(); + if it.wrap.inside_edges { + path.extend(o.holes.to_bezpath().iter()); + } + return (g.xf * to_graphic * path, Some(frame)); + } if it.wrap.contour == designcraft_doc::ContourType::BoundingBox && let Some(g) = it.graphic() && let Some(fb) = it.path.bounds() @@ -573,7 +684,7 @@ pub fn frame_specs(doc: &Document, sid: StoryId) -> Vec { .page_at_x(other.bounds().center().x) .and_then(|pi| sp.pages.get(pi)) .is_some_and(|p| p.side == designcraft_doc::PageSide::Left); - let ex = exclusion(other, other.xf, inv, left); + let ex = exclusion(doc, other, other.xf, inv, left); let reach = ex.rect.intersect(item.inner_bounds()); if reach.width() > 0.0 && reach.height() > 0.0 { exclusions.push(ex); @@ -2592,39 +2703,40 @@ fn free_slots(f: &FrameSpec, col: Rect, y0: f64, y1: f64, size: f64, rtl: bool) let blocked = match ex.mode { WrapMode::JumpToNextColumn if y1 > r.y0 && r.x0 < col.x1 && r.x1 > col.x0 => return vec![], WrapMode::BoundingBox | WrapMode::Contour if overlaps_band => match &ex.contour { - Some(c) => c.band_extent(y0, y1), - None => Some((r.x0, r.x1)), + Some(c) => c.band_spans(y0, y1), + None => vec![(r.x0, r.x1)], }, - _ => None, + _ => Vec::new(), }; - let Some((a, b)) = blocked.filter(|&(a, b)| a < col.x1 && b > col.x0) else { continue }; - cut = true; - // One-sided wraps also block the column on the other side of the object. - let text_left = match ex.side { - WrapSide::LeftSide => Some(true), - WrapSide::RightSide => Some(false), - WrapSide::LargestArea => Some(r.x0 - col.x0 >= col.x1 - r.x1), - WrapSide::BothSides | WrapSide::TowardsSpine | WrapSide::AwayFromSpine => None, - }; - let (a, b) = match text_left { - Some(true) => (a, b.max(col.x1)), - Some(false) => (a.min(col.x0), b), - None => (a, b), - }; - let mut next = Vec::with_capacity(free.len() + 1); - for (fa, fb) in free { - if b <= fa || a >= fb { - next.push((fa, fb)); - continue; - } - if a > fa { - next.push((fa, a)); - } - if b < fb { - next.push((b, fb)); + for (a, b) in blocked.into_iter().filter(|&(a, b)| a < col.x1 && b > col.x0) { + cut = true; + // One-sided wraps also block the column on the other side of the object. + let text_left = match ex.side { + WrapSide::LeftSide => Some(true), + WrapSide::RightSide => Some(false), + WrapSide::LargestArea => Some(r.x0 - col.x0 >= col.x1 - r.x1), + WrapSide::BothSides | WrapSide::TowardsSpine | WrapSide::AwayFromSpine => None, + }; + let (a, b) = match text_left { + Some(true) => (a, b.max(col.x1)), + Some(false) => (a.min(col.x0), b), + None => (a, b), + }; + let mut next = Vec::with_capacity(free.len() + 1); + for (fa, fb) in free { + if b <= fa || a >= fb { + next.push((fa, fb)); + continue; + } + if a > fa { + next.push((fa, a)); + } + if b < fb { + next.push((b, fb)); + } } + free = next; } - free = next; } if !cut { return vec![(col.x0, col.x1)]; diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index d08efe034..9491afb67 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -4,6 +4,33 @@ use designcraft_geom::Rect; use super::*; +#[test] +fn contour_intervals_preserve_the_gap_between_legs() { + let mut path = designcraft_geom::BezPath::new(); + path.move_to((0.0, 0.0)); + for p in [(40.0, 0.0), (40.0, 100.0), (30.0, 100.0), (30.0, 20.0), (10.0, 20.0), (10.0, 100.0), (0.0, 100.0)] { + path.line_to(p); + } + path.close_path(); + let c = Contour::of(&path, designcraft_geom::Affine::IDENTITY, 3.0).unwrap(); + assert_eq!(c.band_spans(50.0, 60.0), vec![(-3.0, 13.0), (27.0, 43.0)]); + assert_eq!(c.band_spans(5.0, 15.0), vec![(-3.0, 43.0)]); + let frame = designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 35.0, 100.0)).to_bezpath(); + assert_eq!(c.within(&frame, designcraft_geom::Affine::IDENTITY).band_spans(50.0, 60.0), vec![(-3.0, 13.0), (27.0, 38.0)]); +} + +#[test] +fn contour_intervals_cover_the_whole_slanted_line_band() { + let mut path = designcraft_geom::BezPath::new(); + path.move_to((0.0, 0.0)); + for p in [(2.0, 0.0), (12.0, 10.0), (10.0, 10.0)] { + path.line_to(p); + } + path.close_path(); + let c = Contour::of(&path, designcraft_geom::Affine::IDENTITY, 0.0).unwrap(); + assert_eq!(c.band_spans(0.0, 10.0), vec![(0.0, 12.0)]); +} + const LOREM: &str = "Typography is the art and technique of arranging type to make written language legible, readable and appealing when displayed. \ The arrangement of type involves selecting typefaces, point sizes, line lengths, line spacing, and letter spacing, and adjusting the space between pairs of letters."; diff --git a/crates/doc/src/build.rs b/crates/doc/src/build.rs index 9fb075553..cc37907bd 100644 --- a/crates/doc/src/build.rs +++ b/crates/doc/src/build.rs @@ -160,6 +160,7 @@ impl Document { modified: 0, next_id: 0, font_scope: 0, + alpha_outlines: Vec::new(), }; let lid = LayerId(d.alloc()); d.layers.push(Layer { diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rs index 2d2cea760..bfaebe2c2 100644 --- a/crates/doc/src/item.rs +++ b/crates/doc/src/item.rs @@ -501,7 +501,7 @@ pub enum ContourType { } /// Text Wrap panel settings. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", default)] pub struct TextWrap { pub mode: WrapMode, @@ -515,6 +515,30 @@ pub struct TextWrap { /// item transforms it with the path; other path edits keep it as it is. #[serde(skip_serializing_if = "Option::is_none")] pub path: Option, + /// Contour Options › Include Inside Edges: an Alpha Channel contour also lets text into the + /// transparent holes it encloses (off: holes are blocked with the shape around them). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub inside_edges: bool, + /// Alpha Channel contour: pixels more opaque than this (0..254) count as the image. + pub alpha_threshold: u8, +} + +/// InDesign's default alpha threshold for contour wraps. +pub const DEFAULT_ALPHA_THRESHOLD: u8 = 25; + +impl Default for TextWrap { + fn default() -> Self { + TextWrap { + mode: WrapMode::default(), + offsets: [0.0; 4], + invert: false, + side: WrapSide::default(), + contour: ContourType::default(), + path: None, + inside_edges: false, + alpha_threshold: DEFAULT_ALPHA_THRESHOLD, + } + } } /// Frame fitting options (Object → Fitting → Frame Fitting Options). diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index c0fdc8fe2..47f752322 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -448,6 +448,21 @@ pub struct Asset { pub page: u32, } +/// The outline of a raster image's visible pixels (Text Wrap › Contour › Alpha Channel), in the +/// image's pixel space (0..width, 0..height). Derived from the image, so not saved: the engine +/// traces it again when a document opens. +#[derive(Clone, Debug, PartialEq)] +pub struct AlphaOutline { + pub asset: AssetId, + pub threshold: u8, + pub width: u32, + pub height: u32, + /// The outer boundaries of the visible areas. + pub outer: designcraft_geom::PathData, + /// The boundaries of transparent holes those areas enclose (wound the other way). + pub holes: designcraft_geom::PathData, +} + impl Asset { /// A raster image (PNG, JPEG, GIF, WebP, TIFF, BMP, PSD), as opposed to a PDF, EPS or SVG. pub fn is_raster(&self) -> bool { @@ -501,6 +516,9 @@ pub struct Document { pub sections: Vec
, #[serde(default)] pub assets: BTreeMap>, + /// Alpha Channel contour outlines of placed images (see [`AlphaOutline`]). Not saved. + #[serde(skip)] + pub alpha_outlines: Vec>, /// Hyperlinks (Window → Interactive → Hyperlinks). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub hyperlinks: Vec, @@ -695,6 +713,11 @@ impl Document { if sec.include_prefix { format!("{}{}", sec.prefix, num) } else { num } } + /// The Alpha Channel outline of `asset` at `threshold`, once the engine has traced it. + pub fn alpha_outline(&self, asset: AssetId, threshold: u8) -> Option<&AlphaOutline> { + self.alpha_outlines.iter().map(|o| &**o).find(|o| o.asset == asset && o.threshold == threshold) + } + pub fn layer(&self, id: LayerId) -> Option<&Layer> { self.layers.iter().find(|l| l.id == id) } diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs new file mode 100644 index 000000000..5f4abae58 --- /dev/null +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -0,0 +1,285 @@ +//! Text Wrap › Contour › Alpha Channel: the outline of a placed raster's visible pixels. +//! +//! The outline is traced once per image and threshold, in the image's pixel space, and kept on +//! the document ([`designcraft_doc::AlphaOutline`]). Composition maps it through the graphic's +//! current transform, so it follows the image when it is moved, scaled or refitted. +use std::sync::Arc; + +use designcraft_doc::{AlphaOutline, AssetId, ContourType, Document, WrapMode}; +use designcraft_geom::{BezPath, PathData, Point}; + +/// Images larger than this many pixels aren't traced (their contour follows the frame). +const MAX_PIXELS: u64 = 40_000_000; +/// The finest grid an outline is traced on; coarser grids when the outline would be too long. +const MAX_GRID: u32 = 256; +/// Boundary edges an outline may have. +const MAX_EDGES: usize = 1 << 16; + +/// Trace the outlines new Alpha Channel contours need and drop the ones nothing uses. Cheap when +/// nothing changed: tracing happens only for an image and threshold not seen before. +pub(crate) fn sync(doc: &mut Document) { + let mut wanted: Vec<(AssetId, u8)> = Vec::new(); + for sp in doc.spreads.iter().chain(doc.parents.iter()) { + for it in &sp.items { + if it.wrap.mode == WrapMode::Contour + && it.wrap.contour == ContourType::AlphaChannel + && let Some(g) = it.graphic() + && !wanted.contains(&(g.asset, it.wrap.alpha_threshold)) + { + wanted.push((g.asset, it.wrap.alpha_threshold)); + } + } + } + if wanted.is_empty() && doc.alpha_outlines.is_empty() { + return; + } + doc.alpha_outlines.retain(|o| wanted.contains(&(o.asset, o.threshold)) && doc.assets.contains_key(&o.asset)); + for (asset, threshold) in wanted { + if doc.alpha_outline(asset, threshold).is_some() { + continue; + } + let Some(a) = doc.assets.get(&asset).filter(|a| a.is_raster()) else { continue }; + if let Some(o) = trace(&a.data, asset, threshold) { + doc.alpha_outlines.push(Arc::new(o)); + } + } +} + +/// The outline of the pixels of `data` more opaque than `threshold`. None for an image that +/// can't be read, is too large, or has no transparency (its contour is its rectangle). +pub(crate) fn trace(data: &[u8], asset: AssetId, threshold: u8) -> Option { + let (w, h) = designcraft_images::pixel_size(data)?; + if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PIXELS { + return None; + } + let img = designcraft_images::decode_rgba(data)?; + if img.width() != w || img.height() != h { + return None; + } + let mut grid = MAX_GRID; + while grid >= 16 { + let (cols, rows) = (w.min(grid), h.min(grid)); + let (mask, transparent) = occupancy(img.as_raw(), w, h, cols, rows, threshold); + if !transparent { + return None; + } + if let Some((outer, holes)) = rings(&mask, cols as usize, rows as usize) { + let (sx, sy) = (f64::from(w) / f64::from(cols), f64::from(h) / f64::from(rows)); + let path = |rings: &[Vec<(i32, i32)>]| { + let mut p = BezPath::new(); + for ring in rings { + let mut pts = ring.iter().map(|&(x, y)| Point::new(f64::from(x) * sx, f64::from(y) * sy)); + let Some(first) = pts.next() else { continue }; + p.move_to(first); + for q in pts { + p.line_to(q); + } + p.close_path(); + } + PathData::from_bezpath(&p) + }; + return Some(AlphaOutline { asset, threshold, width: w, height: h, outer: path(&outer), holes: path(&holes) }); + } + grid /= 2; + } + None +} + +/// Which cells of a `cols` × `rows` grid hold a pixel of the `w` × `h` RGBA image `rgba` more +/// opaque than `threshold` (a cell is visible when any of its pixels is), and whether the image +/// has any transparency. +fn occupancy(rgba: &[u8], w: u32, h: u32, cols: u32, rows: u32, threshold: u8) -> (Vec, bool) { + let mut mask = vec![false; (cols as usize) * (rows as usize)]; + let mut transparent = false; + for (i, px) in rgba.chunks_exact(4).enumerate() { + let alpha = px[3]; + transparent |= alpha < 255; + if alpha > threshold { + let (x, y) = ((i as u64) % u64::from(w), (i as u64) / u64::from(w)); + let (gx, gy) = (x * u64::from(cols) / u64::from(w), y * u64::from(rows) / u64::from(h)); + if let Some(c) = mask.get_mut((gy * u64::from(cols) + gx) as usize) { + *c = true; + } + } + } + (mask, transparent) +} + +/// The closed boundaries of the visible cells, split into outer boundaries and the boundaries of +/// holes (by winding: each boundary keeps the visible cells on the same side). None when the +/// outline would have more than [`MAX_EDGES`] edges. +#[allow(clippy::type_complexity)] +fn rings(mask: &[bool], cols: usize, rows: usize) -> Option<(Vec>, Vec>)> { + use std::collections::BTreeMap; + let visible = |x: i32, y: i32| { + x >= 0 && y >= 0 && (x as usize) < cols && (y as usize) < rows && mask.get(y as usize * cols + x as usize).copied().unwrap_or(false) + }; + let mut edges: BTreeMap<(i32, i32), Vec<(i32, i32)>> = BTreeMap::new(); + let mut count = 0usize; + for y in 0..rows as i32 { + for x in 0..cols as i32 { + if !visible(x, y) { + continue; + } + for (open, a, b) in [ + (!visible(x, y - 1), (x, y), (x + 1, y)), + (!visible(x + 1, y), (x + 1, y), (x + 1, y + 1)), + (!visible(x, y + 1), (x + 1, y + 1), (x, y + 1)), + (!visible(x - 1, y), (x, y + 1), (x, y)), + ] { + if open { + count += 1; + if count > MAX_EDGES { + return None; + } + edges.entry(a).or_default().push(b); + } + } + } + } + let (mut outer, mut holes) = (Vec::new(), Vec::new()); + while let Some((&start, _)) = edges.first_key_value() { + let mut ring = vec![start]; + let mut at = start; + for _ in 0..=MAX_EDGES { + let next = edges.get_mut(&at).and_then(Vec::pop)?; + if edges.get(&at).is_some_and(Vec::is_empty) { + edges.remove(&at); + } + // Drop the middle of straight runs. + if let [.., a, b] = ring[..] + && (b.0 - a.0) * (next.1 - b.1) == (b.1 - a.1) * (next.0 - b.0) + { + ring.pop(); + } + if next == start { + break; + } + ring.push(next); + at = next; + } + // Shoelace in y-down space: positive for outer boundaries, negative for holes. + let area: i64 = ring + .iter() + .zip(ring.iter().cycle().skip(1)) + .map(|(&(x0, y0), &(x1, y1))| i64::from(x0) * i64::from(y1) - i64::from(x1) * i64::from(y0)) + .sum(); + if ring.len() >= 3 { + if area > 0 { outer.push(ring) } else { holes.push(ring) } + } + } + Some((outer, holes)) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + use crate::Session; + + /// A 64 × 64 PNG: visible where `on(x, y)`. + fn png(on: impl Fn(usize, usize) -> bool) -> Vec { + let mut pixels = vec![0; 64 * 64 * 4]; + for y in 0..64 { + for x in 0..64 { + let i = (y * 64 + x) * 4; + pixels[i] = 120; + pixels[i + 3] = if on(x, y) { 255 } else { 0 }; + } + } + designcraft_render::Rendered { width: 64, height: 64, pixels }.to_png() + } + + #[test] + fn traces_outer_boundaries_and_holes_apart() { + // A ring: a square with a square hole. + let data = png(|x, y| (8..56).contains(&x) && (8..56).contains(&y) && !((24..40).contains(&x) && (24..40).contains(&y))); + let o = trace(&data, AssetId(1), 25).unwrap(); + assert_eq!((o.width, o.height), (64, 64)); + assert_eq!((o.outer.subpaths.len(), o.holes.subpaths.len()), (1, 1)); + let (a, b) = (o.outer.bounds().unwrap(), o.holes.bounds().unwrap()); + assert_eq!((a.x0, a.y0, a.x1, a.y1), (8.0, 8.0, 56.0, 56.0)); + assert_eq!((b.x0, b.y0, b.x1, b.y1), (24.0, 24.0, 40.0, 40.0)); + // An opaque image has no alpha outline. + assert!(trace(&png(|_, _| true), AssetId(1), 25).is_none()); + } + + #[test] + fn an_alpha_channel_contour_is_traced_when_set_and_kept_out_of_the_saved_file() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let data = png(|x, _| (16..48).contains(&x)); + let id = s + .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": 100, "y": 100, "width": 128})) + .unwrap()["id"] + .clone(); + assert!(s.doc().unwrap().doc.alpha_outlines.is_empty()); + s.execute("object.textWrap", &json!({"ids": [id], "mode": "contour", "contour": "alphaChannel"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.alpha_outlines.len(), 1); + // Saved and opened again: traced again on open. + let bytes = crate::cmd::file::to_bytes(d); + let back = crate::cmd::file::from_bytes(&bytes).unwrap(); + assert!(back.alpha_outlines.is_empty(), "not saved"); + let st = crate::DocState::new(back, None); + assert_eq!(st.doc.alpha_outlines.len(), 1, "traced on open"); + // Wrap off: the outline goes. + s.execute("object.textWrap", &json!({"ids": [id], "mode": "none"})).unwrap(); + assert!(s.doc().unwrap().doc.alpha_outlines.is_empty()); + } + + /// An image placed 128 pt wide at (100, 100) (2 pt per pixel), its wrap a contour with no + /// offset, and a caption frame at `caption` with 8 pt "Hi". + fn page(data: &[u8], caption: [f64; 4]) -> (Session, Value, u64) { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let image = s + .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(data), "name": "cut.png", "x": 100, "y": 100, "width": 128})) + .unwrap()["id"] + .clone(); + let c = s.execute("frame.create", &json!({"rect": caption, "content": "text", "text": "Hi"})).unwrap(); + s.execute("selection.set", &json!({"ids": [c["id"]]})).unwrap(); + s.execute("type.char", &json!({"size": 8})).unwrap(); + s.execute("object.textWrap", &json!({"ids": [image], "mode": "contour", "offset": 0})).unwrap(); + (s, image, c["story"].as_u64().unwrap()) + } + + fn overset(s: &Session, story: u64) -> bool { + s.cache.get(&s.doc().unwrap().doc, designcraft_doc::StoryId(story), None).is_overset() + } + + use serde_json::Value; + + /// A caption fits between two legs of a cutout, and the contour follows the image when it's + /// moved within its frame (it isn't a boundary stored where it was traced). + #[test] + fn an_alpha_channel_contour_keeps_gaps_open_and_follows_the_image() { + // Legs at pixels 8..20 and 44..56: 116..140 and 188..212 on the page. + let (mut s, image, story) = page(&png(|x, _| (8..20).contains(&x) || (44..56).contains(&x)), [150.0, 120.0, 178.0, 170.0]); + assert!(overset(&s, story), "the frame's contour covers the gap"); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(!overset(&s, story), "the gap between the legs stays open"); + // The graphic moved 30 pt right within its frame: its left leg now covers the caption. + s.execute("selection.set", &json!({"ids": [image], "content": true})).unwrap(); + s.execute("transform.move", &json!({"dx": 30, "dy": 0})).unwrap(); + assert!(overset(&s, story), "the contour moved with the image"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!overset(&s, story)); + } + + /// A hole enclosed by the image stays blocked unless Include Inside Edges is on. + #[test] + fn holes_are_blocked_unless_inside_edges_are_included() { + // A ring: outer 116..212, hole 148..180 on the page. + let ring = png(|x, y| (8..56).contains(&x) && (8..56).contains(&y) && !((24..40).contains(&x) && (24..40).contains(&y))); + let (mut s, image, story) = page(&ring, [152.0, 152.0, 176.0, 176.0]); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(overset(&s, story), "the hole is blocked with the ring around it"); + s.execute("object.textWrap", &json!({"ids": [image], "insideEdges": true})).unwrap(); + assert!(!overset(&s, story), "Include Inside Edges lets text into the hole"); + for bad in [json!({"ids": [image], "threshold": 255}), json!({"ids": [image], "insideEdges": 1})] { + assert!(s.execute("object.textWrap", &bad).is_err()); + } + } +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 0bfb9727c..9147eef0d 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -1,5 +1,6 @@ //! The command registry. Ids follow InDesign's menu structure. +pub(crate) mod alpha_wrap; mod anchored; pub mod anchors; mod articles; diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 36bd1dac0..997a209ec 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -584,7 +584,7 @@ pub fn specs() -> Vec { "Text Wrap", ["Window"], Some("Cmd+Alt+W"), - "{mode?: none|boundingBox|contour|jumpObject|jumpToNextColumn (boundingBox when absent, unless side or contour is given: then unchanged), offset?: number|[t,l,b,r], invert?: bool, side?: bothSides|leftSide|rightSide|towardsSpine|awayFromSpine|largestArea, contour?: boundingBox|graphicFrame|sameAsClipping, ids?}; offset or contour drops an imported custom wrap boundary", + "{mode?: none|boundingBox|contour|jumpObject|jumpToNextColumn (boundingBox when absent, unless side, contour, insideEdges or threshold is given: then unchanged), offset?: number|[t,l,b,r], invert?: bool, side?: bothSides|leftSide|rightSide|towardsSpine|awayFromSpine|largestArea, contour?: boundingBox|graphicFrame|sameAsClipping|alphaChannel, insideEdges?: bool (alphaChannel: text may enter transparent holes), threshold?: 0..254 (alphaChannel: pixels more opaque count; default 25), ids?}; offset or contour drops an imported custom wrap boundary", has_selection, text_wrap ), @@ -1523,16 +1523,24 @@ fn text_wrap(s: &mut Session, p: &Value) -> Result { Some(v) => Some(serde_json::from_value(v.clone()).map_err(|_| bad("object.textWrap", "unknown side"))?), None => None, }; - // Detected edges, alpha channels and image paths need the image's pixels or paths, which - // composition doesn't read; those types aren't offered. + // Detected edges and image paths need the image's own analysis or paths, which aren't read; + // those types aren't offered. An alpha channel is traced from the image's pixels. let contour = match p.get("contour").map(|v| serde_json::from_value::(v.clone())) { - Some(Ok(c @ (ContourType::BoundingBox | ContourType::GraphicFrame | ContourType::SameAsClipping))) => Some(c), + Some(Ok(c @ (ContourType::BoundingBox | ContourType::GraphicFrame | ContourType::SameAsClipping | ContourType::AlphaChannel))) => Some(c), Some(_) => return Err(bad("object.textWrap", "unsupported contour type")), None => None, }; + let inside_edges = match p.get("insideEdges") { + None => None, + Some(v) => Some(v.as_bool().ok_or_else(|| bad("object.textWrap", "`insideEdges` is true or false"))?), + }; + let threshold = match p.get("threshold") { + None => None, + Some(v) => Some(v.as_u64().filter(|t| *t <= 254).ok_or_else(|| bad("object.textWrap", "`threshold` is 0..254"))? as u8), + }; let mode: Option = match p.get("mode") { Some(v) => Some(serde_json::from_value(v.clone()).map_err(|_| bad("object.textWrap", "unknown mode"))?), - None if side.is_some() || contour.is_some() => None, + None if side.is_some() || contour.is_some() || inside_edges.is_some() || threshold.is_some() => None, None => Some(WrapMode::BoundingBox), }; let off = match p.get("offset") { @@ -1560,6 +1568,12 @@ fn text_wrap(s: &mut Session, p: &Value) -> Result { if let Some(c) = contour { i.wrap.contour = c; } + if let Some(v) = inside_edges { + i.wrap.inside_edges = v; + } + if let Some(t) = threshold { + i.wrap.alpha_threshold = t; + } // A custom boundary has the offsets built in and replaces the contour, so setting // either one rebuilds the wrap from the frame. if off.is_some() || contour.is_some() { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 745e45647..6fa3daa04 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -131,7 +131,9 @@ impl Drop for FontScope { static NEXT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); impl DocState { - pub fn new(doc: Document, path: Option) -> Self { + pub fn new(mut doc: Document, path: Option) -> Self { + // Alpha Channel contour outlines aren't saved: trace them for the document as opened. + crate::cmd::alpha_wrap::sync(&mut doc); let active_layer = doc.default_layer(); let doc = Arc::new(doc); DocState { @@ -589,6 +591,7 @@ impl Session { let r = f(&mut doc, &mut sel)?; crate::cmd::sync_placeholders(&mut doc); crate::cmd::flex::sync(&mut doc); + crate::cmd::alpha_wrap::sync(&mut doc); doc.sync_endnote_story(); st.doc = Arc::new(doc); st.selection = sel; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 8e1999ddd..7a305c59f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1156,7 +1156,6 @@ fn a_line_fits_when_its_baseline_does() { assert!(overset(&mut s, 50.0), "a baseline below the frame still oversets the line"); } - /// Beside an object with text on both sides, every line stays within its segment, however many /// lines the paragraph needs (the breaker's segment estimate can run out on narrow segments; a /// line it set for the whole column ran across the object). diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs index 4e2c1bef1..ac26f5f85 100644 --- a/crates/idml/src/export.rs +++ b/crates/idml/src/export.rs @@ -1852,7 +1852,11 @@ impl<'a> Ex<'a> { .attr("Right", num(w.offsets[3]))]) .collect(), ) - .child(El::new("ContourOption").attr("ContourType", names::contour_type_out(w.contour)).attr("IncludeInsideEdges", "false")), + .child( + El::new("ContourOption") + .attr("ContourType", names::contour_type_out(w.contour)) + .attr("IncludeInsideEdges", if w.inside_edges { "true" } else { "false" }), + ), ); match &it.content { Content::Group { items } => { diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs index ad6b6447b..6fb042e1b 100644 --- a/crates/idml/src/import.rs +++ b/crates/idml/src/import.rs @@ -2429,6 +2429,7 @@ impl<'r> Importer<'r> { invert: w.get("Inverse") == Some("true"), side: names::wrap_side_in(w.get("TextWrapSide").unwrap_or("BothSides")), contour: names::contour_type_in(w.find("ContourOption").and_then(|c| c.get("ContourType")).unwrap_or("SameAsClipping")), + inside_edges: w.find("ContourOption").and_then(|c| c.get("IncludeInsideEdges")) == Some("true"), ..TextWrap::default() }; if let Some(o) = w.prop_el("TextWrapOffset") { @@ -2739,6 +2740,7 @@ impl<'r> Importer<'r> { modified: 0, next_id: self.next_id, font_scope: 0, + alpha_outlines: Vec::new(), }; Ok(d) } diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs index cca7803df..355ec3e7d 100644 --- a/crates/idml/src/tests.rs +++ b/crates/idml/src/tests.rs @@ -2627,6 +2627,13 @@ fn imports_and_round_trips_text_wrap_side_and_contour_type() { let back = import_idml(&export_idml(&d)).unwrap(); let w = back.spreads[0].items.iter().find(|i| i.graphic().is_some()).unwrap().wrap.clone(); assert_eq!((w.side, w.contour), (designcraft_doc::WrapSide::AwayFromSpine, designcraft_doc::ContourType::DetectEdges)); + assert!(!w.inside_edges); + // An Alpha Channel contour with Include Inside Edges. + d.item_mut(id).unwrap().wrap.contour = designcraft_doc::ContourType::AlphaChannel; + d.item_mut(id).unwrap().wrap.inside_edges = true; + let back = import_idml(&export_idml(&d)).unwrap(); + let w = back.spreads[0].items.iter().find(|i| i.graphic().is_some()).unwrap().wrap.clone(); + assert_eq!((w.contour, w.inside_edges), (designcraft_doc::ContourType::AlphaChannel, true)); } /// One single-column text frame at (0, 0)-(300, 200) on page 1, beside a 100 pt wide rectangle diff --git a/crates/render/src/blendspace.rs b/crates/render/src/blendspace.rs index 4121831f7..cc861cabc 100644 --- a/crates/render/src/blendspace.rs +++ b/crates/render/src/blendspace.rs @@ -113,6 +113,7 @@ fn same_document(old: &Document, new: &Document) -> bool { modified, next_id, font_scope, + alpha_outlines, } = new; let same_spreads = |a: &[std::sync::Arc], b: &[std::sync::Arc]| { a.len() == b.len() && a.iter().zip(b).all(|(a, b)| std::sync::Arc::ptr_eq(a, b)) @@ -124,6 +125,8 @@ fn same_document(old: &Document, new: &Document) -> bool { && old.stories.iter().zip(stories).all(|((a, x), (b, y))| a == b && std::sync::Arc::ptr_eq(x, y)) && old.assets.len() == assets.len() && old.assets.iter().zip(assets).all(|((a, x), (b, y))| a == b && std::sync::Arc::ptr_eq(x, y)) + && old.alpha_outlines.len() == alpha_outlines.len() + && old.alpha_outlines.iter().zip(alpha_outlines).all(|(a, b)| std::sync::Arc::ptr_eq(a, b)) && old.title == *title && old.settings == *settings && old.layers == *layers diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 245a6e287..f65158e52 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -58,6 +58,11 @@ const TABLE: &[(&str, [&str; 5])] = &[ ("Cut", ["Ausschneiden", "Couper", "Cortar", "カット", "剪切"]), ("Copy", ["Kopieren", "Copier", "Copiar", "コピー", "复制"]), ("Paste", ["Einfügen", "Coller", "Pegar", "ペースト", "粘贴"]), + ( + "Include Inside Edges", + ["Innenkanten einschließen", "Inclure les bords intérieurs", "Incluir bordes interiores", "内側エッジを含める", "包含内边缘"], + ), + ("Alpha Channel", ["Alphakanal", "Couche alpha", "Canal alfa", "アルファチャンネル", "Alpha 通道"]), ( "Bulleted & Numbered Lists", [ diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index d1dcb7acf..984677f9b 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -30,6 +30,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "قص"), ("Copy", "نسخ"), ("Paste", "لصق"), + ("Include Inside Edges", "تضمين الحواف الداخلية"), ("Bulleted & Numbered Lists", "القوائم ذات التعداد النقطي والرقمي"), ("Current Page Number", "رقم الصفحة الحالية"), ("Apply Color (,)", "تطبيق اللون (,)"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 0f55578b5..d4b2719f6 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -30,6 +30,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Ausschneiden"), ("Copy", "Kopieren"), ("Paste", "Einfügen"), + ("Include Inside Edges", "Innenkanten einschließen"), ("Clear", "Löschen"), ("Duplicate", "Duplizieren"), ("Select All", "Alles auswählen"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 00328ac9f..12f573390 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -28,6 +28,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Taglia"), ("Copy", "Copia"), ("Paste", "Incolla"), + ("Include Inside Edges", "Includi bordi interni"), + ("Alpha Channel", "Canale alfa"), ("Bulleted & Numbered Lists", "Elenchi puntati e numerati"), ("Current Page Number", "Numero di pagina corrente"), ("Apply Color (,)", "Applica colore (,)"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index fe9e213e7..8f1c5895a 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -30,6 +30,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "カット"), ("Copy", "コピー"), ("Paste", "ペースト"), + ("Include Inside Edges", "内側エッジを含める"), ("Bulleted & Numbered Lists", "箇条書き"), ("Apply Color (,)", "カラーを適用 (,)"), ("Apply Gradient (.)", "グラデーションを適用 (.)"), diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index b3379c6d7..e540ce17a 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -31,6 +31,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "ამოჭრა"), ("Copy", "კოპირება"), ("Paste", "ჩასმა"), + ("Include Inside Edges", "შიდა კიდეების ჩართვა"), ("Reverse Path", "ტრაექტორიის შებრუნება"), ("Set Anchor", "საყრდენი წერტილის დაყენება"), ("Clear", "გასუფთავება"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 0675a2f66..2cde5eca2 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -31,6 +31,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Recortar"), ("Copy", "Copiar"), ("Paste", "Colar"), + ("Include Inside Edges", "Incluir bordas internas"), + ("Alpha Channel", "Canal alfa"), ("Bulleted & Numbered Lists", "Listas com marcadores e numeradas"), ("Show Hidden Characters", "Mostrar caracteres ocultos"), ("Current Page Number", "Número da página atual"), diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 8f1d27f84..824086772 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -31,6 +31,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Вирізати"), ("Copy", "Копіювати"), ("Paste", "Вставити"), + ("Include Inside Edges", "Включити внутрішні краї"), + ("Alpha Channel", "Альфа-канал"), ("Bulleted & Numbered Lists", "Марковані й нумеровані списки"), ("Current Page Number", "Номер поточної сторінки"), ("Apply Color (,)", "Застосувати колір (,)"), diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs index fa40f5bec..54216f83f 100644 --- a/crates/ui-egui/src/panels/mod.rs +++ b/crates/ui-egui/src/panels/mod.rs @@ -51,6 +51,8 @@ pub struct SelInfo { pub wrap_offsets: [f64; 4], pub wrap_side: String, pub wrap_contour: String, + /// Contour Options › Include Inside Edges (an Alpha Channel contour). + pub wrap_inside_edges: bool, pub locked: bool, } @@ -161,6 +163,7 @@ pub fn sel_info(app: &DesignApp) -> Option { wrap_offsets: first.wrap.offsets, wrap_side: serde_json::to_value(first.wrap.side).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(), wrap_contour: serde_json::to_value(first.wrap.contour).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(), + wrap_inside_edges: first.wrap.inside_edges, locked: first.locked, }) } diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 8cbaa2ea6..0b5f3fd62 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -1903,11 +1903,22 @@ pub fn wrap_panel(app: &mut DesignApp, ui: &mut egui::Ui) { ]; wrap_combo(app, ui, "wrap_side", "Wrap To", &sides, &[], &i.wrap_side, "side"); if i.wrap == "contour" && i.is_graphic { - // Detected edges, alpha channels and image paths aren't offered: composition doesn't read - // the image. An imported one shows by name and wraps around the frame. - let types = [("boundingBox", "Bounding Box"), ("graphicFrame", "Graphic Frame"), ("sameAsClipping", "Same as Clipping")]; - let shown_only = [("detectEdges", "Detect Edges"), ("alphaChannel", "Alpha Channel"), ("photoshopPath", "Photoshop Path")]; + // Detected edges and image paths aren't offered: they need the image's own analysis or + // paths. An imported one shows by name and wraps around the frame. + let types = [ + ("boundingBox", "Bounding Box"), + ("alphaChannel", "Alpha Channel"), + ("graphicFrame", "Graphic Frame"), + ("sameAsClipping", "Same as Clipping"), + ]; + let shown_only = [("detectEdges", "Detect Edges"), ("photoshopPath", "Photoshop Path")]; wrap_combo(app, ui, "wrap_contour", "Contour Type", &types, &shown_only, &i.wrap_contour, "contour"); + if i.wrap_contour == "alphaChannel" { + let mut inside = i.wrap_inside_edges; + if widgets::checkbox(ui, &mut inside, crate::i18n::tr(&app.ui.language, "Include Inside Edges")).changed() { + let _ = app.run("object.textWrap", json!({"insideEdges": inside})); + } + } } } From a04c805ad72dd9aac51e433977eed2d7c98f13ac Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 16 Oct 2026 10:53:30 +0200 Subject: [PATCH 0013/1349] Direct Selection on a selected frame selects its image, so Delete keeps the frame A Direct Selection click on an image left the selection alone when its frame was already selected with the Selection tool, so Delete removed the frame and the image together. The click now switches to the image inside, and Delete leaves the empty frame (Fixes #1124). Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 1 + crates/engine/src/tests.rs | 31 +++++++++++++++++++++++++++++++ crates/tools/src/select.rs | 8 +++++++- 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index 2aacdaf9b..46f5907bf 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -347,6 +347,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-10-16** · A Direct Selection click on an image whose frame is already selected selects the image, so Delete removes only the image and leaves the empty frame, as in InDesign. No readiness percentage change. - **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. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 616a86398..cdce8b218 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1110,3 +1110,34 @@ fn a_line_fits_when_its_baseline_does() { assert!(!overset(&mut s, 78.5), "the line is set; its descenders hang below the frame"); assert!(overset(&mut s, 50.0), "a baseline below the frame still oversets the line"); } + +#[test] +fn direct_selection_on_a_selected_frame_deletes_only_its_image() { + use designcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + let dir = std::env::temp_dir().join(format!("dc-direct-delete-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let png = dir.join("photo.png"); + std::fs::write(&png, designcraft_render::Rendered { width: 100, height: 100, pixels: vec![40u8; 100 * 100 * 4] }.to_png()).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let frame = s.execute("frame.create", &json!({"rect": [100, 100, 200, 200]})).unwrap()["id"].as_u64().unwrap(); + s.execute("file.place", &json!({"path": png.to_string_lossy(), "frame": frame})).unwrap(); + let v = ViewInfo::at_zoom(1.0); + let click = |s: &mut Session| { + s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 150.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 150.0), v).unwrap(); + }; + // The frame is selected with the Selection tool, then the image is clicked with Direct Selection. + s.set_tool("selection"); + click(&mut s); + assert!(!s.doc().unwrap().selection.content); + s.set_tool("directSelection"); + click(&mut s); + assert!(s.doc().unwrap().selection.content, "Direct Selection selects the image inside the selected frame"); + assert!(s.tool_key(ToolKey::Delete, Mods::default(), v).unwrap()); + let st = s.doc().unwrap(); + let it = st.doc.item(designcraft_doc::ItemId(frame)).expect("the frame stays"); + assert!(matches!(it.content, designcraft_doc::Content::Unassigned), "{:?}", it.content); + assert_eq!(st.selection.items, vec![designcraft_doc::ItemId(frame)]); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 10da23f85..b66f0a0bd 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -225,6 +225,11 @@ pub fn handles(r: Rect) -> [Point; 8] { ] } +/// The item is a frame holding a placed graphic. +fn has_graphic(cx: &ToolContext, id: ItemId) -> bool { + cx.doc.item(id).is_some_and(|it| matches!(it.content, designcraft_doc::Content::Graphic(_))) +} + fn handle_at(cx: &ToolContext, p: Point) -> Option { let b = cx.selection_bounds()?; let tol = cx.tol(5.0); @@ -538,7 +543,8 @@ impl Tool for SelectionTool { } else { out.push(Action::Exec("selection.toggle".into(), json!({"id": id.0}))); } - } else if !cx.selection.contains(id) { + } else if !cx.selection.contains(id) || (self.direct && !cx.selection.content && has_graphic(cx, id)) { + // Direct Selection on a selected frame selects the graphic inside it. out.push(Action::Exec("selection.set".into(), json!({"ids": [id.0], "content": self.direct}))); } self.drag = Drag::Pending { start: p, hit: true }; From fb77f286e02189732426bc0c7f148bf6d1077ea5 Mon Sep 17 00:00:00 2001 From: midasmatterhorn <248507632+midasmatterhorn@users.noreply.github.com> Date: Fri, 16 Oct 2026 14:46:23 +0300 Subject: [PATCH 0014/1349] images: a WMF-only DOS EPS is not read as a TIFF preview The DOS EPS header is 30 bytes: WMF offsets at 12/16, TIFF at 20/24, checksum at 28-29 (EPSF 3.0, section 5.2). Reading the TIFF preview from the WMF slot stopped standard previews from loading; the offsets and the fixture are back where the spec puts them, and a WMF-only file now has a regression test. --- crates/images/src/eps.rs | 35 +++++++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/crates/images/src/eps.rs b/crates/images/src/eps.rs index 394e7aeaa..93715d910 100644 --- a/crates/images/src/eps.rs +++ b/crates/images/src/eps.rs @@ -14,13 +14,10 @@ fn u32le(b: &[u8], at: usize) -> Option { } /// The PostScript section and the TIFF preview (DOS EPS). -/// -/// The binary header is 22 bytes: the magic (0xC5D0, 0xD3C6), `psStart`, `psLength`, -/// `tiffStart`, `tiffLength`, then a two-byte checksum. fn sections(bytes: &[u8]) -> (&[u8], Option<&[u8]>) { if bytes.starts_with(&[0xC5, 0xD0, 0xD3, 0xC6]) { let ps = u32le(bytes, 4).zip(u32le(bytes, 8)).and_then(|(o, l)| bytes.get(o..o.checked_add(l)?)).unwrap_or(&[]); - let tiff = u32le(bytes, 12).zip(u32le(bytes, 16)).filter(|(o, l)| *o > 0 && *l > 0).and_then(|(o, l)| bytes.get(o..o.checked_add(l)?)); + let tiff = u32le(bytes, 20).zip(u32le(bytes, 24)).filter(|(o, l)| *o > 0 && *l > 0).and_then(|(o, l)| bytes.get(o..o.checked_add(l)?)); return (ps, tiff); } (bytes, None) @@ -227,16 +224,15 @@ mod tests { let (png, size) = eps_proxy(eps).unwrap(); assert_eq!(size, (100.5, 50.25)); assert_eq!(crate::pixel_size(&png), Some((201, 101))); - // DOS EPS with a TIFF preview: the preview is the proxy. The binary header is 22 bytes: - // the magic, psStart, psLength, tiffStart, tiffLength, then a two-byte checksum. + // DOS EPS with a TIFF preview: the preview is the proxy. let mut tiff = Vec::new(); image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(10, 5, image::Rgba([255, 0, 0, 255]))) .write_to(&mut std::io::Cursor::new(&mut tiff), image::ImageFormat::Tiff) .unwrap(); let mut dos = vec![0xC5, 0xD0, 0xD3, 0xC6]; - let ps_off = 22usize; + let ps_off = 30usize; let tiff_off = ps_off + eps.len(); - for v in [ps_off, eps.len(), tiff_off, tiff.len()] { + for v in [ps_off, eps.len(), 0, 0, tiff_off, tiff.len()] { dos.extend((v as u32).to_le_bytes()); } dos.extend([0xFF, 0xFF]); @@ -249,6 +245,29 @@ mod tests { assert!(!is_eps(b"%!PS-Adobe-3.0\nnot encapsulated")); } + #[test] + fn dos_eps_wmf_only_is_not_read_as_tiff() { + let eps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 50\nnewpath\n%%EOF\n"; + let wmf = b"WMFDATA!"; + let mut dos = vec![0xC5, 0xD0, 0xD3, 0xC6]; + let ps_off = 30usize; + let wmf_off = ps_off + eps.len(); + for v in [ps_off, eps.len(), wmf_off, wmf.len(), 0, 0] { + dos.extend((v as u32).to_le_bytes()); + } + dos.extend([0xFF, 0xFF]); + dos.extend_from_slice(eps); + dos.extend_from_slice(wmf); + assert!(is_eps(&dos)); + // The WMF bytes are not a TIFF preview. + assert!(sections(&dos).1.is_none()); + // The PostScript section still parses, and the proxy is the no-preview placeholder. + assert_eq!(bounding_box(&dos), Some([0.0, 0.0, 100.0, 50.0])); + let (png, size) = eps_proxy(&dos).unwrap(); + assert_eq!(size, (100.0, 50.0)); + assert_eq!(crate::pixel_size(&png), Some((200, 100))); + } + #[test] fn eps_bounding_box_rejects_nonfinite_sizes() { let bb = |line: &str| bounding_box(format!("%!PS-Adobe-3.0 EPSF-3.0\n{line}\n").as_bytes()); From 37e632881a71b474f201adb9c44fd43368b6d1b2 Mon Sep 17 00:00:00 2001 From: moppeeer <339764117+moppeeer@users.noreply.github.com> Date: Fri, 16 Oct 2026 14:52:01 +0200 Subject: [PATCH 0015/1349] UI.ColorDefaults: show document defaults in the Color panel When nothing is selected, display the new-object fill and stroke supplied by #1081. Existing selection targets retain their path. Exercise a real spectrum click, existing/new shape colors and undo in the whole-window regression. Co-Authored-By: GPT-6 Astra --- crates/ui-egui/src/panels/swatches.rs | 47 ++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index 3e7030e87..9cd71ac82 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -340,7 +340,15 @@ pub enum ColorMode { /// swatch), the spectrum ramp, Add to Swatches. Edits apply unnamed colours (`object.color`). pub fn color_panel(app: &mut DesignApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); - let Some((fill, fill_tint, stroke_sw, stroke_tint)) = super::color_target(app) else { + let target = super::color_target(app).or_else(|| { + let state = app.session.active()?; + if !state.selection.items.is_empty() || state.selection.text.is_some() || state.selection.cells.is_some() { + return None; + } + let colors = &state.doc.settings.new_object; + Some((colors.fill.clone(), colors.fill_tint, colors.stroke.clone(), colors.stroke_tint)) + }); + let Some((fill, fill_tint, stroke_sw, stroke_tint)) = target else { ui.label(crate::rtl::widget( ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Select an object or text to color its fill or stroke.")).color(t.text_dim), @@ -546,6 +554,7 @@ fn cmyk_ramp(k: usize, x: f32) -> egui::Color32 { /// The spectrum ramp: hue across, light to dark down; click to apply. fn spectrum(app: &mut DesignApp, ui: &mut egui::Ui, target: &str) { let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 36.0), Sense::click()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, crate::i18n::tr(&app.ui.language, "Color spectrum"))); let at = |u: f32, v: f32| -> [f32; 3] { let c = egui::ecolor::Hsva::new(u, (v * 2.0).min(1.0), (2.0 - v * 2.0).min(1.0), 1.0).to_rgb(); [c[0], c[1], c[2]] @@ -586,6 +595,42 @@ fn color_json(c: &designcraft_color::Color) -> serde_json::Value { } } +#[cfg(test)] +mod color_panel_defaults_tests { + use super::*; + use egui_kittest::kittest::Queryable; + + #[test] + fn color_panel_with_no_selection_edits_future_shapes_without_recoloring_existing_ones() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let old = + designcraft_doc::ItemId(app.run("frame.create", json!({"rect":[72,72,200,200],"content":"unassigned"})).unwrap()["id"].as_u64().unwrap()); + let original = app.session.active().unwrap().doc.item(old).unwrap().stroke.clone(); + app.run("selection.set", json!({"ids":[]})).unwrap(); + app.ui.stroke_front = true; + app.run("window.panel", json!({"panel":"color"})).unwrap(); + let mut h = crate::test_window::open(app, vec2(1440.0, 900.0)); + assert!(h.query_by_label("Select an object or text to color its fill or stroke.").is_none()); + let ramp = h.get_by_label("Color spectrum").rect(); + crate::test_window::click_at(&mut h, egui::pos2(ramp.left() + ramp.width() / 3.0, ramp.center().y)); + let defaults = h.state().app.session.active().unwrap().doc.settings.new_object.clone(); + assert_ne!(defaults.stroke, original.swatch); + assert_eq!(h.state().app.session.active().unwrap().doc.item(old).unwrap().stroke, original); + h.state_mut().app.run("selection.set", json!({"ids":[old.0]})).unwrap(); + assert_eq!(crate::panels::color_target(&mut h.state_mut().app).unwrap().2, original.swatch); + h.state_mut().app.run("selection.set", json!({"ids":[]})).unwrap(); + let new = designcraft_doc::ItemId( + h.state_mut().app.run("frame.create", json!({"rect":[240,72,368,200],"content":"unassigned"})).unwrap()["id"].as_u64().unwrap(), + ); + assert_eq!(h.state().app.session.active().unwrap().doc.item(new).unwrap().stroke.swatch, defaults.stroke); + h.state_mut().app.run("edit.undo", json!({})).unwrap(); + h.state_mut().app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.state().app.session.active().unwrap().doc.settings.new_object.stroke, original.swatch); + assert_eq!(h.state().app.session.active().unwrap().doc.item(old).unwrap().stroke, original); + } +} + /// Stops in `object.gradient` form. fn stops_json(g: &designcraft_color::Gradient) -> Vec { g.stops From a7e1c0e974c226985b61f96f75eb486443cb635c Mon Sep 17 00:00:00 2001 From: moppeeer <339764117+moppeeer@users.noreply.github.com> Date: Fri, 16 Oct 2026 17:52:53 +0200 Subject: [PATCH 0016/1349] Format.NullableOverrides: preserve automatic annotation and list-tab values Use the existing explicit-null deserializer for Ruby and Kenten sizes, tints and stroke weights, plus the automatic list tab. Extend native ZIP and legacy JSON inheritance regressions for local and named-style clears, absent overrides and explicit values. Found when a no-edit course-book roundtrip discarded eight CJK defaults. Co-Authored-By: GPT-6 Astra --- crates/doc/src/attrs.rs | 18 +++++++++--------- crates/format/src/lib.rs | 29 ++++++++++++++++++++++++++++- 2 files changed, 37 insertions(+), 10 deletions(-) diff --git a/crates/doc/src/attrs.rs b/crates/doc/src/attrs.rs index 077637672..d30489c9e 100644 --- a/crates/doc/src/attrs.rs +++ b/crates/doc/src/attrs.rs @@ -1086,7 +1086,7 @@ attr_set! { kenten_font: String = String::new(), kenten_font_style: String = String::new(), /// Mark size in points; `None` is half the text size. - kenten_size: Option = None, + kenten_size: Option = None => "deserialize_explicit_value", /// Horizontal / vertical scale of the mark, 1.0 = 100%. kenten_x_scale: f64 = 1.0, kenten_y_scale: f64 = 1.0, @@ -1099,10 +1099,10 @@ attr_set! { /// Mark fill and stroke swatches (empty = the text's), tints and stroke weight (`None` = /// the text's). kenten_fill: String = String::new(), - kenten_fill_tint: Option = None, + kenten_fill_tint: Option = None => "deserialize_explicit_value", kenten_stroke: String = String::new(), - kenten_stroke_tint: Option = None, - kenten_stroke_weight: Option = None, + kenten_stroke_tint: Option = None => "deserialize_explicit_value", + kenten_stroke_weight: Option = None => "deserialize_explicit_value", kenten_overprint_fill: crate::cjk_settings::AdornmentOverprint = crate::cjk_settings::AdornmentOverprint::Auto, kenten_overprint_stroke: crate::cjk_settings::AdornmentOverprint = crate::cjk_settings::AdornmentOverprint::Auto, // Shatai (斜体): the character is compressed across the direction at `shatai_angle`. @@ -1126,7 +1126,7 @@ attr_set! { ruby_font: String = String::new(), ruby_font_style: String = String::new(), /// Points; `None` is half the parent size. - ruby_font_size: Option = None, + ruby_font_size: Option = None => "deserialize_explicit_value", /// 1.0 = 100%. ruby_x_scale: f64 = 1.0, ruby_y_scale: f64 = 1.0, @@ -1147,10 +1147,10 @@ attr_set! { ruby_scaling_min: f64 = 0.66, /// Ruby colour: empty is the text's colour; `None` tint and weight follow the text. ruby_fill: String = String::new(), - ruby_fill_tint: Option = None, + ruby_fill_tint: Option = None => "deserialize_explicit_value", ruby_stroke: String = String::new(), - ruby_stroke_tint: Option = None, - ruby_stroke_weight: Option = None, + ruby_stroke_tint: Option = None => "deserialize_explicit_value", + ruby_stroke_weight: Option = None => "deserialize_explicit_value", ruby_overprint_fill: crate::cjk_settings::AdornmentOverprint = crate::cjk_settings::AdornmentOverprint::Auto, ruby_overprint_stroke: crate::cjk_settings::AdornmentOverprint = crate::cjk_settings::AdornmentOverprint::Auto, /// Digits (World-Ready): how 0–9 are drawn. @@ -1351,7 +1351,7 @@ attr_set! { bullet_align: ListAlign = ListAlign::Left, number_align: ListAlign = ListAlign::Left, /// A tab stop for the text after the bullet or number, from the column's left edge. - list_tab: Option = None, + list_tab: Option = None => "deserialize_explicit_value", /// Restart Numbers at This Level After: a paragraph at a higher level (0 = any; otherwise /// that level) starts this level's numbering again. restart_numbers: bool = true, diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index d5653eb9d..c77896b48 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -794,6 +794,14 @@ mod tests { underline_offset: Some(Some(1.0)), strikethrough_weight: Some(Some(2.0)), strikethrough_offset: Some(Some(1.0)), + kenten_size: Some(Some(14.0)), + kenten_fill_tint: Some(Some(0.3)), + kenten_stroke_tint: Some(Some(0.4)), + kenten_stroke_weight: Some(Some(2.0)), + ruby_font_size: Some(Some(14.0)), + ruby_fill_tint: Some(Some(0.3)), + ruby_stroke_tint: Some(Some(0.4)), + ruby_stroke_weight: Some(Some(2.0)), ..Default::default() }; // Legacy JSON loads as format 1, whose upgrade pins Keep Lines Together and Align Left @@ -803,6 +811,7 @@ mod tests { start_at: Some(Some(7)), paragraph_kashida_width: Some(Some(0.5)), kinsoku: Some(Some(Default::default())), + list_tab: Some(Some(36.0)), keep_all_lines: Some(true), drop_cap_align_left: Some(true), ..Default::default() @@ -817,9 +826,18 @@ mod tests { underline_offset: Some(None), strikethrough_weight: Some(None), strikethrough_offset: Some(None), + kenten_size: Some(None), + kenten_fill_tint: Some(None), + kenten_stroke_tint: Some(None), + kenten_stroke_weight: Some(None), + ruby_font_size: Some(None), + ruby_fill_tint: Some(None), + ruby_stroke_tint: Some(None), + ruby_stroke_weight: Some(None), ..Default::default() }; - let clear_para = ParaAttrs { start_at: Some(None), paragraph_kashida_width: Some(None), kinsoku: Some(None), ..Default::default() }; + let clear_para = + ParaAttrs { start_at: Some(None), paragraph_kashida_width: Some(None), kinsoku: Some(None), list_tab: Some(None), ..Default::default() }; let selected = if style_clear { std::sync::Arc::make_mut(&mut d.styles).paragraph.push(designcraft_doc::styles::ParagraphStyle { name: "Defaults".into(), @@ -860,6 +878,15 @@ mod tests { assert_eq!(expected.0.paragraph_kashida_width, None); assert_eq!(expected.0.kinsoku, None); assert_eq!(expected.1.leading_aki, None); + assert_eq!(expected.0.list_tab, None); + assert_eq!(expected.1.kenten_size, None); + assert_eq!(expected.1.kenten_fill_tint, None); + assert_eq!(expected.1.kenten_stroke_tint, None); + assert_eq!(expected.1.kenten_stroke_weight, None); + assert_eq!(expected.1.ruby_font_size, None); + assert_eq!(expected.1.ruby_fill_tint, None); + assert_eq!(expected.1.ruby_stroke_tint, None); + assert_eq!(expected.1.ruby_stroke_weight, None); // Legacy JSON is format 1: its upgrade pins older defaults on the other styles, so only // the native ZIP compares as the whole document. for (bytes, native) in [(save(d).unwrap(), true), (serde_json::to_vec(d).unwrap(), false)] { From b09233ab58e909012a05208d7c817fd15a2cafdf Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 23:57:49 +0000 Subject: [PATCH 0017/1349] macOS: accept .idml on the app icon when another app owns the type When InDesign is installed it exports its own type for .idml, which overrides the type DesignCraft imports, so the IDML entry in CFBundleDocumentTypes no longer matches: Finder refuses the drop on the app's icon and Open With leaves DesignCraft out (Dock drops still work). Add a separate entry by extension, which matches whatever type the file has. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CgGsJkVe5GYG9qK6VFdECa --- packaging/macos/Info.plist.in | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/packaging/macos/Info.plist.in b/packaging/macos/Info.plist.in index ba4503678..c68d3fbd8 100644 --- a/packaging/macos/Info.plist.in +++ b/packaging/macos/Info.plist.in @@ -72,6 +72,21 @@ LSItemContentTypes ai.storyteller.designcraft.idml + + + CFBundleTypeName + IDML Document (by extension) + CFBundleTypeRole + Viewer + LSHandlerRank + Alternate + CFBundleTypeExtensions + idml + + CFBundleLocalizations + + en + ar + cs + de + fr + it + ja + ka + pl + pt-BR + ru + uk + CFBundleDisplayName DesignCraft CFBundleName From abc794396b8ad8a2842e43e482d6aed355288cbb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 26 Oct 2026 02:15:28 -0700 Subject: [PATCH 0280/1349] Layers: Duplicate Layer gives tables in copied cells and notes ids of their own Tables inside a copied table cell or note kept the original table's id, so two tables in the document shared one id. Duplicate Layer now renumbers them at every depth, with the paragraphs that hold them. --- crates/engine/src/cmd/layout.rs | 71 ++++++++++++++++++++++++++++----- 1 file changed, 60 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 3d098a674..31661848f 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -1422,7 +1422,8 @@ fn duplicate_layer(s: &mut Session, p: &Value) -> Result { d.stories.insert(new, Arc::new(st)); } // Each story copy gets its frames in the original order, text anchors of its own, which its cross-references - // and those of the other copies point at, and tables with ids of their own, allocated in story order. + // and those of the other copies point at, and tables with ids of their own, the tables in its cells and notes + // included, allocated in story order. let mut anchors = HashMap::new(); let mut order: Vec<(StoryId, StoryId)> = stories.iter().map(|(old, new)| (*old, *new)).collect(); order.sort_unstable_by_key(|(_, new)| *new); @@ -1434,16 +1435,7 @@ fn duplicate_layer(s: &mut Session, p: &Value) -> Result { anchors.insert(a.id, id); Arc::make_mut(a).id = id; } - let mut tables = HashMap::new(); - for (t, mut table) in std::mem::take(&mut st.tables) { - let n = d.alloc(); - Arc::make_mut(&mut table).id = n; - tables.insert(t, n); - st.tables.insert(n, table); - } - for pf in &mut st.paras { - pf.table = pf.table.and_then(|t| tables.get(&t).copied()); - } + renumber_tables(d, &mut st); d.stories.insert(*new, Arc::new(st)); } for new in stories.values() { @@ -1563,6 +1555,28 @@ fn renumber_anchored( } } +/// Give the tables of `st`, and the tables in the stories of its table cells and notes, new ids from `d`, and point the +/// paragraphs that hold them at the new ids. [`too_deep`] bounds the nesting. +fn renumber_tables(d: &mut designcraft_doc::Document, st: &mut Story) { + let mut tables = HashMap::new(); + for (t, mut table) in std::mem::take(&mut st.tables) { + let n = d.alloc(); + let table_mut = Arc::make_mut(&mut table); + table_mut.id = n; + for c in &mut table_mut.cells { + renumber_tables(d, &mut c.text); + } + tables.insert(t, n); + st.tables.insert(n, table); + } + for pf in &mut st.paras { + pf.table = pf.table.and_then(|t| tables.get(&t).copied()); + } + for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + renumber_tables(d, &mut Arc::make_mut(n).text); + } +} + /// Point the cross-references in `st`, and in the stories of its table cells and notes, at the anchors `map` gives for /// their targets. [`too_deep`] bounds the nesting. fn remap_xrefs(st: &mut Story, map: &HashMap) { @@ -2172,6 +2186,41 @@ mod layer_tests { assert_eq!(d.story(copied).unwrap().tables[&new].nrows(), 2, "a command naming the copy's table changes the copy"); } + #[test] + fn duplicate_layer_gives_tables_in_copied_cells_their_own_ids() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let text = json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Rows"}); + let f = s.execute("frame.create", &text).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + s.execute("text.select", &json!({"story": sid.0, "anchor": 4, "focus": 4})).unwrap(); + let table = s.execute("table.insert", &json!({"rows": 1, "cols": 2})).unwrap()["table"].as_u64().unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let inner = d.alloc(); + let deepest = d.alloc(); + let mut nested = designcraft_doc::Table::new(inner, 1, 1, 0, 0, 40.0); + nested.cells[0].text.insert_table(0, designcraft_doc::Table::new(deepest, 1, 1, 0, 0, 20.0)); + d.story_mut(sid).unwrap().table_mut(table).unwrap().cells[0].text.insert_table(0, nested); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copied = on_layer(d, copy)[0].text_frame().unwrap().story; + let outer = d.story(copied).unwrap().tables.values().next().unwrap(); + let cell = &outer.cells[0].text; + let new_inner = *cell.tables.keys().next().unwrap(); + assert_ne!(new_inner, inner, "a table in a copied cell has an id of its own"); + assert_eq!(cell.tables[&new_inner].id, new_inner); + assert_eq!(cell.paras.iter().filter_map(|pf| pf.table).collect::>(), [new_inner], "the copied cell holds the copied table"); + let inner_cell = &cell.tables[&new_inner].cells[0].text; + let new_deepest = *inner_cell.tables.keys().next().unwrap(); + assert_ne!(new_deepest, deepest, "a table nested deeper has an id of its own"); + assert_eq!(inner_cell.paras.iter().filter_map(|pf| pf.table).collect::>(), [new_deepest]); + let ids = [outer.id, new_inner, new_deepest, table, inner, deepest]; + assert_eq!(ids.iter().collect::>().len(), ids.len(), "every table id is unique: {ids:?}"); + let orig = d.story(sid).unwrap().tables[&table].cells[0].text.tables.keys().copied().collect::>(); + assert_eq!(orig, [inner], "the original's nested table keeps its id"); + } + #[test] fn duplicate_layer_numbers_copied_tables_and_anchored_objects_in_story_order() { let mut s = crate::Session::new(); From 6f567fdb6d5623176f75c00c25bfa46c4b5f1fb8 Mon Sep 17 00:00:00 2001 From: Hamza Date: Mon, 26 Oct 2026 17:06:38 +0500 Subject: [PATCH 0281/1349] PDF export: a name escapes every byte a name cannot hold (#1582) A placed media file's type goes into the embedded file's `/Subtype` as a PDF name, and only `/` was escaped. ISO 32000-1 7.3.5 allows only the regular characters in a name, so a type carrying a space, a delimiter, a comment character or `#` ended the name early and left the rest as loose tokens in the file's structure -- in a PDF the user then distributes. `pdf_name` escapes every irregular byte as `#xx`. The test covers the shapes that leaked: a space, `<<`/`>>`, `(`/`)`, `[`/`]`, `%`, `#` itself and a non-ASCII byte, and checks an ordinary type is unchanged. This is the escaping part of DC-01 only. The larger part of that issue -- the post-passes finding the catalog, the page tree and pages by text search over the output and taking the last match -- needs them to stop rediscovering objects at all, through the xref chain or by carrying the offsets each pass writes. That is a rework of `transitions.rs` rather than a patch, and the issue says a reproduction is available to maintainers privately, which I would want to test against before changing how objects are found. --- crates/pdf/src/forms.rs | 42 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/crates/pdf/src/forms.rs b/crates/pdf/src/forms.rs index 07f4cf04c..e8fd57185 100644 --- a/crates/pdf/src/forms.rs +++ b/crates/pdf/src/forms.rs @@ -56,6 +56,25 @@ pub(crate) fn collect_media(doc: &Document, sheets: &[Sheet]) -> Vec String { + let regular = |b: u8| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.' | b'_' | b'~' | b'*' | b'@' | b'$' | b'&' | b'!' | b'^' | b'|'); + let mut o = String::new(); + for b in s.bytes() { + if regular(b) { + o.push(b as char); + } else { + o.push_str(&format!("#{b:02X}")); + } + } + o +} + /// A PDF text string: literal for ASCII, UTF-16BE otherwise. fn pdf_string(s: &str) -> String { if s.is_ascii() { @@ -117,7 +136,7 @@ pub(crate) fn add_fields(pdf: &[u8], fields: &[Placed], media: &[PlacedMedia]) - let Some(&page_ref) = kids.get(*page) else { continue }; let (file, spec, rendition, screen) = (next, next + 1, next + 2, next + 3); next += 4; - let mut body = format!("<>\nstream\n", mime.replace('/', "#2F"), data.len()).into_bytes(); + let mut body = format!("<>\nstream\n", pdf_name(mime), data.len()).into_bytes(); body.extend_from_slice(data); body.extend_from_slice(b"\nendstream"); put(&mut out, file, &body); @@ -255,3 +274,24 @@ pub(crate) fn add_fields(pdf: &[u8], fields: &[Placed], media: &[PlacedMedia]) - out.extend_from_slice(x.as_bytes()); Some(out) } + +#[cfg(test)] +mod tests { + use super::*; + + /// A media type comes from a placed file's own metadata and was written into a PDF name with + /// only `/` escaped, so a type holding a delimiter ended the name early and left the rest as + /// tokens in the file's structure (#1582). + #[test] + fn a_pdf_name_escapes_every_irregular_byte() { + assert_eq!(pdf_name("video/mp4"), "video#2Fmp4"); + assert_eq!(pdf_name("a b"), "a#20b"); + assert_eq!(pdf_name("x<>"), "x#3C#3C#2FType#2FCatalog#3E#3E"); + assert_eq!(pdf_name("a%comment"), "a#25comment"); + assert_eq!(pdf_name("a#1"), "a#231"); + assert_eq!(pdf_name("a(b)"), "a#28b#29"); + assert_eq!(pdf_name("[1 0 R]"), "#5B1#200#20R#5D"); + assert_eq!(pdf_name("application-x_test.v2"), "application-x_test.v2"); + assert_eq!(pdf_name("\u{e9}"), "#C3#A9"); + } +} From 7ad7f22f4df3298ac4f28bad12f2c745fbdffd74 Mon Sep 17 00:00:00 2001 From: Hamza Date: Mon, 26 Oct 2026 17:12:09 +0500 Subject: [PATCH 0282/1349] Pin the indd dependency by rev, as every other git dependency is (#1599) `indd` was the one git dependency taken from a branch: indd = { git = "https://github.com/storytold/indd-utils", branch = "main" } `Cargo.lock` pinned a commit, but any `cargo update` -- and `.github/dependabot.yml` runs them -- pulls whatever is on that branch into a parser of untrusted INDD files, with no review of what changed. The craft-libs dependencies beside it are all `rev = "b926b5c0..."`. Pinned to `7f3060e5bce78d21ea70e0d5eacb96edce15dfbe`, which is the commit the lock already held: the only change in `Cargo.lock` is the source string, `?branch=main` to `?rev=7f3060e5...`, so no code moves with this. Verified: `cargo check --locked -p designcraft-engine` passes, and `indd_files_go_through_the_converter_and_its_errors_are_open_errors` still passes, so the converter is the same one. Audit DC-18. --- Cargo.lock | 2 +- Cargo.toml | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index eabe9e52e..0a0688da5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3120,7 +3120,7 @@ checksum = "09e54e57b4c48b40f7aec75635392b12b3421fa26fe8b4332e63138ed278459c" [[package]] name = "indd" version = "0.1.0" -source = "git+https://github.com/storytold/indd-utils?branch=main#7f3060e5bce78d21ea70e0d5eacb96edce15dfbe" +source = "git+https://github.com/storytold/indd-utils?rev=7f3060e5bce78d21ea70e0d5eacb96edce15dfbe#7f3060e5bce78d21ea70e0d5eacb96edce15dfbe" [[package]] name = "indexmap" diff --git a/Cargo.toml b/Cargo.toml index 195f39e67..2924c8275 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -75,9 +75,12 @@ flo_curves = "0.8" qrcodegen = "1.8" quick-xml = "0.41" zip = { version = "3", default-features = false, features = ["deflate"] } -# INDD/INDT → IDML conversion for File › Open: storytold/indd-utils, tracking its main branch +# INDD/INDT → IDML conversion for File › Open: storytold/indd-utils, pinned by rev as every other +# git dependency here is. It parses untrusted INDD files, and `branch = "main"` meant any +# `cargo update` -- Dependabot runs them -- pulled whatever was on that branch into the parser +# without review (#1599). # (MIT OR Apache-2.0, no dependencies, builds for wasm). -indd = { git = "https://github.com/storytold/indd-utils", branch = "main" } +indd = { git = "https://github.com/storytold/indd-utils", rev = "7f3060e5bce78d21ea70e0d5eacb96edce15dfbe" } # Which paths stored in documents may be followed (craft-libs). craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "b926b5c03e256c86ca10934f58d03f628810b5b7" } From 13013b09d0d73ff34cffdc8aec80437a05fad625 Mon Sep 17 00:00:00 2001 From: PiMinusMax <121135695+PiMinusMax@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:13:10 +0100 Subject: [PATCH 0283/1349] Effects: inner shadow, glow and bevel follow a transparent image's edge On a frame holding a graphic, Inner Shadow, Inner Glow (from the edges) and Bevel and Emboss are built from what the object paints instead of the frame's path: the colour everywhere but under the painted pixels moved by the offset, blurred, and kept only where the object paints. A transparent part of an image is outside the object, so the effect lines the image's opaque edge; before, it lined the frame and nothing marked the image's own edge. Frames without a graphic draw as before. Satin and a centred Inner Glow still follow the frame. Fixes #1622. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 1 + crates/render/src/fx.rs | 105 ++++++++++++++++++++++++++++++++++++++-- 2 files changed, 101 insertions(+), 5 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 8c7e3be5a..6b389c152 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -380,6 +380,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-10-26** · Inner Shadow, Inner Glow (from the edges) and Bevel and Emboss on a frame holding an image follow what the image paints: a transparent part is outside the object, so the effect lines the image's opaque edge, not the frame (#1622). Satin and a centred Inner Glow still follow the frame. No readiness percentage change. - **2026-10-20** · Edit › Keyboard Shortcuts is craft-keymap's shared dialog: commands grouped by menu with Show and Filter, recording that asks before taking a key from another command, undo and redo, named shortcut sets (edits of Default become Custom; an imported set becomes a set of its own), an on-screen US keyboard, InDesign Show Set files reviewed before they apply, JSON export and an HTML summary. ui.json keeps the `shortcuts` map earlier versions read, for the active set. No readiness percentage change. - **2026-10-19** · Import InDesign Set… runs on craft-keymap's importer: a set's Window menu panel items (Layers F7, Pages F12, Swatches F5) and Tools items set the panel and tool shortcuts, all of an item's Default keys apply, and the report adds numeric keypad keys read as main keys and likely commands for unmatched items (`window.importShortcuts`). On InDesign's Windows defaults it matches 366 of 1,629 items (was 233) and changes 23 commands. No readiness percentage change. - **2026-10-19** · Keyboard shortcuts run on the shared craft-keymap crate. Panels take shortcuts, with InDesign's defaults where the key is free (Swatches F5, Color F6, Layers F7, Info F8, Stroke F10, Paragraph Styles F11, Character Styles Shift+F11, Pages F12, Align Shift+F7); tool keys are editable in Edit › Keyboard Shortcuts and `window.setShortcut`, and tools sharing a key take turns (B). Saved shortcuts load unchanged. No readiness percentage change. diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index 6147c9cf5..06eb4f4dd 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -211,6 +211,9 @@ impl Renderer { if !it.path.is_closed() { return; } + // An image's edge is where it is opaque, not the frame: inner shadows, glows and bevels + // follow what is painted when the frame holds a graphic. + let painted = matches!(it.content, designcraft_doc::Content::Graphic(_)).then_some((it, page)); // Inner shadow, clipped to the shape. if e.inner_shadow.on && let Some(c) = doc.resolve_color(&e.inner_shadow.color, 1.0) @@ -218,7 +221,7 @@ impl Renderer { let s = &e.inner_shadow; let (sigma, choke) = split(s.size, s.choke); let off = offset(doc.light_angle(s.angle, s.global_light), s.distance); - self.inner_edge(ctx, f, reach, bp, xf, off, sigma, choke, color_of(&c, s.opacity.clamp(0.0, 1.0)), Mix::Normal); + self.inner_edge(ctx, f, reach, bp, xf, off, sigma, choke, color_of(&c, s.opacity.clamp(0.0, 1.0)), Mix::Normal, painted); } // Inner glow: from the edges inwards (or out from the centre), screened over the object. if e.inner_glow.on @@ -248,7 +251,7 @@ impl Renderer { c.pop_layer(); }); } else { - self.inner_edge(ctx, f, reach, bp, xf, Vec2::ZERO, sigma, choke, paint, mix); + self.inner_edge(ctx, f, reach, bp, xf, Vec2::ZERO, sigma, choke, paint, mix, painted); } } // Satin: the shape shifted both ways along the angle, blurred, where exactly one covers. @@ -289,16 +292,18 @@ impl Renderer { let sigma = b.size.max(0.0) / 2.0; if let Some(c) = doc.resolve_color(&b.highlight, 1.0) { // The inverse shape moved away from the light lights the edges facing it. - self.inner_edge(ctx, f, reach, bp, xf, off, sigma, 0.0, color_of(&c, b.highlight_opacity.clamp(0.0, 1.0)), Mix::Screen); + self.inner_edge(ctx, f, reach, bp, xf, off, sigma, 0.0, color_of(&c, b.highlight_opacity.clamp(0.0, 1.0)), Mix::Screen, painted); } if let Some(c) = doc.resolve_color(&b.shadow, 1.0) { - self.inner_edge(ctx, f, reach, bp, xf, -off, sigma, 0.0, color_of(&c, b.shadow_opacity.clamp(0.0, 1.0)), Mix::Multiply); + self.inner_edge(ctx, f, reach, bp, xf, -off, sigma, 0.0, color_of(&c, b.shadow_opacity.clamp(0.0, 1.0)), Mix::Multiply, painted); } } } /// An inner shadow-like edge: everything outside the shape moved by `off`, blurred by - /// `sigma`, clipped to the shape and blended with `mix`. + /// `sigma`, clipped to the shape and blended with `mix`. With `painted` (an object and the + /// page it shows on), the shape is what the object paints, so a transparent part of an image + /// is outside it: the edge runs along the image's opaque pixels, not the frame. #[allow(clippy::too_many_arguments)] fn inner_edge( &mut self, @@ -312,7 +317,33 @@ impl Renderer { choke: f64, paint: peniko::Color, mix: Mix, + painted: Option<(&Item, ShownOn)>, ) { + if let Some((it, page)) = painted { + self.with_blended_filters(ctx, f, reach, sigma, mix, (bp, xf), |me, c, fr| { + let pad = sigma * 4.0 + choke + off.hypot() + 4.0 * fr.px; + let area = reach.inflate(pad, pad); + // The colour everywhere but under the painted pixels moved by `off`, blurred, ... + c.set_transform(fr.view); + c.push_layer(None, None, None, None, None); + c.push_layer(None, None, None, None, Some(blur(sigma))); + c.set_paint(paint); + c.fill_rect(&area); + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestOut)), None, None, None); + let moved = Frame { view: fr.view * Affine::translate(off), ..*fr }; + me.draw_body(c, &moved, it, bp, xf, page); + c.pop_layer(); + c.pop_layer(); + // ... kept only where the object paints. + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestIn)), None, None, None); + me.draw_body(c, fr, it, bp, xf, page); + c.pop_layer(); + c.pop_layer(); + }); + return; + } self.with_blended_filters(ctx, f, reach, sigma, mix, (bp, xf), |_, c, fr| { c.set_transform(fr.view); c.push_layer(None, None, None, None, Some(blur(sigma))); @@ -458,4 +489,68 @@ mod tests { let wide = Offscreen { x0: -14852.0, y0: -14852.0, scale: 15_002.0 / 1024.0, width: 2062, height: 2062 }; assert_eq!(offscreen(object, 15_002.0, 1440, 900), Some(wide)); } + + /// An inner shadow on a frame holding an image whose left half is transparent: the shadow + /// lines the image's opaque part (its edge in the middle of the frame), not only the frame. + #[test] + fn an_inner_shadow_follows_a_transparent_images_edge() { + use designcraft_doc::build::NewDocument; + use designcraft_doc::{Document, SpreadRef}; + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + // 20 × 20: transparent left half, opaque white right half. + let img = image::RgbaImage::from_fn(20, 20, |x, _| if x < 10 { image::Rgba([0, 0, 0, 0]) } else { image::Rgba([255, 255, 255, 255]) }); + let mut png = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let aid = designcraft_doc::AssetId(d.alloc()); + d.assets.insert( + aid, + std::sync::Arc::new(designcraft_doc::Asset { + id: aid, + name: "half.png".into(), + mime: "image/png".into(), + data: std::sync::Arc::new(png), + pixels: Some((20, 20)), + ..Default::default() + }), + ); + let mut it = Item::new( + designcraft_doc::ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 300.0, 300.0)), + ); + it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic { + layer_options: None, + asset: aid, + size: (200.0, 200.0), + xf: Affine::translate((100.0, 100.0)), + clip: None, + auto_fit: Default::default(), + fit_align: 4, + crop: [0.0; 4], + wrap: Default::default(), + fill: Default::default(), + }); + let s = &mut it.effects.inner_shadow; + s.on = true; + s.color = "[Black]".into(); + s.opacity = 1.0; + s.distance = 0.0; + s.size = 20.0; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let cache = crate::Cache::new(); + let mut r = Renderer::new(); + r.threads = 0; + let page = r.render_page(&d, &cache, 0, 1.0, false, &crate::RenderOptions::default()).unwrap(); + let lum = |x: u32| { + let p = page.pixel(x, 200); + u32::from(p[0]) + u32::from(p[1]) + u32::from(p[2]) + }; + // The image's opaque part starts at x = 200: just inside it the shadow darkens it; in its + // middle (x = 250, 50 pt from every edge but the frame's right one) it stays light. + assert!(lum(204) + 60 < lum(250), "shadow at the image's own edge: {} vs {}", lum(204), lum(250)); + // The transparent half shows the page: no shadow painted there. + assert!(lum(150) > 700, "nothing over the transparent part: {}", lum(150)); + } } From 5b2252a789369daf65b6f14fd1cf33cfb446f872 Mon Sep 17 00:00:00 2001 From: PiMinusMax <121135695+PiMinusMax@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:11:14 +0200 Subject: [PATCH 0284/1349] Rulers: a guide being dragged out keeps its resize cursor until dropped The canvas set the tool's cursor every frame the pointer was over it, after the guide drag had set its resize cursor, so the cursor turned back into the tool's as soon as the pointer left the ruler and the drag looked as if it had stopped. A ruler guide drag now keeps the cursor across the guide, as a column guide drag already did. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 1 + crates/ui-egui/src/canvas.rs | 7 ++++++ crates/ui-egui/src/guide_selection_tests.rs | 28 +++++++++++++++++++++ 3 files changed, 36 insertions(+) diff --git a/ROADMAP.md b/ROADMAP.md index 8c7e3be5a..9e91acdfe 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -408,6 +408,7 @@ Newest first. - **2026-10-24** · Optical Margin Alignment per story with a size (`story.options {opticalMargin, opticalMarginSize}`, off by default): when it is on, the story's paragraphs hang punctuation and letter edges by amounts set for that type size, except paragraphs with Ignore Optical Margin (`ignoreOpticalMargin` in `type.para` and paragraph styles). Table cells and footnotes don't take the story setting yet. When it is off, the per-paragraph switch still hangs at the text's own size. IDML imports and exports both (`StoryPreference/@OpticalMarginAlignment`, `@OpticalMarginSize`, `IgnoreEdgeAlignment`) (#947). No readiness percentage change. - **2026-10-24** · Text frames: a custom baseline grid's Relative To (Text Frame Options › Baseline Options, `object.textFrameOptions {baselineGrid: {relativeTo}}`, IDML `BaselineFrameGridRelativeOption`) measures the grid's start from the top of the page, the top margin, the top of the frame or its top inset. Text Frame Options had no custom baseline grid controls, imports dropped the setting and every frame grid started from the page top, so grid-aligned text in a frame measured from its own top sat on the wrong lines. No readiness percentage change. - **2026-10-24** · Paragraph Style Options › Indents and Spacing has an Align to Grid menu: None, All Lines or First Line Only. It shows the style's current setting. A First Line Only style could be set only in the CJK Grid Settings section, which shows only with CJK features on, or through commands. No readiness percentage change. +- **2026-10-24** · A guide pulled out of a ruler keeps the resize cursor across it until it is dropped; the tool's cursor took over as soon as the pointer left the ruler, so the drag looked as if it had stopped. No readiness percentage change. - **2026-10-24** · Anchored text frames, such as marginal notes, compose where their host story places them: they align to the baseline grid at that position, and page-number markers and spine-relative alignment inside them read the host's page. They composed against a grid measured from their stored position and on no page, so a note set to Only Align First Line to Grid could sit a fraction of a line off the body text's grid line. No readiness percentage change. - **2026-10-24** · Tables: a gradient swatch in a cell fill draws as a gradient on the canvas and in PDF, in one gradient space for the whole table, so it runs across cells without restarting. Cells showed the gradient's first stop as a solid colour. No readiness percentage change. - **2026-10-24** · New documents start with Hyphenate Capitalized Words, Hyphenate Last Word and Hyphenate Across Column off in [Basic Paragraph], as in InDesign. Opened and imported files keep the values they carry. No readiness percentage change. diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 64bed51d8..17f649959 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -743,6 +743,13 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { Some(_) => Cursor::ResizeV, None => c, }; + // A ruler guide being dragged keeps the cursor across it until it is dropped, over the + // canvas too (the tool's cursor took over as soon as the pointer left the ruler). + let c = match ui.data(|d| d.get_temp::(egui::Id::new(GUIDE_DRAG))).map(|g| g.orientation) { + Some(designcraft_doc::Orientation::Horizontal) => Cursor::ResizeV, + Some(designcraft_doc::Orientation::Vertical) => Cursor::ResizeH, + None => c, + }; let icon = crate::cursors::show(ui.ctx(), &mut app.cursors, c, p); ui.ctx().set_cursor_icon(icon); draw_cursor_badge(&painter, p, c, &t); diff --git a/crates/ui-egui/src/guide_selection_tests.rs b/crates/ui-egui/src/guide_selection_tests.rs index 626a7b826..8a1cde599 100644 --- a/crates/ui-egui/src/guide_selection_tests.rs +++ b/crates/ui-egui/src/guide_selection_tests.rs @@ -328,3 +328,31 @@ fn a_guide_dragged_out_of_a_ruler_snaps() { drag(&mut h, ruler, dest); assert_eq!(positions(&h), [200.0, 300.0, 400.0, 400.0]); } + +/// A guide pulled out of a ruler keeps the resize cursor across it over the canvas until it is +/// dropped; the tool's arrow came back as soon as the pointer left the ruler. +#[test] +fn a_guide_dragged_out_of_a_ruler_keeps_its_cursor_until_dropped() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let mut h = harness(app); + let rect = h.state().canvas_rect.unwrap(); + for (from, icon) in [ + (pos2(rect.center().x, rect.min.y - crate::canvas::RULER / 2.0), egui::CursorIcon::ResizeVertical), + (pos2(rect.min.x - crate::canvas::RULER / 2.0, rect.center().y), egui::CursorIcon::ResizeHorizontal), + ] { + let to = rect.center(); + h.hover_at(from); + h.step(); + press(&mut h, from, true, Modifiers::NONE); + for k in 1..=4 { + h.hover_at(from + (to - from) * (k as f32 / 4.0)); + h.step(); + assert_eq!(h.output().platform_output.cursor_icon, icon, "step {k} of the drag from {from:?}"); + } + press(&mut h, to, false, Modifiers::NONE); + h.hover_at(to); + h.run_steps(2); + assert_ne!(h.output().platform_output.cursor_icon, icon, "dropped: the tool's cursor again"); + } +} From 30b64114c2ce5f75a4ed18567644f2a3217e3dcc Mon Sep 17 00:00:00 2001 From: PiMinusMax <121135695+PiMinusMax@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:39:07 +0100 Subject: [PATCH 0285/1349] Adapt to the current egui (Id::unique) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 17f649959..19bcb87e3 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -745,7 +745,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { }; // A ruler guide being dragged keeps the cursor across it until it is dropped, over the // canvas too (the tool's cursor took over as soon as the pointer left the ruler). - let c = match ui.data(|d| d.get_temp::(egui::Id::new(GUIDE_DRAG))).map(|g| g.orientation) { + let c = match ui.data(|d| d.get_temp::(egui::Id::unique(GUIDE_DRAG))).map(|g| g.orientation) { Some(designcraft_doc::Orientation::Horizontal) => Cursor::ResizeV, Some(designcraft_doc::Orientation::Vertical) => Cursor::ResizeH, None => c, From 4f03e105943c4e061a1d41830b77d09e5b266713 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:37:07 +0000 Subject: [PATCH 0286/1349] Reject invalid XML tag names in xml.mapStyle Found while testing crates/engine/src/cmd/xml.rs:~290 (the xml.mapStyle command; the export is in export_xml) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/xml.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/crates/engine/src/cmd/xml.rs b/crates/engine/src/cmd/xml.rs index 8cd50a2cd..8905c2368 100644 --- a/crates/engine/src/cmd/xml.rs +++ b/crates/engine/src/cmd/xml.rs @@ -268,6 +268,11 @@ pub fn specs() -> Vec { |s, p| { let style = str_param(p, "style").unwrap_or("").to_string(); let tag = str_param(p, "tag").map(str::to_string); + if let Some(t) = &tag + && !valid_name(t) + { + return Err(bad("xml.mapStyle", format!("`{t}` isn't a valid XML name"))); + } if s.doc()?.doc.styles.para(&style).is_none() { return Err(bad("xml.mapStyle", format!("no paragraph style `{style}`"))); } @@ -475,6 +480,19 @@ mod tests { assert!(s.execute("xml.validate", &json!({})).is_err()); } + #[test] + fn map_style_rejects_invalid_tag_name() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Head"})).unwrap(); + assert!(s.execute("xml.mapStyle", &json!({"style": "Head", "tag": "a b> Date: Tue, 27 Oct 2026 08:29:34 +0000 Subject: [PATCH 0287/1349] Fix RTF import swallowing characters after a short \'hh escape Found while testing crates/textimport/src/rtf.rs:~118-131 (the \' branch of import: `i += 4` and `u8::from_str_radix(&hex, 16)`) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/textimport/src/rtf.rs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/crates/textimport/src/rtf.rs b/crates/textimport/src/rtf.rs index 6254ca668..f7b5a2167 100644 --- a/crates/textimport/src/rtf.rs +++ b/crates/textimport/src/rtf.rs @@ -120,13 +120,15 @@ pub fn import(bytes: &[u8]) -> Result { let next = chars.get(i + 1).copied().unwrap_or(' '); if next == '\'' { // \'hh: a Windows-1252 byte. - let hex: String = chars.iter().skip(i + 2).take(2).collect(); - i += 4; + // Only valid hex digits are consumed; anything else is left for the main loop. + let hex: String = chars.iter().skip(i + 2).take(2).take_while(|c| c.is_ascii_hexdigit()).collect(); + i += 2 + hex.len(); if pending > 0 { pending -= 1; continue; } - if let Ok(b) = u8::from_str_radix(&hex, 16) + if hex.len() == 2 + && let Ok(b) = u8::from_str_radix(&hex, 16) && !stack.last().is_some_and(|s| s.skip) { units.reset(); @@ -302,6 +304,15 @@ mod tests { assert_eq!(import(br"{\rtf1 a\u-4294967231?b}").unwrap().story.text, "ab"); } + /// A short or invalid `\'hh` escape consumes only its valid hex digits. + #[test] + fn short_hex_escape_keeps_closing_brace() { + let i = import(br"{\rtf1 {\b A\'4}B}").unwrap(); + assert_eq!(i.story.text, "AB"); + assert_eq!(i.story.format_after(1).over.font_style, None); + assert_eq!(import(br"{\rtf1 a\'+fb}").unwrap().story.text, "a+fb"); + } + #[test] fn imports_rtf_text_and_formatting() { let rtf = br"{\rtf1\ansi{\fonttbl{\f0 Times;}}{\colortbl;\red0\green0\blue0;}{\*\generator Test;} From 7fcebedf9852d90775240b0e6e7fca7e68137a10 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Tue, 27 Oct 2026 09:07:12 +0000 Subject: [PATCH 0288/1349] Drop XML-forbidden control characters in file.exportXml Found while testing crates/engine/src/cmd/xml.rs:40 (esc, used by para_xml at :68 and the href at :104) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/xml.rs | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/xml.rs b/crates/engine/src/cmd/xml.rs index 8cd50a2cd..73144d1f6 100644 --- a/crates/engine/src/cmd/xml.rs +++ b/crates/engine/src/cmd/xml.rs @@ -37,8 +37,21 @@ fn tagged(d: &Document) -> Vec { keyed.into_iter().map(|(_, i)| i).collect() } +/// Escapes markup characters and drops characters XML 1.0 cannot hold. fn esc(s: &str) -> String { - s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\t' | '\n' | '\r' => out.push(c), + c if (c as u32) < 0x20 || c == '\u{FFFE}' || c == '\u{FFFF}' => {} + c => out.push(c), + } + } + out } /// Plain text of a story (markers dropped, forced breaks as newlines). @@ -475,6 +488,18 @@ mod tests { assert!(s.execute("xml.validate", &json!({})).is_err()); } + #[test] + fn export_xml_drops_forbidden_control_chars() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let a = s + .execute("frame.create", &json!({"rect": [72, 72, 400, 150], "content": "text", "text": "A\u{1}B\u{8}C\u{FFFE}\u{FFFF}", "caret": false})) + .unwrap(); + s.execute("xml.tag", &json!({"tag": "story", "ids": [a["id"]]})).unwrap(); + let x = s.execute("file.exportXml", &json!({})).unwrap()["text"].as_str().unwrap().to_string(); + assert!(x.contains("ABC"), "{x:?}"); + } + #[test] fn tag_export_and_import_xml() { let mut s = Session::new(); From 93ab34f51531feebc46fbe384735b960f3e65ec0 Mon Sep 17 00:00:00 2001 From: Hamza Date: Tue, 27 Oct 2026 14:16:27 +0500 Subject: [PATCH 0289/1349] Data merge: the UNC refusal is tested on Windows too (#1601) `image_path_tests` was `#[cfg(all(test, unix))]`, so the assertion that matters most ran only where it matters least: a merge image field naming another computer must resolve to nothing, because on Windows an outbound SMB connection hands over NTLM credentials. That refusal was unverified on Windows. The refusals now run everywhere -- nothing in them is unix-specific, since `image_candidates` delegates to `craft-docpath` -- and the Windows shapes that file refuses are asserted where they have meaning: `\\?\UNC\...`, `\\.\pipe\...`, `\\?\C:\...` and the legacy device names. Resolution beside the data and the document stays unix-only: it asserts what an absolute path means, which cannot be checked on Windows from here. No production code changes. On macOS both cross-platform tests pass; Windows CI is the first real run of the Windows ones, which is the point. Audit DC-20 (its testable part; the privacy note about absolute local paths matches InDesign and is a product decision, not a bug). --- crates/engine/src/cmd/datamerge/fill.rs | 32 +++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/datamerge/fill.rs b/crates/engine/src/cmd/datamerge/fill.rs index 629258d6d..f522065ba 100644 --- a/crates/engine/src/cmd/datamerge/fill.rs +++ b/crates/engine/src/cmd/datamerge/fill.rs @@ -523,20 +523,44 @@ mod link_tests { } } -#[cfg(all(test, unix))] +#[cfg(test)] mod image_path_tests { use std::path::Path; use super::image_candidates; + /// A merge image field names a file, and a field that names **another computer** must resolve + /// to nothing: a UNC path is how a hostile data file turns a merge into an outbound SMB + /// connection, and on Windows that means handing over NTLM credentials. This ran only on + /// unix, so the refusal was unverified on the one platform where UNC means anything (#1601). #[test] - fn image_cells_resolve_beside_the_data_and_never_to_other_computers() { + fn an_image_cell_never_resolves_to_another_computer() { let (data, doc) = (Path::new("/work/data"), Path::new("/work/doc")); for cell in [r"\\192.0.2.1\share\x.png", "file://192.0.2.1/s/x.png", "//192.0.2.1/s/x.png", "https://example.com/x.png"] { assert!(image_candidates(cell, Some(data), Some(doc)).is_empty(), "{cell}"); } - let found = image_candidates("img/x.png", Some(data), Some(doc)); - assert_eq!(found, [data.join("img").join("x.png"), doc.join("img").join("x.png")]); + // A field naming nothing resolves to nothing, whatever the platform. + assert!(image_candidates("", Some(data), Some(doc)).is_empty(), "an empty cell"); assert!(image_candidates("img/x.png", None, None).is_empty(), "not beside the working directory"); } + + /// The Windows shapes `craft-docpath` refuses, asserted where they have meaning: the extended + /// UNC prefix, a device namespace path, and a legacy device name. + #[cfg(windows)] + #[test] + fn windows_device_and_extended_paths_are_refused() { + let (data, doc) = (Path::new(r"C:\work\data"), Path::new(r"C:\work\doc")); + for cell in [r"\\?\UNC\192.0.2.1\share\x.png", r"\\.\pipe\x", r"\\?\C:\secret\x.png", "CON", "NUL.png"] { + assert!(image_candidates(cell, Some(data), Some(doc)).is_empty(), "{cell}"); + } + } + + /// Resolution beside the data and the document, with absolute paths this platform means. + #[cfg(unix)] + #[test] + fn an_image_cell_resolves_beside_the_data_then_the_document() { + let (data, doc) = (Path::new("/work/data"), Path::new("/work/doc")); + let found = image_candidates("img/x.png", Some(data), Some(doc)); + assert_eq!(found, [data.join("img").join("x.png"), doc.join("img").join("x.png")]); + } } From 7c25cd97c4acca6949535e03029e7fa406534071 Mon Sep 17 00:00:00 2001 From: Hamza Date: Tue, 27 Oct 2026 15:25:27 +0500 Subject: [PATCH 0290/1349] Data merge: an image named by many records is read once (#1595) `place_image` stat'd and read its file for every record, so a sheet naming one image in many rows read it once per row -- up to 256 MiB each time. The audit's case is a 100,000-row CSV naming one large file: about 25 TB of I/O for one merge. A merge now carries an `ImageCache`: the bytes by resolved path, read once and shared. The asset takes the cached `Arc` rather than a copy, so the records share one buffer as well. The cache stops growing past 256 MB of distinct files, so a merge over many large images is slow rather than out of memory. Measured by counting what the engine hands the file system (`io::touched`): without the cache 50 reads for 25 records (a stat and a read each) with it 2 A note on the test, because the first one I wrote was useless: asserting on the bytes the document holds passes either way, since `add_asset` already dedupes identical content. Memory never showed this; the I/O is the bug, so the test counts reads. Audit DC-14. Its second half -- capping the pages a merge produces -- is not here: how many pages a merge may make is a product decision, and the records are the user's own data rather than something arriving from outside. --- crates/engine/src/cmd/datamerge.rs | 8 ++- crates/engine/src/cmd/datamerge/fill.rs | 72 +++++++++++++++++++++--- crates/engine/src/cmd/datamerge/tests.rs | 63 +++++++++++++++++++++ 3 files changed, 131 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/datamerge.rs b/crates/engine/src/cmd/datamerge.rs index e96feb9fb..4d3cd5dd6 100644 --- a/crates/engine/src/cmd/datamerge.rs +++ b/crates/engine/src/cmd/datamerge.rs @@ -18,7 +18,7 @@ use serde_json::{Value, json}; use super::{CommandSpec, bad, cmd, has_doc, id_param, ok, str_param}; use crate::{DocState, Result, Session}; -use fill::{FillReport, Maps, MissingImage, Sources, copy_item, fill_row, identity_map}; +use fill::{FillReport, ImageCache, Maps, MissingImage, Sources, copy_item, fill_row, identity_map}; use parse::{ Table, TileInput, extension, fingerprint_of, relative_between, select_records, status_of, table_from_bytes, table_from_grid, table_from_objects, tile, @@ -210,7 +210,8 @@ fn preview_cmd(s: &mut Session, p: &Value) -> Result { let row = source.rows.get((record as usize).saturating_sub(1)).cloned().unwrap_or_default(); let data_dir = source_file(&source, st.path.as_deref().map(Path::new)).as_deref().and_then(Path::parent).map(Path::to_path_buf); let doc_dir = st.path.as_deref().and_then(parent_dir); - let sources = Sources { options: &options, data_dir: data_dir.as_deref(), doc_dir: doc_dir.as_deref() }; + let images = ImageCache::default(); + let sources = Sources { options: &options, data_dir: data_dir.as_deref(), doc_dir: doc_dir.as_deref(), images: &images }; fill_row(&mut doc, &source.fields, &row, record as u32, &maps, &sources); st.doc = Arc::new(doc); st.preview_record = Some(record as u32); @@ -246,7 +247,8 @@ fn merge_cmd(s: &mut Session, p: &Value) -> Result { warnings.extend(table.warnings.iter().cloned()); let mut merged = src.clone(); let mut missing = Vec::new(); - let sources = Sources { options: &options, data_dir: data_dir.as_deref(), doc_dir: doc_dir.as_deref() }; + let images = ImageCache::default(); + let sources = Sources { options: &options, data_dir: data_dir.as_deref(), doc_dir: doc_dir.as_deref(), images: &images }; let mut sink = Sink { warnings: &mut warnings, missing: &mut missing, parent: false }; if options.per_page == "multiple" { tile_records(&mut merged, &src, &table, &selected, &sources, &mut sink)?; diff --git a/crates/engine/src/cmd/datamerge/fill.rs b/crates/engine/src/cmd/datamerge/fill.rs index 629258d6d..965e87bd7 100644 --- a/crates/engine/src/cmd/datamerge/fill.rs +++ b/crates/engine/src/cmd/datamerge/fill.rs @@ -4,7 +4,7 @@ //! unfilled template. A placeholder whose frame or story is not in the map is left as it is. use std::collections::HashMap; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::sync::Arc; use designcraft_doc::{ @@ -134,6 +134,53 @@ pub struct Sources<'a> { pub options: &'a MergeOptions, pub data_dir: Option<&'a Path>, pub doc_dir: Option<&'a Path>, + /// Images this merge has already read, by the path they resolved to. + /// + /// Every record used to stat and read its image again, so a 100,000-row sheet naming the same + /// file read it 100,000 times -- up to 256 MiB each, around 25 TB of I/O for one merge + /// (#1595). Shared by `&`, so the cache is behind a `RefCell`. + pub images: &'a ImageCache, +} + +/// Image files read during one merge: the bytes by path, and the total read so far. +#[derive(Default)] +pub struct ImageCache { + inner: std::cell::RefCell, +} + +#[derive(Default)] +struct ImageCacheInner { + files: std::collections::HashMap>>, + bytes: usize, +} + +/// Bytes of distinct image files one merge keeps. Past this the cache stops growing and files are +/// read as before, so a merge over many large images is slow rather than out of memory. +const MAX_CACHED_IMAGE_BYTES: usize = 256 << 20; + +impl ImageCache { + /// The bytes of `path`, reading it once per merge. `read` is called only on a miss. + fn get_or_read(&self, path: &Path, read: impl FnOnce() -> Option>) -> Option>> { + if let Some(found) = self.inner.borrow().files.get(path) { + return Some(found.clone()); + } + let bytes = std::sync::Arc::new(read()?); + let mut inner = self.inner.borrow_mut(); + if inner.bytes.saturating_add(bytes.len()) <= MAX_CACHED_IMAGE_BYTES { + inner.bytes = inner.bytes.saturating_add(bytes.len()); + inner.files.insert(path.to_path_buf(), bytes.clone()); + } + Some(bytes) + } + + /// How many distinct files this merge has read, for the tests. + pub fn len(&self) -> usize { + self.inner.borrow().files.len() + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } } /// Replacements and hyperlinks collected while walking the placeholders of one record. @@ -360,15 +407,20 @@ fn create_link(doc: &mut designcraft_doc::Document, anchor: PlaceholderAnchor, d } fn place_image(doc: &mut designcraft_doc::Document, item: ItemId, field: &str, cell: &str, record: u32, sources: &Sources, report: &mut FillReport) { - let Sources { options, data_dir, doc_dir } = *sources; + let Sources { options, data_dir, doc_dir, images } = *sources; let cands = image_candidates(cell, data_dir, doc_dir); let found = cands.iter().find_map(|p| { - // Refuse huge files before reading them; a too-large image counts as missing. - let len = crate::io::metadata(p).ok()?.len(); - if len == 0 || len > super::MAX_IMAGE_FILE_BYTES { - return None; - } - crate::io::read_file(p).ok().filter(|b| !b.is_empty()).map(|b| (p.clone(), b)) + // Read once per merge: many records naming one file is the normal case, and reading it + // per record is the amplification (#1595). + let bytes = images.get_or_read(p, || { + // Refuse huge files before reading them; a too-large image counts as missing. + let len = crate::io::metadata(p).ok()?.len(); + if len == 0 || len > super::MAX_IMAGE_FILE_BYTES { + return None; + } + crate::io::read_file(p).ok().filter(|b| !b.is_empty()) + })?; + Some((p.clone(), bytes)) }); let Some((path, bytes)) = found else { if let Some(it) = doc.item_mut(item) { @@ -430,7 +482,9 @@ fn place_image(doc: &mut designcraft_doc::Document, item: ItemId, field: &str, c name, mime: designcraft_render::image_mime(&bytes).to_string(), link, - data: Arc::new(bytes), + // The cached buffer is shared with every other record naming this file, rather than + // copied per record (#1595). + data: bytes, pixels: Some((pw, ph)), ..Default::default() }); diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index 5cee93730..9e7c284a5 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -519,6 +519,69 @@ fn typed_fields_keep_style_and_unknown_markers() { assert_eq!(story.format_after(at).over.size, Some(21.0)); } +/// Every record stat'd and read its image again, so a sheet naming one file in many rows read it +/// once per row -- up to 256 MiB each time (#1595). A merge reads a file once and the records +/// share the bytes. +#[test] +fn one_image_named_by_many_records_is_read_once() { + let dir = scratch("image-reads"); + let data = dir.join("data"); + std::fs::create_dir_all(&data).unwrap(); + let shared = dir.join("shared.png"); + write_png(&shared); + // 25 records, all naming the same file. + let rows: String = (0..25).map(|_| format!("{}\n", shared.display())).collect(); + write(&data.join("many.csv"), &format!("@Photo\n{rows}")); + + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": data.join("many.csv")})); + let frame = exec(&mut s, "frame.create", json!({"rect": [36.0, 36.0, 80.0, 80.0], "content": "graphic"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "item": frame["id"]})); + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["records"], 25); + assert_eq!(r["missingImages"].as_array().map(Vec::len).unwrap_or(0), 0, "every record found the image"); + + // Each record has its graphic, and they share one buffer: the document holds the file's bytes + // once however many records named it. + let doc = &s.documents()[s.active_index().unwrap()].doc; + let graphics: Vec<_> = doc + .spreads + .iter() + .flat_map(|sp| &sp.items) + .filter_map(|it| match &it.content { + Content::Graphic(g) => Some(g.asset), + _ => None, + }) + .collect(); + assert_eq!(graphics.len(), 25, "one graphic per record"); +} + +/// The same merge, counting what the engine actually hands the file system: `io::touched` records +/// every path read, so the reads are counted rather than inferred. The document already shares +/// identical asset bytes, so memory alone does not show this -- the I/O is the bug (#1595). +#[test] +fn a_merge_reads_a_repeated_image_once_not_once_per_record() { + let dir = scratch("image-read-count"); + let data = dir.join("data"); + std::fs::create_dir_all(&data).unwrap(); + let shared = dir.join("shared.png"); + write_png(&shared); + let rows: String = (0..25).map(|_| format!("{}\n", shared.display())).collect(); + write(&data.join("many.csv"), &format!("@Photo\n{rows}")); + + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": data.join("many.csv")})); + let frame = exec(&mut s, "frame.create", json!({"rect": [36.0, 36.0, 80.0, 80.0], "content": "graphic"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "item": frame["id"]})); + + let (r, seen) = crate::io::touched(|| exec(&mut s, "data.merge", json!({}))); + assert_eq!(r["records"], 25); + let reads = seen.iter().filter(|p| p.ends_with("shared.png")).count(); + assert!(reads <= 2, "the image is read once for the merge, not once per record: {reads} reads for 25 records"); +} + #[test] fn images_resolve_in_order_and_roles_win() { let dir = scratch("images"); From e6a14a516a2f847922e6a2e25a68c43646256bc0 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Tue, 27 Oct 2026 11:02:53 +0000 Subject: [PATCH 0291/1349] Keep underline, strikethrough, caps and tracking in EPUB/HTML character styles and overrides Found while testing crates/epub/src/css.rs:~128-153 (the character-style loop in stylesheet_with) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/epub/src/css.rs | 31 +++++++++++++++++++++++++------ crates/epub/src/tests.rs | 23 +++++++++++++++++++++++ 2 files changed, 48 insertions(+), 6 deletions(-) diff --git a/crates/epub/src/css.rs b/crates/epub/src/css.rs index 526b10a40..3a8639cec 100644 --- a/crates/epub/src/css.rs +++ b/crates/epub/src/css.rs @@ -150,6 +150,7 @@ pub(crate) fn stylesheet_with(doc: &Document, generics: &BTreeMap out.push_str("text-transform: uppercase; "), + Some(designcraft_doc::Capitalization::SmallCaps | designcraft_doc::Capitalization::OpenTypeAllSmallCaps) => { + out.push_str("font-variant: small-caps; ") + } + _ => {} + } + // One declaration: a later `text-decoration` would replace the earlier one. + match (c.underline == Some(true), c.strikethrough == Some(true)) { + (true, true) => out.push_str("text-decoration: underline line-through; "), + (true, false) => out.push_str("text-decoration: underline; "), + (false, true) => out.push_str("text-decoration: line-through; "), + (false, false) => {} + } +} + pub(crate) fn override_css(doc: &Document, o: &CharAttrs) -> String { let mut s = String::new(); if let Some(f) = &o.font_style { @@ -174,12 +198,7 @@ pub(crate) fn override_css(doc: &Document, o: &CharAttrs) -> String { { let _ = write!(s, "color: {h}; "); } - if o.underline == Some(true) { - s.push_str("text-decoration: underline; "); - } - if o.capitalization == Some(designcraft_doc::Capitalization::AllCaps) { - s.push_str("text-transform: uppercase; "); - } + attrs_decor_css(o, &mut s); s.trim_end().to_string() } diff --git a/crates/epub/src/tests.rs b/crates/epub/src/tests.rs index f216fe95f..6cae6159f 100644 --- a/crates/epub/src/tests.rs +++ b/crates/epub/src/tests.rs @@ -922,3 +922,26 @@ fn char_css_joins_underline_and_strikethrough_in_one_declaration() { assert!(css(false, true).contains("text-decoration: line-through;")); assert!(!css(false, false).contains("text-decoration")); } + +#[test] +fn character_styles_keep_decorations_caps_and_tracking() { + let mut d = Document::new(&NewDocument::default()); + d.styles_mut().character.push(designcraft_doc::CharacterStyle { + name: "Under".into(), + based_on: None, + chars: CharAttrs { + underline: Some(true), + strikethrough: Some(true), + capitalization: Some(designcraft_doc::Capitalization::AllCaps), + tracking: Some(100.0), + ..Default::default() + }, + shortcut: String::new(), + }); + let css = css::stylesheet(&d); + assert!(css.contains("text-decoration: underline line-through;"), "{css}"); + assert!(css.contains("text-transform: uppercase;"), "{css}"); + assert!(css.contains("letter-spacing: 0.100em;"), "{css}"); + let o = CharAttrs { strikethrough: Some(true), ..Default::default() }; + assert_eq!(css::override_css(&d, &o), "text-decoration: line-through;"); +} From e8c0a191806cdffcfa70a5c4e7a662cbdf946be1 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Tue, 27 Oct 2026 11:26:46 +0000 Subject: [PATCH 0292/1349] Fix duplicated xref format text before an unclosed '<' in IDML export Found while testing crates/idml/src/export/designmap.rs:208-230 (xref_format_el) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/idml/src/export/designmap.rs | 30 ++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/crates/idml/src/export/designmap.rs b/crates/idml/src/export/designmap.rs index adce1cbd0..6dc907c64 100644 --- a/crates/idml/src/export/designmap.rs +++ b/crates/idml/src/export/designmap.rs @@ -206,10 +206,10 @@ fn xref_format_el(i: usize, f: &designcraft_doc::XrefFormat) -> El { }; let mut rest = f.definition.as_str(); while let Some(a) = rest.find('<') { + let Some(b) = rest[a..].find('>') else { break }; if a > 0 { block(&mut el, "CustomStringBuildingBlock", &rest[..a], "", false); } - let Some(b) = rest[a..].find('>') else { break }; let tag = rest[a + 1..a + b].trim().trim_end_matches('/').trim(); let attr = |k: &str| tag.find(&format!("{k}=\"")).and_then(|i| tag[i + k.len() + 2..].split('"').next()).unwrap_or("").to_string(); match tag.split_whitespace().next().unwrap_or("") { @@ -350,3 +350,31 @@ fn text_variable_el(v: &designcraft_doc::vars::TextVariable) -> El { } e } + +#[cfg(test)] +mod tests { + use super::*; + use crate::xml::Node; + + fn custom_text(definition: &str) -> String { + let f = designcraft_doc::XrefFormat { name: "x".into(), definition: definition.into() }; + xref_format_el(0, &f) + .children + .iter() + .filter_map(|n| match n { + Node::El(e) if e.get("BlockType") == Some("CustomStringBuildingBlock") => e.get("CustomText").map(str::to_string), + _ => None, + }) + .collect() + } + + #[test] + fn xref_format_unclosed_angle_bracket_keeps_text_once() { + assert_eq!(custom_text("a < b"), "a < b"); + } + + #[test] + fn xref_format_well_formed_keeps_custom_text() { + assert_eq!(custom_text("p of "), "p of "); + } +} From bb49e566277d083db153aef11d9c81cbb0a818a1 Mon Sep 17 00:00:00 2001 From: Hamza Date: Tue, 27 Oct 2026 16:30:57 +0500 Subject: [PATCH 0293/1349] Fonts: a missing Korean sans face falls back to a sans one (#1692) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rebuilt on the split `fontdb/`: `KOREAN_SANS_FALLBACKS` and `sans_by_name` sit in `fontdb/fallback.rs` beside `KOREAN_FALLBACKS`, `cjk_chain` takes the style, `fallback_for_styled` is on both `ScopedFonts` and `FontDb`, and the tests live in `fontdb/tests/fallback.rs` where that file's other fallback tests are. `KOREAN_FALLBACKS` is serif-first (AppleMyungjo, Apple SD Gothic Neo, Batang, Malgun Gothic...), so on Windows the first installed entry is Batang. A document whose Korean text asks for faces that are not installed -- KoPub Dotum, KHNP Han Dotum, BM Dohyeon -- came out in a serif face throughout: the report measured 5,298 characters of one school document turning from sans to serif. The font is not installed, so its name is all there is to go on. `sans_by_name` reads the style out of the family name: Dotum (돋움), Gulim (굴림), Gothic (고딕), Sans, Headline, Graphic and Dohyeon are sans; Batang (바탕), Myungjo/Myeongjo (명조), Gungsuh (궁서) and Serif are serif. Serif is tested first, so "Noto Serif KR" is not caught by the `sans` rule. A run whose requested face is sans draws its fallback from the sans chain, which leads with the system faces. If the requested name says neither, the substitute's own name decides, which leaves today's chain in place. The tests do not depend on which fonts the machine has: they pin the name classification and the chain order -- the first sans entry comes before Batang, and the serif chain still leads with a serif face, so a missing Myungjo is not turned into a sans one. `fallback_for` keeps its signature and delegates, so the ruby, kenten and image callers are unchanged. --- crates/compose/src/shape.rs | 14 +++++- crates/fonts/src/fontdb.rs | 1 + crates/fonts/src/fontdb/db.rs | 5 ++ crates/fonts/src/fontdb/fallback.rs | 58 +++++++++++++++++++++-- crates/fonts/src/fontdb/scoped.rs | 9 +++- crates/fonts/src/fontdb/tests/fallback.rs | 38 +++++++++++++++ crates/fonts/src/lib.rs | 2 +- 7 files changed, 119 insertions(+), 8 deletions(-) diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs index 0f739e16e..6c9aca4d3 100644 --- a/crates/compose/src/shape.rs +++ b/crates/compose/src/shape.rs @@ -784,8 +784,16 @@ fn shape_run_raw( // The language picks the fallback for CJK characters the primary font lacks. Without // fallback, the primary font sets them: the shaper gives its .notdef (glyph 0). let lang = designcraft_doc::language_tag(&p.language); + // A missing Korean face is replaced by one of its own style: the requested name says whether + // it was Dotum/Gothic or Batang/Myungjo, and if it does not, the substitute's own name does, + // which keeps today's chain (#1692). + let prefer_sans = designcraft_fonts::sans_by_name(&p.font_family).or_else(|| designcraft_fonts::sans_by_name(&primary.family)); let fallback = |c: char| { - if auto_leading.glyph_fallback { db.fallback_for(c, primary.id(), lang).unwrap_or_else(|| primary.clone()) } else { primary.clone() } + if auto_leading.glyph_fallback { + db.fallback_for_styled(c, primary.id(), lang, prefer_sans).unwrap_or_else(|| primary.clone()) + } else { + primary.clone() + } }; let strong = |c| match unicode_bidi::bidi_class(c) { unicode_bidi::BidiClass::AL => Some(true), @@ -1116,7 +1124,9 @@ fn shape_segment( let lang = designcraft_doc::language_tag(&p.language); let mut segments: Vec<(usize, usize, Arc)> = Vec::new(); for (at, c) in label.char_indices() { - let selected = if face.covers(c) { face.clone() } else { db.fallback_for(c, face.id(), lang).unwrap_or_else(|| face.clone()) }; + let prefer_sans = designcraft_fonts::sans_by_name(&p.font_family).or_else(|| designcraft_fonts::sans_by_name(&face.family)); + let selected = + if face.covers(c) { face.clone() } else { db.fallback_for_styled(c, face.id(), lang, prefer_sans).unwrap_or_else(|| face.clone()) }; if let Some((_, end, previous)) = segments.last_mut().filter(|(_, _, previous)| previous.id() == selected.id()) { *end = at + c.len_utf8(); let _ = previous; diff --git a/crates/fonts/src/fontdb.rs b/crates/fonts/src/fontdb.rs index d0f0054f8..6e145ade0 100644 --- a/crates/fonts/src/fontdb.rs +++ b/crates/fonts/src/fontdb.rs @@ -138,6 +138,7 @@ pub(crate) use face::{measured_top, plausible}; use fallback::FallbackSnapshotHook; #[cfg(not(target_arch = "wasm32"))] use fallback::SysFallback; +pub use fallback::sans_by_name; pub use names::{base_style, same_style}; use outline::FlipPen; pub use scoped::ScopedFonts; diff --git a/crates/fonts/src/fontdb/db.rs b/crates/fonts/src/fontdb/db.rs index 30b2b4b28..c97a06dd7 100644 --- a/crates/fonts/src/fontdb/db.rs +++ b/crates/fonts/src/fontdb/db.rs @@ -197,6 +197,11 @@ impl FontDb { self.scoped(0).fallback_for(c, exclude, language) } + /// [`ScopedFonts::fallback_for_styled`] on the shared scope. + pub fn fallback_for_styled(&self, c: char, exclude: u32, language: Option<&str>, prefer_sans: Option) -> Option> { + self.scoped(0).fallback_for_styled(c, exclude, language, prefer_sans) + } + /// The box drawn for `face`'s missing glyph (.notdef) when the font's own has no outline, in /// font units, y-down: a hollow rectangle across the glyph's advance, cap height tall. `None` /// when the font draws its own. diff --git a/crates/fonts/src/fontdb/fallback.rs b/crates/fonts/src/fontdb/fallback.rs index 7e29fa4b3..ad8acc538 100644 --- a/crates/fonts/src/fontdb/fallback.rs +++ b/crates/fonts/src/fontdb/fallback.rs @@ -92,7 +92,56 @@ const TRADITIONAL_CHINESE_FALLBACKS: &[&str] = &[ "Source Han Sans TC", ]; -const KOREAN_FALLBACKS: &[&str] = &[ +/// Korean fallbacks for a missing **sans** (Dotum/Gothic) face, system faces first. +/// +/// [`KOREAN_FALLBACKS`] is serif-first, so on Windows the first installed entry is Batang and a +/// document whose Korean text asked for KoPub Dotum or BM Dohyeon came out in a serif face -- +/// 5,298 characters of one school document, turning it from sans to serif (#1692). +pub(super) const KOREAN_SANS_FALLBACKS: &[&str] = &[ + "Malgun Gothic", + "Apple SD Gothic Neo", + "Dotum", + "Gulim", + "Noto Sans CJK KR", + "Source Han Sans K", + "Noto Sans KR", + "Noto Serif CJK KR", + "Batang", +]; + +/// Whether a Korean family name says the face is sans (`Some(true)`) or serif (`Some(false)`). +/// `None` when the name does not say, so the caller decides. +/// +/// Korean family names carry the style: Dotum (돋움), Gulim (굴림) and Gothic (고딕) are sans; +/// Batang (바탕), Myungjo/Myeongjo (명조) and Gungsuh (궁서) are serif. A missing font's name is +/// the only thing left to go on, since the font itself is not there to classify (#1692). +pub fn sans_by_name(family: &str) -> Option { + let lower = family.to_lowercase(); + let has = |needles: &[&str]| needles.iter().any(|n| lower.contains(n)); + // Serif first: "Myungjo Gothic" does not exist, but a name holding both reads as the serif + // it names, and "Sans" inside "Noto Sans Myungjo" would otherwise win. + if has(&["batang", "myungjo", "myeongjo", "gungsuh", "serif", "\u{BC14}\u{D5D5}", "\u{BA85}\u{C870}", "\u{AD81}\u{C11C}"]) { + return Some(false); + } + if has(&[ + "dotum", + "gothic", + "gulim", + "sans", + "headline", + "graphic", + "dohyeon", + "\u{B3CB}\u{C6C0}", + "\u{ACE0}\u{B515}", + "\u{AD74}\u{B9BC}", + "\u{ADF8}\u{B798}\u{D53D}", + ]) { + return Some(true); + } + None +} + +pub(super) const KOREAN_FALLBACKS: &[&str] = &[ "AppleMyungjo", "Apple SD Gothic Neo", "Batang", @@ -146,9 +195,10 @@ fn japanese_chain() -> &'static [&'static str] { /// The CJK fallback chain for `c` in `language` (a BCP 47 tag). The script decides where it is /// unambiguous (Hangul is Korean, kana Japanese, Bopomofo Traditional Chinese); ideographs and CJK /// punctuation follow the language, and have no chain without a CJK one. -pub(super) fn cjk_chain(c: char, language: Option<&str>) -> Option<&'static [&'static str]> { +pub(super) fn cjk_chain(c: char, language: Option<&str>, prefer_sans: Option) -> Option<&'static [&'static str]> { + let korean = if prefer_sans == Some(true) { KOREAN_SANS_FALLBACKS } else { KOREAN_FALLBACKS }; match c as u32 { - 0x1100..=0x11FF | 0x3130..=0x318F | 0xA960..=0xA97F | 0xAC00..=0xD7FF | 0xFFA0..=0xFFDC => return Some(KOREAN_FALLBACKS), + 0x1100..=0x11FF | 0x3130..=0x318F | 0xA960..=0xA97F | 0xAC00..=0xD7FF | 0xFFA0..=0xFFDC => return Some(korean), 0x3040..=0x30FF | 0x31F0..=0x31FF | 0xFF66..=0xFF9F | 0x1B000..=0x1B16F => return Some(japanese_chain()), 0x3100..=0x312F | 0x31A0..=0x31BF => return Some(TRADITIONAL_CHINESE_FALLBACKS), // Radicals, CJK symbols and punctuation, kanbun, strokes, enclosed and compatibility @@ -171,7 +221,7 @@ pub(super) fn cjk_chain(c: char, language: Option<&str>) -> Option<&'static [&'s let language = language?; match language.split('-').next()? { "ja" => Some(japanese_chain()), - "ko" => Some(KOREAN_FALLBACKS), + "ko" => Some(korean), "zh" if language.starts_with("zh-Hant") => Some(TRADITIONAL_CHINESE_FALLBACKS), "zh" => Some(SIMPLIFIED_CHINESE_FALLBACKS), _ => None, diff --git a/crates/fonts/src/fontdb/scoped.rs b/crates/fonts/src/fontdb/scoped.rs index 8fba9ff6e..e0881ff05 100644 --- a/crates/fonts/src/fontdb/scoped.rs +++ b/crates/fonts/src/fontdb/scoped.rs @@ -390,7 +390,14 @@ impl ScopedFonts<'_> { /// then load order, the document's fonts last) that covers `c`. On native, system fonts are /// cataloged and loaded lazily the first time no loaded face covers a character. pub fn fallback_for(&self, c: char, exclude: u32, language: Option<&str>) -> Option> { - if let Some(chain) = cjk_chain(c, language).or_else(|| script_chain(c)) + self.fallback_for_styled(c, exclude, language, None) + } + + /// [`Self::fallback_for`] following the style of the font that was asked for: `Some(true)` + /// takes the sans chain, so a missing Dotum or Gothic face is replaced by a sans one instead + /// of by the first installed serif (#1692). `None` keeps the chain as it was. + pub fn fallback_for_styled(&self, c: char, exclude: u32, language: Option<&str>, prefer_sans: Option) -> Option> { + if let Some(chain) = cjk_chain(c, language, prefer_sans).or_else(|| script_chain(c)) && let Some(f) = chain.iter().find_map(|family| self.chain_face(family, c, exclude)) { return Some(f); diff --git a/crates/fonts/src/fontdb/tests/fallback.rs b/crates/fonts/src/fontdb/tests/fallback.rs index 19eb30cec..d385a8fd9 100644 --- a/crates/fonts/src/fontdb/tests/fallback.rs +++ b/crates/fonts/src/fontdb/tests/fallback.rs @@ -1,6 +1,7 @@ //! CJK fallback follows the character's language (and the script where it is unambiguous). use crate::fontdb::FontDb; +use crate::fontdb::fallback::{KOREAN_FALLBACKS, KOREAN_SANS_FALLBACKS, cjk_chain, sans_by_name}; use crate::testing::font_with; const HAN: char = '直'; @@ -157,3 +158,40 @@ fn malayalam_fonts_load_from_the_font_folders_when_first_needed() { assert!(!db.is_loaded("Noto Sans Malayalam")); assert_eq!(family(&db, KA, None).as_deref(), Some("Noto Sans Malayalam")); } + +/// A missing Korean face is replaced by one of its own style. The name is all there is to go +/// on, since the font itself is not installed to classify (#1692). +#[test] +fn a_korean_family_name_says_sans_or_serif() { + for sans in ["KoPub Dotum Bold", "KHNP Han Dotum", "BM Dohyeon", "Malgun Gothic", "\u{B3CB}\u{C6C0}\u{CCB4}", "\u{ACE0}\u{B515}", "Noto Sans KR"] + { + assert_eq!(sans_by_name(sans), Some(true), "{sans} is sans"); + } + for serif in ["Batang", "HCR Batang", "KoPub Myungjo", "\u{BA85}\u{C870}", "Gungsuh", "Noto Serif KR"] { + assert_eq!(sans_by_name(serif), Some(false), "{serif} is serif"); + } + // A name that says neither leaves the choice to the caller. + for unknown in ["Times New Roman", "Helvetica", "Arial Unicode MS", ""] { + assert_eq!(sans_by_name(unknown), None, "{unknown} says neither"); + } +} + +/// The reported bug is the order of the chain: on Windows the first installed entry of the +/// serif-first chain is Batang, so every missing Dotum face came out serif (#1692). +#[test] +fn the_sans_chain_puts_a_sans_face_before_batang() { + let hangul = '\u{D55C}'; + let sans = cjk_chain(hangul, None, Some(true)).expect("Hangul has a chain"); + let serif = cjk_chain(hangul, None, None).expect("Hangul has a chain"); + assert_eq!(serif, KOREAN_FALLBACKS, "without a style the chain is unchanged"); + assert_eq!(sans, KOREAN_SANS_FALLBACKS); + + let batang = |chain: &[&str]| chain.iter().position(|f| *f == "Batang"); + let first_sans = |chain: &[&str]| chain.iter().position(|f| sans_by_name(f) == Some(true)); + assert!(first_sans(sans) < batang(sans), "the sans chain reaches a sans face first: {sans:?}"); + // And the Windows and macOS system faces are the first two entries, so an installed + // system font is preferred to a downloaded one. + assert_eq!(&sans[..2], &["Malgun Gothic", "Apple SD Gothic Neo"]); + // The serif chain still leads with serif faces, so a missing Myungjo is not made sans. + assert_eq!(sans_by_name(serif[0]), Some(false), "the serif chain still leads serif: {:?}", serif[0]); +} diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs index aca293d12..30b54e206 100644 --- a/crates/fonts/src/lib.rs +++ b/crates/fonts/src/lib.rs @@ -20,7 +20,7 @@ mod vertical; pub use features::{FontFeatures, font_features}; pub use fontdb::{ DOCUMENT_FONTS_FOLDER, DocumentFonts, FALLBACK_FAMILY, FaceRef, FontDb, FontFace, FontSource, MAX_DOCUMENT_FONT_BYTES, MAX_DOCUMENT_FONT_FILES, - MAX_DOCUMENT_FONTS_TOTAL, ReloadedFonts, ScopedFonts, base_style, bundled, same_style, system_font_dirs, + MAX_DOCUMENT_FONTS_TOTAL, ReloadedFonts, ScopedFonts, base_style, bundled, same_style, sans_by_name, system_font_dirs, }; pub use group::{FamilyInfo, FontGroup, sort_for_menu}; pub use harfrust::Feature; From 516998d4494ee33472359c6eab029e07a7215838 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:33:17 +0000 Subject: [PATCH 0294/1349] Export form field borders from the item stroke Fixes #1881 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/pdf/src/forms.rs | 16 ++++++++++------ crates/pdf/src/tests.rs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/crates/pdf/src/forms.rs b/crates/pdf/src/forms.rs index 07f4cf04c..bf0d955fc 100644 --- a/crates/pdf/src/forms.rs +++ b/crates/pdf/src/forms.rs @@ -10,8 +10,9 @@ use designcraft_doc::{Document, FieldKind, FormField, Item, MediaOptions}; use crate::export::Sheet; use crate::transitions::{bracketed, int_after, object, rfind}; -/// A field placed on an output page: (page index, PDF rectangle, field). -pub(crate) type Placed = (usize, [f64; 4], FormField); +/// A field placed on an output page: (page index, PDF rectangle, field, border width, 0 when the +/// item has no stroke). +pub(crate) type Placed = (usize, [f64; 4], FormField, f64); /// A placed video or sound on an output page: (page index, PDF rectangle, file name, MIME type, /// bytes, options). @@ -37,7 +38,8 @@ pub(crate) fn collect(doc: &Document, sheets: &[Sheet]) -> Vec { let mut out = Vec::new(); visit(doc, sheets, |pi, r, it| { if let Some(f) = &it.form_field { - out.push((pi, r, f.clone())); + let bw = if it.stroke.is_none() || !it.stroke.weight.is_finite() { 0.0 } else { it.stroke.weight }; + out.push((pi, r, f.clone(), bw)); } }); out @@ -158,13 +160,14 @@ pub(crate) fn add_fields(pdf: &[u8], fields: &[Placed], media: &[PlacedMedia]) - put(&mut out, font, b"<>"); } let mut all = Vec::new(); - for (page, r, f) in fields { + for (page, r, f, bw) in fields { let Some(&page_ref) = kids.get(*page) else { continue }; let rect = format!("[{:.2} {:.2} {:.2} {:.2}]", r[0], r[1], r[2], r[3]); let (w, h) = (r[2] - r[0], r[3] - r[1]); let fs = if f.font_size > 0.0 { f.font_size } else { 0.0 }; + let (bc, bs) = if *bw > 0.0 { ("/BC[0.45 0.45 0.45]", format!("/BS<>")) } else { ("", "/BS<>".to_string()) }; let common = format!( - "/Type/Annot/Subtype/Widget/T{}/Rect{rect}/F 4/P {page_ref} 0 R/MK<>/DA(/Helv {fs:.1} Tf 0 g)", + "/Type/Annot/Subtype/Widget/T{}/Rect{rect}/F 4/P {page_ref} 0 R/MK<<{bc}/BG[1 1 1]>>{bs}/DA(/Helv {fs:.1} Tf 0 g)", pdf_string(&f.name) ); let req = if f.required { 2 } else { 0 }; @@ -175,7 +178,8 @@ pub(crate) fn add_fields(pdf: &[u8], fields: &[Placed], media: &[PlacedMedia]) - } FieldKind::CheckBox => { // Appearances: an empty box, and a box with a check mark. - let border = format!("0.45 G 1 w 0.5 0.5 {:.2} {:.2} re S", (w - 1.0).max(0.0), (h - 1.0).max(0.0)); + let border = + if *bw > 0.0 { format!("0.45 G 1 w 0.5 0.5 {:.2} {:.2} re S", (w - 1.0).max(0.0), (h - 1.0).max(0.0)) } else { String::new() }; let check = format!( "{border} 0 g {:.2} w 1 J 1 j {:.2} {:.2} m {:.2} {:.2} l {:.2} {:.2} l S", (w.min(h) * 0.12).max(0.8), diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index b06fad47d..9c3a9ff9a 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -791,6 +791,36 @@ fn only_printed_fields_and_buttons_export() { assert_eq!(all.matches("/Link").count(), shown.matches("/Link").count(), "only the shown button"); } +#[test] +fn form_field_border_follows_the_item_stroke() { + use designcraft_doc::{FieldKind, FormField, Shape, Stroke}; + use designcraft_geom::shapes::rectangle; + let export = |stroke: Stroke| { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let mut it = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, rectangle(Rect::new(72.0, 72.0, 250.0, 96.0))); + it.stroke = stroke; + it.form_field = Some(FormField { + kind: FieldKind::TextField, + name: "name".into(), + value: String::new(), + options: Vec::new(), + multiline: false, + required: false, + font_size: 0.0, + }); + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + uncompressed(&d, PdfOptions::default()) + }; + let none = export(Stroke { weight: 0.0, swatch: designcraft_color::swatch::NONE.into(), ..Stroke::default() }); + assert!(none.contains("/Subtype/Widget")); + assert!(none.contains("/BS<>"), "no border width"); + assert!(!none.contains("/BC"), "no border colour"); + let stroked = export(Stroke { weight: 1.0, ..Stroke::default() }); + assert!(stroked.contains("/BS< Date: Tue, 27 Oct 2026 08:54:35 -0700 Subject: [PATCH 0295/1349] Remap text anchors in duplicated cells and notes --- crates/engine/src/cmd/layout/layers.rs | 88 ++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) diff --git a/crates/engine/src/cmd/layout/layers.rs b/crates/engine/src/cmd/layout/layers.rs index f9943007a..fc8c7ecf2 100644 --- a/crates/engine/src/cmd/layout/layers.rs +++ b/crates/engine/src/cmd/layout/layers.rs @@ -119,6 +119,7 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { Arc::make_mut(a).id = id; } renumber_tables(d, &mut st); + renumber_nested_anchors(d, &mut st, &mut anchors); d.stories.insert(*new, Arc::new(st)); } for new in stories.values() { @@ -260,6 +261,25 @@ fn renumber_tables(d: &mut designcraft_doc::Document, st: &mut Story) { } } +fn renumber_nested_anchors(d: &mut designcraft_doc::Document, st: &mut Story, anchors: &mut HashMap) { + fn child(d: &mut designcraft_doc::Document, st: &mut Story, anchors: &mut HashMap) { + for anchor in &mut st.anchors { + let id = d.alloc(); + anchors.insert(anchor.id, id); + Arc::make_mut(anchor).id = id; + } + renumber_nested_anchors(d, st, anchors); + } + for table in st.tables.values_mut() { + for cell in &mut Arc::make_mut(table).cells { + child(d, &mut cell.text, anchors); + } + } + for note in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + child(d, &mut Arc::make_mut(note).text, anchors); + } +} + /// Point the cross-references in `st`, and in the stories of its table cells and notes, at the anchors `map` gives for /// their targets. [`too_deep`] bounds the nesting. fn remap_xrefs(st: &mut Story, map: &HashMap) { @@ -709,6 +729,74 @@ mod layer_tests { assert_eq!(d.find_anchor(st.anchors[0].id).map(|a| a.0), Some(copied)); } + #[test] + fn duplicate_layer_remaps_anchors_in_cells_and_notes() { + use designcraft_doc::Story; + use std::sync::Arc; + + fn add_anchor(st: &mut Story, id: u64) { + st.insert_anchor(0, "Nested heading"); + Arc::make_mut(&mut st.anchors[0]).id = id; + st.insert_xref(st.len(), designcraft_doc::CrossRef { target: id, format: String::new() }); + } + fn collect(st: &Story, values: &mut Vec<(u64, u64)>) { + for (a, x) in st.anchors.iter().zip(st.xrefs.iter()) { + values.push((a.id, x.target)); + } + for table in st.tables.values() { + for cell in &table.cells { + collect(&cell.text, values); + } + } + for note in st.notes.iter().chain(st.endnotes.iter()) { + collect(¬e.text, values); + } + } + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Rows"})).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let table_id = d.alloc(); + let nested_id = d.alloc(); + let anchor_ids = [d.alloc(), d.alloc(), d.alloc(), d.alloc()]; + let mut table = designcraft_doc::Table::new(table_id, 1, 1, 0, 0, 40.0); + let cell = &mut table.cells[0].text; + add_anchor(cell, anchor_ids[0]); + let mut nested = designcraft_doc::Table::new(nested_id, 1, 1, 0, 0, 20.0); + add_anchor(&mut nested.cells[0].text, anchor_ids[1]); + cell.insert_table(cell.len(), nested); + cell.insert_note(cell.len(), "Footnote", Default::default()).unwrap(); + add_anchor(&mut Arc::make_mut(&mut cell.notes[0]).text, anchor_ids[2]); + cell.insert_endnote(cell.len(), "Endnote", Default::default()).unwrap(); + add_anchor(&mut Arc::make_mut(&mut cell.endnotes[0]).text, anchor_ids[3]); + d.story_mut(sid).unwrap().insert_table(0, table); + let mut original = Vec::new(); + collect(d.story(sid).unwrap(), &mut original); + assert_eq!(original.len(), 4); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copied = on_layer(d, copy)[0].text_frame().unwrap().story; + let mut after = Vec::new(); + collect(d.story(copied).unwrap(), &mut after); + assert_eq!(after.len(), original.len()); + let unique: std::collections::HashSet<_> = after.iter().map(|(id, _)| *id).collect(); + assert_eq!(unique.len(), after.len()); + for (id, target) in &after { + assert!(!anchor_ids.contains(id), "copied nested anchor retains original id {id}"); + assert_eq!(id, target, "copied reference points to its copied anchor"); + } + let mut unchanged = Vec::new(); + collect(d.story(sid).unwrap(), &mut unchanged); + assert_eq!(unchanged, original); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + let mut redone = Vec::new(); + collect(s.doc().unwrap().doc.story(copied).unwrap(), &mut redone); + assert_eq!(redone, after); + } + #[test] fn duplicate_layer_gives_copied_tables_their_own_ids() { let mut s = crate::Session::new(); From 450789d627c865c488dd3826afc4568b536bb6d0 Mon Sep 17 00:00:00 2001 From: macadminHU <51995175+macrobi@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:05:17 +0100 Subject: [PATCH 0296/1349] HU1: align the moved panel test path for the module merge MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Upstream d77fdf2d moved these tests to crates/ui-egui/src/panel_docking/tests.rs. The tested local merge preserves every test body from both parents there. Remove the obsolete path to unblock GitHub’s web conflict resolver; the remaining module integration follows immediately. --- crates/ui-egui/src/panel_docking_tests.rs | 1281 --------------------- 1 file changed, 1281 deletions(-) delete mode 100644 crates/ui-egui/src/panel_docking_tests.rs diff --git a/crates/ui-egui/src/panel_docking_tests.rs b/crates/ui-egui/src/panel_docking_tests.rs deleted file mode 100644 index 73f98f612..000000000 --- a/crates/ui-egui/src/panel_docking_tests.rs +++ /dev/null @@ -1,1281 +0,0 @@ -use super::{ - CANVAS, Column, DOCK_LABELS, DesignApp, Floating, ICON_GROUPS, Layout, Node, PanelContent, Placed, Side, Value, area_id, cancel_gesture, - close_visible, default_layout, dock_columns, hit_id, icon_column, in_iconic_column, json, layout_of, modal_open, open_window_drops, panel_menu, - set_iconic, showing, tab_group, tab_id, valid, window_groups, -}; -use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; -use egui_kittest::{Harness, kittest::Queryable}; - -fn app() -> DesignApp { - DesignApp::new(designcraft_engine::Session::new(), Default::default()) -} - -#[test] -fn panel_commands_group_split_reorder_float_and_restore_without_duplicate_ownership() { - let mut app = app(); - app.run("window.panel.move", json!({"panel":"swatches", "anchor":"layers", "zone":"top"})).unwrap(); - app.run("window.panel.move", json!({"panel":"properties", "anchor":"swatches", "before":"swatches"})).unwrap(); - let before_float = app.ui.docking.clone().unwrap(); - app.run("window.panel.float", json!({"panel":"properties", "x":50,"y":70,"width":330,"height":410})).unwrap(); - assert!(app.ui.docking.as_ref().unwrap().floating.iter().flat_map(window_groups).any(|g| g.panels == ["properties"])); - app.run("window.panel.dock", json!({"panel":"properties"})).unwrap(); - assert_eq!(app.ui.docking.as_ref().unwrap(), &before_float); - app.run("window.panel.close", json!({"panel":"properties"})).unwrap(); - assert!(!app.ui.docking.as_ref().unwrap().contains(&"properties".into())); - app.run("window.panel.activate", json!({"panel":"properties"})).unwrap(); - assert_eq!(app.ui.docking.as_ref().unwrap(), &before_float); - let layout = app.ui.docking.as_ref().unwrap(); - assert!(valid(layout)); - let unique: std::collections::HashSet<_> = layout.panels().into_iter().collect(); - assert_eq!(unique.len(), layout.panels().len()); - let saved = serde_json::to_value(&app.ui).unwrap(); - let restored: crate::UiState = serde_json::from_value(saved).unwrap(); - assert_eq!(restored.docking, app.ui.docking); - assert_eq!(restored.docking_hidden, app.ui.docking_hidden); -} - -#[test] -fn invalid_panel_requests_are_atomic_and_do_not_enter_a_custom_workspace() { - let mut app = app(); - for (id, params) in [ - ("window.panel.move", json!({"panel":"layers","anchor":"unknown"})), - ("window.panel.move", json!({"panel":"layers","anchor":"properties","before":"unknown"})), - ("window.panel.move", json!({"panel":"layers","anchor":"properties","zone":42})), - ("window.panel.float", json!({"panel":"layers","width":-10})), - ("window.panel.float", json!({"panel":"unknown"})), - ("window.panel.float", json!({"panel":"layers","x":"invalid"})), - ] { - let old = app.ui.docking.clone(); - let hidden = app.ui.docking_hidden.clone(); - assert!(app.run(id, params).is_err(), "{id}"); - assert_eq!(app.ui.docking, old); - assert_eq!(app.ui.docking_hidden, hidden); - } -} - -fn harness(app: DesignApp, size: egui::Vec2) -> Harness<'static, DesignApp> { - let mut ready = false; - let mut harness = Harness::builder().with_size(size).with_step_dt(1.0 / 60.0).build_ui_state( - move |ui, app: &mut DesignApp| { - if !ready { - crate::theme::install_fonts(ui.ctx(), &app.ui.language); - crate::theme::apply(ui.ctx(), &crate::theme::Tokens::for_brightness(crate::theme::Brightness::MediumDark)); - ready = true; - return; - } - egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| crate::panel_docking::show(app, ui)); - }, - app, - ); - harness.run_steps(4); - harness -} - -fn drag(h: &mut Harness<'static, DesignApp>, from: Pos2, to: Pos2) { - h.event(Event::PointerMoved(from)); - h.run_steps(1); - h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.run_steps(1); - for step in 1..=8 { - h.event(Event::PointerMoved(from + (to - from) * (step as f32 / 8.0))); - h.run_steps(1); - } - h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(3); -} - -#[test] -fn ordinary_panel_tab_drag_enters_shared_docking_and_can_redock_into_another_tab_group() { - let mut h = harness(app(), vec2(1280.0, 800.0)); - let source = h.query_all_by_label("Layers").find(|node| node.rect().height() <= 45.0).unwrap().rect().center(); - drag(&mut h, source, egui::pos2(160.0, 140.0)); - let layout = h.state().ui.docking.as_ref().expect("ordinary tab drag starts shared docking"); - assert!(layout.floating.iter().flat_map(window_groups).any(|g| g.panels.contains(&"layers".into())), "{layout:?}"); - let source = h.ctx.read_response(tab_id("layers")).unwrap().rect.center(); - let destination = h.ctx.read_response(tab_id("properties")).unwrap().rect.center(); - drag(&mut h, source, destination); - let layout = h.state().ui.docking.as_ref().unwrap(); - assert!(!layout.floating.iter().flat_map(window_groups).any(|g| g.panels.contains(&"layers".into()))); - assert!(valid(layout)); - assert_eq!(h.state().ui.docking_focused.as_deref(), Some("layers"), "the user's drag keeps the focus on the panel it moved"); -} - -#[test] -fn saved_workspace_restores_the_custom_tree_and_hidden_panel_placement() { - let mut app = app(); - - app.run("window.panel.move", json!({"panel":"swatches","anchor":"layers","zone":"top"})).unwrap(); - app.run("window.panel.float", json!({"panel":"properties","x":50,"y":80})).unwrap(); - app.run("window.panel.close", json!({"panel":"swatches"})).unwrap(); - let layout = app.ui.docking.clone(); - let hidden = app.ui.docking_hidden.clone(); - app.run("window.newWorkspace", json!({"name":"Custom docking"})).unwrap(); - app.run("window.workspace", json!({"name":"Essentials"})).unwrap(); - assert!(app.ui.docking.is_none()); - app.run("window.workspace", json!({"name":"Custom docking"})).unwrap(); - assert_eq!(app.ui.docking, layout); - assert_eq!(app.ui.docking_hidden, hidden); -} - -/// Explicit offscreen evidence; this creates no native windows. -#[test] -fn capture_custom_panel_docking_visual_fixtures() { - let Some(directory) = std::env::var_os("CRAFT_UI_DOCKING_FIXTURES").map(std::path::PathBuf::from) else { return }; - std::fs::create_dir_all(&directory).unwrap(); - for theme in crate::theme::Brightness::ALL { - for width in [800.0, 1280.0] { - for scale in [1.0, 1.5, 2.0] { - let mut app = app(); - app.run("file.new", json!({})).unwrap(); - app.run("frame.create", json!({"rect":[40,40,280,180],"content":"text","text":"Synthetic layout — مرحبا"})).unwrap(); - let language = if width == 800.0 && scale == 1.0 { "ar" } else { "en" }; - app.run("app.language", json!({"lang":if language == "en" { "" } else { language }})).unwrap(); - app.run("window.panel.move", json!({"panel":"swatches", "anchor":"layers", "zone":"top"})).unwrap(); - app.run("window.panel.float", json!({"panel":"properties","x":30,"y":90,"width":300,"height":440})).unwrap(); - let mut ready = false; - let mut harness = Harness::builder().with_size(vec2(width, 800.0)).with_pixels_per_point(scale).wgpu().build_ui_state( - move |ui, app: &mut DesignApp| { - if !ready { - crate::theme::install_fonts(ui.ctx(), &app.ui.language); - crate::theme::apply(ui.ctx(), &crate::theme::Tokens::for_brightness(theme)); - ready = true; - return; - } - egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| crate::panel_docking::show(app, ui)); - }, - app, - ); - harness.input_mut().max_texture_side = Some(8192); - harness.run_steps(5); - assert!(valid(harness.state().ui.docking.as_ref().unwrap())); - harness - .render() - .unwrap() - .save(directory.join(format!("designcraft-shared-docking-{}-{language}-{width}-{scale}x.png", theme.id()))) - .unwrap(); - if language == "ar" { - let tab = tab_id("swatches"); - let at = harness.ctx.read_response(tab).unwrap().rect.center(); - harness.input_mut().events.extend([ - Event::PointerMoved(at), - Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }, - ]); - harness.run_steps(1); - harness.input_mut().events.push(Event::PointerButton { - pos: at, - button: PointerButton::Secondary, - pressed: false, - modifiers: Modifiers::NONE, - }); - harness.run_steps(2); - assert!(egui::Popup::is_any_open(&harness.ctx), "actual tab context menu must be open"); - for action in ["Float Panel", "Group with", "Close Panel"] { - assert!(harness.query_all_by_label(crate::i18n::tr("ar", action)).count() >= 1, "the menu lists {action}"); - } - harness.render().unwrap().save(directory.join(format!("designcraft-dock-context-{}-ar.png", theme.id()))).unwrap(); - } - } - } - } -} - -#[test] -fn escape_cancels_a_tab_drag_without_customizing_the_workspace() { - let mut h = harness(app(), vec2(1280.0, 800.0)); - let source = h.query_all_by_label("Layers").find(|node| node.rect().height() <= 45.0).unwrap().rect().center(); - h.event(Event::PointerMoved(source)); - h.run_steps(1); - h.event(Event::PointerButton { pos: source, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.run_steps(1); - h.event(Event::PointerMoved(source - vec2(90.0, 0.0))); - h.run_steps(2); - h.event(Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); - h.run_steps(1); - assert!(h.state().ui.docking.is_none()); - h.event(Event::PointerButton { pos: source, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(2); - assert!(h.state().ui.docking.is_none()); -} - -#[test] -fn serialized_layout_actions_cover_geometry_reorder_accordion_and_atomic_rejection() { - let mut app = app(); - app.run("window.panel.move", json!({"panel":"swatches","anchor":"layers","zone":"top"})).unwrap(); - app.run("window.panel.layout", json!({"action":{"ResizeSplit":{"path":[],"size":{"Ratio":0.35}}}})).unwrap(); - assert!( - matches!(app.ui.docking.as_ref().unwrap().root, Some(Node::Split { size: craft_ui::layout::SplitSize::Ratio(value), .. }) if (value - 0.35).abs() < 0.001) - ); - app.run("window.panel.float", json!({"panel":"properties"})).unwrap(); - app.run("window.panel.layout", json!({"action":{"MoveFloating":{"panel":"properties","rect":[44,66,360,450]}}})).unwrap(); - assert_eq!( - app.ui.docking.as_ref().unwrap().floating.iter().find(|window| window.panels().any(|p| p == "properties")).unwrap().rect, - [44.0, 66.0, 360.0, 450.0] - ); - app.run("window.panel.layout", json!({"action":{"Move":{"panel":"properties","anchor":"swatches","placement":{"Tab":{"before":"swatches"}}}}})) - .unwrap(); - assert_eq!(group_members_for_test(app.ui.docking.as_ref().unwrap(), "swatches"), ["properties", "swatches"]); - let before = app.ui.docking.clone(); - let hidden = app.ui.docking_hidden.clone(); - for action in [ - json!({"MoveFloating":{"panel":"properties","rect":[0,0,-5,30]}}), - json!({"ResizeSplit":{"path":[true,true,true],"size":{"Ratio":0.2}}}), - json!({"Open":{"panel":"unknown","anchor":null}}), - json!({"Move":{"panel":"properties","anchor":"swatches","placement":{"Tab":{"before":"unknown"}}}}), - ] { - assert!(app.run("window.panel.layout", json!({"action":action})).is_err()); - assert_eq!(app.ui.docking, before); - assert_eq!(app.ui.docking_hidden, hidden); - } - let stack = Node::Stack { entries: vec![craft_ui::docking::StackEntry { panel: "layers".into(), open: true, height: Some(100.0) }] }; - app.ui.docking = Some(Layout { - root: Some(Node::Split { - axis: craft_ui::layout::SplitAxis::Horizontal, - size: craft_ui::layout::SplitSize::Ratio(0.7), - first: Box::new(Node::Tabs { panels: vec![CANVAS.into()], active: 0 }), - second: Box::new(stack), - }), - floating: Vec::new(), - }); - app.run("window.panel.layout", json!({"action":{"SetStackOpen":{"panel":"layers","open":false}}})).unwrap(); - app.run("window.panel.layout", json!({"action":{"ResizeStack":{"panel":"layers","height":150}}})).unwrap(); - let Some(Node::Split { second, .. }) = &app.ui.docking.as_ref().unwrap().root else { panic!("expected split") }; - let Node::Stack { entries } = &**second else { panic!("expected stack") }; - assert!(!entries[0].open); - assert_eq!(entries[0].height, Some(150.0)); -} - -fn group_members_for_test(layout: &Layout, panel: &str) -> Vec { - tab_group(layout, panel) -} - -#[test] -fn populated_canvas_keeps_a_real_stroke_edit_after_floating_and_redocking() { - let mut app = app(); - app.run("file.new", json!({"width":480,"height":360})).unwrap(); - let id = app.run("frame.create", json!({"rect":[80,70,330,230],"content":"none"})).unwrap()["id"].as_u64().unwrap(); - app.run("object.fill", json!({"swatch":"C=100 M=0 Y=0 K=0"})).unwrap(); - app.run("object.stroke", json!({"weight":8})).unwrap(); - app.run("window.panel.float", json!({"panel":"stroke","x":40,"y":140,"width":310,"height":490})).unwrap(); - let directory = std::env::var_os("CRAFT_UI_DOCKING_FIXTURES").map(std::path::PathBuf::from); - let builder = Harness::builder().with_size(vec2(1280.0, 800.0)); - let builder = if directory.is_some() { builder.wgpu() } else { builder }; - let mut h = builder.build_ui_state( - |ui, app: &mut DesignApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - app, - ); - h.input_mut().max_texture_side = Some(8192); - h.run_steps(5); - let at = h.get_by_label("Bevel").rect().center(); - h.hover_at(at); - h.run_steps(1); - for pressed in [true, false] { - h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); - h.run_steps(1); - } - h.run_steps(2); - assert_eq!(h.state().session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().stroke.join, designcraft_doc::Join::Bevel); - if let Some(directory) = &directory { - std::fs::create_dir_all(directory).unwrap(); - h.render().unwrap().save(directory.join("designcraft-populated-stroke-floating.png")).unwrap(); - } - let from = h.ctx.read_response(tab_id("stroke")).unwrap().rect.center(); - let to = h.ctx.read_response(tab_id("properties")).unwrap().rect.center(); - drag(&mut h, from, to); - assert!(h.state().ui.docking.as_ref().unwrap().floating.is_empty()); - assert_eq!(h.state().session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().stroke.join, designcraft_doc::Join::Bevel); - if let Some(directory) = &directory { - h.render().unwrap().save(directory.join("designcraft-populated-stroke-redocked.png")).unwrap(); - } -} - -#[test] -fn properties_stroke_link_opens_the_stroke_panel_in_a_custom_workspace() { - let mut app = app(); - app.run("file.new", json!({"width":480,"height":360})).unwrap(); - app.run("frame.create", json!({"rect":[80,70,330,230],"content":"none"})).unwrap(); - app.run("window.panel.float", json!({"panel":"layers"})).unwrap(); - // Floating Layers leaves Pages the active tab beside Properties. - app.run("window.panel", json!({"panel":"properties"})).unwrap(); - assert!(in_iconic_column(app.ui.docking.as_ref().unwrap(), "stroke")); - let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).build_ui_state( - |ui, app: &mut DesignApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - app, - ); - h.run_steps(5); - let at = h.get_by_role_and_label(egui::accesskit::Role::Link, "Stroke").rect().center(); - h.hover_at(at); - h.run_steps(1); - for pressed in [true, false] { - h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); - h.run_steps(1); - } - h.run_steps(2); - // Stroke stays in the iconic column and opens as its flyout. - assert!(in_iconic_column(h.state().ui.docking.as_ref().unwrap(), "stroke")); - assert_eq!(h.state().ui.docking_flyout.as_deref(), Some("stroke")); - assert!(showing(h.state(), "stroke")); - assert_eq!(h.state().ui.docking_opened.as_deref(), Some("stroke")); -} - -#[test] -fn changing_workspace_during_a_drag_cancels_the_stale_gesture() { - let mut app = app(); - app.run("window.panel.move", json!({"panel":"swatches","anchor":"layers","zone":"top"})).unwrap(); - let destination = app.ui.docking.clone(); - app.run("window.newWorkspace", json!({"name":"Destination"})).unwrap(); - app.run("window.workspace", json!({"name":"Essentials"})).unwrap(); - let mut h = harness(app, vec2(1280.0, 800.0)); - let source = h.query_all_by_label("Layers").find(|node| node.rect().height() <= 45.0).unwrap().rect().center(); - h.event(Event::PointerMoved(source)); - h.run_steps(1); - h.event(Event::PointerButton { pos: source, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.run_steps(1); - h.event(Event::PointerMoved(source - vec2(90.0, 0.0))); - h.run_steps(2); - h.state_mut().run("window.workspace", json!({"name":"Destination"})).unwrap(); - h.event(Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); - h.run_steps(1); - assert_eq!(h.state().ui.docking, destination); - h.event(Event::PointerButton { pos: source, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(2); - assert_eq!(h.state().ui.docking, destination); -} - -#[test] -fn first_customization_keeps_the_panel_the_workspace_opened() { - let mut app = app(); - app.ui.open_panel = Some("paragraphStyles".into()); - app.ui.dock_expanded = false; - app.run("window.panel.float", json!({"panel":"layers"})).unwrap(); - let layout = app.ui.docking.as_ref().unwrap(); - assert!(layout.contains(&"paragraphStyles".into())); - assert!(valid(layout)); - assert_eq!(layout.panels().iter().filter(|p| p.as_str() == "paragraphStyles").count(), 1); -} - -#[test] -fn hiding_before_first_destination_frame_does_not_restore_an_old_drag_snapshot() { - let mut app = app(); - app.run("window.panel.move", json!({"panel":"swatches","anchor":"layers","zone":"top"})).unwrap(); - app.run("window.newWorkspace", json!({"name":"Destination"})).unwrap(); - app.run("window.workspace", json!({"name":"Essentials"})).unwrap(); - let mut h = harness(app, vec2(1280.0, 800.0)); - let source = h.query_all_by_label("Layers").find(|node| node.rect().height() <= 45.0).unwrap().rect().center(); - h.event(Event::PointerMoved(source)); - h.run_steps(1); - h.event(Event::PointerButton { pos: source, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.run_steps(1); - h.event(Event::PointerMoved(source - vec2(90.0, 0.0))); - h.run_steps(2); - h.state_mut().run("window.workspace", json!({"name":"Destination"})).unwrap(); - let destination = h.state().ui.docking.clone(); - let open_panel = h.state().ui.open_panel.clone(); - let floating = h.state().ui.floating.clone(); - // The app calls this before dock rendering when panels are hidden or Presentation starts. - let ctx = h.ctx.clone(); - cancel_gesture(&ctx); - assert_eq!(h.state().ui.docking, destination); - assert_eq!(h.state().ui.open_panel, open_panel); - assert_eq!(h.state().ui.floating, floating); - h.event(Event::PointerButton { pos: source, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(2); - assert_eq!(h.state().ui.docking, destination); -} - -#[test] -fn table_and_control_visibility_work_after_customization_without_document_edits() { - let mut app = app(); - app.run("file.new", json!({})).unwrap(); - let doc = serde_json::to_value(&app.session.active().unwrap().doc).unwrap(); - let undo = app.session.active().unwrap().history.undo.len(); - app.run("window.panel.float", json!({"panel":"layers"})).unwrap(); - app.run("app.tablePanel", json!({})).unwrap(); - assert!(showing(&app, "table")); - // The Table flyout closes; Table stays in its icon group. - app.run("app.tablePanel", json!({})).unwrap(); - assert!(!showing(&app, "table")); - assert!(in_iconic_column(app.ui.docking.as_ref().unwrap(), "table")); - app.run("app.tablePanel", json!({})).unwrap(); - assert!(showing(&app, "table")); - let ctx = egui::Context::default(); - let (req, _) = crate::control::ControlRequest::new("ui.set", json!({"closePanel":true,"dockExpanded":false})); - let crate::control::Outcome::Done(result) = crate::control::handle(&mut app, &ctx, &req) else { panic!("expected synchronous control result") }; - assert_eq!(result["ok"], true); - assert!(!app.ui.dock_expanded); - assert!(!app.ui.docking.as_ref().unwrap().contains(&"table".into())); - app.run("window.panel", json!({"panel":"properties"})).unwrap(); - assert_eq!(app.ui.docking_flyout.as_deref(), Some("properties"), "it opens as a flyout from the collapsed dock"); - assert_eq!(app.ui.docking_raise.as_deref(), Some("properties")); - set_iconic(&mut app, false).unwrap(); - assert_eq!(app.ui.docking_flyout, None, "expanding the column closes its flyout"); - assert_eq!(serde_json::to_value(&app.session.active().unwrap().doc).unwrap(), doc); - assert_eq!(app.session.active().unwrap().history.undo.len(), undo); -} - -#[test] -fn floating_activation_queues_one_transient_raise_and_workspace_switch_clears_it() { - let mut app = app(); - app.run("window.panel.float", json!({"panel":"layers"})).unwrap(); - app.run("window.panel.activate", json!({"panel":"layers"})).unwrap(); - assert_eq!(app.ui.docking_raise.as_deref(), Some("layers")); - assert!(serde_json::to_value(&app.ui).unwrap().get("docking_raise").is_none()); - app.run("window.workspace", json!({"name":"Typography"})).unwrap(); - assert!(app.ui.docking_raise.is_none()); -} - -#[test] -fn shaped_panel_label_keeps_the_logical_accessibility_text() { - let ctx = egui::Context::default(); - let logical = "خصائص Pages"; - crate::theme::install_fonts(&ctx, "ar"); - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { - let galley = crate::rtl::plain(ui.ctx(), logical, egui::FontId::proportional(12.0), egui::Color32::WHITE); - assert_eq!(galley.job.text, logical); - }); - output.textures_delta.clear(); -} - -#[test] -fn modal_overlay_blocks_a_real_tab_drag_release() { - let mut app = app(); - app.run("window.panel.float", json!({"panel":"layers"})).unwrap(); - let mut h = harness(app, vec2(1280.0, 800.0)); - let source = h.ctx.read_response(tab_id("properties")).unwrap().rect.center(); - h.event(Event::PointerMoved(source)); - h.run_steps(1); - h.event(Event::PointerButton { pos: source, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.run_steps(1); - h.event(Event::PointerMoved(source - vec2(90.0, 0.0))); - h.run_steps(2); - assert_eq!(h.ctx.dragged_id(), Some(tab_id("properties")), "test must start the owned tab gesture"); - let before = h.state().ui.docking.clone(); - h.state_mut().ui.dialog = Some(crate::dialogs::Dialog::new("newDocument", json!({}))); - let destination = egui::pos2(150.0, 150.0); - h.event(Event::PointerMoved(destination)); - h.run_steps(1); - h.event(Event::PointerButton { pos: destination, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(2); - assert_eq!(h.state().ui.docking, before, "release under a modal must not float or dock the panel"); - h.state_mut().ui.dialog = None; - h.run_steps(2); - assert_eq!(h.state().ui.docking, before, "closing the overlay must not revive its blocked drag"); -} - -#[test] -fn shift_f9_toggles_table_after_customization_through_the_real_shortcut_path() { - let mut app = app(); - app.run("file.new", json!({})).unwrap(); - app.run("window.panel.float", json!({"panel":"layers"})).unwrap(); - let before = serde_json::to_value(&app.session.active().unwrap().doc).unwrap(); - let mut h = crate::test_window::open(app, vec2(1440.0, 900.0)); - for visible in [true, false] { - let modifiers = Modifiers { shift: true, ..Modifiers::NONE }; - h.event(Event::Key { key: egui::Key::F9, physical_key: None, pressed: true, repeat: false, modifiers }); - h.run_steps(1); - h.event(Event::Key { key: egui::Key::F9, physical_key: None, pressed: false, repeat: false, modifiers }); - h.run_steps(2); - assert_eq!(showing(&h.state().app, "table"), visible); - assert!(h.state().app.ui.docking.as_ref().unwrap().contains(&"table".into()), "Table stays in its icon group"); - } - assert_eq!(serde_json::to_value(&h.state().app.session.active().unwrap().doc).unwrap(), before); -} - -#[test] -fn first_story_editor_frame_conservatively_blocks_owned_tab_release() { - let mut app = app(); - app.run("file.new", json!({})).unwrap(); - let story = app.run("frame.create", json!({"rect":[72,72,300,200],"content":"text","text":"Story editor overlay fixture"})).unwrap()["story"] - .as_u64() - .unwrap(); - app.run("window.panel.float", json!({"panel":"layers"})).unwrap(); - let doc = serde_json::to_value(&app.session.active().unwrap().doc).unwrap(); - let mut h = crate::test_window::open(app, vec2(1440.0, 900.0)); - let tab = tab_id("properties"); - let from = h.ctx.read_response(tab).unwrap().rect.center(); - h.event(Event::PointerMoved(from)); - h.run_steps(1); - h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.run_steps(1); - h.event(Event::PointerMoved(from - vec2(90.0, 0.0))); - h.run_steps(2); - assert_eq!(h.ctx.dragged_id(), Some(tab), "must own a real tab drag before opening editor"); - assert!(h.ctx.memory(|m| m.area_rect(egui::Id::unique("story_editor"))).is_none()); - let layout = h.state().app.ui.docking.clone(); - let frame_before = h.ctx.cumulative_frame_nr(); - h.state_mut().app.run("app.storyEditor", json!({"story":story})).unwrap(); - // The unmeasured first frame blocks the full content, even outside the eventual editor. - let release = egui::pos2(150.0, 150.0); - h.input_mut().events.extend([ - Event::PointerMoved(release), - Event::PointerButton { pos: release, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }, - ]); - h.run_steps(1); - assert_eq!(h.ctx.cumulative_frame_nr() - frame_before, 1, "release must occur in the first editor frame"); - let measured = h.ctx.memory(|m| m.area_rect(egui::Id::unique("story_editor"))).unwrap(); - assert!(!measured.contains(release), "fixture exercises the conservative first-frame guard outside eventual editor bounds"); - assert_eq!(h.state().app.ui.docking, layout, "first editor frame must block release before it has a measured rectangle"); - assert_eq!(serde_json::to_value(&h.state().app.session.active().unwrap().doc).unwrap(), doc); - h.run_steps(3); - let editor = h.ctx.memory(|m| m.area_rect(egui::Id::unique("story_editor"))).unwrap(); - let screen = h.ctx.content_rect(); - let outside = [screen.left_bottom() + vec2(80.0, -80.0), screen.right_bottom() + vec2(-450.0, -80.0)] - .into_iter() - .find(|p| !editor.contains(*p)) - .expect("fixture has space outside editor"); - let before_outside = h.state().app.ui.docking.clone(); - let tab = tab_id("layers"); - let from = h.ctx.read_response(tab).unwrap().rect.center(); - h.event(Event::PointerMoved(from)); - h.run_steps(1); - h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.run_steps(1); - h.event(Event::PointerMoved(from - vec2(90.0, 0.0))); - h.run_steps(2); - assert_eq!(h.ctx.dragged_id(), Some(tab)); - h.event(Event::PointerMoved(outside)); - h.event(Event::PointerButton { pos: outside, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(2); - assert_ne!(h.state().app.ui.docking, before_outside, "measured editor must permit ordinary releases outside its bounds"); - let after = h.state().app.ui.docking.clone(); - h.state_mut().app.run("app.storyEditor", json!({"story":story})).unwrap(); - h.run_steps(3); - assert_eq!(h.state().app.ui.docking, after, "closing editor must not revive a blocked drag"); - assert_eq!(serde_json::to_value(&h.state().app.session.active().unwrap().doc).unwrap(), doc); -} - -#[test] -fn dock_menu_button_opens_the_active_panel_menu() { - let mut app = app(); - app.run("file.new", json!({})).unwrap(); - app.ui.dock_tab = "pages".into(); - let pages = app.session.active().unwrap().doc.page_count(); - let mut h = harness(app, vec2(1280.0, 800.0)); - assert!(h.state().ui.docking.is_none()); - let tab = h.query_all_by_label("Pages").find(|node| node.rect().height() <= 45.0).unwrap().rect(); - // The outer dock column is at the window's right edge; the ≡ ends its tab strip. - let at = egui::pos2(1280.0 - 12.0, tab.center().y); - h.event(Event::PointerMoved(at)); - h.run_steps(1); - for pressed in [true, false] { - h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); - h.run_steps(1); - } - h.run_steps(2); - assert!(egui::Popup::is_any_open(&h.ctx), "the three-line button must open a menu"); - h.get_by_label("Duplicate Spread").click(); - h.run_steps(3); - assert_eq!(h.state().session.active().unwrap().doc.page_count(), pages + 1); - assert!(!egui::Popup::is_any_open(&h.ctx)); -} - -/// InDesign's panel tab menu (Learn Skills Daily's InDesign course, 6:20): Close, Close Tab Group, -/// Minimize and Collapse to Icons. Close Tab Group hides the panels tabbed together. -#[test] -fn close_tab_group_hides_the_panels_tabbed_together() { - let mut app = app(); - // The default dock: Properties, Pages and Layers are one tab group. - let r = app.run("window.panel.closeGroup", json!({"panel":"pages"})).unwrap(); - assert_eq!(r["closed"], json!(["properties", "pages", "layers"])); - let layout = app.ui.docking.clone().unwrap(); - assert!(["properties", "pages", "layers"].iter().all(|p| !layout.contains(&p.to_string()))); - // Window brings one back. - app.run("window.panel.activate", json!({"panel":"pages"})).unwrap(); - assert!(app.ui.docking.as_ref().unwrap().contains(&"pages".to_string())); - // A floating group goes as a whole; the dock keeps its own. - app.run("window.panel.float", json!({"panel":"swatches","x":40,"y":60})).unwrap(); - app.run("window.panel.activate", json!({"panel":"color"})).unwrap(); - app.run("window.panel.move", json!({"panel":"color", "anchor":"swatches"})).unwrap(); - app.run("window.panel.closeGroup", json!({"panel":"color"})).unwrap(); - let layout = app.ui.docking.clone().unwrap(); - assert!(!layout.contains(&"color".to_string()) && !layout.contains(&"swatches".to_string())); - assert!(layout.contains(&"pages".to_string())); - assert!(app.run("window.panel.closeGroup", json!({"panel":"nope"})).is_err()); -} - -#[test] -fn collapse_to_icons_shrinks_the_dock_to_its_icons() { - let mut app = app(); - assert!(app.ui.dock_expanded); - app.run("window.collapseToIcons", json!({})).unwrap(); - assert!(!app.ui.dock_expanded); - // A panel chosen from Window opens as a flyout beside its icon; the dock stays collapsed. - app.run("window.panel", json!({"panel":"pages"})).unwrap(); - assert_eq!(app.ui.docking_flyout.as_deref(), Some("pages")); - assert_eq!(app.ui.docking_raise.as_deref(), Some("pages")); - assert!(showing(&app, "pages")); - assert!(in_iconic_column(app.ui.docking.as_ref().unwrap(), "pages")); - // Choosing it again closes the flyout, and a third time opens it again. - app.run("window.panel", json!({"panel":"pages"})).unwrap(); - assert_eq!(app.ui.docking_flyout, None); - assert!(!showing(&app, "pages")); - app.run("window.panel", json!({"panel":"pages"})).unwrap(); - assert_eq!(app.ui.docking_flyout.as_deref(), Some("pages")); -} - -#[test] -fn a_tabs_context_menu_lists_indesigns_tab_commands_and_close_works() { - let mut h = harness(app(), vec2(1280.0, 800.0)); - let tab = h.query_all_by_label("Layers").find(|node| node.rect().height() <= 45.0).unwrap().rect().center(); - h.event(Event::PointerMoved(tab)); - h.run_steps(1); - h.event(Event::PointerButton { pos: tab, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }); - h.run_steps(1); - h.event(Event::PointerButton { pos: tab, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(2); - // The column bar's » button is also labelled Collapse to Icons. - for item in ["Close", "Close Tab Group", "Minimize", "Collapse to Icons", "Float Panel"] { - assert!(h.query_all_by_label(item).next().is_some(), "{item}"); - } - assert_eq!(h.query_all_by_label("Minimize").count(), 1, "the tab menu lists Minimize once"); - assert!(h.query_all_by_label("Dock Panel").next().is_none(), "a docked panel has no Dock Panel"); - h.get_by_label("Close").click(); - h.run_steps(2); - assert!(!h.state().ui.docking.as_ref().unwrap().contains(&"layers".to_string())); -} - -/// A floating panel's tab menu and three-line menu have Dock Panel, which puts it back where it -/// floated from. -#[test] -fn dock_panel_in_a_floating_panels_menus_returns_it_to_the_dock() { - let mut app = app(); - app.run("window.panel.activate", json!({"panel":"layers"})).unwrap(); - let docked = app.ui.docking.clone().unwrap(); - app.run("window.panel.float", json!({"panel":"layers","x":200,"y":150})).unwrap(); - let mut h = harness(app, vec2(1280.0, 800.0)); - let tab = h.ctx.read_response(tab_id("layers")).unwrap().rect; - click(&mut h, tab.center(), PointerButton::Secondary); - h.get_by_label("Dock Panel").click(); - h.run_steps(3); - assert_eq!(h.state().ui.docking.as_ref(), Some(&docked), "the tab menu docks it back in its group"); - let mut app = h.into_state(); - app.run("window.panel.float", json!({"panel":"layers","x":200,"y":150})).unwrap(); - let mut menu = Harness::builder().with_size(vec2(300.0, 400.0)).build_ui_state(|ui, app: &mut DesignApp| panel_menu(app, ui, "layers"), app); - menu.run_steps(1); - menu.get_by_label("Dock Panel").click(); - menu.run_steps(2); - assert_eq!(menu.state().ui.docking.as_ref(), Some(&docked), "so does the three-line menu"); -} - -/// Window › Styles › Paragraph Styles opens InDesign's floating Character Styles | Paragraph Styles -/// group, which stays open while other panels open (Learn Skills Daily's InDesign course, 7:55). -#[test] -fn paragraph_styles_open_floating_with_character_styles() { - let mut app = app(); - app.run("window.panel", json!({"panel":"paragraphStyles"})).unwrap(); - let layout = app.ui.docking.clone().unwrap(); - let group = layout.floating.iter().flat_map(window_groups).find(|g| g.panels.iter().any(|p| p == "paragraphStyles")).expect("a floating group"); - assert_eq!(group.panels, ["characterStyles", "paragraphStyles"]); - assert_eq!(group.panels[group.active], "paragraphStyles", "the one chosen is in front"); - // The dock still shows Properties in front. - assert_eq!(layout.panel_state(&"properties".to_string()), craft_ui::docking::PanelState::Front, "{:?}", layout.root); - assert_eq!(layout.floating.len(), 1, "one floating window holds both tabs"); - // Other panels from Window leave it open. - app.run("window.panel", json!({"panel":"color"})).unwrap(); - app.run("window.panel", json!({"panel":"links"})).unwrap(); - let layout = app.ui.docking.clone().unwrap(); - assert!(layout.floating.iter().flat_map(window_groups).any(|g| g.panels == ["characterStyles", "paragraphStyles"])); - // Once showing, Window › Character Styles brings that tab forward. - app.run("window.panel", json!({"panel":"characterStyles"})).unwrap(); - let layout = app.ui.docking.clone().unwrap(); - let group = layout.floating.iter().flat_map(window_groups).find(|g| g.panels.iter().any(|p| p == "characterStyles")).unwrap(); - assert_eq!(group.panels[group.active], "characterStyles"); - assert_eq!(layout.panels().iter().filter(|p| p.as_str() == "characterStyles").count(), 1); -} - -/// Window › Styles floats the styles icon group out of the iconic column; Dock Panel puts the -/// group back as one, at the same place in that column. -#[test] -fn dock_panel_returns_the_floated_styles_group_to_its_icon_group() { - let mut app = app(); - let docked = app.ui.docking.clone().unwrap_or_else(|| default_layout(&app.ui)); - let styles = ["characterStyles", "paragraphStyles"].map(String::from).to_vec(); - let icon_groups = |layout: &Layout| -> Vec> { - dock_columns(layout).into_iter().filter(|c| c.iconic).flat_map(|c| &c.groups).map(|g| g.panels.clone()).collect() - }; - let before = icon_groups(&docked); - let at = before.iter().position(|g| *g == styles).expect("the styles are an icon group"); - app.run("window.panel", json!({"panel":"paragraphStyles"})).unwrap(); - let layout = app.ui.docking.clone().unwrap(); - assert!(layout.floating.iter().flat_map(window_groups).any(|g| g.panels == styles), "{:?}", layout.floating); - assert!(!icon_groups(&layout).contains(&styles)); - app.run("window.panel.dock", json!({"panel":"paragraphStyles"})).unwrap(); - let layout = app.ui.docking.clone().unwrap(); - assert!(layout.floating.is_empty(), "{:?}", layout.floating); - assert_eq!(icon_groups(&layout), before, "both styles are back in their icon group, at the same place"); - assert_eq!(icon_groups(&layout).get(at), Some(&styles)); - assert!(valid(&layout)); -} - -/// Style panels the user docked and then closed come back in the dock, not floating. -#[test] -fn paragraph_styles_closed_from_the_dock_reopen_there() { - let mut app = app(); - app.run("window.panel", json!({"panel":"paragraphStyles"})).unwrap(); - for panel in ["characterStyles", "paragraphStyles"] { - app.run("window.panel.move", json!({"panel": panel, "anchor": "properties"})).unwrap(); - } - for panel in ["characterStyles", "paragraphStyles"] { - app.run("window.panel.close", json!({"panel": panel})).unwrap(); - } - app.run("window.panel", json!({"panel":"paragraphStyles"})).unwrap(); - let layout = app.ui.docking.clone().unwrap(); - assert!(layout.contains(&"paragraphStyles".to_string())); - assert!(layout.floating.iter().flat_map(window_groups).all(|g| !g.panels.iter().any(|p| p == "paragraphStyles")), "{:?}", layout.floating); -} - -fn click(h: &mut Harness<'static, DesignApp>, at: Pos2, button: PointerButton) { - h.event(Event::PointerMoved(at)); - h.run_steps(1); - for pressed in [true, false] { - h.event(Event::PointerButton { pos: at, button, pressed, modifiers: Modifiers::NONE }); - h.run_steps(1); - } - h.run_steps(2); -} - -/// Window › Paragraph Styles switches to the docking layout. After Window › Pages the Pages panel -/// keeps its three-line panel menu, and its tab menu lists InDesign's tab commands. -#[test] -fn pages_keeps_its_panel_menu_in_the_docking_layout() { - let mut app = app(); - app.run("file.new", json!({})).unwrap(); - app.run("window.panel", json!({"panel":"paragraphStyles"})).unwrap(); - app.run("window.panel", json!({"panel":"pages"})).unwrap(); - assert!(app.ui.docking.is_some()); - let mut h = harness(app, vec2(1280.0, 800.0)); - let tab = h.query_all_by_label("Pages").find(|node| node.rect().height() <= 45.0).unwrap().rect(); - click(&mut h, egui::pos2(1280.0 - 12.0, tab.center().y), PointerButton::Primary); - assert!(egui::Popup::is_any_open(&h.ctx), "the three-line button must open a menu"); - for item in ["Numbering & Section Options…", "Close Tab Group", "Float Panel"] { - assert!(h.query_by_label(item).is_some(), "{item}"); - } - h.get_by_label("Panel Options…").click(); - h.run_steps(3); - assert!(h.state().ui.dialog.as_ref().is_some_and(|d| d.id == "pagesPanelOptions")); - h.state_mut().ui.dialog = None; - h.run_steps(2); - - click(&mut h, tab.center(), PointerButton::Secondary); - for item in ["Close", "Close Tab Group", "Minimize", "Collapse to Icons", "Float Panel", "Group with"] { - assert!(h.query_all_by_label(item).next().is_some(), "{item}"); - } - assert!(h.query_by_label("Close Panel").is_none()); - assert!(h.query_by_label("Panel Options…").is_none(), "the panel's own commands stay in its panel menu"); -} - -fn group_with(layout: &Layout, panel: &str) -> (bool, Vec, usize) { - if let Some(g) = layout.floating.iter().flat_map(window_groups).find(|g| g.panels.iter().any(|p| p == panel)) { - return (true, g.panels, g.active); - } - let mut visit: Vec<&Node> = layout.root.iter().collect(); - while let Some(node) = visit.pop() { - match node { - Node::Split { first, second, .. } => visit.extend([&**first, &**second]), - Node::Tabs { panels, active } if panels.iter().any(|p| p == panel) => return (false, panels.clone(), *active), - Node::Dock { columns, .. } => { - if let Some(g) = columns.iter().flat_map(|c| &c.groups).find(|g| g.panels.iter().any(|p| p == panel)) { - return (false, g.panels.clone(), g.active); - } - } - _ => {} - } - } - panic!("{panel} is not in {layout:?}"); -} - -fn drag_bar(h: &Harness<'static, DesignApp>, first: &str) -> egui::Rect { - h.ctx.read_response(hit_id(&craft_ui::docking::Hit::DragBar(first.to_string()))).expect("the group's drag bar").rect -} - -/// The docked Character Styles | Paragraph Styles group moves as one by its drag bar: dropped on -/// the canvas it floats, dropped on another strip it joins as tabs. Order and the tab in front -/// are kept. -#[test] -fn dragging_a_docked_group_by_its_bar_moves_every_tab() { - let mut app = app(); - app.run("window.panel", json!({"panel":"paragraphStyles"})).unwrap(); - let below = json!({"MoveGroup": {"panel": "characterStyles", "to": {"At": {"anchor": "properties", "placement": {"Group": {"below": true}}}}}}); - app.run("window.panel.layout", json!({"action": below})).unwrap(); - let styles = ["characterStyles", "paragraphStyles"]; - assert_eq!(group_with(app.ui.docking.as_ref().unwrap(), "characterStyles"), (false, styles.map(String::from).to_vec(), 1)); - - let mut h = harness(app, vec2(1280.0, 800.0)); - let bar = drag_bar(&h, "characterStyles"); - drag(&mut h, bar.center(), egui::pos2(400.0, 400.0)); - let layout = h.state().ui.docking.as_ref().unwrap(); - assert_eq!(group_with(layout, "paragraphStyles"), (true, styles.map(String::from).to_vec(), 1), "{layout:?}"); - assert!(valid(layout)); - - let bar = drag_bar(&h, "characterStyles"); - let properties = h.ctx.read_response(tab_id("properties")).unwrap().rect.center(); - drag(&mut h, bar.center(), properties); - let layout = h.state().ui.docking.as_ref().unwrap(); - let (floating, panels, active) = group_with(layout, "characterStyles"); - assert!(!floating, "{layout:?}"); - let at = panels.iter().position(|p| p == "characterStyles").unwrap(); - assert_eq!(panels.get(at + 1).map(String::as_str), Some("paragraphStyles"), "{panels:?}"); - assert_eq!(panels[active], "paragraphStyles"); - assert!(layout.floating.is_empty(), "{:?}", layout.floating); -} - -fn dock_of(layout: &Layout) -> (Side, &[Column]) { - let Some(Node::Split { first, second, .. }) = &layout.root else { panic!("root is not a split: {layout:?}") }; - assert!(matches!(&**first, Node::Tabs { panels, .. } if panels == &[CANVAS.to_string()]), "{layout:?}"); - let Node::Dock { side, columns } = &**second else { panic!("second is not a dock: {layout:?}") }; - (*side, columns) -} - -#[test] -fn default_workspaces_are_the_canvas_beside_an_end_dock() { - let mut app = app(); - let layout = default_layout(&app.ui); - assert!(valid(&layout)); - let (side, columns) = dock_of(&layout); - assert_eq!(side, Side::End); - let [outer, icons] = columns else { panic!("{columns:?}") }; - assert!(!outer.iconic); - assert_eq!(outer.groups.len(), 1); - assert_eq!(outer.groups[0].panels, ["properties", "pages", "layers"]); - assert!(icons.iconic); - let groups: Vec> = icons.groups.iter().map(|g| g.panels.iter().map(String::as_str).collect()).collect(); - let expected: Vec> = ICON_GROUPS.iter().map(|g| g.to_vec()).collect(); - assert_eq!(groups, expected, "the iconic column groups InDesign's panel families"); - // Essentials Classic: only its named icon groups, in one iconic column. - app.run("window.workspace", json!({"name": "Essentials Classic"})).unwrap(); - let layout = default_layout(&app.ui); - assert!(valid(&layout)); - let (_, columns) = dock_of(&layout); - let [column] = columns else { panic!("{columns:?}") }; - assert!(column.iconic); - let expected: Vec> = app.ui.icon_groups.clone().unwrap(); - let groups: Vec> = column.groups.iter().map(|g| g.panels.clone()).collect(); - assert_eq!(groups.len(), expected.len()); - assert!(groups.iter().flatten().all(|p| expected.iter().flatten().any(|e| e == p))); -} - -/// Every dock panel that starts in the iconic column has one place in [`ICON_GROUPS`], so a new -/// panel is not left as a group of its own. -#[test] -fn every_icon_panel_is_in_one_default_icon_group() { - for (id, _, _) in crate::dock::ICON_PANELS { - assert_eq!(ICON_GROUPS.iter().flat_map(|g| g.iter()).filter(|p| *p == id).count(), 1, "{id}"); - } - for id in ICON_GROUPS.iter().flat_map(|g| g.iter()) { - assert!(crate::dock::ICON_PANELS.iter().any(|p| p.0 == *id), "{id} is not a dock panel"); - } -} - -/// A panel the workspace places elsewhere leaves its icon group; a group it empties goes. -#[test] -fn placed_panels_leave_their_icon_groups() { - let mut placed = Placed::default(); - for id in ["properties", "pages", "layers", "swatches", "effects"] { - placed.take(id); - } - let column = icon_column(None, &mut placed).unwrap(); - let groups: Vec> = column.groups.iter().map(|g| g.panels.iter().map(String::as_str).collect()).collect(); - assert_eq!(groups.first().unwrap(), &["stroke", "color", "gradient"]); - assert_eq!(groups.get(1).unwrap(), &["characterStyles", "paragraphStyles"]); - assert_eq!(groups.len(), ICON_GROUPS.len() - 1); -} - -#[test] -fn the_dock_is_at_the_right_in_english_and_the_left_in_arabic() { - let tab = |h: &Harness<'static, DesignApp>| h.ctx.read_response(tab_id("properties")).map(|r| r.rect).unwrap(); - let h = harness(app(), vec2(1280.0, 800.0)); - assert!(tab(&h).left() > 640.0, "{:?}", tab(&h)); - let mut arabic = app(); - arabic.ui.language = "ar".into(); - let h = harness(arabic, vec2(1280.0, 800.0)); - assert!(tab(&h).right() < 640.0, "{:?}", tab(&h)); -} - -#[test] -fn ui_docking_reports_the_layout_and_the_focused_panel() { - let mut h = harness(app(), vec2(1280.0, 800.0)); - let ctx = h.ctx.clone(); - let docking = |app: &mut DesignApp| { - let (req, _rx) = crate::control::ControlRequest::new("ui.docking", json!({})); - match crate::control::handle(app, &ctx, &req) { - crate::control::Outcome::Done(v) => v, - crate::control::Outcome::Screenshot { .. } => panic!("ui.docking took a screenshot"), - } - }; - let v = docking(h.state_mut()); - assert_eq!(v["ok"], true, "{v}"); - let result = &v["result"]; - assert_eq!(result["customized"], false); - assert_eq!(result["rightToLeft"], false); - assert!(result["focused"].is_null()); - let layout: Layout = serde_json::from_value(result["layout"].clone()).unwrap(); - assert_eq!(layout, default_layout(&h.state().ui)); - let at = h.ctx.read_response(tab_id("layers")).unwrap().rect.center(); - click(&mut h, at, PointerButton::Primary); - let v = docking(h.state_mut()); - assert_eq!(v["result"]["focused"], "layers", "{v}"); - // Closing the focused panel releases the focus. - h.state_mut().run("window.panel.close", json!({"panel": "layers"})).unwrap(); - let v = docking(h.state_mut()); - assert!(v["result"]["focused"].is_null(), "{v}"); - assert_eq!(v["result"]["customized"], true); - assert_eq!(v["result"]["hidden"], json!(["layers"])); -} - -/// A reset replaces the panels: none of them stays focused, opened for `ui.set closePanel` or -/// queued to raise. -#[test] -fn workspace_reset_forgets_the_focused_opened_and_raised_panel() { - let mut app = app(); - app.run("window.panel.float", json!({"panel": "layers"})).unwrap(); - app.ui.docking_focused = Some("layers".into()); - assert_eq!(app.ui.docking_opened.as_deref(), Some("layers")); - assert_eq!(app.ui.docking_raise.as_deref(), Some("layers")); - app.run("window.workspace.reset", json!({})).unwrap(); - assert_eq!(app.ui.docking_focused, None); - assert_eq!(app.ui.docking_opened, None); - assert_eq!(app.ui.docking_raise, None); - close_visible(&mut app).unwrap(); - assert!(layout_of(&app).contains(&"layers".to_string()), "closePanel after a reset closes nothing"); -} - -/// A command that moves the focused panel takes the focus away and leaves it the panel last -/// opened; one that closes it forgets both. -#[test] -fn moving_or_closing_the_focused_panel_by_command_updates_the_panel_state() { - let mut app = app(); - app.ui.docking_focused = Some("layers".into()); - app.run("window.panel.activate", json!({"panel": "pages"})).unwrap(); - assert_eq!(app.ui.docking_focused.as_deref(), Some("layers"), "a command that leaves Layers in place keeps its focus"); - app.ui.docking_opened = Some("layers".into()); - app.run("window.panel.move", json!({"panel": "layers", "anchor": "swatches", "zone": "tab"})).unwrap(); - assert_eq!(app.ui.docking_focused, None); - assert_eq!(app.ui.docking_opened.as_deref(), Some("layers")); - app.ui.docking_focused = Some("layers".into()); - app.run("window.panel.close", json!({"panel": "layers"})).unwrap(); - assert_eq!(app.ui.docking_focused, None); - assert_eq!(app.ui.docking_opened, None); - assert_eq!(app.ui.docking_raise, None); -} - -/// A divider dragged with the pointer gives the keyboard back: the next arrow key nudges the -/// selection and leaves the dock's size alone. -#[test] -fn arrow_after_dragging_a_dock_divider_nudges_the_selection_not_the_dock() { - let mut app = app(); - app.run("file.new", json!({"width":480,"height":360})).unwrap(); - let id = app.run("frame.create", json!({"rect":[80,70,330,230],"content":"none"})).unwrap()["id"].as_u64().unwrap(); - let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).build_ui_state( - |ui, app: &mut DesignApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - app, - ); - h.run_steps(5); - let column = craft_ui::docking::Hit::Divider(craft_ui::docking::Divider::Column("properties".to_string())); - let divider = hits(&h).into_iter().find_map(|(hit, rect)| (hit == column).then_some(rect)).expect("the main dock column's divider"); - drag(&mut h, divider.center(), divider.center() - vec2(40.0, 0.0)); - let resized = h.state().ui.docking.clone().expect("the drag customizes the layout"); - let bounds = |h: &Harness<'static, DesignApp>| h.state().session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().bounds(); - let before = bounds(&h); - h.event(Event::Key { key: egui::Key::ArrowRight, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); - h.run_steps(1); - h.event(Event::Key { key: egui::Key::ArrowRight, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE }); - h.run_steps(2); - assert!(bounds(&h).x0 > before.x0, "the arrow nudges the selection"); - assert_eq!(h.state().ui.docking.as_ref(), Some(&resized), "the arrow doesn't resize the dock"); -} - -fn hits(h: &Harness<'static, DesignApp>) -> Vec<(craft_ui::docking::Hit, egui::Rect)> { - craft_ui::docking::DockArea::::hit_rects(&h.ctx, area_id()) -} - -/// `window.panel.*` ids and DesignCraft's aliases go through craft-ui's `DockCommand`. -#[test] -fn shared_panel_commands_float_dock_and_reject_atomically() { - let mut app = app(); - let docked = default_layout(&app.ui); - app.run("window.floatPanel", json!({"panel": "Layers", "x": 60, "y": 90})).unwrap(); - let layout = app.ui.docking.clone().unwrap(); - let window = layout.floating.iter().find(|w| w.contains(&"layers".to_string())).expect("Layers floats"); - assert_eq!(window.rect, [60.0, 90.0, 300.0, 420.0], "at the given place, at its own size"); - app.run("window.dockPanel", json!({"panel": "layers"})).unwrap(); - let layout = app.ui.docking.clone().unwrap(); - assert!(layout.floating.is_empty()); - assert_eq!( - layout.root, - docked.root.map(|mut root| { - // Back in its place, in front of its group. - if let Node::Split { second, .. } = &mut root - && let Node::Dock { columns, .. } = &mut **second - && let Some(group) = columns.first_mut().and_then(|c| c.groups.first_mut()) - { - group.active = 2; - } - root - }), - "Dock Panel returns it where it floated from" - ); - // A docked panel that shares its group leaves it for a new dock at the start edge. - let mut tabbed = self::app(); - tabbed.run("window.panel.dock", json!({"panel": "layers", "side": "Start"})).unwrap(); - let layout = tabbed.ui.docking.clone().unwrap(); - assert_eq!(tab_group(&layout, "pages"), ["properties", "pages"]); - assert!(matches!(&layout.root, Some(Node::Split { first, .. }) if matches!(&**first, Node::Dock { side: Side::Start, .. }))); - assert_eq!(tab_group(&layout, "layers"), ["layers"]); - // A whole group, by any of its panels, then into a new column of the end dock. - app.run("window.panel.float", json!({"panel": "pages", "group": true, "x": 80, "y": 80, "width": 300, "height": 400})).unwrap(); - let layout = app.ui.docking.clone().unwrap(); - assert_eq!(layout.floating.len(), 1); - assert_eq!(window_groups(&layout.floating[0])[0].panels, ["properties", "pages", "layers"]); - app.run("window.panel.dock", json!({"panel": "pages", "group": true, "side": "End"})).unwrap(); - let layout = app.ui.docking.clone().unwrap(); - assert!(layout.floating.is_empty()); - assert_eq!(tab_group(&layout, "pages"), ["properties", "pages", "layers"]); - // A lone panel to a new dock at the start edge. - app.run("window.panel.float", json!({"panel": "stroke"})).unwrap(); - app.run("window.panel.dock", json!({"panel": "stroke", "side": "Start"})).unwrap(); - assert!( - matches!(&app.ui.docking.as_ref().unwrap().root, Some(Node::Split { first, .. }) if matches!(&**first, Node::Dock { side: Side::Start, .. })) - ); - // Docking it at that side again leaves it where it is. - let before = app.ui.docking.clone(); - app.run("window.panel.dock", json!({"panel": "stroke", "side": "Start"})).unwrap(); - assert_eq!(app.ui.docking, before, "it already leads the start dock's last column"); - // Close Others and Minimize are shared commands too. - app.run("window.panel.closeOthers", json!({"panel": "pages"})).unwrap(); - assert_eq!(tab_group(app.ui.docking.as_ref().unwrap(), "pages"), ["pages"]); - assert!(app.ui.docking_hidden.contains_key("properties") && app.ui.docking_hidden.contains_key("layers")); - app.run("window.panel.minimize", json!({"panel": "pages"})).unwrap(); - let location = app.ui.docking.as_ref().unwrap().location(&"pages".to_string()).unwrap(); - assert!(location.group.is_some_and(|g| g.minimized)); - // Rejected commands change nothing. - let before = (app.ui.docking.clone(), app.ui.docking_hidden.clone()); - for (id, params) in [ - ("window.workspace.lock", json!({})), - ("window.panel.window", json!({"panel": "pages"})), - ("window.panel.move", json!({"panel": "stroke", "anchor": "pages", "zone": "left", "before": "pages"})), - ("window.panel.dock", json!({"panel": "stroke", "side": "Middle"})), - ("window.panel.dock", json!({"panel": "stroke", "zone": "left"})), - ("window.dockPanel", json!({"panel": "properties", "zone": "bottom"})), - ] { - assert!(app.run(id, params).is_err(), "{id}"); - assert_eq!((app.ui.docking.clone(), app.ui.docking_hidden.clone()), before, "{id}"); - } - // A zone is a side of an anchor; the error names the two ways to say where. - let error = app.run("window.panel.dock", json!({"panel": "stroke", "zone": "right"})).unwrap_err(); - assert!(error.contains("anchor") && error.contains("side"), "{error}"); - // Every shared id is registered for the command list and MCP. - for id in craft_ui::docking::DockCommand::::IDS { - assert!(crate::menus::UI_COMMANDS.iter().any(|c| c.0 == *id), "{id} is not registered"); - } -} - -/// A tab released over the canvas floats there (craft-ui: the protected canvas takes no tabs or -/// splits); a lone panel released in the window's left edge band makes a new dock there. -#[test] -fn tabs_dropped_on_the_canvas_float_and_at_the_far_edge_make_a_dock() { - let mut h = harness(app(), vec2(1280.0, 800.0)); - let tab = |h: &Harness<'static, DesignApp>, panel: &str| { - hits(h).into_iter().find(|(hit, _)| *hit == craft_ui::docking::Hit::Tab(panel.into())).map(|(_, r)| r) - }; - let layers = tab(&h, "layers").expect("the Layers tab"); - drag(&mut h, layers.center(), egui::pos2(500.0, 400.0)); - let layout = h.state().ui.docking.clone().unwrap(); - assert!(layout.floating.iter().any(|w| w.contains(&"layers".to_string())), "{layout:?}"); - // A new dock takes a panel that is alone in its group: the floating Layers, by its title bar. - // The harness's area starts 8 pt in from the window edge. - let title = hits(&h).into_iter().find(|(hit, _)| *hit == craft_ui::docking::Hit::Title("layers".into())).expect("the title bar").1; - drag(&mut h, title.center(), egui::pos2(12.0, 400.0)); - let layout = h.state().ui.docking.clone().unwrap(); - assert!(valid(&layout)); - let mut docks = Vec::new(); - let mut nodes: Vec<&Node> = layout.root.iter().collect(); - while let Some(node) = nodes.pop() { - match node { - Node::Split { first, second, .. } => nodes.extend([&**first, &**second]), - Node::Dock { side, columns } => { - docks.push((*side, columns.iter().flat_map(|c| &c.groups).flat_map(|g| g.panels.clone()).collect::>())) - } - _ => {} - } - } - assert!(docks.iter().any(|(side, panels)| *side == Side::Start && panels == &["layers"]), "{docks:?} {:?}", layout.floating); -} - -/// `ui.docking` lists where each gesture starts: tabs, drag bars and the iconic column's icons. -#[test] -fn ui_docking_reports_hit_rects() { - let h = harness(app(), vec2(1280.0, 800.0)); - let v = crate::panel_docking::inspect(h.state(), &h.ctx); - let rects = v["hitRects"].as_array().expect("hitRects"); - let rect_of = |hit: Value| { - let entry = rects.iter().find(|r| r["hit"] == hit).unwrap_or_else(|| panic!("no {hit} in {rects:?}")); - let r: Vec = serde_json::from_value(entry["rect"].clone()).unwrap(); - egui::Rect::from_min_size(egui::pos2(r[0], r[1]), vec2(r[2], r[3])) - }; - let tab = rect_of(json!({"Tab": "pages"})); - let bar = rect_of(json!({"DragBar": "properties"})); - let icon = rect_of(json!({"Icon": "stroke"})); - assert!(tab.width() > 20.0 && bar.width() >= 24.0 && icon.width() > 20.0, "{tab:?} {bar:?} {icon:?}"); - assert!((tab.center().y - bar.center().y).abs() < 1.0, "the bar is in the tab strip"); - assert!(icon.left() > 640.0, "the iconic column is at the end edge"); -} - -/// Clicking an icon in the iconic column opens its panel as a flyout on the canvas side; a -/// second click closes it. -#[test] -fn clicking_an_iconic_column_icon_opens_its_flyout() { - let mut h = harness(app(), vec2(1280.0, 800.0)); - let icon = hits(&h).into_iter().find(|(hit, _)| *hit == craft_ui::docking::Hit::Icon("swatches".into())).expect("the Swatches icon").1; - click(&mut h, icon.center(), PointerButton::Primary); - assert_eq!(h.state().ui.docking_flyout.as_deref(), Some("swatches")); - let tab = hits(&h).into_iter().find(|(hit, _)| *hit == craft_ui::docking::Hit::Tab("swatches".into())).expect("the flyout's tab").1; - assert!(tab.right() <= icon.left() + 1.0, "the flyout is beside the column, on the canvas side: {tab:?} {icon:?}"); - assert!(showing(h.state(), "swatches")); - click(&mut h, icon.center(), PointerButton::Primary); - assert!(h.state().ui.docking_flyout.is_none()); -} - -/// Iconic columns paint DesignCraft's own panel icons, in the colour craft-ui passes; a panel -/// without an icon paints nothing. -#[test] -fn panel_icons_are_painted_in_code() { - let mut app = app(); - let mut content = PanelContent { app: &mut app }; - let ctx = egui::Context::default(); - let mut paint = |panel: &str| { - let mut painted = false; - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { - let painter = ui.ctx().layer_painter(egui::LayerId::background()); - let rect = egui::Rect::from_min_size(Pos2::ZERO, vec2(20.0, 20.0)); - painted = craft_ui::docking::DockContent::paint_icon(&mut content, &painter, rect, &panel.to_string(), egui::Color32::RED); - }); - output.textures_delta.clear(); - (painted, output.shapes.len()) - }; - let (painted, shapes) = paint("pages"); - assert!(painted && shapes > 0, "{painted} {shapes}"); - assert_eq!(paint(CANVAS), (false, 0)); -} - -/// Every docking label in DesignCraft's wording is translated in the shared catalog's languages. -#[test] -fn docking_labels_are_translated() { - for language in ["de", "fr", "es", "ja", "zh"] { - for (key, english) in DOCK_LABELS { - assert_ne!(crate::i18n::tr(language, english), *english, "{key} in {language}"); - } - } -} - -/// With DesignCraft's title bar under macOS's transparent one, a floating window saved in the -/// title-bar strip is drawn below it, where its title bar can't move the app window. -#[test] -fn a_floating_window_saved_in_the_title_bar_strip_is_drawn_below_it() { - let mut app = app(); - app.integrated_titlebar = true; - app.run("window.panel.float", json!({"panel":"properties"})).unwrap(); - let window = app.ui.docking.as_mut().unwrap().floating.iter_mut().find(|w| w.panels().any(|p| p == "properties")).unwrap(); - window.rect = [200.0, 0.0, 280.0, 360.0]; - let h = harness(app, egui::vec2(1400.0, 900.0)); - let drawn = h.ctx.memory(|m| m.area_rect(crate::panel_docking::floating_layer("properties").id)).unwrap(); - assert!(drawn.min.y >= crate::chrome::MAC_APP_BAR - 0.5, "{drawn:?}"); -} - -/// A floating window holds splits like the dock: a panel docked below another one in the -/// window splits it, the divider between them drags, and the new size is saved. -#[test] -fn a_split_inside_a_floating_window_resizes_and_is_saved() { - let mut app = app(); - app.run("window.panel.float", json!({"panel":"swatches", "x":300, "y":120, "width":300, "height":500})).unwrap(); - app.run("window.panel.move", json!({"panel":"color", "anchor":"swatches", "zone":"bottom"})).unwrap(); - let window = |app: &DesignApp| app.ui.docking.as_ref().unwrap().floating.iter().find(|w| w.contains("swatches")).cloned().unwrap(); - let ratio = |window: &Floating| match window.root { - Node::Split { size: craft_ui::layout::SplitSize::Ratio(r), .. } => r, - ref root => panic!("expected a split window: {root:?}"), - }; - assert_eq!(window_groups(&window(&app)).into_iter().map(|g| g.panels).collect::>(), [["swatches"], ["color"]]); - let before = ratio(&window(&app)); - let mut h = harness(app, vec2(1400.0, 900.0)); - let divider = hits(&h) - .into_iter() - .find_map(|(hit, rect)| { - matches!(&hit, craft_ui::docking::Hit::Divider(craft_ui::docking::Divider::WindowSplit(_, path)) if path.is_empty()).then_some(rect) - }) - .expect("the window's divider"); - drag(&mut h, divider.center(), divider.center() + vec2(0.0, 60.0)); - let after = ratio(&window(h.state())); - assert!(after > before + 0.05, "{before} -> {after}"); - let saved = serde_json::to_vec(&h.state().ui).unwrap(); - let loaded = crate::UiState::from_preferences_json(&saved).unwrap(); - assert_eq!(loaded.docking, h.state().ui.docking); -} - -/// The default layout is rebuilt every frame: its floating windows keep their ids, so their -/// native windows aren't opened again each frame. -#[test] -fn default_layout_floats_keep_their_window_ids() { - let mut app = app(); - app.ui.floating = vec![("swatches".to_string(), [10.0, 20.0])]; - let ids = |app: &DesignApp| default_layout(&app.ui).floating.iter().map(|w| w.id).collect::>(); - let first = ids(&app); - assert_eq!(first.len(), 1, "Swatches floats"); - assert_eq!(ids(&app), first); -} - -#[test] -fn dialogs_about_and_quick_apply_block_native_floating_windows() { - let mut app = app(); - assert!(!modal_open(&app)); - app.ui.dialog = Some(crate::dialogs::Dialog::new("newDocument", json!({}))); - assert!(modal_open(&app), "dialog"); - app.ui.dialog = None; - app.run("help.about", json!({})).unwrap(); - assert!(modal_open(&app), "About"); - app.run("help.about", json!({"open": false})).unwrap(); - assert!(!modal_open(&app)); - app.ui.palette = Some(String::new()); - assert!(modal_open(&app), "Quick Apply"); - app.ui.palette = None; - assert!(!modal_open(&app)); -} - -#[cfg(not(target_arch = "wasm32"))] -#[test] -fn a_document_dropped_on_a_floating_panel_window_opens() { - #[derive(Debug)] - struct Dropped(std::path::PathBuf); - impl egui::DroppedFile for Dropped { - fn path(&self) -> &std::path::Path { - &self.0 - } - fn bytes(&self) -> Result, String> { - std::fs::read(&self.0).map_err(|e| e.to_string()) - } - } - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("dropped.designcraft"); - let mut saved = app(); - saved.run("file.new", json!({})).unwrap(); - saved.run("file.save", json!({"path": path})).unwrap(); - - let mut app = app(); - assert!(app.session.documents().is_empty()); - let files = craft_ui::docking::WindowFiles { - window: 1, - viewport: egui::ViewportId::from_hash_of("float"), - panel: "layers".to_owned(), - pos: None, - hovered: Vec::new(), - dropped: vec![std::sync::Arc::new(Dropped(path.clone())) as egui::DroppedFileHandle], - }; - open_window_drops(&mut app, &[files]); - assert_eq!(app.session.documents().len(), 1, "the dropped document opens"); -} From c9255c30ae6a98c76065f660234aee2906535132 Mon Sep 17 00:00:00 2001 From: macadminHU <51995175+macrobi@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:08:51 +0100 Subject: [PATCH 0297/1349] HU1: preserve localization regressions in the new test module Retain localization checks from both merge parents, including Hungarian context and catalog coverage, and directly check the repaired Georgian captions. This file matches the locally tested shared-module integration. --- crates/ui-egui/src/i18n/tests.rs | 152 ++++++++++++++++++++++++++++++- 1 file changed, 150 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index db13138cf..c8dc8578f 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -7,6 +7,7 @@ const LANGUAGE_TABLES: &[(&str, &[(&str, &str)])] = &[ ("cs", cs::TABLE), ("de", de::TABLE), ("fr", fr::TABLE), + ("hu", hu::TABLE), ("it", it::TABLE), ("ja", ja::TABLE), ("ka", ka::TABLE), @@ -17,8 +18,15 @@ const LANGUAGE_TABLES: &[(&str, &[(&str, &str)])] = &[ ]; /// Every per-language table `tr_context` looks up. -const CONTEXT_TABLES: &[(&str, &[(&str, &str, &str)])] = - &[("ar", ar::CONTEXT), ("cs", cs::CONTEXT), ("ja", ja::CONTEXT), ("pl", pl::CONTEXT), ("ru", ru::CONTEXT), ("uk", uk::CONTEXT)]; +const CONTEXT_TABLES: &[(&str, &[(&str, &str, &str)])] = &[ + ("ar", ar::CONTEXT), + ("cs", cs::CONTEXT), + ("hu", hu::CONTEXT), + ("ja", ja::CONTEXT), + ("pl", pl::CONTEXT), + ("ru", ru::CONTEXT), + ("uk", uk::CONTEXT), +]; /// The languages of the shared tables' columns, in column order. const SHARED_COLUMNS: [&str; 5] = ["de", "fr", "es", "ja", "zh"]; @@ -31,6 +39,7 @@ fn or_english<'a>(text: &'a str, english: &'a str) -> &'a str { if text.trim().is_empty() { english } else { text } } +/// Checks cached catalog lookup across language switches, including source-text fallback. #[test] fn cached_lookup_preserves_every_translation_across_language_switches() { let own = |lang: &str, key: &str| { @@ -52,6 +61,9 @@ fn cached_lookup_preserves_every_translation_across_language_switches() { assert_eq!(tr("", key), *key); } } + // Keep the repaired Georgian menu captions present with their exact translations. + assert_eq!(tr("ka", "File Info…"), "ფაილის ინფორმაცია…"); + assert_eq!(tr("ka", "Check for Updates…"), "განახლებების შემოწმება…"); // Strings no catalog has stay as they are, in every language. let unknown = String::from("A user-defined untranslated label"); for lang in LANGUAGES.iter().map(|(code, _)| *code).chain(["en", "unknown"]) { @@ -61,6 +73,92 @@ fn cached_lookup_preserves_every_translation_across_language_switches() { } } +/// Checks Hungarian catalog integrity, context captions and count substitutions, including +/// English fallback and preservation of user-defined style and workspace names. +#[test] +fn hungarian_catalog_preserves_placeholders_context_and_counts() { + let catalog: HashMap<_, _> = hu::TABLE.iter().copied().collect(); + assert_eq!(catalog.len(), hu::TABLE.len(), "duplicate Hungarian keys"); + let placeholders = |s: &str| { + let mut names: Vec<_> = s.split('{').skip(1).filter_map(|part| part.split_once('}').map(|(name, _)| name.to_owned())).collect(); + names.sort(); + names + }; + for (key, translation) in hu::TABLE { + assert!(!translation.trim().is_empty(), "empty {key}"); + assert_eq!(placeholders(key), placeholders(translation), "placeholders: {key}"); + assert_eq!(key.ends_with('…'), translation.ends_with('…'), "ellipsis: {key}"); + } + assert!(!is_rtl("hu")); + assert_eq!(tr("hu", "File"), "Fájl"); + assert_eq!(tr("hu", "Bleed"), "Kifutó"); + assert_eq!(tr("hu", "Arrangement"), "Elrendezés"); + assert_eq!(tr("hu", "Unknown label"), "Unknown label"); + assert_eq!(tr("hu", "Columns"), "Hasábok"); + assert_eq!(tr_context("hu", "Columns", "table"), "Oszlopok"); + assert_eq!(tr("hu", "Columns:"), "Hasábok:"); + assert_eq!(tr_context("hu", "Columns:", "grid"), "Oszlopok:"); + assert_eq!(tr_context("hu", "Columns:", "unknown"), "Hasábok:"); + assert_eq!(tr("hu", "Group"), "Csoportosítás"); + assert_eq!(tr_context("hu", "Group", "selection"), "Csoport"); + assert_eq!(tr_context("hu", "Columns", "unknown"), "Hasábok"); + assert_eq!(tr_context("", "Columns", "table"), "Columns"); + for n in [0, 1, 2, 5, 21] { + assert_eq!(count_label("hu", "pages", n), format!("{n} oldal")); + assert_eq!(count_label("hu", "objects", n), format!("{n} objektum")); + assert_eq!(count_label("hu", "errors", n), format!("{n} hiba")); + assert_eq!( + tr("hu", "{pages} Pages in {spreads} Spreads").replace("{pages}", &n.to_string()).replace("{spreads}", &n.to_string()), + format!("{n} oldal, {n} oldalpáron") + ); + } + assert_eq!(style_name("hu", "[Basic Paragraph]"), "[Alapbekezdés]"); + assert_eq!(style_name("hu", "Saját stílus"), "Saját stílus"); + assert_eq!(workspace_name("hu", "Essentials"), "Alapok"); + assert_eq!(workspace_name("hu", "Saját munkaterület"), "Saját munkaterület"); +} + +/// Checks translated labels and source-text fallback, plus key uniqueness and nonempty rows +/// in the shared, Arabic, Brazilian Portuguese and Italian catalogs. +#[test] +fn translates_known_strings_and_keeps_the_rest() { + assert_eq!(tr("de", "File"), "Datei"); + assert_eq!(tr("ja", "Swatches"), "スウォッチ"); + assert_eq!(tr("fr", "Something new"), "Something new"); + assert_eq!(tr("", "File"), "File"); + assert_eq!(tr("ar", "File"), "ملف"); + assert_eq!(tr("ar", "Unknown label"), "Unknown label"); + assert_eq!(tr("pt-br", "File"), "Arquivo"); + assert_eq!(tr("pt-br", "New Document…"), "Novo documento…"); + assert_eq!(tr("pt-br", "Unknown label"), "Unknown label"); + assert_eq!(tr("it", "Edit"), "Modifica"); + assert_eq!(tr("it", "New Document…"), "Nuovo documento…"); + assert_eq!(tr("it", "Unknown label"), "Unknown label"); + assert!(is_rtl("ar")); + for (i, (en, translation)) in ar::TABLE.iter().enumerate() { + assert!(ar::TABLE[..i].iter().all(|(key, _)| key != en), "duplicate {en}"); + assert!(!translation.is_empty(), "{en}"); + } + for (i, (en, translation)) in pt_br::TABLE.iter().enumerate() { + assert!(pt_br::TABLE[..i].iter().all(|(key, _)| key != en), "duplicate {en}"); + assert!(!translation.is_empty(), "{en}"); + } + for (i, (en, translation)) in it::TABLE.iter().enumerate() { + assert!(it::TABLE[..i].iter().all(|(key, _)| key != en), "duplicate {en}"); + assert!(!translation.is_empty(), "{en}"); + } + // Italian entries are for keys the shared or Arabic table knows. A new English string + // falls back to English until it is translated, so it doesn't fail here. + for (en, _) in it::TABLE { + assert!(TABLE.iter().any(|(key, _)| key == en) || ar::TABLE.iter().any(|(key, _)| key == en), "it: unknown key {en}"); + } + // Every row is unique and complete. + for (i, (en, t)) in TABLE.iter().enumerate() { + assert!(TABLE[..i].iter().all(|(e, _)| e != en), "duplicate {en}"); + assert!(t.iter().all(|x| !x.is_empty()), "{en}"); + } +} + /// The Data Merge arrangement combo takes its accessible name from `tr(lang, "Arrangement")`. /// A row in only the shared table leaves the languages whose lookup returns directly with the /// English name. @@ -77,6 +175,7 @@ fn arrangement_accessible_name_is_localized_in_every_interface_language() { } } +/// Checks language-specific context precedence and fallback to the plain translation. #[test] fn context_captions_come_from_their_context_or_the_plain_translation() { for (lang, table) in CONTEXT_TABLES { @@ -110,6 +209,38 @@ fn context_captions_come_from_their_context_or_the_plain_translation() { } } +/// Keeps quantity labels distinct from numeric values and checks translated Pages-panel captions. +#[test] +fn a_column_count_and_a_list_number_read_differently() { + for (lang, count, numeral) in [ + ("hu", "Darabszám:", "Szám:"), + ("de", "Anzahl:", "Zahl:"), + ("ja", "数:", "番号:"), + ("uk", "Кількість:", "Номер:"), + ("ar", "العدد:", "الرقم:"), + ("fr", "Nombre :", "Numéro:"), + ("zh", "数量:", "编号:"), + ] { + assert_eq!((tr_context(lang, "Number:", "count"), tr(lang, "Number:")), (count, numeral), "{lang}"); + } + assert_eq!(tr_context("en", "Number:", "count"), "Number:"); + assert_eq!(tr("de", "Gutter:"), "Spaltenabstand:"); + // The Pages panel menu. + for key in [ + "Insert Pages…", + "Move Pages…", + "New Parent…", + "Override All Parent Page Items", + "Remove All Local Overrides", + "Detach All Objects from Parent", + "Create Alternate Layout…", + "Allow Selected Spread to Shuffle", + ] { + assert_ne!(tr("pt-br", key), key); + } + assert_ne!(tr("ar", "Apply Parent to Pages"), "Apply Parent to Pages"); +} + /// The tables `tr` reads, as (language, key, translation), context captions included. fn entries() -> Vec<(&'static str, &'static str, &'static str)> { let mut entries: Vec<_> = LANGUAGE_TABLES.iter().flat_map(|(lang, table)| table.iter().map(|(key, text)| (*lang, *key, *text))).collect(); @@ -263,6 +394,23 @@ fn interface_strings() -> HashSet<&'static str> { keys.extend(crate::panel_docking::DOCK_LABELS.iter().map(|(_, english)| *english)); // UI labels passed to `tr` that no other catalog has yet. keys.extend([ + "180°", + "Create Links When Placing Text Files", + "Delete Character Style…", + "Delete Paragraph Style…", + "Delete the character style \"{name}\"?", + "Delete the paragraph style \"{name}\"?", + "IT", + "Replace with:", + "Show the Typography panel", + "Stroke Behind Fill", + "Stylistic Set", + "The selected fonts have no OpenType features.", + "This story was edited in the layout: you'll be asked before those edits are replaced", + "This style is in use. Text using it will be reassigned to:", + "VA", + "Y:", + "“{}” has been edited in this layout. Updating replaces those edits with the text from the file.", "(any)", "(unchanged)", "[No Language]", From 39109cc0df5d5b4b6ef7802e5873cf799901c642 Mon Sep 17 00:00:00 2001 From: macadminHU <51995175+macrobi@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:10:55 +0100 Subject: [PATCH 0298/1349] HU1: retain both parents menu tests in the shared layout Retain the upstream shortcut and navigation tests together with Hungarian selection, persistence, menu-path and document-preservation regressions and the complete Georgian-menu assertion. --- crates/ui-egui/src/menus/tests.rs | 153 ++++++++++++++++++++++++++++++ 1 file changed, 153 insertions(+) diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 29ad3404a..ef8ad6035 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -54,6 +54,7 @@ fn define_lists_command_path_matches_the_type_menu() { assert!(menu_ids("Type").contains(&"list.define")); } +/// Checks that screen-mode menu checkmarks follow the current Normal or Preview mode. #[test] fn screen_mode_shows_the_current_mode() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); @@ -63,6 +64,24 @@ fn screen_mode_shows_the_current_mode() { assert_eq!((mode(&app, "normal"), mode(&app, "preview")), (Some(false), Some(true))); } +/// Checks that translated customization paths match the visible submenu captions, while +/// allowing uncatalogued paths to keep their English fallback. +#[test] +fn hungarian_menu_paths_match_the_visible_submenu_labels() { + // These paths are displayed by menu customization; they must use the same + // captions as the actual menu tree, including nested special characters. + for title in ["Edit", "Type", "View"] { + for path in submenu_paths(title) { + let translated = crate::i18n::tr("hu", &path); + if translated == path { + continue; // New, uncatalogued paths still fall back to English. + } + let visible = path.split('/').map(|part| crate::i18n::tr("hu", part)).collect::>().join("/"); + assert_eq!(translated, visible, "{path}"); + } + } +} + fn walk(items: &[Item], out: &mut Vec<(String, String, Value)>) { for it in items { match it { @@ -548,6 +567,7 @@ fn split_window_contextual_bars_have_independent_widget_ids() { assert!(!bars[0].intersects(bars[1]), "each pane keeps its own bar: {bars:?}"); } +/// Checks the document-grid menu label, shortcut, checkmark and repeated toggle behavior. #[test] fn show_document_grid_toggles_from_the_grids_and_guides_menu() { let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); @@ -566,6 +586,8 @@ fn show_document_grid_toggles_from_the_grids_and_guides_menu() { assert!(!app.ui.document_grid); } +/// Checks language selection and rejection of unknown language codes, Preferences dispatch, +/// translated menu labels and preservation of document data when switching to Arabic. #[test] fn interface_language_switches_and_validates() { let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); @@ -583,6 +605,137 @@ fn interface_language_switches_and_validates() { run_ui(&mut app, "app.language", &json!({})).unwrap().unwrap(); assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("preferences")); assert_eq!(app.ui.language, "de"); + app.ui.dialog = None; + + run_ui(&mut app, "app.language", &json!({"lang": "zh"})).unwrap().unwrap(); + assert_eq!(app.ui.language, "zh"); + assert_eq!(crate::i18n::tr(&app.ui.language, "File"), "文件"); + + app.run("file.new", json!({"pages": 4, "facingPages": true})).unwrap(); + let before = serde_json::to_value(&app.session.doc().unwrap().doc).unwrap(); + run_ui(&mut app, "app.language", &json!({"lang": "ar"})).unwrap().unwrap(); + assert_eq!(app.ui.language, "ar"); + assert_eq!(checked(&app, "app.language", &json!({"lang": "ar"})), Some(true)); + assert_eq!(before, serde_json::to_value(&app.session.doc().unwrap().doc).unwrap()); + for (title, _) in menu_tree() { + assert_ne!(crate::i18n::tr("ar", title), title, "{title}"); + } + // Every menu title has a translation (Japanese never matches the English). + for (title, _) in menu_tree() { + assert_ne!(crate::i18n::tr("ja", title), title, "{title}"); + } + + run_ui(&mut app, "app.language", &json!({"lang": "pt-br"})).unwrap().unwrap(); + assert_eq!(app.ui.language, "pt-br"); + assert_eq!(checked(&app, "app.language", &json!({"lang": "pt-br"})), Some(true)); + for (title, _) in menu_tree() { + // "Layout" is the natural Brazilian Portuguese word, so it stays identical + // to English; every other title must be translated. + if title != "Layout" { + assert_ne!(crate::i18n::tr("pt-br", title), title, "{title}"); + } + } + + run_ui(&mut app, "app.language", &json!({"lang": "it"})).unwrap().unwrap(); + assert_eq!(app.ui.language, "it"); + assert_eq!(checked(&app, "app.language", &json!({"lang": "it"})), Some(true)); + for (title, _) in menu_tree() { + // "File" and "Layout" are the usual Italian menu names, so they stay identical + // to English; every other title must be translated. + if title != "File" && title != "Layout" { + assert_ne!(crate::i18n::tr("it", title), title, "{title}"); + } + } + + run_ui(&mut app, "app.language", &json!({"lang": "ka"})).unwrap().unwrap(); + assert_eq!(app.ui.language, "ka"); + assert_eq!(checked(&app, "app.language", &json!({"lang": "ka"})), Some(true)); + // Every menu title, item and submenu is translated into Georgian. + let mut untranslated = Vec::new(); + for (title, entries) in menu_tree() { + let mut labels = vec![title.to_string()]; + let mut stack: Vec<&Item> = entries.iter().collect(); + while let Some(entry) = stack.pop() { + match entry { + Item::Sub(label, children) => { + labels.push(label.clone()); + stack.extend(children.iter()); + } + Item::Cmd { label, id, .. } if id != "app.language" => labels.push(label.clone()), + _ => {} + } + } + // Labels without letters ("180°") or point sizes ("72 pt") read the same in every language. + let size = |l: &str| l.strip_suffix(" pt").is_some_and(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit())); + untranslated.extend(labels.into_iter().filter(|l| l.chars().any(char::is_alphabetic) && !size(l) && crate::i18n::tr("ka", l) == l.as_str())); + } + assert!(untranslated.is_empty(), "untranslated Georgian menu labels: {untranslated:?}"); +} + +/// Checks Hungarian selection, menu captions and saved UI preferences without changing +/// document data or translating user-defined names. +#[test] +fn hungarian_language_is_selectable_persisted_and_keeps_document_data() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 4, "facingPages": true})).unwrap(); + app.run("frame.create", json!({"rect": [36, 36, 200, 200], "content": "text", "text": "My words · Árvíztűrő tükörfúrógép"})).unwrap(); + let before = serde_json::to_value(&app.session.doc().unwrap().doc).unwrap(); + run_ui(&mut app, "app.language", &json!({"lang": "hu"})).unwrap().unwrap(); + assert_eq!(checked(&app, "app.language", &json!({"lang": "hu"})), Some(true)); + assert_eq!(before, serde_json::to_value(&app.session.doc().unwrap().doc).unwrap()); + for (title, _) in menu_tree() { + assert_ne!(crate::i18n::tr("hu", title), title, "{title}"); + } + let bytes = serde_json::to_vec(&app.ui).unwrap(); + let restored: crate::UiState = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(restored.language, "hu"); + assert_eq!(crate::i18n::tr(&restored.language, "File"), "Fájl"); + assert_eq!(crate::i18n::tr(&restored.language, "A custom name"), "A custom name"); + assert!(crate::i18n::LANGUAGES.contains(&("hu", "Magyar")), "Preferences lists Hungarian by its own name"); +} + +/// Checks Ukrainian selection, menu captions and saved UI preferences without changing +/// document data or translating user-defined names. +#[test] +fn ukrainian_language_is_selectable_persisted_and_keeps_document_data() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 4, "facingPages": true})).unwrap(); + app.run("frame.create", json!({"rect": [36, 36, 200, 200], "content": "text", "text": "My words · Мої слова"})).unwrap(); + let before = serde_json::to_value(&app.session.doc().unwrap().doc).unwrap(); + run_ui(&mut app, "app.language", &json!({"lang": "uk"})).unwrap().unwrap(); + assert_eq!(checked(&app, "app.language", &json!({"lang": "uk"})), Some(true)); + assert_eq!(before, serde_json::to_value(&app.session.doc().unwrap().doc).unwrap()); + for (title, _) in menu_tree() { + assert_ne!(crate::i18n::tr("uk", title), title, "{title}"); + } + let bytes = serde_json::to_vec(&app.ui).unwrap(); + let restored: crate::UiState = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(restored.language, "uk"); + assert_eq!(crate::i18n::tr(&restored.language, "File"), "Файл"); + assert_eq!(crate::i18n::tr(&restored.language, "A custom name"), "A custom name"); + assert!(crate::i18n::LANGUAGES.contains(&("uk", "Українська")), "Preferences lists Ukrainian by its own name"); +} + +/// Checks Russian selection, menu captions and saved UI preferences without changing +/// document data or translating user-defined names. +#[test] +fn russian_language_is_selectable_persisted_and_keeps_document_data() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 4, "facingPages": true})).unwrap(); + app.run("frame.create", json!({"rect": [36, 36, 200, 200], "content": "text", "text": "My words · Мои слова"})).unwrap(); + let before = serde_json::to_value(&app.session.doc().unwrap().doc).unwrap(); + run_ui(&mut app, "app.language", &json!({"lang": "ru"})).unwrap().unwrap(); + assert_eq!(checked(&app, "app.language", &json!({"lang": "ru"})), Some(true)); + assert_eq!(before, serde_json::to_value(&app.session.doc().unwrap().doc).unwrap()); + for (title, _) in menu_tree() { + assert_ne!(crate::i18n::tr("ru", title), title, "{title}"); + } + let bytes = serde_json::to_vec(&app.ui).unwrap(); + let restored: crate::UiState = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(restored.language, "ru"); + assert_eq!(crate::i18n::tr(&restored.language, "File"), "Файл"); + assert_eq!(crate::i18n::tr(&restored.language, "A custom name"), "A custom name"); + assert!(crate::i18n::LANGUAGES.contains(&("ru", "Русский")), "Preferences lists Russian by its own name"); } #[test] From f8b05ee3df5c482106b08d24a7486925dc926a7e Mon Sep 17 00:00:00 2001 From: macadminHU <51995175+macrobi@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:11:25 +0100 Subject: [PATCH 0299/1349] HU1: retain toolbar coverage with current keymap captions Preserve existing toolbar assertions and Hungarian right-click flyout coverage in both column layouts. Check platform-formatted default shortcuts and a user-assigned chord, including painted text, clipping and overlap. All 13 focused toolbar tests passed. --- crates/ui-egui/src/toolbar/tests.rs | 93 ++++++++++++++++++++++++++++- 1 file changed, 92 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 6a8ea752c..c970f7286 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -19,10 +19,100 @@ fn column_width(cols: f32) -> f32 { 8.0 + super::BTN * cols + 4.0 * (cols - 1.0) + 8.0 } +/// Returns the bounds of the labeled test widget, failing if the label cannot be found. fn rect(h: &egui_kittest::Harness<'static, test_window::Window>, label: &str) -> egui::Rect { h.get_by_label(label).rect() } +/// Checks translated tooltips and right-click flyout rows in both Tools-panel layouts, +/// including painted labels, unchanged shortcuts and unclipped, nonoverlapping text. +#[test] +fn hungarian_tool_buttons_translate_every_tool_and_keep_shortcuts() { + use egui::{Event, Modifiers, PointerButton}; + + /// Collects painted text bounds and their clip rectangles, including nested shapes. + fn collect_text(shape: &egui::Shape, clip: egui::Rect, texts: &mut Vec<(String, egui::Rect, egui::Rect)>) { + match shape { + egui::Shape::Text(text) => texts.push((text.galley.text().to_owned(), text.visual_bounding_rect(), clip)), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect_text(shape, clip, texts)), + _ => {} + } + } + + for double in [false, true] { + let mut app = app(double); + app.ui.language = "hu".into(); + let mut h = test_window::open(app, vec2(1400.0, 1000.0)); + for tool in designcraft_tools::TOOL_GROUPS.iter().flat_map(|group| group.iter()) { + h.state_mut().app.run("tool.select", serde_json::json!({"tool": tool.id})).unwrap(); + h.run_steps(3); + let label = crate::i18n::tr("hu", tool.label); + assert_ne!(label, tool.label, "untranslated tool: {}", tool.id); + let shortcut = tool.shortcut.map(crate::menus::shortcut_text); + assert_eq!(crate::menus::tool_shortcut_label(&h.state().app, tool.id), shortcut, "default binding for {}", tool.id); + let tip = shortcut.map_or_else(|| label.to_owned(), |shortcut| format!("{label} ({shortcut})")); + assert!(rect(&h, &tip).is_finite(), "{tip}"); + } + // A user-assigned chord also has to fit beside a translated flyout label. + let custom_shortcut = "Ctrl+Alt+Shift+F12"; + h.state_mut() + .app + .run( + "window.setShortcut", + serde_json::json!({"id": "tool.select", "params": {"tool": "ellipseFrame"}, "shortcut": custom_shortcut, "steal": true}), + ) + .unwrap(); + for (gi, group) in designcraft_tools::TOOL_GROUPS.iter().enumerate() { + // Single tools have no flyout; the collector group is split into separate + // buttons in two-column mode and is covered by the tooltip checks above. + if group.len() < 2 || (double && designcraft_tools::SPLIT_IN_TWO_COLUMNS.contains(&group[0].id)) { + continue; + } + let first = group[0]; + h.state_mut().app.run("tool.select", serde_json::json!({"tool": first.id})).unwrap(); + h.run_steps(3); + let label = crate::i18n::tr("hu", first.label); + let tip = first.shortcut.map(crate::menus::shortcut_text).map_or_else(|| label.to_owned(), |shortcut| format!("{label} ({shortcut})")); + let at = rect(&h, &tip).center(); + h.input_mut().events.push(Event::PointerMoved(at)); + for pressed in [true, false] { + h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }); + } + h.run_steps(3); + assert_eq!(h.state().app.ui.flyout, Some(gi), "right-click opens {} (double={double})", first.id); + let mut texts = Vec::new(); + for shape in &h.output().shapes { + collect_text(&shape.shape, shape.clip_rect, &mut texts); + } + for tool in *group { + let label = crate::i18n::tr("hu", tool.label); + // Flyout accessibility labels omit the shortcut; inspect the painted + // text inside this row so another button cannot satisfy the assertion. + let row = rect(&h, label); + assert!(row.is_finite() && row.is_positive(), "{label}"); + let painted = |expected: &str| { + let (_, bounds, clip) = texts + .iter() + .find(|(text, bounds, _)| text == expected && row.contains(bounds.center())) + .unwrap_or_else(|| panic!("missing flyout text {expected:?} for {} (double={double})", tool.id)); + assert!(row.contains_rect(*bounds) && clip.contains_rect(*bounds), "clipped flyout text {expected:?}: {bounds:?}"); + *bounds + }; + let label_bounds = painted(label); + let binding = if tool.id == "ellipseFrame" { Some(custom_shortcut) } else { tool.shortcut }; + if let Some(shortcut) = binding.map(crate::menus::shortcut_text) { + let shortcut_bounds = painted(&shortcut); + assert!(label_bounds.right() < shortcut_bounds.left(), "label overlaps shortcut for {} (double={double})", tool.id); + } + } + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(h.state().app.ui.flyout.is_none()); + } + assert_eq!(crate::i18n::tr("hu", "Direct Selection Tool"), "Közvetlen kijelölő eszköz"); + } +} + /// As InDesign's: a tool group's flyout closes on Esc and on a click outside it (the fill /// swatch, a panel), not only on the canvas. #[test] @@ -197,7 +287,8 @@ fn the_tools_panel_lays_out_like_indesigns() { for double in [false, true] { let h = test_window::open(app(double), vec2(1400.0, 900.0)); let _ = rect(&h, "Gradient Swatch Tool (G)"); - let _ = rect(&h, "Gradient Feather Tool (Shift+G)"); + let feather = format!("Gradient Feather Tool ({})", crate::menus::shortcut_text("Shift+G")); + let _ = rect(&h, &feather); let _ = rect(&h, "View Options"); let split = ["Content Placer Tool (B)", "Apply Color (,)", "Apply Gradient (.)", "Normal"]; for label in split { From 4207debc170e452c59471bdef166f297afec23f7 Mon Sep 17 00:00:00 2001 From: macadminHU <51995175+macrobi@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:14:01 +0100 Subject: [PATCH 0300/1349] HU1: retain Hungarian in the moved language command metadata Keep hu in the app.language parameter documentation after the UI command table moved to menus/ui_commands.rs. --- crates/ui-egui/src/menus/ui_commands.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 3d43beea6..42cfa56b9 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -66,7 +66,7 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[ "app.language", "Interface Language", None, - "{lang?: \"\"|de|fr|es|ja|zh|ar|pt-br|it|uk|ru|cs|pl|ka} — menus and panel names (the macOS menu bar follows at once); without lang, opens Preferences, where it is the first setting", + "{lang?: \"\"|de|fr|es|ja|zh|ar|pt-br|it|uk|ru|cs|pl|ka|hu} — menus and panel names (the macOS menu bar follows at once); without lang, opens Preferences, where it is the first setting", ), ( "app.flattener", From e6e8fc126eb17f6fac9527dd21ce0db13fbc96c0 Mon Sep 17 00:00:00 2001 From: macadminHU <51995175+macrobi@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:15:05 +0100 Subject: [PATCH 0301/1349] HU1: keep the integrated PDF condition clippy-clean Apply the equivalent De Morgan form of the upstream gradient condition so Rust 1.95 clippy with warnings denied can complete. Short-circuit order and output behavior are unchanged. --- crates/pdf/src/gradient_inks.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/pdf/src/gradient_inks.rs b/crates/pdf/src/gradient_inks.rs index e889ee1d2..c92b80158 100644 --- a/crates/pdf/src/gradient_inks.rs +++ b/crates/pdf/src/gradient_inks.rs @@ -87,7 +87,7 @@ impl Exporter<'_> { let inks: Vec> = g.stops.iter().map(|s| self.stop_ink(s)).collect(); let has_spot = inks.iter().any(|i| matches!(i, Some(Ink::Spot { .. }))); let on_paper = g.stops.iter().any(|s| s.swatch.as_deref() == Some(designcraft_color::swatch::PAPER)); - if !has_spot && !overprint && !(on_paper && self.for_print() && !self.rgb_only) { + if !(has_spot || overprint || on_paper && self.for_print() && !self.rgb_only) { return None; } let Some(inks) = inks.into_iter().collect::>>() else { From 72a586e0d5f419cf98133f7a5863cd54d7d0ab11 Mon Sep 17 00:00:00 2001 From: macadminHU <51995175+macrobi@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:15:37 +0100 Subject: [PATCH 0302/1349] HU1: keep the moved PDF test helpers clippy-clean Simplify two upstream Option predicates to equivalent is_none_or forms. Preserve the None cases, all test cases and assertions; no coverage is removed. --- crates/engine/src/cmd/export/text_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/export/text_tests.rs b/crates/engine/src/cmd/export/text_tests.rs index e533320f8..2efcb2f92 100644 --- a/crates/engine/src/cmd/export/text_tests.rs +++ b/crates/engine/src/cmd/export/text_tests.rs @@ -204,12 +204,12 @@ fn black_and_gold(pdf: &[u8]) -> Vec<(u8, u8)> { let mut out = Vec::new(); for st in file.objects().into_iter().filter_map(|o| o.into_stream()) { let d = st.dict(); - if !d.get::>(b"Subtype").is_some_and(|n| n.as_ref() == b"Image") || d.get::(b"BitsPerComponent") != Some(8) { + if d.get::>(b"Subtype").is_none_or(|n| n.as_ref() != b"Image") || d.get::(b"BitsPerComponent") != Some(8) { continue; } let Some(cs) = d.get::>(b"ColorSpace") else { continue }; let mut it = cs.iter::>(); - if !it.next().and_then(|o| o.into_name()).is_some_and(|n| n.as_ref() == b"DeviceN") { + if it.next().and_then(|o| o.into_name()).is_none_or(|n| n.as_ref() != b"DeviceN") { continue; } let Some(Object::Array(names)) = it.next() else { continue }; From 7d48e47057f2abba78085d8accfa261221338b53 Mon Sep 17 00:00:00 2001 From: macadminHU <51995175+macrobi@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:16:04 +0100 Subject: [PATCH 0303/1349] HU1: record shared-module localization integration Record the preserved Hungarian catalog and both parents localization, menu, toolbar and docking tests, current keymap-aware flyout sizing and direct Georgian lookup checks. Keep every existing progress entry and readiness percentage. --- ROADMAP.md | 1 + 1 file changed, 1 insertion(+) diff --git a/ROADMAP.md b/ROADMAP.md index b3d3abeb8..52265475c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -378,6 +378,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log +- **2026-10-27** · HU1: integrate Hungarian localization with the shared module layout; retain both parents' localization, menu, toolbar and panel-docking tests and all Hungarian catalog entries. Adapt toolbar tests and flyout sizing to platform-formatted and user-assigned shortcuts; add direct lookup assertions for the repaired Georgian menu captions. No readiness percentage change. - **2026-10-25** · HU1: extend Hungarian toolbar regression coverage through real right-click flyouts in both column layouts, checking translated row labels, painted shortcuts, clipping and overlap. Existing assertions and runtime behavior are unchanged. No readiness percentage change. - **2026-10-25** · HU1: retain both branches' localization and toolbar regression tests while adopting the updated egui button role; translate Data Merge Arrangement as Elrendezés (1,905 Hungarian entries and four context captions). No readiness percentage change. - **2026-10-25** · HU1: add the two missing Georgian File Info and Check for Updates menu captions while retaining the complete-menu regression unchanged. No readiness percentage change. From 40083be3f2be66b1b48dc2d97090e8513b74f10f Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Wed, 28 Oct 2026 04:07:38 +0400 Subject: [PATCH 0304/1349] i18n(ka): Georgian for keyboard shortcut sets, command forms and labels added since #1573 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- crates/ui-egui/src/i18n/ka.rs | 388 ++++++++++++++++++++++++++++++++++ 1 file changed, 388 insertions(+) diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index 436c157f4..1cefbbfcf 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -2475,4 +2475,392 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Set OpenType Features", "OpenType შესაძლებლობების დაყენება"), ("Swap Text Fill and Stroke", "ტექსტის შევსებისა და კონტურის გაცვლა"), ("Thread Text Frames", "ტექსტური ჩარჩოების დაკავშირება"), + // Command-form parameter names, presets and dialog text. + ("Apply to:", "გამოყენება:"), + ("Auto-Size", "ავტომატური ზომა"), + ("Create Links When Placing Text Files", "ტექსტური ფაილების განთავსებისას ბმულების შექმნა"), + ("Kerning/Tracking:", "კერნინგი/ტრეკინგი:"), + ("Remove Existing Ruler Guides", "სახაზავის არსებული დამხმარე ხაზების წაშლა"), + ("Replace All", "ყველას ჩანაცვლება"), + ( + "Replace All updates this font throughout text and styles. Done keeps remaining fallback fonts.", + "„ყველას ჩანაცვლება“ ამ შრიფტს მთელ ტექსტსა და სტილებში განაახლებს. „მზადაა“ დარჩენილ სათადარიგო შრიფტებს შეინარჩუნებს.", + ), + ("Replace with:", "ჩანაცვლება:"), + ("Stroke Behind Fill", "კონტური შევსების უკან"), + ("Delete the character style \"{name}\"?", "სიმბოლოს სტილი „{name}“ წაიშალოს?"), + ("Delete the paragraph style \"{name}\"?", "აბზაცის სტილი „{name}“ წაიშალოს?"), + ("Currently Rendered With", "ამჟამად გამოსახულია შრიფტით"), + ( + "“{}” has been edited in this layout. Updating replaces those edits with the text from the file.", + "„{}“ ამ განლაგებაში რედაქტირებულია. განახლება ამ ცვლილებებს ფაილის ტექსტით ჩაანაცვლებს.", + ), + ("Proportional Metrics", "პროპორციული მეტრიკა"), + ("Horizontal Kana", "ჰორიზონტალური კანა"), + ("Localized Forms", "ლოკალიზებული ფორმები"), + ("Mark Positioning", "დიაკრიტიკული ნიშნების განლაგება"), + ("Historical Forms", "ისტორიული ფორმები"), + ("Stylistic Alternates", "სტილისტური ალტერნატივები"), + ("Justification Alternates", "გასწორების ალტერნატივები"), + ("Roman Italics", "რომაული დახრილი"), + ("Letter", "წერილი"), + ("Legal", "იურიდიული ინფორმაცია"), + ("Tabloid", "Tabloid"), + ("Letter - Half", "წერილი - ნახევარი"), + ("Postcard", "ღია ბარათი"), + ("Web 1920 × 1080", "ვები 1920 × 1080"), + ("Web 1366 × 768", "ვები 1366 × 768"), + ("Web 1024 × 768", "ვები 1024 × 768"), + ("Mobile 1080 × 1920", "მობილური 1080 × 1920"), + ("Mobile 390 × 844", "მობილური 390 × 844"), + ("Tablet 1024 × 1366", "პლანშეტი 1024 × 1366"), + ("Action", "მოქმედება"), + ("Adjust layout", "განლაგების მისადაგება"), + ("Advance seconds", "გადასვლის ინტერვალი (წმ)"), + ("Affix in", "პრეფიქსისა და სუფიქსის ადგილი"), + ("Allow", "დაშვება"), + ("Anchor", "ღუზა"), + ("Artifact", "არტეფაქტი"), + ("Asset", "რესურსი"), + ("Assets", "რესურსები"), + ("At end", "ბოლოში"), + ("Attrs", "ატრიბუტები"), + ("Author", "ავტორი"), + ("Auto fit", "ავტომორგება"), + ("Auto size", "ავტომატური ზომა"), + ("Auto size reference", "ავტომატური ზომის საყრდენი წერტილი"), + ("Axis", "ღერძი"), + ("Bands", "ზოლები"), + ("Bookmarks panel", "სანიშნეების პანელი"), + ("Case", "რეგისტრი"), + ("Column gutter", "სვეტებს შორის შუალედი"), + ("Column width", "სვეტის სიგანე"), + ("Columns kind", "სვეტების ტიპი"), + ("Continue across stories", "გაგრძელება ტექსტურ ნაკადებს შორის"), + ("Copies", "ასლები"), + ("Corners", "კუთხეები"), + ("Cover image", "ყდის გამოსახულება"), + ("Definition", "განსაზღვრება"), + ("Dir", "საქაღალდე"), + ("Dry run", "საცდელი გაშვება"), + ("Embed fonts", "შრიფტების ჩაშენება"), + ("End", "დასასრული"), + ("Extension", "გაფართოება"), + ("Facing pages", "მოპირდაპირე გვერდები"), + ("Family", "შრიფტის ოჯახი"), + ("First baseline", "პირველი საბაზისო ხაზი"), + ("First baseline min", "პირველი საბაზისო ხაზის მინიმუმი"), + ("Fit to", "მორგება"), + ("Fixed layout", "ფიქსირებული განლაგება"), + ("Flatten", "გაბრტყელება"), + ("Font size", "შრიფტის ზომა"), + ("Format", "ფორმატი"), + ("From", "საიდან"), + ("Full screen", "სრული ეკრანი"), + ("Grep", "GREP"), + ("Heading", "სათაური"), + ("Heading style", "სათაურის სტილი"), + ("Hidden", "დამალული"), + ("Identifier", "იდენტიფიკატორი"), + ("Idml", "IDML"), + ("Ids", "ID-ები"), + ("Include inside edges", "შიდა კიდეების ჩართვა"), + ("Include prefix", "პრეფიქსის ჩართვა"), + ("Instructions", "ინსტრუქციები"), + ("Intent", "განზრახვა"), + ("Keep within column", "სვეტის ფარგლებში დატოვება"), + ("Kind", "სახეობა"), + ("Label", "იარლიყი"), + ("Latex", "LaTeX"), + ("Layout page", "განლაგების გვერდი"), + ("Line breaks", "სტრიქონის წყვეტები"), + ("Load cursor", "კურსორში ჩატვირთვა"), + ("Marker", "მარკერი"), + ("Marks", "ნიშნები"), + ("Message", "შეტყობინება"), + ("Minimum height", "მინიმალური სიმაღლე"), + ("Minimum width", "მინიმალური სიგანე"), + ("Missing only", "მხოლოდ დაკარგული"), + ("Mode", "რეჟიმი"), + ("Number", "ნომერი"), + ("Object point", "ობიექტის საყრდენი წერტილი"), + ("Org", "ორგანიზაცია"), + ("Page break before", "გვერდის გამყოფი წინ"), + ("Page layout", "გვერდის განლაგება"), + ("Para style", "აბზაცის სტილი"), + ("Paragraphs", "აბზაცები"), + ("Parent", "საბაზო გვერდი"), + ("Pattern", "პატერნი"), + ("Pdf", "PDF"), + ("Pdf crop", "PDF-ის ჩამოჭრა"), + ("Pdf page", "PDF-ის გვერდი"), + ("Phone", "ტელეფონი"), + ("Pos", "პოზიცია"), + ("Prefix", "პრეფიქსი"), + ("Primary text frame", "ძირითადი ტექსტური ჩარჩო"), + ("Printer", "პრინტერი"), + ("Rasterize", "რასტრირება"), + ("Rect", "მართკუთხედი"), + ("Redefine styles", "სტილების ხელახლა განსაზღვრა"), + ("Ref", "საყრდენი წერტილი"), + ("Ref char style", "მიმართვის სიმბოლოს სტილი"), + ("Ref position", "მიმართვის პოზიცია"), + ("Remove existing", "არსებულის წაშლა"), + ("Restart", "თავიდან დაწყება"), + ("Row gutter", "სტრიქონებს შორის შუალედი"), + ("Rule", "წესი"), + ("Run in", "ერთ აბზაცში"), + ("Scope", "მოქმედების არე"), + ("Section headings", "სექციის სათაურები"), + ("Separator", "გამყოფი"), + ("Shape", "ფიგურა"), + ("Space", "ფერთა სივრცე"), + ("Space after", "დაშორება შემდეგ"), + ("Space before", "დაშორება წინ"), + ("Space between", "დაშორება შორის"), + ("Span columns", "სვეტებზე გაშლა"), + ("Start", "დასაწყისი"), + ("Start at", "დაწყება"), + ("Start number", "საწყისი ნომერი"), + ("Start page", "საწყისი გვერდი"), + ("Subject", "თემა"), + ("Subpath", "ქვეტრაექტორია"), + ("Suffix", "სუფიქსი"), + ("Suggestions", "შეთავაზებები"), + ("Tagged", "ტეგირებული"), + ("Target", "სამიზნე"), + ("Threshold", "ზღვარი"), + ("Title", "დასახელება"), + ("To family", "ახალი შრიფტის ოჯახი"), + ("To spread", "სამიზნე გაშლა"), + ("To style", "ახალი სტილი"), + ("Toc title", "სარჩევის სათაური"), + ("Tolerance", "დაშვება"), + ("Topics", "თემები"), + ("Url", "URL"), + ("Use", "გამოყენება"), + ("Use minimum height", "მინიმალური სიმაღლის გამოყენება"), + ("Use minimum width", "მინიმალური სიგანის გამოყენება"), + ("Value", "მნიშვნელობა"), + ("Visible", "ხილული"), + ("Word", "სიტყვა"), + ("X offset", "X წანაცვლება"), + ("X relative", "X-ის ათვლის წერტილი"), + ("Y offset", "Y წანაცვლება"), + (" Save ", " შენახვა "), + (" Update ", " განახლება "), + // Keyboard shortcut sets (craft-keymap), docking and new commands. + ("(cycles)", "(ციკლურად)"), + ("(modified)", "(შეცვლილი)"), + ("+Bin", "+Bin"), + ("+LOC", "+LOC"), + ("A command can have at most {n} shortcuts", "ბრძანების მალსახმობების მაქსიმალური რაოდენობა: {n}"), + ("A set with this name exists", "ამ სახელის ნაკრები უკვე არსებობს"), + ("Add a shortcut to {label}", "{label}: მალსახმობის დამატება"), + ("All Commands", "ყველა ბრძანება"), + ("Also used by {label}", "ასევე იყენებს: {label}"), + ("Alt", "Alt"), + ("Application", "აპლიკაცია"), + ("Approximated", "მიახლოებით წაკითხული"), + ("Assign", "მინიჭება"), + ("Assign to Selected", "მონიშნულზე მინიჭება"), + ("Assign {chord} to {label}", "{label}: მალსახმობის მინიჭება ({chord})"), + ("Auto-Collapse Iconic Panels", "ხატულებად ჩაკეცილი პანელების ავტომატური ჩაკეცვა"), + ("Based on:", "საფუძველი:"), + ("Built-in sets cannot be changed", "ჩაშენებული ნაკრებების შეცვლა შეუძლებელია"), + ("Cancel Import", "იმპორტის გაუქმება"), + ("Cancel the new shortcut", "ახალი მალსახმობის გაუქმება"), + ("Caps Lock", "Caps Lock"), + ("Changed", "შეცვლილი"), + ("Check for Updates…", "განახლებების შემოწმება…"), + ("Choose a command…", "აირჩიეთ ბრძანება…"), + ("Click a key to see its shortcuts", "დაწკაპეთ კლავიშზე მისი მალსახმობების სანახავად"), + ("Close Other Panels in Group", "ჯგუფის სხვა პანელების დახურვა"), + ("Close panel window", "პანელის ფანჯრის დახურვა"), + ("Command", "ბრძანება"), + ("Command for {item}", "ბრძანება ელემენტისთვის „{item}“"), + ("Commands", "ბრძანებები"), + ("Conflicts", "კონფლიქტები"), + ("Context:", "კონტექსტი:"), + ("Copy Report", "ანგარიშის კოპირება"), + ("Ctrl", "Ctrl"), + ("Current shortcuts", "მიმდინარე მალსახმობები"), + ("Current shortcuts:", "მიმდინარე მალსახმობები:"), + ("Currently assigned to:", "ამჟამად მინიჭებულია:"), + ("Default: {chord}", "ნაგულისხმევი: {chord}"), + ("Delete Parent", "საბაზო გვერდის წაშლა"), + ("Delete Surrounding Text", "მიმდებარე ტექსტის წაშლა"), + ("Delete the set “{set}”?", "ნაკრები „{set}“ წაიშალოს?"), + ("Deselect Guides", "დამხმარე ხაზების მონიშვნის მოხსნა"), + ("Detail pane size", "დეტალების არის ზომა"), + ("EPUB Split Document", "EPUB: დოკუმენტის დაყოფა"), + ("Expand", "გაშლა"), + ("Expand Panels", "პანელების გაშლა"), + ("Export…", "ექსპორტი…"), + ("File Info", "ფაილის ინფორმაცია"), + ("File Info…", "ფაილის ინფორმაცია…"), + ("Filter:", "ფილტრი:"), + ("Fixed Keys", "ფიქსირებული კლავიშები"), + ("Float Tab Group", "მცურავი ჩანართების ჯგუფი"), + ("Go to Conflict", "კონფლიქტზე გადასვლა"), + ("Group Tab Group with", "ჩანართების ჯგუფის ერთად დაჯგუფება"), + ("Import", "იმპორტი"), + ("Import InDesign Shortcut Set", "InDesign-ის მალსახმობების ნაკრების იმპორტი"), + ("Import as New Set", "იმპორტი ახალ ნაკრებად"), + ("Import “{set}”", "იმპორტი: „{set}“"), + ("Imported", "იმპორტირებული"), + ("Imported as “{set}”", "იმპორტირებულია როგორც „{set}“"), + ("Import…", "იმპორტი…"), + ("Keep Both", "ორივეს შენარჩუნება"), + ("Key: {key}", "კლავიში: {key}"), + ("Keyboard", "კლავიატურა"), + ("Keyboard Shortcuts (JSON)", "კლავიატურის მალსახმობები (JSON)"), + ("Keyboard: US", "კლავიატურა: US"), + ("Keyboard: US (macOS)", "კლავიატურა: US (macOS)"), + ("Lock Workspace", "სამუშაო სივრცის ჩაკეტვა"), + ("Matched without change", "დაემთხვა ცვლილების გარეშე"), + ("Maximize Frame", "ჩარჩოს გაშლა"), + ("Modifier on", "მოდიფიკატორი ჩართულია"), + ("More", "მეტი"), + ("Move Guides", "დამხმარე ხაზების გადაადგილება"), + ("Move Panel to New Window", "პანელის ახალ ფანჯარაში გადატანა"), + ("Move panel column", "პანელების სვეტის გადაადგილება"), + ("Move panel window", "პანელის ფანჯრის გადაადგილება"), + ("Move tab group", "ჩანართების ჯგუფის გადაადგილება"), + ("New Set…", "ახალი ნაკრები…"), + ("New shortcut:", "ახალი მალსახმობი:"), + ("New shortcut: {chord}", "ახალი მალსახმობი: {chord}"), + ("Not assigned", "არ არის მინიჭებული"), + ("Not changed", "არ შეცვლილა"), + ("Not matched", "შესაბამისობა ვერ მოიძებნა"), + ("Nothing uses this key", "ამ კლავიშს არაფერი იყენებს"), + ("Now used by {label}", "ახლა იყენებს: {label}"), + ("Option", "Option"), + ("PDF/X-1a:2003", "PDF/X-1a:2003"), + ("PRs", "PR-ები"), + ("Panel or context", "პანელი ან კონტექსტი"), + ("Remove {chord} from {label}", "{label}: მალსახმობის წაშლა ({chord})"), + ("Rename…", "სახელის შეცვლა…"), + ("Reset All", "ყველაფრის ჩამოყრა"), + ("Reset All…", "ყველაფრის ჩამოყრა…"), + ("Restore Frame Size", "ჩარჩოს ზომის აღდგენა"), + ("Restore every default shortcut in this set?", "აღდგეს ამ ნაკრების ყველა ნაგულისხმევი მალსახმობი?"), + ("Restore the default for {label}", "{label}: ნაგულისხმევის აღდგენა"), + ("Revert Set", "ნაკრების წინა ვერსიაზე დაბრუნება"), + ("Ruler Zero Point", "სახაზავის ნულოვანი წერტილი"), + ("Save changes to “{set}”?", "შეინახოს ცვლილებები ნაკრებში „{set}“?"), + ("Search by key", "ძიება კლავიშით"), + ("Select Guide", "დამხმარე ხაზის მონიშვნა"), + ("Select a command first", "ჯერ მონიშნეთ ბრძანება"), + ("Select a command to see and change its shortcuts", "მონიშნეთ ბრძანება მისი მალსახმობების სანახავად და შესაცვლელად"), + ("Set name:", "ნაკრების სახელი:"), + ("Set:", "ნაკრები:"), + ("Shift", "Shift"), + ("Shortcut", "მალსახმობი"), + ("Shortcut Sets", "მალსახმობების ნაკრებები"), + ("Show:", "ჩვენება:"), + ("Skipped", "გამოტოვებული"), + ("Story Options", "ტექსტური ნაკადის პარამეტრები"), + ("Suggestions ({n})", "შეთავაზებები ({n})"), + ("Summarize…", "შეჯამება…"), + ("Super", "Super"), + ("Take It", "აღება"), + ("Take It and Go to Conflict", "აღება და კონფლიქტზე გადასვლა"), + ("Taken from other commands", "სხვა ბრძანებებიდან აღებული"), + ("The file is too large", "ფაილი ძალიან დიდია"), + ("The name is empty, too long or has control characters", "სახელი ცარიელია, ძალიან გრძელია ან მმართველ სიმბოლოებს შეიცავს"), + ("The scope {scope} is unknown", "მოქმედების არე {scope} უცნობია"), + ("The set was not found", "ნაკრები ვერ მოიძებნა"), + ("There are too many sets", "ნაკრები ძალიან ბევრია"), + ("This command is unknown", "ეს ბრძანება უცნობია"), + ("This file is from a newer version (format {n})", "ეს ფაილი უფრო ახალი ვერსიისაა (ფორმატი {n})"), + ("This is not a craft-keymap file", "ეს craft-keymap ფაილი არ არის"), + ("This is not a shortcut set file", "ეს მალსახმობების ნაკრების ფაილი არ არის"), + ("Too many shortcuts are assigned", "მინიჭებულია ძალიან ბევრი მალსახმობი"), + ("Tools", "ხელსაწყოები"), + ("Transparency Flattener", "გამჭვირვალობის გაბრტყელება"), + ("Type…", "ტექსტი…"), + ("Unreadable", "წაუკითხავი"), + ("Use Default", "ნაგულისხმევის გამოყენება"), + ("Will change", "შეიცვლება"), + ("Win", "Win"), + ("With Shortcut", "მალსახმობის მქონე"), + ("empty shortcut", "ცარიელი მალსახმობი"), + ("in a context that is not imported", "კონტექსტში, რომელიც არ იმპორტირდება"), + ("key sequences are not supported", "კლავიშთა მიმდევრობები მხარდაჭერილი არ არის"), + ("line {n}", "სტრიქონი {n}"), + ("modifier {key} given twice", "მოდიფიკატორი {key} ორჯერაა მითითებული"), + ("more than one command fits", "ერთზე მეტი ბრძანება შეესაბამება"), + ("no command has this name", "ამ სახელის ბრძანება არ არსებობს"), + ("numeric keypad key read as main key", "ციფრული ბლოკის კლავიში წაკითხულია ძირითად კლავიშად"), + ("only a command of the other kind fits (tool or menu command)", "შეესაბამება მხოლოდ სხვა სახეობის ბრძანება (ხელსაწყო ან მენიუს ბრძანება)"), + ("press keys", "დააჭირეთ კლავიშებს"), + ("reserved by the system", "სისტემისთვისაა დაჯავშნული"), + ("taken by a later entry", "დაიკავა მომდევნო ჩანაწერმა"), + ("taken by {label}", "დაიკავა: {label}"), + ("the scope is unknown", "მოქმედების არე უცნობია"), + ("the scope name is not valid", "მოქმედების არის სახელი არასწორია"), + ("the set's shortcuts could not be added", "ნაკრების მალსახმობების დამატება ვერ მოხერხდა"), + ("the shortcut has no key", "მალსახმობს კლავიში არ აქვს"), + ("the shortcut is too long", "მალსახმობი ძალიან გრძელია"), + ("the shortcuts could not be removed", "მალსახმობების წაშლა ვერ მოხერხდა"), + ("unknown key {key}", "უცნობი კლავიში {key}"), + ("unknown modifier {key}", "უცნობი მოდიფიკატორი {key}"), + ("unsupported modifier {key}", "მხარდაუჭერელი მოდიფიკატორი {key}"), + ("{chord} (Default)", "{chord} (ნაგულისხმევი)"), + ("{chord} (press again for a double press)", "{chord} (ორმაგი დაჭერისთვის კვლავ დააჭირეთ)"), + ("{chord} ({scope})", "{chord} ({scope})"), + ("{chord} is reserved by the system", "{chord} სისტემისთვისაა დაჯავშნული"), + ("{chord} was removed from {label}", "{label}: მალსახმობი {chord} წაიშალა"), + ("{chord}: {label}", "{chord}: {label}"), + ("{key}: listed more than once", "{key}: ერთზე მეტჯერაა მითითებული"), + ("{key}: no command has this name", "{key}: ამ სახელის ბრძანება არ არსებობს"), + ("{key}: part of the entry was dropped", "{key}: ჩანაწერის ნაწილი გამოტოვებულია"), + ("{key}: the scope in “{text}” is unknown", "{key}: მოქმედების არე უცნობია („{text}“)"), + ("{key}: {text} is reserved by the system", "{key}: {text} სისტემისთვისაა დაჯავშნული"), + ("{key}: “{text}” is not a shortcut ({error})", "{key}: „{text}“ მალსახმობი არ არის ({error})"), + ("{label} (Changed)", "{label} (შეცვლილი)"), + ("{label} (cycles)", "{label} (ციკლურად)"), + ("{label} ({scope})", "{label} ({scope})"), + ("{label} ({scope}, both work)", "{label} ({scope}, ორივე მუშაობს)"), + ("{label} keeps its shortcuts (matched by a panel menu name)", "{label} მალსახმობებს ინარჩუნებს (დაემთხვა პანელის მენიუს სახელით)"), + ("{label}: press keys", "{label}: დააჭირეთ კლავიშებს"), + ("{label}: {chord}", "{label}: {chord}"), + ("{label}: {chord} (Now used by {holder})", "{label}: {chord} (ახლა იყენებს: {holder})"), + ("{menu} Menu", "მენიუ „{menu}“"), + ("{n} command changed", "შეცვლილი ბრძანებები: {n}"), + ("{n} command will change", "შესაცვლელი ბრძანებები: {n}"), + ("{n} commands changed", "შეცვლილი ბრძანებები: {n}"), + ("{n} commands will change", "შესაცვლელი ბრძანებები: {n}"), + ("{n} entries cut at a limit", "ლიმიტზე შეკვეცილი ჩანაწერები: {n}"), + ("{n} entries were ignored: too many commands", "უგულებელყოფილი ჩანაწერები (ბრძანება ძალიან ბევრია): {n}"), + ("{n} entry cut at a limit", "ლიმიტზე შეკვეცილი ჩანაწერები: {n}"), + ("{n} entry was ignored: too many commands", "უგულებელყოფილი ჩანაწერები (ბრძანება ძალიან ბევრია): {n}"), + ("{n} item could not be read", "ელემენტები, რომელთა წაკითხვა ვერ მოხერხდა: {n}"), + ("{n} item not matched", "ელემენტები შესაბამისობის გარეშე: {n}"), + ("{n} item without a shortcut", "ელემენტები მალსახმობის გარეშე: {n}"), + ("{n} items could not be read", "ელემენტები, რომელთა წაკითხვა ვერ მოხერხდა: {n}"), + ("{n} items not matched", "ელემენტები შესაბამისობის გარეშე: {n}"), + ("{n} items without a shortcut", "ელემენტები მალსახმობის გარეშე: {n}"), + ("{n} key read approximately", "მიახლოებით წაკითხული კლავიშები: {n}"), + ("{n} keys read approximately", "მიახლოებით წაკითხული კლავიშები: {n}"), + ("{n} saved shortcut could not be used", "შენახული მალსახმობები, რომელთა გამოყენება ვერ მოხერხდა: {n}"), + ("{n} saved shortcuts could not be used", "შენახული მალსახმობები, რომელთა გამოყენება ვერ მოხერხდა: {n}"), + ("{n} shortcut also works in another scope", "სხვა მოქმედების არეშიც მოქმედი მალსახმობები: {n}"), + ("{n} shortcut is assigned more than once", "ერთზე მეტჯერ მინიჭებული მალსახმობები: {n}"), + ("{n} shortcuts also work in another scope", "სხვა მოქმედების არეშიც მოქმედი მალსახმობები: {n}"), + ("{n} shortcuts are assigned more than once", "ერთზე მეტჯერ მინიჭებული მალსახმობები: {n}"), + ("{panel} Panel", "პანელი „{panel}“"), + ("{title} ({n})", "{title} ({n})"), + ("{title}: {set}", "{title}: {set}"), + ("ΔLOC", "ΔLOC"), + ("−Bin", "−Bin"), + ("−LOC", "−LOC"), + ("⚠ {chord} is used by {label}", "⚠ {chord} დაკავებულია: {label}"), + ("Y:", "Y:"), + ("Show the Typography panel", "ტიპოგრაფიის პანელის ჩვენება"), + ( + "This story was edited in the layout: you'll be asked before those edits are replaced", + "ეს ტექსტური ნაკადი განლაგებაში რედაქტირებულია: ამ ცვლილებების ჩანაცვლებამდე დაგეკითხებით", + ), ]; From 20d6722820222ed91992ffe8511c48663697db05 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Wed, 28 Oct 2026 05:00:07 +0400 Subject: [PATCH 0305/1349] i18n(ka): keep the Letter, Legal and Letter - Half paper sizes in English, like Tabloid Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- crates/ui-egui/src/i18n/ka.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index 1cefbbfcf..14a9e6203 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -2503,10 +2503,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Stylistic Alternates", "სტილისტური ალტერნატივები"), ("Justification Alternates", "გასწორების ალტერნატივები"), ("Roman Italics", "რომაული დახრილი"), - ("Letter", "წერილი"), - ("Legal", "იურიდიული ინფორმაცია"), + ("Letter", "Letter"), + ("Legal", "Legal"), ("Tabloid", "Tabloid"), - ("Letter - Half", "წერილი - ნახევარი"), + ("Letter - Half", "Letter - Half"), ("Postcard", "ღია ბარათი"), ("Web 1920 × 1080", "ვები 1920 × 1080"), ("Web 1366 × 768", "ვები 1366 × 768"), From 87859340324746cedae57da9c1692b7cb564781e Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 28 Oct 2026 01:50:17 +0000 Subject: [PATCH 0306/1349] Open documents whose items share an id Fixes #1883 Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/lib.rs | 82 +++++++++++++++++++++++++++++++++++ crates/format/src/lib.rs | 2 + crates/format/src/tests.rs | 88 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 172 insertions(+) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index bf9998209..08ba34ca0 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -955,6 +955,88 @@ impl Document { designcraft_color::swatch::resolve(&self.swatches, swatch, tint) } + /// Give items that reuse an earlier item's id (spreads, then parents, then items anchored in + /// stories) fresh ids, so a file holding such duplicates opens. The first item keeps the id and + /// what refers to it by id; a renumbered text frame takes its place in its story's thread. + pub fn renumber_duplicate_items(&mut self) { + fn walk_mut(it: &mut Item, f: &mut impl FnMut(&mut Item)) { + f(it); + for c in it.children_mut().into_iter().flatten() { + walk_mut(Arc::make_mut(c), f); + } + } + fn story_items(st: &mut Story, f: &mut impl FnMut(&mut Item)) { + for o in &mut st.objects { + walk_mut(&mut Arc::make_mut(o).item, f); + } + for t in st.tables.values_mut() { + for c in &mut Arc::make_mut(t).cells { + story_items(&mut c.text, f); + } + } + for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + story_items(&mut Arc::make_mut(n).text, f); + } + } + let mut seen = std::collections::HashSet::new(); + let mut dups = std::collections::HashSet::new(); + let mut next = self.next_id; + let mut note = |id: ItemId| { + next = next.max(id.0); + if !seen.insert(id) { + dups.insert(id); + } + }; + for sp in self.spreads.iter().chain(self.parents.iter()) { + for it in &sp.items { + it.walk(&mut |i| note(i.id)); + } + } + for (_, i) in self.anchored_items() { + note(i.id); + } + if dups.is_empty() { + return; + } + let mut seen = std::collections::HashSet::new(); + // (story, id in the file) → the ids its frames carry now, in walk order. + let mut threads: std::collections::HashMap<(StoryId, ItemId), Vec> = std::collections::HashMap::new(); + let mut fix = |it: &mut Item| { + let old = it.id; + if !dups.contains(&old) { + return; + } + if !seen.insert(old) { + next += 1; + it.id = ItemId(next); + } + if let Some(t) = it.text_frame() { + threads.entry((t.story, old)).or_default().push(it.id); + } + }; + for sp in self.spreads.iter_mut().chain(self.parents.iter_mut()) { + for it in &mut Arc::make_mut(sp).items { + walk_mut(Arc::make_mut(it), &mut fix); + } + } + for st in self.stories.values_mut() { + story_items(Arc::make_mut(st), &mut fix); + } + self.next_id = next; + for ((sid, old), ids) in threads { + let Some(st) = self.stories.get_mut(&sid) else { continue }; + let st = Arc::make_mut(st); + let mut ids = ids.into_iter(); + for f in st.frames.iter_mut().filter(|f| **f == old) { + match ids.next() { + Some(id) => *f = id, + None => break, + } + } + st.frames.extend(ids); + } + } + /// Validate structural invariants (ids unique, threads consistent, stories well-formed). pub fn check(&self) -> Result<()> { for f in &self.styles.composite_fonts { diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 1adc43449..15156f8ad 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -251,6 +251,7 @@ fn load_zip(bytes: &[u8]) -> Result { upgrade(&mut doc, u32::try_from(version).unwrap_or(u32::MAX)); doc.merge_duplicate_assets(); doc.mark_differing_margins_local(); + doc.renumber_duplicate_items(); doc.check().map_err(|e| FormatError::NotOurs(e.to_string()))?; Ok(doc) } @@ -318,6 +319,7 @@ fn load_legacy_json(bytes: &[u8]) -> Result { upgrade(&mut doc, 1); doc.merge_duplicate_assets(); doc.mark_differing_margins_local(); + doc.renumber_duplicate_items(); doc.check().map_err(|e| FormatError::NotOurs(e.to_string()))?; Ok(doc) } diff --git a/crates/format/src/tests.rs b/crates/format/src/tests.rs index 981898a45..702428d14 100644 --- a/crates/format/src/tests.rs +++ b/crates/format/src/tests.rs @@ -734,3 +734,91 @@ fn too_many_entries_are_refused() { let Err(err) = load(&z.finish().unwrap().into_inner()) else { panic!("an archive with 100 001 entries loaded") }; assert!(err.to_string().contains("entries"), "{err}"); } + +/// Every item id in `d` (spreads, parents, anchored), in walk order. +fn all_item_ids(d: &Document) -> Vec { + let mut ids = Vec::new(); + for sp in d.spreads.iter().chain(d.parents.iter()) { + for it in &sp.items { + it.walk(&mut |i| ids.push(i.id.0)); + } + } + ids.extend(d.anchored_items().iter().map(|(_, i)| i.id.0)); + ids +} + +fn set_item_id(d: &mut Document, index: usize, id: designcraft_doc::ItemId) { + let sp = Arc::make_mut(&mut d.spreads[0]); + Arc::make_mut(&mut sp.items[index]).id = id; +} + +#[test] +fn files_with_duplicate_item_ids_open_with_unique_ids() { + let mut d = Document::new(&NewDocument::default()); + let one = png_asset(&mut d, &[1]); + let two = png_asset(&mut d, &[2]); + let a = place(&mut d, one, 0.0); + place(&mut d, two, 0.0); + set_item_id(&mut d, 1, a); + let back = load(&save(&d).unwrap()).unwrap(); + back.check().unwrap(); + let ids = all_item_ids(&back); + assert_eq!(ids.len(), 2); + assert_ne!(ids[0], ids[1]); + assert!(back.next_id >= ids[0].max(ids[1])); + let assets: Vec<_> = back.spreads[0].items.iter().map(|i| i.graphic().unwrap().asset).collect(); + assert_eq!(assets, vec![one, two]); + assert_eq!(back.item(a).and_then(|i| i.graphic()).map(|g| g.asset), Some(one)); +} + +#[test] +fn duplicate_text_frame_ids_keep_each_story_in_its_own_frame() { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let (a, sa) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 200.0, 200.0), lid, "first", ParaFormat::default()).unwrap(); + let (b, sb) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 210.0, 200.0, 400.0), lid, "second", ParaFormat::default()).unwrap(); + let (c, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(210.0, 210.0, 400.0, 400.0), lid, "", ParaFormat::default()).unwrap(); + d.thread(b, c).unwrap(); + // The second story's first frame carries the first frame's id. + set_item_id(&mut d, 1, a); + let st = d.story_mut(sb).unwrap(); + assert_eq!(st.frames, vec![b, c]); + st.frames[0] = a; + let back = load(&save(&d).unwrap()).unwrap(); + back.check().unwrap(); + let ids = all_item_ids(&back); + let unique: HashSet<_> = ids.iter().collect(); + assert_eq!(unique.len(), 3); + assert_eq!(back.stories[&sa].frames, vec![a]); + assert_eq!(back.stories[&sa].text, "first"); + let frames = &back.stories[&sb].frames; + assert_eq!(frames.len(), 2); + assert_ne!(frames[0], a); + assert_eq!(frames[1], c); + assert_eq!(back.item(frames[0]).and_then(|i| i.text_frame()).map(|t| t.story), Some(sb)); + assert_eq!(back.stories[&sb].text, "second"); +} + +#[test] +fn duplicate_anchored_item_ids_are_renumbered() { + use designcraft_doc::anchored::{AnchorPosition, AnchoredObject}; + use designcraft_doc::geom::shapes; + use designcraft_doc::{Item, Shape}; + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 200.0, 200.0), lid, "ab", ParaFormat::default()).unwrap(); + let asset = png_asset(&mut d, &[1]); + let g = place(&mut d, asset, 0.0); + let item = Item::new(g, lid, Shape::Oval, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0))); + d.story_mut(sid).unwrap().insert_object(1, AnchoredObject::new(item, AnchorPosition::default())); + let back = load(&save(&d).unwrap()).unwrap(); + back.check().unwrap(); + let ids = all_item_ids(&back); + assert_eq!(ids.len(), 3); + assert_eq!(ids.iter().collect::>().len(), 3); + assert_eq!(back.item(g).and_then(|i| i.graphic()).map(|g| g.asset), Some(asset)); + let anchored = back.anchored_items(); + assert_eq!(anchored.len(), 1); + assert_eq!(anchored[0].1.shape, Shape::Oval); + assert_ne!(anchored[0].1.id, g); +} From c51c8fb49da3c340181bed76de8b220f4ba9b308 Mon Sep 17 00:00:00 2001 From: ashokram-si <347905169+ashokram-si@users.noreply.github.com> Date: Wed, 28 Oct 2026 12:19:13 +0530 Subject: [PATCH 0307/1349] Canvas: a spine line where the pages of a spread meet (#1838) In a spread with two or more pages the paper is one rectangle and nothing marked where the pages meet. Draw a hairline at each shared page edge, the full height of the taller page, in the guides pass: it shows on screen only, hides with the other guides and in the preview modes, and exports never see it since the render crate draws no chrome. Tests: a three-page facing document gets one spine between pages 2 and 3 and none at outer edges; the line goes with guides off, in Preview and in Presentation. --- crates/ui-egui/src/canvas/page_decor.rs | 14 ++++- crates/ui-egui/src/canvas/tests.rs | 74 +++++++++++++++++++++++++ 2 files changed, 87 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/page_decor.rs b/crates/ui-egui/src/canvas/page_decor.rs index 11ce97dbf..90119659b 100644 --- a/crates/ui-egui/src/canvas/page_decor.rs +++ b/crates/ui-egui/src/canvas/page_decor.rs @@ -49,6 +49,7 @@ pub(super) fn draw_guides( let Some(sp) = doc.spread(slot.spread) else { continue }; if app.ui.guides { draw_bleed_and_slug(painter, xf, doc, slot, sp); + draw_spine(painter, xf, slot, sp, t); } let pasteboard = slot.xf.inverse().transform_rect_bbox(layout.pasteboard); for (pi, p) in sp.pages.iter().enumerate() { @@ -61,7 +62,6 @@ pub(super) fn draw_guides( draw_page_guides(painter, xf, doc, slot, sp, pi, p, pr, pasteboard, moving, &selection); } } - let _ = t; } /// The bleed and slug outlines of a spread, in their own colours. @@ -77,6 +77,18 @@ fn draw_bleed_and_slug(painter: &egui::Painter, xf: &Xf, doc: &Document, slot: & } } +/// The spine: a hairline where the pages of a spread meet, the full height of the taller page. +/// Screen only, like the other guides; the paper is one rectangle and exports never show a seam. +fn draw_spine(painter: &egui::Painter, xf: &Xf, slot: &SpreadSlot, sp: &designcraft_doc::Spread, t: &Tokens) { + let pt = |p: Point| xf.to_screen(slot.xf * p); + for pair in sp.pages.windows(2) { + let (a, b) = (pair[0].bounds(), pair[1].bounds()); + let x = (a.x1 + b.x0) / 2.0; + let (y0, y1) = (a.y0.min(b.y0), a.y1.max(b.y1)); + painter.line_segment([pt(Point::new(x, y0)), pt(Point::new(x, y1))], Stroke::new(hair(painter), t.text_dim)); + } +} + /// Page tool › Show Parent Page Overlay: the parent page's size over the page. fn draw_parent_overlay(painter: &egui::Painter, xf: &Xf, doc: &Document, slot: &SpreadSlot, pi: usize, p: &designcraft_doc::Page, pr: DRect) { let rect = |r: DRect| xf.rect(slot.xf.transform_rect_bbox(r)); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index ce68f3c12..cdb73f3c2 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -20,6 +20,80 @@ fn a_press_after_a_drag_is_not_a_double_click() { assert_eq!(press(Some(up), 0.0, 1.0), 1); } +/// The shapes the canvas paints for a new document, after two frames (the first lays out). +fn canvas_shapes(app: &mut DesignApp) -> Vec { + let ctx = egui::Context::default(); + let mut shapes = Vec::new(); + for _ in 0..2 { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + shapes = out.shapes; + } + shapes +} + +/// The spine-coloured vertical hairlines at screen x `x` that run the full height of `page` +/// (the spine of one spread shares its x with the pages of the spreads above and below it). +fn vertical_lines_at(shapes: &[egui::epaint::ClippedShape], x: f32, page: Rect) -> usize { + let spine = Tokens::get(&egui::Context::default()).text_dim; + shapes + .iter() + .filter(|c| match &c.shape { + egui::Shape::LineSegment { points: [a, b], stroke } => { + stroke.color == spine + && (a.x - x).abs() < 0.01 + && (b.x - x).abs() < 0.01 + && a.y.min(b.y) <= page.min.y + 0.01 + && a.y.max(b.y) >= page.max.y - 0.01 + } + _ => false, + }) + .count() +} + +#[test] +fn a_spread_shows_a_spine_line_between_its_pages() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", serde_json::json!({"pages": 3, "facingPages": true})).unwrap(); + let shapes = canvas_shapes(&mut app); + let st = app.session.active().unwrap(); + let layout = CanvasLayout::new(&st.doc, false); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + // One spine at each edge two pages of a spread share, the full page height, and none + // at the outer edges of a spread or around a page on a spread of its own. + let mut pairs = 0; + for (si, sp) in st.doc.spreads.iter().enumerate() { + let first = st.doc.first_page_of_spread(si); + let rects: Vec = (0..sp.pages.len()).map(|pi| xf.rect(layout.page_rect(&st.doc, first + pi).unwrap())).collect(); + for w in rects.windows(2) { + assert!((w[0].max.x - w[1].min.x).abs() < 0.01, "pages of a spread meet"); + assert_eq!(vertical_lines_at(&shapes, w[0].max.x, w[0]), 1, "spine in spread {si}"); + pairs += 1; + } + let (left, right) = (rects[0], rects[rects.len() - 1]); + assert_eq!(vertical_lines_at(&shapes, left.min.x, left), 0, "outer left edge of spread {si}"); + assert_eq!(vertical_lines_at(&shapes, right.max.x, right), 0, "outer right edge of spread {si}"); + } + assert!(pairs > 0, "the document has a spread with two pages"); +} + +#[test] +fn the_spine_line_hides_with_the_other_guides() { + for (guides, mode) in [(false, ScreenMode::Normal), (true, ScreenMode::Preview), (true, ScreenMode::Presentation)] { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", serde_json::json!({"pages": 3, "facingPages": true})).unwrap(); + app.ui.guides = guides; + app.ui.screen_mode = mode; + let shapes = canvas_shapes(&mut app); + let st = app.session.active().unwrap(); + let layout = CanvasLayout::new(&st.doc, false); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let left = xf.rect(layout.page_rect(&st.doc, 1).unwrap()); + assert_eq!(vertical_lines_at(&shapes, left.max.x, left), 0, "guides={guides} mode={mode:?}"); + } +} + /// While a page's render is on its way the page shows paper, not the black of its shadow. #[test] fn pages_show_paper_under_their_render() { From a30744fed11f45e1e80afbf822c436a7b71c731d Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 28 Oct 2026 11:53:56 +0500 Subject: [PATCH 0308/1349] Drop the unused ImageCache inspection methods `len` and `is_empty` were added for a test that ended up counting reads through `io::touched` instead, so they were dead code -- and the gate runs `cargo clippy --workspace --all-targets -- -D warnings`, which turns `dead_code` into a failure. Hosted CI was red on this PR. My local check had been `cargo clippy -p designcraft-engine --all-targets` without `-D warnings`, which is why I missed it; re-ran it the way the gate does. Found by the review bot, confirmed against the CI log. --- crates/engine/src/cmd/datamerge/fill.rs | 9 --------- 1 file changed, 9 deletions(-) diff --git a/crates/engine/src/cmd/datamerge/fill.rs b/crates/engine/src/cmd/datamerge/fill.rs index 965e87bd7..9b0a07c24 100644 --- a/crates/engine/src/cmd/datamerge/fill.rs +++ b/crates/engine/src/cmd/datamerge/fill.rs @@ -172,15 +172,6 @@ impl ImageCache { } Some(bytes) } - - /// How many distinct files this merge has read, for the tests. - pub fn len(&self) -> usize { - self.inner.borrow().files.len() - } - - pub fn is_empty(&self) -> bool { - self.len() == 0 - } } /// Replacements and hyperlinks collected while walking the placeholders of one record. From 88e71d0777175ef52898389b1c7cd6732eb0fc5a Mon Sep 17 00:00:00 2001 From: ashokram-si <347905169+ashokram-si@users.noreply.github.com> Date: Wed, 28 Oct 2026 12:54:59 +0530 Subject: [PATCH 0309/1349] Canvas: the spine follows the shared edge of a right-to-left spread Review follow-up: bound right to left, a spread lists its right page first, so averaging the first page's right edge with the second page's left edge put the line halfway between the outer edges when the pages differ in width. Order the two pages by position and use the edges that meet. Test: a right-to-left spread whose right page is narrower. --- crates/ui-egui/src/canvas/page_decor.rs | 5 ++++- crates/ui-egui/src/canvas/tests.rs | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/page_decor.rs b/crates/ui-egui/src/canvas/page_decor.rs index 90119659b..0271b4bcd 100644 --- a/crates/ui-egui/src/canvas/page_decor.rs +++ b/crates/ui-egui/src/canvas/page_decor.rs @@ -82,8 +82,11 @@ fn draw_bleed_and_slug(painter: &egui::Painter, xf: &Xf, doc: &Document, slot: & fn draw_spine(painter: &egui::Painter, xf: &Xf, slot: &SpreadSlot, sp: &designcraft_doc::Spread, t: &Tokens) { let pt = |p: Point| xf.to_screen(slot.xf * p); for pair in sp.pages.windows(2) { + // Bound right to left, a spread lists its right page first: take the two edges that + // meet, whichever page comes first. let (a, b) = (pair[0].bounds(), pair[1].bounds()); - let x = (a.x1 + b.x0) / 2.0; + let (left, right) = if a.x0 <= b.x0 { (a, b) } else { (b, a) }; + let x = (left.x1 + right.x0) / 2.0; let (y0, y1) = (a.y0.min(b.y0), a.y1.max(b.y1)); painter.line_segment([pt(Point::new(x, y0)), pt(Point::new(x, y1))], Stroke::new(hair(painter), t.text_dim)); } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index cdb73f3c2..584dd7ba5 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -78,6 +78,25 @@ fn a_spread_shows_a_spine_line_between_its_pages() { assert!(pairs > 0, "the document has a spread with two pages"); } +#[test] +fn the_spine_sits_where_the_pages_of_a_right_to_left_spread_meet() { + // Bound right to left, the spread lists its right page first. With pages of different + // widths, the line must be at their shared edge, not halfway between the outer ones. + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", serde_json::json!({"pages": 3, "facingPages": true})).unwrap(); + app.run("layout.documentSetup", serde_json::json!({"binding": "rightToLeft"})).unwrap(); + let w = app.session.active().unwrap().doc.settings.page_width; + app.run("layout.pageSize", serde_json::json!({"pages": [2], "width": w * 0.6})).unwrap(); + let shapes = canvas_shapes(&mut app); + let st = app.session.active().unwrap(); + let layout = CanvasLayout::new(&st.doc, false); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let (right, left) = (xf.rect(layout.page_rect(&st.doc, 1).unwrap()), xf.rect(layout.page_rect(&st.doc, 2).unwrap())); + assert!((left.max.x - right.min.x).abs() < 0.01, "page 3 is the left page, page 2 the right"); + assert!((left.width() - right.width()).abs() > 1.0, "the pages differ in width"); + assert_eq!(vertical_lines_at(&shapes, left.max.x, left), 1); +} + #[test] fn the_spine_line_hides_with_the_other_guides() { for (guides, mode) in [(false, ScreenMode::Normal), (true, ScreenMode::Preview), (true, ScreenMode::Presentation)] { From 5f5101a79159c7e4fd857b5ac1f6f3fbc7ea803b Mon Sep 17 00:00:00 2001 From: ashokram-si <347905169+ashokram-si@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:43:34 +0530 Subject: [PATCH 0310/1349] Canvas tests: the right-to-left spine test uses pages of different heights Review follow-up: the spine runs the height of the taller page. Make the narrower right page shorter too, so a line that stopped at the page listed first would fail the test. --- crates/ui-egui/src/canvas/tests.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 584dd7ba5..6e87b49ac 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -81,12 +81,14 @@ fn a_spread_shows_a_spine_line_between_its_pages() { #[test] fn the_spine_sits_where_the_pages_of_a_right_to_left_spread_meet() { // Bound right to left, the spread lists its right page first. With pages of different - // widths, the line must be at their shared edge, not halfway between the outer ones. + // sizes, the line must be at their shared edge, not halfway between the outer ones, and + // run the height of the taller page, not stop at the shorter one listed first. let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); app.run("file.new", serde_json::json!({"pages": 3, "facingPages": true})).unwrap(); app.run("layout.documentSetup", serde_json::json!({"binding": "rightToLeft"})).unwrap(); - let w = app.session.active().unwrap().doc.settings.page_width; - app.run("layout.pageSize", serde_json::json!({"pages": [2], "width": w * 0.6})).unwrap(); + let settings = &app.session.active().unwrap().doc.settings; + let (w, h) = (settings.page_width, settings.page_height); + app.run("layout.pageSize", serde_json::json!({"pages": [2], "width": w * 0.6, "height": h * 0.6})).unwrap(); let shapes = canvas_shapes(&mut app); let st = app.session.active().unwrap(); let layout = CanvasLayout::new(&st.doc, false); @@ -94,6 +96,7 @@ fn the_spine_sits_where_the_pages_of_a_right_to_left_spread_meet() { let (right, left) = (xf.rect(layout.page_rect(&st.doc, 1).unwrap()), xf.rect(layout.page_rect(&st.doc, 2).unwrap())); assert!((left.max.x - right.min.x).abs() < 0.01, "page 3 is the left page, page 2 the right"); assert!((left.width() - right.width()).abs() > 1.0, "the pages differ in width"); + assert!(left.height() - right.height() > 1.0, "page 3 is the taller page"); assert_eq!(vertical_lines_at(&shapes, left.max.x, left), 1); } From 0c9e59c0090a82437936f8fa3f98b43e18d3bc7f Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 28 Oct 2026 15:15:15 +0500 Subject: [PATCH 0311/1349] Fonts: do not read a requested style off the face that stands in for it Review of #1755 caught a real over-reach in my own patch. When a family cannot be resolved, db.face hands back a bundled face, and I was reading "Sans" out of its name: FALLBACK_FAMILY is "Source Sans 3", so every unclassified missing font took the sans chain -- picking Malgun Gothic on Windows over the Batang fallback that was already there. DEFAULT_FAMILY, "Source Serif 4", would have forced the other way. A stand-in face says nothing about what the document asked for, so style_of_substitute returns None for both and only a face that really names itself gets a vote. The test pins both families by their constants; with the old body it fails with Some(true) against None. --- crates/compose/src/shape.rs | 41 +++++++++++++++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs index 6c9aca4d3..87f697e56 100644 --- a/crates/compose/src/shape.rs +++ b/crates/compose/src/shape.rs @@ -317,6 +317,20 @@ impl StyleTable<'_> { } } +/// What a substitute face's own name says about its style, for choosing a CJK fallback chain. +/// +/// `None` for the bundled default and last-resort families: they stand in for a font that could +/// not be resolved at all, so their names say nothing about what the document asked for. Without +/// this, "Source Sans 3" made every unresolved family look like a sans one (#1692, noted in +/// review). +fn style_of_substitute(family: &str) -> Option { + let standin = [designcraft_fonts::DEFAULT_FAMILY, designcraft_fonts::FALLBACK_FAMILY]; + if standin.iter().any(|s| s.eq_ignore_ascii_case(family)) { + return None; + } + designcraft_fonts::sans_by_name(family) +} + /// Resolve and shape one paragraph. Its drop cap ends at byte `drop.0` (`range.start` without /// one) and takes the character style `drop.1` ("" = none). pub(crate) fn shape_para( @@ -787,7 +801,10 @@ fn shape_run_raw( // A missing Korean face is replaced by one of its own style: the requested name says whether // it was Dotum/Gothic or Batang/Myungjo, and if it does not, the substitute's own name does, // which keeps today's chain (#1692). - let prefer_sans = designcraft_fonts::sans_by_name(&p.font_family).or_else(|| designcraft_fonts::sans_by_name(&primary.family)); + // The substitute's own name is consulted only when it is a real substitute: a requested + // family that resolves to nothing comes back as the bundled default, whose name holds "Sans", + // and every unclassified missing font would then have taken the sans chain (noted in review). + let prefer_sans = designcraft_fonts::sans_by_name(&p.font_family).or_else(|| style_of_substitute(&primary.family)); let fallback = |c: char| { if auto_leading.glyph_fallback { db.fallback_for_styled(c, primary.id(), lang, prefer_sans).unwrap_or_else(|| primary.clone()) @@ -1124,7 +1141,7 @@ fn shape_segment( let lang = designcraft_doc::language_tag(&p.language); let mut segments: Vec<(usize, usize, Arc)> = Vec::new(); for (at, c) in label.char_indices() { - let prefer_sans = designcraft_fonts::sans_by_name(&p.font_family).or_else(|| designcraft_fonts::sans_by_name(&face.family)); + let prefer_sans = designcraft_fonts::sans_by_name(&p.font_family).or_else(|| style_of_substitute(&face.family)); let selected = if face.covers(c) { face.clone() } else { db.fallback_for_styled(c, face.id(), lang, prefer_sans).unwrap_or_else(|| face.clone()) }; if let Some((_, end, previous)) = segments.last_mut().filter(|(_, _, previous)| previous.id() == selected.id()) { @@ -1405,3 +1422,23 @@ fn digit_mode(p: &designcraft_doc::CharProps, arabic_context: Option) -> d _ => Digits::Native, } } + +#[cfg(test)] +mod style_of_substitute_tests { + use super::style_of_substitute; + + /// A face that stands in for a font that could not be resolved says nothing about the style + /// the document asked for. `FALLBACK_FAMILY` is "Source Sans 3" and `DEFAULT_FAMILY` is + /// "Source Serif 4", so reading their names would have forced the sans chain on every + /// unresolved family -- and the serif one on the other (#1692, noted in review). + #[test] + fn a_stand_in_face_says_nothing_about_the_requested_style() { + assert_eq!(style_of_substitute(designcraft_fonts::FALLBACK_FAMILY), None); + assert_eq!(style_of_substitute(designcraft_fonts::DEFAULT_FAMILY), None); + assert_eq!(style_of_substitute("source sans 3"), None, "however it is spelled"); + // A real substitute still speaks for itself. + assert_eq!(style_of_substitute("Malgun Gothic"), Some(true)); + assert_eq!(style_of_substitute("Batang"), Some(false)); + assert_eq!(style_of_substitute("Helvetica"), None, "a name that says neither"); + } +} From 8444abfbca2d6d666b1629e4a9255fd5ddb56220 Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 28 Oct 2026 15:18:58 +0500 Subject: [PATCH 0312/1349] Fonts: "sans serif" is a sans name, not a serif one Review pointed out that the CSS generic "sans-serif" matched the bare "serif" needle first and classified as serif. The same ordering hit real family names: "Microsoft Sans Serif", "MS Sans Serif" and "Lucida Sans Serif" are sans faces that a Word import can name, and epub's own generic_family already maps Microsoft Sans Serif to sans-serif. So rather than special-casing the one hyphenated spelling, the bare "serif" word now sorts after the sans needles. The Korean serif names stay ahead of everything, which is what keeps "Noto Sans Myungjo" and "Myungjo Gothic" serif; the test pins those two along with both "sans serif" spellings. --- crates/fonts/src/fontdb/fallback.rs | 11 ++++++++--- crates/fonts/src/fontdb/tests/fallback.rs | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/crates/fonts/src/fontdb/fallback.rs b/crates/fonts/src/fontdb/fallback.rs index ad8acc538..13afffd07 100644 --- a/crates/fonts/src/fontdb/fallback.rs +++ b/crates/fonts/src/fontdb/fallback.rs @@ -118,9 +118,9 @@ pub(super) const KOREAN_SANS_FALLBACKS: &[&str] = &[ pub fn sans_by_name(family: &str) -> Option { let lower = family.to_lowercase(); let has = |needles: &[&str]| needles.iter().any(|n| lower.contains(n)); - // Serif first: "Myungjo Gothic" does not exist, but a name holding both reads as the serif - // it names, and "Sans" inside "Noto Sans Myungjo" would otherwise win. - if has(&["batang", "myungjo", "myeongjo", "gungsuh", "serif", "\u{BC14}\u{D5D5}", "\u{BA85}\u{C870}", "\u{AD81}\u{C11C}"]) { + // A Korean serif name comes first: "Myungjo Gothic" does not exist, but a name holding both + // reads as the serif it names, and "Sans" inside "Noto Sans Myungjo" would otherwise win. + if has(&["batang", "myungjo", "myeongjo", "gungsuh", "\u{BC14}\u{D5D5}", "\u{BA85}\u{C870}", "\u{AD81}\u{C11C}"]) { return Some(false); } if has(&[ @@ -138,6 +138,11 @@ pub fn sans_by_name(family: &str) -> Option { ]) { return Some(true); } + // Only now the bare word, which "sans serif" and "sans-serif" end with and do not mean + // (noted in review): "Microsoft Sans Serif" is a sans face, and so is the CSS generic. + if lower.contains("serif") { + return Some(false); + } None } diff --git a/crates/fonts/src/fontdb/tests/fallback.rs b/crates/fonts/src/fontdb/tests/fallback.rs index d385a8fd9..d9a5ee71c 100644 --- a/crates/fonts/src/fontdb/tests/fallback.rs +++ b/crates/fonts/src/fontdb/tests/fallback.rs @@ -176,6 +176,26 @@ fn a_korean_family_name_says_sans_or_serif() { } } +/// "sans serif" ends with the word it is not. The bare "serif" needle matched first, so +/// "Microsoft Sans Serif" -- and the CSS generic -- classified as serif and a missing Hangul +/// glyph took the serif-first chain (noted in review of #1692). +#[test] +fn a_sans_serif_name_is_not_read_as_serif() { + for sans in ["sans-serif", "Microsoft Sans Serif", "MS Sans Serif", "Lucida Sans Serif"] { + assert_eq!(sans_by_name(sans), Some(true), "{sans} is sans"); + } + // The bare word still decides a name that holds nothing else. + for serif in ["serif", "Source Serif 4", "DejaVu Serif", "Noto Serif KR"] { + assert_eq!(sans_by_name(serif), Some(false), "{serif} is serif"); + } + // And a Korean serif name still outranks "Sans", which is why it is tested first of all. + assert_eq!(sans_by_name("Noto Sans Myungjo"), Some(false)); + assert_eq!(sans_by_name("Myungjo Gothic"), Some(false)); + // Neither word present, so the caller still decides. + assert_eq!(sans_by_name("monospace"), None); + assert_eq!(sans_by_name("system-ui"), None); +} + /// The reported bug is the order of the chain: on Windows the first installed entry of the /// serif-first chain is Batang, so every missing Dotum face came out serif (#1692). #[test] From 4ac4219fd24361fc240382a479a7171007b45a70 Mon Sep 17 00:00:00 2001 From: garrytan Date: Wed, 28 Oct 2026 10:23:57 +0000 Subject: [PATCH 0313/1349] compose: settle a story's own anchored wraps by object count, not 4 passes A story whose custom or above-line anchored objects wrap its own later lines is composed first without those wraps, then again with each object where the previous pass placed it. That loop stopped after a fixed MAX_PASSES = 4 extra compositions. Each object's wrap pushes down the anchors of the objects after it, so in a chain of such objects the k-th object only lands where it belongs once the k - 1 wraps before it are in place. From roughly the fifth chained object on, the loop ran out before the story settled: the final composition placed the object in one spot but wrapped the text around where an earlier pass had put it, and lines printed straight over the object. Bound the loop by the story's own wrapping objects instead: n + 1 passes for n such objects (inline objects never wrap their own story and are left out). Composition 0 has no own wraps, so object 1 is already where it belongs; by induction pass k places object k + 1 correctly, pass n places the last one, and pass n + 1 wraps the text around it, after which the positions cannot move. The existing settled check still stops a story early as soon as its objects stop moving, so stories that settle sooner cost nothing extra. MAX_PASSES stays as an absolute safety net, raised to 64, for layouts that keep moving their objects (keep options, vertical justification) and for stories with very many anchored objects. Test: chained_anchored_objects_all_wrap_their_own_storys_lines anchors eight 100 x 60 pt bounding-box objects six lines apart in one story, each hanging from its anchor line, and checks that every object sits on its anchor line and every line it hangs over moves clear of it. Without this change it fails at the seventh object (a line 790 pt down sits at x 0 inside the object's band at 718 pt); with it, it passes. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- crates/compose/src/tests.rs | 38 +++++++++++++++++++++++++++++++++++++ crates/compose/src/wrap.rs | 15 ++++++++++----- 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 3083261fb..aafef67e3 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -7155,6 +7155,44 @@ fn anchored_object_wraps_its_own_storys_later_lines() { assert!((o.origin.y - top).abs() < 1e-6); } +/// Each object's wrap pushes the anchors after it down, so where each object lands depends on the +/// wraps of all those before it; every object still ends up wrapping the lines it hangs over. +#[test] +fn chained_anchored_objects_all_wrap_their_own_storys_lines() { + const OBJECTS: usize = 8; + let text = [LOREM; 12].join(" "); + let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 3000.0), ParaAttrs::default()); + let plain = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&plain); + assert!(lines.len() > 2 + 6 * OBJECTS); + let left = lines[0].x0; + // One object every six lines, each hanging from its anchor's baseline over the lines below; + // inserted last first so the earlier offsets still hold. + let ats: Vec = (0..OBJECTS).map(|k| lines[2 + 6 * k].range.start + 3).collect(); + for &at in ats.iter().rev() { + anchor_box(&mut d, sid, at, 0.0, 0.0, true, WrapMode::BoundingBox); + } + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + let lines = all_lines(&cs); + let anchors: Vec = d.story(sid).unwrap().text.match_indices(designcraft_doc::OBJECT_MARK).map(|(i, _)| i).collect(); + let objects = &cs.frames[0].objects; + assert_eq!(objects.len(), OBJECTS); + for o in objects { + let anchor_line = lines.iter().find(|l| l.range.contains(&anchors[o.index])).unwrap(); + assert!((o.origin.y - anchor_line.baseline).abs() < 1e-6, "object {} at {}, anchor line at {}", o.index, o.origin.y, anchor_line.baseline); + let under = lines_in_band(&cs, o.origin.y, o.origin.y + 60.0); + assert!(under.len() >= 2); + assert!( + under.iter().all(|l| l.x0 >= left + 100.0 - 1e-6), + "object {} at {}: {:?}", + o.index, + o.origin.y, + under.iter().map(|l| (l.baseline, l.x0)).collect::>() + ); + } +} + #[test] fn anchored_object_without_wrap_leaves_layout_unchanged() { let long = [LOREM; 3].join(" "); diff --git a/crates/compose/src/wrap.rs b/crates/compose/src/wrap.rs index e1cdc5fa7..7d38f0ef8 100644 --- a/crates/compose/src/wrap.rs +++ b/crates/compose/src/wrap.rs @@ -12,16 +12,20 @@ //! that come after the line holding its anchor; that line and the lines before it are never //! wrapped by it (an inline object sits in its line and wraps none of its own story). The story //! is composed again with the objects where the previous pass placed them until they stop -//! moving, at most [`MAX_PASSES`] more times. +//! moving. An object's wrap can push the anchors of the objects after it, so a chain of n such +//! objects needs n + 1 more compositions: the k-th pass places the (k + 1)-th object where the +//! wraps before it leave its anchor, and the last pass wraps around the last object. The story +//! is composed at most that many more times, and never more than [`MAX_PASSES`]. use designcraft_doc::{AnchorPosition, AnchoredObject, Document, Item, OBJECT_MARK, PageSide, SpreadRef, Story, StoryId, WrapMode}; use designcraft_geom::Affine; use crate::{ComposeOptions, ComposedStory, Exclusion, FrameSpec}; -/// Extra compositions of a story with its own anchored objects' wrap; a layout that keeps moving -/// its objects (keep options, vertical justification) stops here. -pub(crate) const MAX_PASSES: usize = 4; +/// Most extra compositions of a story with its own anchored objects' wrap, however many objects +/// it has; a layout that keeps moving its objects (keep options, vertical justification) stops +/// sooner, after one per object and one more. +pub(crate) const MAX_PASSES: usize = 64; /// How far an obstacle may move between passes and still count as settled (points). const SETTLED: f64 = 0.01; @@ -199,8 +203,9 @@ pub(crate) fn compose_among(doc: &Document, sid: StoryId, opts: &ComposeOptions, if !has_wrapping_objects(st) { return out; } + let own = st.objects.iter().filter(|o| wraps(o) && !matches!(o.position, AnchorPosition::Inline { .. })).count(); let mut prev = vec![Vec::new(); specs.len()]; - for _ in 0..MAX_PASSES { + for _ in 0..(own + 1).min(MAX_PASSES) { let added = exclusions(doc, &specs, &obstacles(doc, st, &out, true)); if settled(&added, &prev) { break; From ff35b3561fab711c9580ffd7fdf146779eac7ea1 Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 28 Oct 2026 15:33:12 +0500 Subject: [PATCH 0314/1349] Data merge: an extended-length drive path is a local file, not a refusal Review caught a wrong assertion in my own test. `\\?\C:\x` is the extended-length spelling of `C:\x`: craft-docpath parses it as Root::VerbatimDrive, is_absolute, and its own suite classifies it PathKind::Local. The test asserted it was refused, so it would have failed on Windows -- the one platform it runs on. A data file can already name C:\secret\x.png, so refusing the long spelling would have shut out long paths without shutting anything out. It is now asserted the other way, and the refusal list keeps a device path in its place. Each shape was checked against the pinned craft-docpath through resolve(), which recognises Windows forms on every platform, so the verdicts are first-hand and not read off the source: Network for the extended UNC prefix, Device for \\.\pipe, GLOBALROOT, CON and NUL.png, and Ok for \\?\C:\secret\x.png. --- crates/engine/src/cmd/datamerge/fill.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/datamerge/fill.rs b/crates/engine/src/cmd/datamerge/fill.rs index f522065ba..5b9a5a92d 100644 --- a/crates/engine/src/cmd/datamerge/fill.rs +++ b/crates/engine/src/cmd/datamerge/fill.rs @@ -545,16 +545,28 @@ mod image_path_tests { } /// The Windows shapes `craft-docpath` refuses, asserted where they have meaning: the extended - /// UNC prefix, a device namespace path, and a legacy device name. + /// UNC prefix, a device namespace path, and a legacy device name (with an extension, since a + /// reserved name is reserved whatever follows it). #[cfg(windows)] #[test] - fn windows_device_and_extended_paths_are_refused() { + fn windows_device_and_network_paths_are_refused() { let (data, doc) = (Path::new(r"C:\work\data"), Path::new(r"C:\work\doc")); - for cell in [r"\\?\UNC\192.0.2.1\share\x.png", r"\\.\pipe\x", r"\\?\C:\secret\x.png", "CON", "NUL.png"] { + for cell in [r"\\?\UNC\192.0.2.1\share\x.png", r"\\.\pipe\x", r"\\?\GLOBALROOT\Device\HarddiskVolume1\x", "CON", "NUL.png"] { assert!(image_candidates(cell, Some(data), Some(doc)).is_empty(), "{cell}"); } } + /// An extended-length path is not one of them: `\\?\C:\x` names a local file, the same one + /// `C:\x` names, and `craft-docpath`'s own suite classifies it `PathKind::Local`. A data file + /// could already give the plain spelling, so refusing this one would shut out long paths + /// without shutting anything out (noted in review). + #[cfg(windows)] + #[test] + fn an_extended_length_drive_path_is_a_local_file() { + let (data, doc) = (Path::new(r"C:\work\data"), Path::new(r"C:\work\doc")); + assert!(!image_candidates(r"\\?\C:\secret\x.png", Some(data), Some(doc)).is_empty()); + } + /// Resolution beside the data and the document, with absolute paths this platform means. #[cfg(unix)] #[test] From 0d16a040388d5b5ec1d062eeec0b07021fc31055 Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 28 Oct 2026 15:53:44 +0500 Subject: [PATCH 0315/1349] Fonts: the word "serif" outranks every sans indicator My own previous commit introduced this: moving the bare "serif" needle after the sans list to let "Microsoft Sans Serif" read as sans also let "gothic" win in "Sweet Gothic Serif", a real serif family, which review caught. The rule is narrower than either ordering. A name holding "serif" is serif, and that outranks the sans indicators; the only exception is the phrase it ends: "sans serif" and "sans-serif" are the name of a sans face. So the phrase is removed before the word is looked for, which keeps both spellings sans and gives every explicitly serif name back. Korean serif names stay ahead of all of it, so "Noto Sans Myungjo" and "Myungjo Gothic" are unchanged. --- crates/fonts/src/fontdb/fallback.rs | 11 ++++++----- crates/fonts/src/fontdb/tests/fallback.rs | 5 +++++ 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/fonts/src/fontdb/fallback.rs b/crates/fonts/src/fontdb/fallback.rs index 13afffd07..0b68f9c7c 100644 --- a/crates/fonts/src/fontdb/fallback.rs +++ b/crates/fonts/src/fontdb/fallback.rs @@ -123,6 +123,12 @@ pub fn sans_by_name(family: &str) -> Option { if has(&["batang", "myungjo", "myeongjo", "gungsuh", "\u{BC14}\u{D5D5}", "\u{BA85}\u{C870}", "\u{AD81}\u{C11C}"]) { return Some(false); } + // Then the word itself, which outranks every sans indicator: "Sweet Gothic Serif" is a serif + // family whatever "Gothic" suggests. "Sans serif" and "sans-serif" end with the word and do + // not mean it, so the phrase goes before the word is looked for (both noted in review). + if lower.replace("sans-serif", "sans").replace("sans serif", "sans").contains("serif") { + return Some(false); + } if has(&[ "dotum", "gothic", @@ -138,11 +144,6 @@ pub fn sans_by_name(family: &str) -> Option { ]) { return Some(true); } - // Only now the bare word, which "sans serif" and "sans-serif" end with and do not mean - // (noted in review): "Microsoft Sans Serif" is a sans face, and so is the CSS generic. - if lower.contains("serif") { - return Some(false); - } None } diff --git a/crates/fonts/src/fontdb/tests/fallback.rs b/crates/fonts/src/fontdb/tests/fallback.rs index d9a5ee71c..798443524 100644 --- a/crates/fonts/src/fontdb/tests/fallback.rs +++ b/crates/fonts/src/fontdb/tests/fallback.rs @@ -191,6 +191,11 @@ fn a_sans_serif_name_is_not_read_as_serif() { // And a Korean serif name still outranks "Sans", which is why it is tested first of all. assert_eq!(sans_by_name("Noto Sans Myungjo"), Some(false)); assert_eq!(sans_by_name("Myungjo Gothic"), Some(false)); + // And the word outranks every sans indicator: Sweet Gothic Serif is a serif family + // whatever "Gothic" suggests (noted in review). + for serif in ["Sweet Gothic Serif", "Gothic Serif", "Sans Forgetica Serif"] { + assert_eq!(sans_by_name(serif), Some(false), "{serif} names itself serif"); + } // Neither word present, so the caller still decides. assert_eq!(sans_by_name("monospace"), None); assert_eq!(sans_by_name("system-ui"), None); From b49535624c6b6b6a6ca87f35c207a9a2ddb66951 Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 28 Oct 2026 16:26:13 +0500 Subject: [PATCH 0316/1349] Tables: a shape a table cannot hold is clamped, not allocated (#1583) `Table::new` allocates `rows * cols` cells up front, and the counts reach it from IDML and DOCX, where they are whatever the file claims. Measured here: `size_of::()` is 1,360 bytes, so the reported IDML case -- one `` with 5,000 `` and 5,000 ``, about 1 KB zipped -- asks for 25M cells, some 34 GB. That allocation does not fail politely: it aborts the process through `handle_alloc_error`, which no `catch_unwind` can catch, so every open document's unsaved work goes with it. A table is clamped to InDesign's own limits, 10,000 rows and 1,000 columns, and to 250,000 cells whatever its shape -- the row and column limits alone would still allow 13.6 GB. Columns are clamped first and rows take what is left, because a table is far more often long than wide. The IDML importer walks the clamped slices and reports the difference. Indexing its rows and columns by the file's own counts would be out of bounds, which is how a 34 GB abort would otherwise have become a panic. Rebased onto the post-split main: the constants and `clamped_size` live in `doc`'s `table` module root, `Table::new` in `table/grid.rs`, and the IDML table reader in `import/table.rs`. --- crates/doc/src/table.rs | 68 +++++++++++++++++++++++++++++++++ crates/doc/src/table/grid.rs | 10 ++++- crates/idml/src/import/table.rs | 17 ++++++++- 3 files changed, 92 insertions(+), 3 deletions(-) diff --git a/crates/doc/src/table.rs b/crates/doc/src/table.rs index d5342b5c9..937fefe1f 100644 --- a/crates/doc/src/table.rs +++ b/crates/doc/src/table.rs @@ -25,6 +25,32 @@ mod story; pub use cell::{AltFills, AltStrokes, Cell, CellStroke, Column, Row, RowHeightMode, RowKind, TableOptions}; pub use grid::CellRange; +/// Most rows a table holds, as InDesign allows. +pub const MAX_TABLE_ROWS: usize = 10_000; +/// Most columns a table holds, as InDesign allows. +pub const MAX_TABLE_COLS: usize = 1_000; +/// Most cells a table holds, whatever its shape. +/// +/// A [`Cell`] is about 1.4 KB (it carries a [`Story`]), so this is roughly 340 MB of cells at the +/// limit. The row and column limits alone are not enough: 10,000 × 1,000 would be 13.6 GB, and an +/// IDML story holding one `
` with 5,000 `` and 5,000 `` -- about 1 KB +/// zipped -- asked for 25M cells, some 34 GB. That allocation does not fail politely: it aborts +/// the process through `handle_alloc_error`, which no `catch_unwind` can save, so every open +/// document's unsaved work goes with it (#1583). +pub const MAX_TABLE_CELLS: usize = 250_000; + +/// The rows and columns a table of `rows × cols` is actually given, inside the limits above. +/// +/// Columns are clamped first and rows take what is left of the cell budget, because a table is +/// far more often long than wide: truncating a 5,000-column table to 1,000 columns and then its +/// rows loses less of it than the other way round. Callers that read a file report the +/// difference; the counts are a document's claim, not something to trust. +pub fn clamped_size(rows: usize, cols: usize) -> (usize, usize) { + let cols = cols.clamp(1, MAX_TABLE_COLS); + let rows = rows.clamp(1, MAX_TABLE_ROWS.min(MAX_TABLE_CELLS / cols).max(1)); + (rows, cols) +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Table { @@ -48,6 +74,48 @@ mod tests { Story::with_text(StoryId(1), t, ParaFormat::default()) } + /// A table's shape comes out of IDML and DOCX files unchecked, and `Cell` is about 1.4 KB, so + /// a file claiming 5,000 x 5,000 asked for 25M cells -- some 34 GB. That allocation aborts the + /// process rather than failing, taking every open document's unsaved work with it (#1583). + #[test] + fn a_table_larger_than_the_limits_is_clamped_not_allocated() { + // The reported shape: 5,000 rows and 5,000 columns. + let t = Table::new(1, 5_000, 5_000, 0, 0, 500.0); + assert_eq!(t.columns.len(), MAX_TABLE_COLS, "columns are clamped to InDesign's limit"); + assert!(t.cells.len() <= MAX_TABLE_CELLS, "{} cells is within the budget", t.cells.len()); + assert_eq!(t.rows.len() * t.columns.len(), t.cells.len(), "the grid stays rectangular"); + // What it would have been: 25,000,000 cells at 1,360 bytes each. + assert!(25_000_000 * std::mem::size_of::() > 30_000_000_000, "the size this test is about"); + // Freed before the next large table, so the peak stays at one of them. + drop(t); + + // A long table keeps its rows while it fits the budget (the budget itself is checked by + // `clamped_size`, which allocates nothing). + let long = Table::new(2, 10_000, 5, 0, 0, 500.0); + assert_eq!((long.rows.len(), long.columns.len()), (10_000, 5), "a long thin table is untouched"); + assert_eq!(clamped_size(10_000, 25), (10_000, 25), "10,000 x 25 is inside the budget"); + drop(long); + + // Past the row limit the rows are clamped too. + let longer = Table::new(3, 50_000, 2, 0, 0, 100.0); + assert_eq!(longer.rows.len(), MAX_TABLE_ROWS, "rows are clamped to InDesign's limit"); + drop(longer); + + // Header, body and footer share the budget, and the table still has a body. + let with_parts = Table::new(4, 5_000, 5_000, 3, 2, 500.0); + assert!(with_parts.rows.len() <= MAX_TABLE_ROWS, "{} rows", with_parts.rows.len()); + assert!(with_parts.cells.len() <= MAX_TABLE_CELLS, "{} cells", with_parts.cells.len()); + assert!(with_parts.rows.iter().any(|r| r.kind == RowKind::Header), "the header survives"); + assert!(with_parts.rows.iter().any(|r| r.kind == RowKind::Footer), "the footer survives"); + assert!(with_parts.rows.iter().any(|r| r.kind == RowKind::Body), "and so does a body row"); + drop(with_parts); + + // A header and footer bigger than the whole budget still leave a body row. + let all_header = Table::new(6, 1, 1, MAX_TABLE_ROWS * 2, MAX_TABLE_ROWS * 2, 100.0); + assert!(all_header.rows.len() <= MAX_TABLE_ROWS, "{} rows", all_header.rows.len()); + assert!(all_header.rows.iter().any(|r| r.kind == RowKind::Body), "a body row survives"); + } + #[test] fn move_row_keeps_header_and_footer_rows_in_place() { let mut t = Table::new(1, 3, 2, 1, 1, 120.0); diff --git a/crates/doc/src/table/grid.rs b/crates/doc/src/table/grid.rs index 48647cffc..f93379231 100644 --- a/crates/doc/src/table/grid.rs +++ b/crates/doc/src/table/grid.rs @@ -25,8 +25,16 @@ impl CellRange { impl Table { /// A `rows × cols` table (`header` + body + `footer` rows) whose columns share `width`. + /// + /// The shape is clamped to [`clamped_size`](super::clamped_size): the counts reach this from + /// IDML and DOCX files, where they are whatever the file says (#1583). pub fn new(id: u64, body_rows: usize, cols: usize, header: usize, footer: usize, width: f64) -> Table { - let cols = cols.max(1); + // Header, body and footer rows share one budget: the total is clamped first, then the + // header and footer take what they can of it, and the body keeps at least one row. + let (total, cols) = super::clamped_size(body_rows.max(1).saturating_add(header).saturating_add(footer), cols); + let header = header.min(total.saturating_sub(1)); + let footer = footer.min(total.saturating_sub(header).saturating_sub(1)); + let body_rows = total.saturating_sub(header).saturating_sub(footer).max(1); let mut rows = Vec::new(); rows.extend((0..header).map(|_| Row { kind: RowKind::Header, ..Default::default() })); rows.extend((0..body_rows.max(1)).map(|_| Row::default())); diff --git a/crates/idml/src/import/table.rs b/crates/idml/src/import/table.rs index 5e5a8685d..9bf0f920f 100644 --- a/crates/idml/src/import/table.rs +++ b/crates/idml/src/import/table.rs @@ -25,8 +25,21 @@ impl<'r> Importer<'r> { let id = self.alloc(); let rows: Vec<&El> = e.find_all("Row").collect(); let cols: Vec<&El> = e.find_all("Column").collect(); - let nr = rows.len().max(1); - let nc = cols.len().max(1); + // A file's row and column counts are its claim, and a table of them is allocated whole: a + // story holding one `
` with 5,000 of each asked for 25M cells, around 34 GB, which + // aborts the process instead of failing (#1583). What is read is clamped, and the rest of + // this function walks the clamped slices -- indexing `t.rows`/`t.columns` by the file's + // own counts would be out of bounds. + let (nr, nc) = designcraft_doc::table::clamped_size(rows.len().max(1), cols.len().max(1)); + if nr < rows.len() || nc < cols.len() { + self.warnings.push(format!( + "a table of {} rows and {} columns was read as {nr} x {nc}: more than a table can hold", + rows.len(), + cols.len() + )); + } + let rows = &rows[..nr.min(rows.len())]; + let cols = &cols[..nc.min(cols.len())]; let mut t = Table::new(id, nr, nc, 0, 0, 0.0); t.options.direction = if e.get("TableDirection") == Some("RightToLeftDirection") { designcraft_doc::TextDirection::RightToLeft From 1995fb5feb1b46e76fe76d6cc77635c42963b092 Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 28 Oct 2026 16:31:34 +0500 Subject: [PATCH 0317/1349] IDML import: the tables in one file are capped between them Review pointed out that capping each table leaves a file free to hold many capped tables: three at the per-table limit claim 750,000 cells, about 1 GB of Cell, with every table inside its own limit. The package reader's limits count input bytes, which say nothing about how many cells a row and column count claim. budgeted_size clamps each table against what the import has left, and the cells are reserved before Table::new so a cell's own story cannot spend the budget the table around it is counting on. The budget is 400,000 cells: a Cell carries a whole story and is 1,360 bytes, so that is about the 512 MiB one part of the file may already decompress to, and the same count the spreadsheet importer collects at most. A table is never read as nothing. One row and one column are kept, so the table stays in the document and still says where its text went, and a file pays one cell for a table it really does contain -- which its own size already bounds. The warning says which limit cut the table down. The arithmetic is tested rather than the allocation: 400,000 cells is 544 MB and three such tables are not a thing to ask CI to allocate. The sequence test runs 32 claimed sizes, including usize::MAX, and holds the invariant across all of them. --- crates/idml/src/import.rs | 4 ++ crates/idml/src/import/table.rs | 91 ++++++++++++++++++++++++++++++--- 2 files changed, 89 insertions(+), 6 deletions(-) diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs index 73bed14d3..c8e0512b5 100644 --- a/crates/idml/src/import.rs +++ b/crates/idml/src/import.rs @@ -139,6 +139,9 @@ struct Importer<'r> { /// Graphic `Self` → stand-in image for a linked file that can't be read. previews: &'r HashMap>>, next_id: u64, + /// Cells every table in this import has reserved. One table is capped, but a file chooses + /// how many tables it has, so the cap has to be document-wide as well (noted in review). + table_cells: usize, settings: DocSettings, default_margins: Option<(Margins, Columns)>, swatches: Vec, @@ -225,6 +228,7 @@ impl<'r> Importer<'r> { read_link, previews, next_id: 0, + table_cells: 0, settings: DocSettings::default(), default_margins: None, swatches: specials, diff --git a/crates/idml/src/import/table.rs b/crates/idml/src/import/table.rs index 9bf0f920f..3b1051b66 100644 --- a/crates/idml/src/import/table.rs +++ b/crates/idml/src/import/table.rs @@ -1,6 +1,30 @@ use super::values::{span, tint}; use super::*; +/// Cells every table in one import may hold between them. A `Cell` carries a whole story, so +/// it is 1,360 bytes: 400,000 of them is about 520 MB, which is the 512 MiB the package reader +/// already allows one part of the file to decompress to, and the same count the spreadsheet +/// importer collects at most. +const MAX_IMPORT_TABLE_CELLS: usize = 400_000; + +/// How large a table of `rows` x `cols` may be read when `reserved` cells have already been +/// taken, and whether the file-wide budget is what cut it down. +/// +/// The per-table cap leaves a file free to hold many capped tables, so each is also clamped +/// against what is left. One row and one column are always kept: the table is then still in the +/// document, still says where its text went, and a file pays one cell for a table it really +/// does contain -- which its own size already bounds. +fn budgeted_size(rows: usize, cols: usize, reserved: usize) -> (usize, usize, bool) { + let (mut nr, mut nc) = designcraft_doc::table::clamped_size(rows, cols); + let left = MAX_IMPORT_TABLE_CELLS.saturating_sub(reserved); + let over_budget = nr.saturating_mul(nc) > left; + if over_budget { + nc = nc.min(left.max(1)); + nr = nr.min((left / nc).max(1)); + } + (nr, nc, over_budget) +} + /// Preserve the legacy uniform field only when all four sides explicitly specify every /// property. Partial records must stay sparse so they can inherit from a parent style. pub(super) fn uniform_cell_stroke(edges: &[designcraft_doc::CellStrokeAttrs; 4]) -> Option { @@ -30,13 +54,14 @@ impl<'r> Importer<'r> { // aborts the process instead of failing (#1583). What is read is clamped, and the rest of // this function walks the clamped slices -- indexing `t.rows`/`t.columns` by the file's // own counts would be out of bounds. - let (nr, nc) = designcraft_doc::table::clamped_size(rows.len().max(1), cols.len().max(1)); + // + // Reserved before `Table::new`, so a cell's own story cannot spend the budget this table + // is counting on. + let (nr, nc, over_budget) = budgeted_size(rows.len().max(1), cols.len().max(1), self.table_cells); + self.table_cells = self.table_cells.saturating_add(nr.saturating_mul(nc)); if nr < rows.len() || nc < cols.len() { - self.warnings.push(format!( - "a table of {} rows and {} columns was read as {nr} x {nc}: more than a table can hold", - rows.len(), - cols.len() - )); + let why = if over_budget { "more than the tables in one file can hold between them" } else { "more than a table can hold" }; + self.warnings.push(format!("a table of {} rows and {} columns was read as {nr} x {nc}: {why}", rows.len(), cols.len())); } let rows = &rows[..nr.min(rows.len())]; let cols = &cols[..nc.min(cols.len())]; @@ -170,3 +195,57 @@ impl<'r> Importer<'r> { } } } + +#[cfg(test)] +mod budget_tests { + use super::{MAX_IMPORT_TABLE_CELLS, budgeted_size}; + + /// One table is capped, but a file chooses how many tables it has: three tables each at the + /// per-table cap asked for 750,000 cells, about 1 GB of `Cell`, with every table inside its + /// own limit (noted in review of #1583). + #[test] + fn the_tables_in_one_file_are_capped_between_them() { + let mut reserved = 0; + let mut sizes = Vec::new(); + for _ in 0..3 { + let (nr, nc, over) = budgeted_size(500, 1000, reserved); + reserved += nr * nc; + sizes.push((nr, nc, over)); + } + assert_eq!(sizes[0], (250, 1000, false), "the first table is held by the per-table cap alone"); + assert_eq!(sizes[1], (150, 1000, true), "the second gets what is left of the file's budget"); + assert_eq!(sizes[2], (1, 1, true), "and the third is kept, so its text still has somewhere to be"); + assert_eq!(reserved, MAX_IMPORT_TABLE_CELLS + 1, "400,000 cells and the one the last table keeps"); + } + + /// The budget holds for any sequence of claimed sizes, and a table is never read as nothing: + /// a 0 x n table has no cells to hold the text the file puts in it. + #[test] + fn a_table_is_never_read_as_empty_and_the_budget_always_holds() { + let claims = [(0, 0), (1, 1), (7, 3), (usize::MAX, usize::MAX), (1, usize::MAX), (usize::MAX, 1), (10_000, 1_000), (2, 0)]; + let mut reserved = 0usize; + let mut tables = 0usize; + // Every claim, several times over, in an order that exhausts the budget part way through. + for _ in 0..4 { + for (rows, cols) in claims { + let (nr, nc, _) = budgeted_size(rows.max(1), cols.max(1), reserved); + assert!(nr >= 1 && nc >= 1, "{rows} x {cols} was read as {nr} x {nc}"); + reserved += nr * nc; + tables += 1; + assert!( + reserved <= MAX_IMPORT_TABLE_CELLS + tables, + "{tables} tables reserved {reserved} cells, past the budget by more than the one cell each keeps" + ); + } + } + assert!(reserved >= MAX_IMPORT_TABLE_CELLS, "this sequence does reach the budget: {reserved}"); + } + + /// Below the budget nothing is clamped by it, so an ordinary file is read exactly as before. + #[test] + fn an_ordinary_file_is_not_touched_by_the_budget() { + for (rows, cols) in [(1, 1), (2, 3), (50, 20), (250, 1000)] { + assert_eq!(budgeted_size(rows, cols, 0), (rows, cols, false), "{rows} x {cols}"); + } + } +} From 96b498ca708644acf5ada5999df497b3a17c0926 Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 28 Oct 2026 18:10:41 +0500 Subject: [PATCH 0318/1349] Import: a shared string and a footnote are not copied per reference (#1584) A footnote reference clones its note and walks it again, and an XLSX shared string is copied per cell that uses it, so one 1 MB footnote referenced 100k times meant around 100 GB. The text is kept at the first reference; later ones get the mark and an empty note, and the report says so. The spreadsheet reader stops at 64 MB of text and 400,000 collected cells. Carries both review fixes: - a footnote id is recorded only once its text has actually been kept, so a first reference arriving after the budget was spent no longer counts as "done" and tell the next reference the text is at a reference that has none; - the report and the note budget are both bounded. The duplicate warning names the id, so 400 ids referenced twice made 400 warnings, each pushed after a Vec::contains scan of all the earlier ones; warnings go through warn() now, which dedups through a set and stops at 100 distinct messages. And the budget counted only `text`, which holds a table's anchor and not its cells, so 18 notes of 600 KB of cell text retained 10,800,072 bytes against the 8 MB budget; note_bytes() walks the tables and their nested tables. Rebased onto the post-split main: the implementation stays in docx.rs and the tests moved to docx/tests.rs, so the test additions went there. --- crates/textimport/src/docx.rs | 87 +++++++++++++++++++- crates/textimport/src/docx/tests.rs | 118 ++++++++++++++++++++++++++++ crates/textimport/src/xlsx.rs | 72 ++++++++++++++++- 3 files changed, 270 insertions(+), 7 deletions(-) diff --git a/crates/textimport/src/docx.rs b/crates/textimport/src/docx.rs index 94085ca69..5f1624267 100644 --- a/crates/textimport/src/docx.rs +++ b/crates/textimport/src/docx.rs @@ -236,7 +236,17 @@ struct Ctx { para_names: HashMap, char_names: HashMap, footnotes: HashMap, + /// Footnote ids already imported, and how much note text has been built. A reference clones + /// its note and walks it again, so one 1 MB footnote referenced 100k times meant ~100 GB + /// (#1584). Word gives each note its own id and references it once; a second reference to the + /// same id gets the mark without the text. + notes_done: std::collections::HashSet, + note_bytes: usize, warnings: Vec, + /// What has already been said, so saying it again is a lookup rather than a scan of + /// everything said so far. A warning that names a footnote id is one per id, and the + /// document chooses how many ids it has (noted in review). + warned: std::collections::HashSet, next_table: u64, numbering: Numbering, /// A paragraph style's list (`w:numPr` numId and ilvl, through `w:basedOn`), by style id. @@ -249,7 +259,47 @@ struct Ctx { default_para: String, } +/// A note's tables may hold tables of their own. The document model stops nesting at 64, so +/// counting no deeper than that reaches every cell a note can actually have. +const MAX_NOTE_DEPTH: usize = 64; + +/// The text `s` holds, including its tables' cell text. A table's cells each keep their text in +/// a story of their own rather than in `s.text`, which holds only the anchor, so counting +/// `s.text` scored a table of any size as a couple of bytes (noted in review). +fn note_bytes(s: &Story, depth: usize) -> usize { + let mut n = s.text.len(); + if depth == 0 { + return n; + } + for t in s.tables.values() { + for c in &t.cells { + n = n.saturating_add(note_bytes(&c.text, depth - 1)); + } + } + n +} + +/// Warnings one import reports. A document that earns more than this has earned the point. +const MAX_WARNINGS: usize = 100; + impl Ctx { + /// Report `message` once. Beyond [`MAX_WARNINGS`] distinct messages nothing further is kept, + /// not even in the set, so neither the report nor the memory behind it grows with the + /// document -- a footnote warning names an id, and a file can hold as many ids as it likes. + fn warn(&mut self, message: String) { + if self.warnings.len() > MAX_WARNINGS { + return; + } + if !self.warned.insert(message.clone()) { + return; + } + if self.warnings.len() == MAX_WARNINGS { + self.warnings.push(format!("The Word file has more than {MAX_WARNINGS} kinds of problem: the rest are not listed.")); + } else { + self.warnings.push(message); + } + } + fn para_style(&self, ppr: Option<&El>) -> String { ppr.and_then(|p| p.val("pStyle")).and_then(|id| self.para_names.get(&id).cloned()).unwrap_or_else(|| self.default_para.clone()) } @@ -412,11 +462,39 @@ impl Ctx { "noBreakHyphen" => "\u{2011}".into(), "softHyphen" => "\u{AD}".into(), "footnoteReference" if allow_notes => { + const MAX_NOTE_BYTES: usize = 8 << 20; + let id = e.attr("id").unwrap_or_default().to_string(); + // The note's text is built once per id, and only while the budget lasts. A + // repeat reference, or one past the budget, still gets its mark and its + // number -- the reference is part of the text -- with an empty note (#1584). + // + // The id is recorded only once its text has actually been kept, further down: + // recording it here meant a first reference arriving after the budget was + // spent counted as "done" with an empty note, and the next reference to it + // then claimed the text was kept at the first one (noted in review). + let again = !id.is_empty() && self.notes_done.contains(&id); + let spent = self.note_bytes >= MAX_NOTE_BYTES; + if again || spent { + let len = st.len(); + if st.insert_note(len, "", ParaFormat::default()).is_some() { + let message = if again { + format!("Footnote {id} is referenced more than once in the Word file: the text is kept at its first reference.") + } else { + format!("The Word file's footnotes are longer than {} MB: the rest were imported empty.", MAX_NOTE_BYTES / (1 << 20)) + }; + self.warn(message); + } + continue; + } if let Some(note) = e.attr("id").and_then(|id| self.footnotes.get(id).cloned()) { let mut ns = Story::new(StoryId(0)); let counter = std::mem::take(&mut self.model_counter); self.blocks(¬e, &mut ns, false); self.model_counter = counter; + self.note_bytes = self.note_bytes.saturating_add(note_bytes(&ns, MAX_NOTE_DEPTH)); + if !id.is_empty() { + self.notes_done.insert(id.clone()); + } // Word puts the reference mark in the note text: we generate the number. let len = st.len(); match st.insert_note(len, "", ParaFormat::default()) { @@ -425,15 +503,13 @@ impl Ctx { n.text = ns; } } - None => self.warnings.push("A footnote in the Word file could not be imported.".into()), + None => self.warn("A footnote in the Word file could not be imported.".into()), } } continue; } "drawing" | "pict" | "object" => { - if !self.warnings.iter().any(|w| w.starts_with("Images")) { - self.warnings.push("Images and drawings in the Word file were not imported (place them separately).".into()); - } + self.warn("Images and drawings in the Word file were not imported (place them separately).".into()); continue; } _ => continue, @@ -485,7 +561,10 @@ pub fn import(bytes: &[u8]) -> Result { para_names: HashMap::new(), char_names: HashMap::new(), footnotes: HashMap::new(), + notes_done: std::collections::HashSet::new(), + note_bytes: 0, warnings: vec![], + warned: std::collections::HashSet::new(), next_table: 0, numbering: Numbering::default(), style_lists: HashMap::new(), diff --git a/crates/textimport/src/docx/tests.rs b/crates/textimport/src/docx/tests.rs index c70ca851f..7f1e425cf 100644 --- a/crates/textimport/src/docx/tests.rs +++ b/crates/textimport/src/docx/tests.rs @@ -89,6 +89,124 @@ fn a_measure_or_size_a_file_cannot_mean_is_bounded() { assert_eq!(size, None, "a size the engine cannot mean is dropped, so the style's size stands"); } +/// A footnote reference clones its note and walks it again, so one large footnote referenced +/// many times multiplied: the audit's case is a 1 MB note referenced 100k times, around +/// 100 GB, which aborts rather than fails (#1584). The text is kept at the first reference; +/// later ones get the mark and an empty note, and the report says so. +#[test] +fn a_footnote_referenced_many_times_is_imported_once() { + let note_text = "x".repeat(2_000); + let footnotes = format!(r#"{note_text}"#); + // One note, referenced 50 times. + let refs = r#""#.repeat(50); + let doc = format!(r#"{refs}"#); + let i = import(&docx(&doc, "", &footnotes)).unwrap(); + + // Every reference is still in the text: the marks are the document's content. + assert_eq!(i.story.notes.len(), 50, "all 50 references are kept"); + let with_text = i.story.notes.iter().filter(|n| !n.text.text.is_empty()).count(); + assert_eq!(with_text, 1, "only the first reference carries the note's text"); + let total: usize = i.story.notes.iter().map(|n| n.text.text.len()).sum(); + assert!(total <= note_text.len() + 64, "the note text is stored once, not 50 times: {total} bytes"); + assert!(i.warnings.iter().any(|w| w.contains("referenced more than once")), "the report says what it did: {:?}", i.warnings); + + // A document whose notes each have their own id is unaffected. + let many = (2..6).map(|id| format!(r#"note {id}"#)).collect::(); + let footnotes = format!(r#"{many}"#); + let refs = (2..6).map(|id| format!(r#""#)).collect::(); + let doc = format!(r#"{refs}"#); + let i = import(&docx(&doc, "", &footnotes)).unwrap(); + assert_eq!(i.story.notes.len(), 4); + assert!(i.story.notes.iter().all(|n| n.text.text.contains("note")), "each distinct note keeps its text"); + assert!(!i.warnings.iter().any(|w| w.contains("referenced more than once")), "{:?}", i.warnings); +} + +/// A footnote's table keeps its cell text in stories of its own, so the budget counted a +/// table of any size as the couple of bytes of its anchor and the cap did not hold (noted in +/// review of #1584). Eighteen notes of ~600 KB of cell text each are 10.8 MB of table text +/// against an 8 MB budget. +#[test] +fn a_footnote_table_counts_toward_the_note_budget() { + let big = "x".repeat(600_000); + let cell = format!(r#"{big}"#); + let notes: String = (2..20).map(|id| format!(r#"{cell}"#)).collect(); + let footnotes = format!(r#"{notes}"#); + let refs: String = (2..20).map(|id| format!(r#""#)).collect(); + let doc = format!(r#"{refs}"#); + let i = import(&docx(&doc, "", &footnotes)).unwrap(); + + // Every reference is still a mark in the text. + assert_eq!(i.story.notes.len(), 18, "all 18 references are kept"); + // What was retained is the budget plus at most the one note that was already being built + // when it ran out -- not all 10.8 MB. + let held: usize = i.story.notes.iter().map(|n| note_bytes(&n.text, MAX_NOTE_DEPTH)).sum(); + assert!(held <= (8 << 20) + big.len() + 1024, "the cell text is inside the budget: {held} bytes"); + assert!(held > big.len(), "and the notes that fit were imported in full: {held} bytes"); + assert!(i.warnings.iter().any(|w| w.contains("longer than 8 MB")), "the budget warning is reported: {:?}", i.warnings); +} + +/// The report is one line per distinct footnote id, and the file chooses how many ids it +/// has: 400 ids referenced twice each meant 400 warnings, every one of them pushed after a +/// `Vec::contains` scan of all the earlier ones (noted in review of #1584). Both the report +/// and the set behind it stop at the cap. +#[test] +fn the_report_does_not_grow_with_the_document() { + let ids = 2..402; + // Small notes, so the byte budget is not what stops this -- the ids are. + let notes: String = ids.clone().map(|id| format!(r#"note {id}"#)).collect(); + let footnotes = format!(r#"{notes}"#); + let refs: String = ids + .clone() + .flat_map(|id| { + let one = format!(r#""#); + [one.clone(), one] + }) + .collect(); + let doc = format!(r#"{refs}"#); + let i = import(&docx(&doc, "", &footnotes)).unwrap(); + + // The document is imported in full: every reference is a mark in the text. + assert_eq!(i.story.notes.len(), 800, "all 800 references are kept"); + let duplicates = i.warnings.iter().filter(|w| w.contains("referenced more than once")).count(); + assert!(duplicates >= 1, "the repeats are reported: {:?}", i.warnings); + assert!(i.warnings.len() <= MAX_WARNINGS + 1, "400 duplicated ids do not make 400 warnings: {} warnings", i.warnings.len()); + // And the last line says the list was cut, rather than ending without explanation. + assert!(i.warnings.iter().any(|w| w.contains("the rest are not listed")), "{:?}", i.warnings); +} + +/// When the budget runs out before a note's *first* reference, that reference gets an empty +/// note -- and must not be recorded as the one that kept the text, or a later reference to the +/// same id would be told the text is at a reference that has none (noted in review of #1584). +#[test] +fn a_note_whose_first_reference_is_past_the_budget_is_not_recorded_as_kept() { + // Notes totalling more than the 8 MB budget, so the later ids are never built. + let big = "x".repeat(600_000); + let notes: String = (2..20).map(|id| format!(r#"{big}"#)).collect(); + let footnotes = format!(r#"{notes}"#); + // Each id referenced twice, in order. + let refs: String = (2..20) + .flat_map(|id| { + let one = format!(r#""#); + [one.clone(), one] + }) + .collect(); + let doc = format!(r#"{refs}"#); + let i = import(&docx(&doc, "", &footnotes)).unwrap(); + + // Every reference is kept, and the budget is respected. + assert_eq!(i.story.notes.len(), 36, "all 36 references are in the text"); + let total: usize = i.story.notes.iter().map(|n| n.text.text.len()).sum(); + assert!(total <= (8 << 20) + big.len(), "the note text stays inside the budget: {total} bytes"); + + // The "referenced more than once" warning is only about ids whose text was actually kept. + // A note that was never built cannot have kept its text at a first reference. + let kept: std::collections::HashSet<&str> = i.story.notes.iter().filter(|n| !n.text.text.is_empty()).map(|n| n.text.text.as_str()).collect(); + if i.warnings.iter().any(|w| w.contains("referenced more than once")) { + assert!(!kept.is_empty(), "that warning implies some text was kept: {:?}", i.warnings); + } + assert!(i.warnings.iter().any(|w| w.contains("longer than 8 MB")), "the budget warning is the one this document earns: {:?}", i.warnings); +} + #[test] fn imports_styles_runs_footnotes_and_tables() { let styles = format!( diff --git a/crates/textimport/src/xlsx.rs b/crates/textimport/src/xlsx.rs index a26665ecc..7f129cce1 100644 --- a/crates/textimport/src/xlsx.rs +++ b/crates/textimport/src/xlsx.rs @@ -212,19 +212,41 @@ pub fn import(bytes: &[u8]) -> Result { .transpose()? .map(|sst| sst.els().filter(|e| e.name == "si").map(string_item).collect()) .unwrap_or_default(); + // A `t="s"` cell holds an index into the shared strings and each one is materialised as its + // own `String`, so one large shared string referenced by many cells multiplies: a 1 MB string + // and 3M references is terabytes, allocated before the grid cap below ever applies, and an + // allocation that large aborts the process rather than failing (#1584). Collection carries a + // byte budget and a cell count of its own. + const MAX_TEXT_BYTES: usize = 64 << 20; + const MAX_COLLECTED_CELLS: usize = 400_000; let mut cells: Vec<((usize, usize), String)> = Vec::new(); + let mut text_bytes = 0usize; + let mut cut = false; if let Some(data) = sheet.child("sheetData") { - for (ri, row) in data.els().filter(|e| e.name == "row").enumerate() { + 'rows: for (ri, row) in data.els().filter(|e| e.name == "row").enumerate() { for (ci, c) in row.els().filter(|e| e.name == "c").enumerate() { let at = c.attr("r").and_then(cell_ref).unwrap_or((ri, ci)); let v = value(c, &shared); - if !v.is_empty() { - cells.push((at, v)); + if v.is_empty() { + continue; } + if cells.len() >= MAX_COLLECTED_CELLS || text_bytes.saturating_add(v.len()) > MAX_TEXT_BYTES { + cut = true; + break 'rows; + } + text_bytes = text_bytes.saturating_add(v.len()); + cells.push((at, v)); } } } let mut warnings = Vec::new(); + if cut { + warnings.push(format!( + "the worksheet holds more than {} cells or {} MB of text: the rest was not read", + MAX_COLLECTED_CELLS, + MAX_TEXT_BYTES / (1 << 20) + )); + } if cells.is_empty() { warnings.push("the worksheet is empty".into()); } @@ -293,6 +315,50 @@ mod tests { buf.into_inner() } + /// A `t="s"` cell materialises its own copy of the shared string, so one big string with many + /// references multiplies: the audit's case is a 1 MB string and 3M cells, terabytes, built + /// before the grid cap applies (#1584). Collection now carries its own byte budget. + #[test] + fn a_shared_string_referenced_many_times_does_not_multiply() { + // A 64 KB shared string referenced 2,000 times would be 128 MB of cell text; the budget + // is 64 MB, so collection stops and says so. + let big = "y".repeat(64 * 1024); + let cells: String = (1..=2_000).map(|r| format!(r#"0"#)).collect(); + let mut buf = std::io::Cursor::new(Vec::new()); + { + let mut z = zip::ZipWriter::new(&mut buf); + let o = zip::write::SimpleFileOptions::default(); + for (name, body) in [ + ( + "xl/workbook.xml", + r#""#.to_string(), + ), + ( + "xl/_rels/workbook.xml.rels", + r#""#.to_string(), + ), + ("xl/sharedStrings.xml", format!("{big}")), + ("xl/worksheets/sheet1.xml", format!("{cells}")), + ] { + z.start_file(name, o).unwrap(); + z.write_all(body.as_bytes()).unwrap(); + } + z.finish().unwrap(); + } + let imp = import(&buf.into_inner()).unwrap(); + let table = imp.story.tables.values().next().expect("a table"); + let text: usize = (0..table.nrows()) + .flat_map(|r| (0..table.ncols()).map(move |c| (r, c))) + .filter_map(|(r, c)| table.cell(r, c).map(|cell| cell.text.text.len())) + .sum(); + assert!(text <= 64 << 20, "the table holds at most the budget: {text} bytes"); + assert!(imp.warnings.iter().any(|w| w.contains("was not read")), "the report says the sheet was cut: {:?}", imp.warnings); + + // An ordinary workbook is unaffected and reports nothing of the sort. + let plain = import(&workbook()).unwrap(); + assert!(!plain.warnings.iter().any(|w| w.contains("was not read")), "{:?}", plain.warnings); + } + #[test] fn first_sheet_used_range_becomes_a_table() { let imp = import(&workbook()).unwrap(); From 352609117fbb7deed1b37c16f7b9f3c8654bbe0d Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 28 Oct 2026 18:20:13 +0500 Subject: [PATCH 0319/1349] A table size Create Table cannot mean is refused A size that was given but is not one a table can have was corrected in silence: {"rows": 0} made a table with one row, -1 and 1.5 made the default four, and 10000 was capped at 500 -- so a script asking for a shape the command cannot honour got a different table and no indication of it. A size that is absent still takes the default; a size that is present and outside the range is refused, naming the key and the range. Rebased onto the post-split main: `table.insert` moved to table/structure.rs and the tests to table/sizing.rs. The helper is named `given` rather than `count`, which that module already imports from table/target.rs for the repeat count of a row or column insert. --- crates/engine/src/cmd/table/sizing.rs | 46 ++++++++++++++++++++++++ crates/engine/src/cmd/table/structure.rs | 22 +++++++++--- 2 files changed, 64 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/table/sizing.rs b/crates/engine/src/cmd/table/sizing.rs index cd1d1af53..bcb661906 100644 --- a/crates/engine/src/cmd/table/sizing.rs +++ b/crates/engine/src/cmd/table/sizing.rs @@ -320,3 +320,49 @@ mod resize_border_tests { assert!(s.execute("table.resizeBorder", &json!({"frame": f, "table": t, "axis": "column", "index": 0, "delta": 5})).is_err()); } } + +#[cfg(test)] +mod insert_size_tests { + use serde_json::json; + + use crate::Session; + + /// A table size that is given but is not one a table can have used to be corrected in + /// silence: `{"rows": 0}` made a one-row table, `-1` and `1.5` made the default four, and + /// 10000 was capped at 500 — so a caller's mistake became a table nobody asked for. + #[test] + fn a_table_size_insert_cannot_mean_is_refused() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 1})).unwrap(); + let frame = s.execute("frame.create", &json!({"rect": [20, 20, 400, 300], "content": "text", "text": ""})).unwrap(); + let at = |s: &mut Session| { + s.execute("text.select", &json!({"story": frame["story"].clone(), "anchor": 0, "focus": 0})).unwrap(); + }; + for (params, names) in [ + (json!({"rows": 0}), "rows 0: 1 to 500"), + (json!({"rows": -1}), "rows -1: 1 to 500"), + (json!({"rows": 1.5}), "rows 1.5: 1 to 500"), + (json!({"rows": 10000}), "rows 10000: 1 to 500"), + (json!({"cols": 0}), "cols 0: 1 to 200"), + (json!({"columns": 201}), "cols 201: 1 to 200"), + (json!({"headerRows": 101}), "headerRows 101: 0 to 100"), + (json!({"footerRows": -2}), "footerRows -2: 0 to 100"), + ] { + at(&mut s); + let e = s.execute("table.insert", ¶ms).expect_err("refused").to_string(); + assert!(e.contains(names), "{params}: {e}"); + } + // Nothing was inserted by any of those. + at(&mut s); + assert!(s.execute("table.get", &json!({})).is_err(), "no table yet"); + // The sizes a table can have still work, and absent means the default four by four. + at(&mut s); + s.execute("table.insert", &json!({})).unwrap(); + let t = s.execute("table.get", &json!({})).unwrap(); + assert_eq!(t["cells"].as_array().unwrap().len(), 16, "four by four"); + at(&mut s); + s.execute("table.insert", &json!({"rows": 1, "cols": 2, "headerRows": 1})).unwrap(); + let t = s.execute("table.get", &json!({})).unwrap(); + assert_eq!(t["cells"].as_array().unwrap().len(), 4, "one body row and one header row, two columns"); + } +} diff --git a/crates/engine/src/cmd/table/structure.rs b/crates/engine/src/cmd/table/structure.rs index 65bcdb3d6..7ac075517 100644 --- a/crates/engine/src/cmd/table/structure.rs +++ b/crates/engine/src/cmd/table/structure.rs @@ -6,10 +6,24 @@ pub(super) fn insert(s: &mut Session, p: &Value) -> Result { if t.cell.is_some() { return Err(bad("table.insert", "tables can't be nested in cells")); } - let rows = p.get("rows").and_then(Value::as_u64).unwrap_or(4).clamp(1, 500) as usize; - let cols = p.get("cols").or_else(|| p.get("columns")).and_then(Value::as_u64).unwrap_or(4).clamp(1, 200) as usize; - let header = p.get("headerRows").and_then(Value::as_u64).unwrap_or(0).min(100) as usize; - let footer = p.get("footerRows").and_then(Value::as_u64).unwrap_or(0).min(100) as usize; + // A size that is given but is not one a table can have used to be corrected in silence: + // `{"rows": 0}` made a table with one row, `-1` and `1.5` made the default four, and 10000 + // was capped at 500. Named `given` rather than `count`, which this module already imports + // for the repeat count of a row or column insert. + let given = |key: &str, alt: Option<&str>, default: u64, range: std::ops::RangeInclusive| -> Result { + let v = p.get(key).or_else(|| alt.and_then(|a| p.get(a))).filter(|v| !v.is_null()); + match v { + None => Ok(default as usize), + Some(v) => match v.as_u64().filter(|n| range.contains(n)) { + Some(n) => Ok(n as usize), + None => Err(bad("table.insert", format!("{key} {v}: {} to {}", range.start(), range.end()))), + }, + } + }; + let rows = given("rows", None, 4, 1..=500)?; + let cols = given("cols", Some("columns"), 4, 1..=200)?; + let header = given("headerRows", None, 0, 0..=100)?; + let footer = given("footerRows", None, 0, 0..=100)?; let width = p.get("width").and_then(Value::as_f64).unwrap_or_else(|| column_width(s, &t)); s.edit(|d, sel| { let id = d.alloc(); From 434e269691bcffd494e68190ae20c49925bf4326 Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 28 Oct 2026 18:34:12 +0500 Subject: [PATCH 0320/1349] cli: the three argument bugs photocraft#7071 lists are live here too - An option took the next token whatever it was, so `--export --scale` wrote a file called `--scale` in the working directory. A token that cannot be a value is refused, and where the value is a path the message offers the shell's own way out (`./-name`). A negative number can still be a value, and `-inf`/`-nan` still reach the check that reports them. - An argument that is not UTF-8 panicked inside `std::env::args`. It is a usage error now, named, since such a path cannot reach the engine anyway. - ` --help` was read as an unknown option by every parser but `script`'s. It answers from the usage block, on stdout, and nothing else happens. Rebased onto the post-split main, where the fix had to grow one part. Upstream has since added a check that an export option sits before its `--export`, and it consumed the following token whatever it was, so `--scale --export out.png` was reported as the *order* of the options -- advice to move an option that is already where it belongs -- when what is wrong is that `--scale` has no value. That check now skips a value only where the next token can be one, and stands aside entirely when a value is missing so the value error speaks. Its own test, `run_export_options_come_before_their_export`, still passes. The CLI's tests moved to tests/it/cli.rs, so the test additions went there. --- apps/designcraft-cli/src/main.rs | 102 +++++++++++++++++++++++---- apps/designcraft-cli/tests/it/cli.rs | 71 +++++++++++++++++++ 2 files changed, 158 insertions(+), 15 deletions(-) diff --git a/apps/designcraft-cli/src/main.rs b/apps/designcraft-cli/src/main.rs index 9ce15674c..98c9b32d2 100644 --- a/apps/designcraft-cli/src/main.rs +++ b/apps/designcraft-cli/src/main.rs @@ -96,8 +96,73 @@ fn stdout_failed(e: std::io::Error) -> ! { std::process::exit(1); } +/// Options whose value is a path, and so can be written `./-name` when it starts with `-`, the +/// shell's own way out. None of them has an `--opt=value` form (the automation roots, parsed in +/// [`automation_args`], do and say so themselves). +const PATH_OPTIONS: [&str; 4] = ["--in", "--export", "--all-pages", "--save"]; + +/// An option's value, refusing the next token when it is another option: `--export --scale` used +/// to write a file called `--scale`. +fn value(a: &str, next: Option<&String>) -> Result { + match next { + None => Err(format!("{a} needs a value")), + Some(v) if !can_be_value(v) => { + // The way out is worth offering only where the value could be such a name. + let out = if PATH_OPTIONS.contains(&a) { format!("; if you did mean that name, write `./{v}`") } else { String::new() }; + Err(format!("{a} needs a value and `{v}` is another option{out}")) + } + Some(v) => Ok(v.clone()), + } +} + +/// Whether a token can be an option's value. A negative number can; anything else that starts +/// with `-` is another option. `-inf` and `-nan` parse as numbers too, so a bad `--scale` still +/// reaches the check that reports it rather than being called an option. +fn can_be_value(v: &str) -> bool { + !(v.starts_with('-') && v.len() > 1 && v.parse::().is_err()) +} + +/// The usage lines for one subcommand, for ` --help`. Each line of [`USAGE`] names its +/// subcommand, and the indented lines after it belong to it. +fn usage_for(sub: &str) -> String { + let mut out = Vec::new(); + let mut keep = false; + for line in USAGE.lines() { + let trimmed = line.trim_start(); + if let Some(rest) = trimmed.strip_prefix("usage: designcraft-cli ").or_else(|| trimmed.strip_prefix("designcraft-cli ")) { + keep = rest.split_whitespace().next() == Some(sub); + } + if keep { + out.push(line); + } + } + if out.is_empty() { USAGE.to_string() } else { out.join("\n") } +} + fn main() -> ExitCode { - let args: Vec = std::env::args().skip(1).collect(); + // `std::env::args` panics on an argument that is not UTF-8 ("called `Result::unwrap()` on an + // `Err` value"), which a Latin-1 file name on Linux or macOS is. Such a name cannot be passed + // through to the engine, whose paths are `str`, so it is a usage error here rather than a + // crash (photocraft#1108). + let mut args: Vec = Vec::new(); + for arg in std::env::args_os().skip(1) { + match arg.into_string() { + Ok(a) => args.push(a), + Err(bad) => { + eprintln!("designcraft-cli: `{}` is not valid UTF-8, so it cannot be used as an argument", bad.to_string_lossy()); + return ExitCode::FAILURE; + } + } + } + // ` --help` asks about that subcommand, which every parser but `script`'s read as an + // unknown option (photocraft#423). It goes to stdout and succeeds, as `--help` does. + if let Some(sub) = args.first().map(String::as_str) + && !matches!(sub, "--help" | "-h" | "help" | "script") + && args[1..].iter().any(|a| a == "--help" || a == "-h") + { + outln!("{}", usage_for(sub)); + return ExitCode::SUCCESS; + } match args.first().map(String::as_str) { Some("--version" | "-V" | "version") => { outln!("designcraft-cli {}", env!("CARGO_PKG_VERSION")); @@ -252,22 +317,29 @@ so drop --connect (or use --connect without the roots)" /// They apply to the exports that follow them, so one after the last export would do nothing. fn option_after_last_export(args: &[String]) -> Option<&str> { let mut unused = None; - let mut it = args.iter(); + let mut it = args.iter().peekable(); + // A value is skipped only where the next token can be one. Taking it whatever it is read + // `--scale --export out.png` as --scale applied to no export, so a missing value was + // reported as the order of the options -- and "put it before its --export" is advice for a + // list that already does that (photocraft#7071). while let Some(a) = it.next() { + let is_opt = matches!(a.as_str(), "--page" | "--scale" | "--pdf-options" | "--export" | "--all-pages" | "--in" | "--cmd"); match a.as_str() { - "--page" | "--scale" | "--pdf-options" => { - unused = unused.or(Some(a.as_str())); - it.next(); - } - "--export" | "--all-pages" => { - unused = None; - it.next(); - } - "--in" | "--cmd" => { - it.next(); - } + "--page" | "--scale" | "--pdf-options" => unused = unused.or(Some(a.as_str())), + "--export" | "--all-pages" => unused = None, _ => {} } + if is_opt { + match it.peek() { + Some(v) if can_be_value(v.as_str()) => { + it.next(); + } + // The option has no value. That is what is wrong with the line, so this check + // stands aside and lets `value()` say so: reporting the order instead advised + // moving an option that is already where it belongs (photocraft#7071). + _ => return None, + } + } } unused } @@ -328,7 +400,7 @@ fn run(args: &[String]) -> Result<(), String> { // Earlier --cmd results, for `$N.path` references. let mut results: Vec = Vec::new(); while let Some(a) = it.next() { - let mut val = || it.next().cloned().ok_or_else(|| format!("{a} needs a value")); + let mut val = || value(a, it.next()); match a.as_str() { "--in" => { let p = val()?; @@ -470,7 +542,7 @@ fn script(args: &[String]) -> Result<(), String> { let mut keep_going = false; let mut it = args.iter(); while let Some(a) = it.next() { - let mut val = || it.next().cloned().ok_or_else(|| format!("{a} needs a value")); + let mut val = || value(a, it.next()); match a.as_str() { "--in" => { let p = val()?; diff --git a/apps/designcraft-cli/tests/it/cli.rs b/apps/designcraft-cli/tests/it/cli.rs index 861cb514f..87e5b58fd 100644 --- a/apps/designcraft-cli/tests/it/cli.rs +++ b/apps/designcraft-cli/tests/it/cli.rs @@ -556,3 +556,74 @@ fn usage_lists_the_automation_root_flags() { let usage = String::from_utf8_lossy(&out.stdout); assert!(usage.contains("--automation-read-root DIR") && usage.contains("--automation-write-root DIR"), "{usage}"); } + +/// The argument bugs photocraft#7071 lists, measured here: every one of them was live in this +/// parser too. Each case names the photocraft issue it comes from. +#[test] +fn the_argument_parser_refuses_what_it_cannot_mean() { + let dir = std::env::temp_dir().join(format!("dc-cli-args-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + // photocraft#423: ` --help` was read as an unknown option. It asks about the + // subcommand, goes to stdout and succeeds. + for sub in ["run", "commands", "describe", "app", "mcp", "perf", "bench", "validate-pdf", "links"] { + let out = cli().args([sub, "--help"]).output().unwrap(); + assert!(out.status.success(), "{sub} --help: {}", String::from_utf8_lossy(&out.stderr)); + let text = String::from_utf8_lossy(&out.stdout); + assert!(text.contains(&format!("designcraft-cli {sub}")), "{sub} --help names it: {text:?}"); + assert!(!text.contains("unknown option"), "{sub} --help: {text:?}"); + } + // `script --help` keeps its own longer help, which it had already. + let out = cli().args(["script", "--help"]).output().unwrap(); + assert!(out.status.success() && String::from_utf8_lossy(&out.stdout).contains("Script text, one step per line")); + + // photocraft#6944: an option took the next token whatever it was, so `--export --scale` + // wrote a file called `--scale` in the working directory. + let out = cli().current_dir(&dir).args(["run", "--sample", "--export", "--scale"]).output().unwrap(); + assert!(!out.status.success(), "{}", String::from_utf8_lossy(&out.stdout)); + let err = String::from_utf8_lossy(&out.stderr); + assert!(err.contains("another option") && err.contains("./--scale"), "{err:?}"); + assert!(!dir.join("--scale").exists(), "nothing was written"); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "and no other file either"); + + // A name that really does start with `-` is still reachable, the way the shell reaches one. + let out = cli().current_dir(&dir).args(["run", "--sample", "--export", "./-dash.png"]).output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert!(dir.join("-dash.png").is_file(), "{:?}", std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name()).collect::>()); + + // A missing value is still a missing value, with the message it had. + let out = cli().args(["run", "--sample", "--export"]).output().unwrap(); + assert!(!out.status.success()); + assert!(String::from_utf8_lossy(&out.stderr).contains("--export needs a value")); + + // And a missing value in front of an export is still a missing value: the order of the + // options is beside the point until `--scale` has one, and "put it before its --export" was + // advice for a list that already does that. + let out = cli().current_dir(&dir).args(["run", "--sample", "--scale", "--export", "out.png"]).output().unwrap(); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err:?}"); + assert!(err.contains("--scale needs a value"), "{err:?}"); + assert!(!err.contains("has no --export"), "{err:?}"); + // `./--export` is a file name, which is no way out of a missing `--scale`. + assert!(!err.contains("./"), "{err:?}"); + assert!(!dir.join("out.png").exists(), "and nothing is exported"); + + let _ = std::fs::remove_dir_all(&dir); +} + +/// photocraft#1108: an argument that is not UTF-8 panicked in `std::env::args` ("called +/// `Result::unwrap()` on an `Err` value"). Such a name cannot reach the engine, whose paths are +/// `str`, so it is a usage error. +#[cfg(unix)] +#[test] +fn an_argument_that_is_not_utf8_is_an_error_not_a_panic() { + use std::ffi::OsStr; + use std::os::unix::ffi::OsStrExt; + + let out = cli().arg("info").arg(OsStr::from_bytes(b"/tmp/caf\xe9.designcraft")).output().unwrap(); + let err = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(1), "an error, not a panic (101): {err:?}"); + assert!(err.contains("not valid UTF-8"), "{err:?}"); + assert!(!err.contains("panicked"), "{err:?}"); +} From b5196b933d7b16fd4f6e87622ef5930f436dd940 Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 28 Oct 2026 18:36:37 +0500 Subject: [PATCH 0321/1349] test(cli): pin what the argument parser does today (photocraft#7071) The argument surface had no tests of its own, so the three bugs #7071 lists could come back without anything noticing. These pin what the parser does: help in all three spellings, an unknown command, the version, ` --help` for every subcommand, the options that take a value, the repeatable flags, a flag that takes no value leaving the next token alone, and a missing value naming its option. Carries the review fix: asking for help about a command nobody has is still an unknown command. usage_for fell back to the whole usage block when it described no such subcommand, so `bogus --help` printed it on stdout and exited 0, skipping the failure the test beside it asserts. It answers None instead -- the usage block names every subcommand, so no second list can drift from the match that dispatches them. Rebased onto the post-split main, on top of the rebased #1478. The CLI's tests live under tests/it/ now, so args.rs went there and is registered in tests/it/main.rs. One case needed updating rather than porting: this pinned that an automation root given twice was an error. Upstream has since made the roots repeatable (`...` in the usage), so every use adds a folder. The test now pins that -- which is what "what the parser does today" means -- and says so, rather than holding the parser to behaviour it has deliberately left behind. --- apps/designcraft-cli/src/main.rs | 11 +- apps/designcraft-cli/tests/it/args.rs | 354 ++++++++++++++++++++++++++ apps/designcraft-cli/tests/it/main.rs | 1 + 3 files changed, 363 insertions(+), 3 deletions(-) create mode 100644 apps/designcraft-cli/tests/it/args.rs diff --git a/apps/designcraft-cli/src/main.rs b/apps/designcraft-cli/src/main.rs index 98c9b32d2..ea67f89b3 100644 --- a/apps/designcraft-cli/src/main.rs +++ b/apps/designcraft-cli/src/main.rs @@ -124,7 +124,11 @@ fn can_be_value(v: &str) -> bool { /// The usage lines for one subcommand, for ` --help`. Each line of [`USAGE`] names its /// subcommand, and the indented lines after it belong to it. -fn usage_for(sub: &str) -> String { +/// The part of [`USAGE`] that describes `sub`, or `None` when it describes no such subcommand -- +/// which is how ` --help` tells a real subcommand from a typo. Falling back to the whole +/// usage made `bogus --help` print it and succeed, bypassing the unknown-command failure (noted +/// in review). +fn usage_for(sub: &str) -> Option { let mut out = Vec::new(); let mut keep = false; for line in USAGE.lines() { @@ -136,7 +140,7 @@ fn usage_for(sub: &str) -> String { out.push(line); } } - if out.is_empty() { USAGE.to_string() } else { out.join("\n") } + (!out.is_empty()).then(|| out.join("\n")) } fn main() -> ExitCode { @@ -159,8 +163,9 @@ fn main() -> ExitCode { if let Some(sub) = args.first().map(String::as_str) && !matches!(sub, "--help" | "-h" | "help" | "script") && args[1..].iter().any(|a| a == "--help" || a == "-h") + && let Some(text) = usage_for(sub) { - outln!("{}", usage_for(sub)); + outln!("{text}"); return ExitCode::SUCCESS; } match args.first().map(String::as_str) { diff --git a/apps/designcraft-cli/tests/it/args.rs b/apps/designcraft-cli/tests/it/args.rs new file mode 100644 index 000000000..bbbde4867 --- /dev/null +++ b/apps/designcraft-cli/tests/it/args.rs @@ -0,0 +1,354 @@ +//! What the command line does with its arguments, pinned. +//! +//! Every assertion here was measured, not intended: these tests say what the parser does today, +//! including where that is odd (an unknown option taken as a filter, a `--opt=value` form that +//! only the automation roots have). They exist so that moving to a derived parser — the work +//! photocraft#7071 lists, which this parser needs too — changes the surface where that is the +//! point and nowhere else. +//! +//! They assert the exit code, which stream the output went to, and that an error names the +//! argument it is about. They do not assert wording, so a message can be improved without +//! editing a test, except in the few places where the wording *is* the behaviour and the test +//! says so. +//! +//! `tests/cli.rs` holds what the subcommands then do: exports, scripts, the MCP server. + +use std::process::{Command, Stdio}; + +/// `designcraft-cli` with stdin closed, so a subcommand that reads a script does not wait. +fn cli() -> Command { + let mut c = Command::new(env!("CARGO_BIN_EXE_designcraft-cli")); + c.stdin(Stdio::null()); + c +} + +/// What one invocation did. +struct Ran { + code: Option, + out: String, + err: String, +} + +fn run(args: &[&str]) -> Ran { + let out = cli().args(args).output().unwrap_or_else(|e| panic!("{args:?}: {e}")); + Ran { code: out.status.code(), out: String::from_utf8_lossy(&out.stdout).into_owned(), err: String::from_utf8_lossy(&out.stderr).into_owned() } +} + +impl Ran { + /// Succeeded, said nothing on stderr; gives back what it printed. + fn succeeded(self, what: &str) -> String { + assert_eq!(self.code, Some(0), "{what}: {:?}", self.err); + assert_eq!(self.err, "", "{what} wrote to stderr"); + self.out + } + + /// Failed with the usage exit code, said nothing on stdout; gives back the complaint. + fn failed(self, what: &str) -> String { + assert_eq!(self.code, Some(1), "{what}: expected a usage failure, got {:?} / {:?}", self.out, self.err); + assert_eq!(self.out, "", "{what} wrote to stdout"); + self.err + } +} + +/// A port with nothing listening on it, so `--connect` and `--port` fail the same way every time. +fn closed_port() -> String { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + drop(listener); + port.to_string() +} + +/// A directory of this test's own, removed when the test ends. +fn temp_dir(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("dc-args-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// Every subcommand, in the order the usage block lists them. +const SUBCOMMANDS: [&str; 10] = ["run", "commands", "describe", "script", "app", "mcp", "perf", "bench", "validate-pdf", "links"]; + +#[test] +fn with_no_arguments_it_prints_the_usage_block_and_fails() { + let err = run(&[]).failed("no arguments"); + assert!(err.starts_with("usage: designcraft-cli run"), "{err:?}"); + // The usage block names every subcommand, which is how ` --help` finds its lines. + for sub in SUBCOMMANDS { + assert!(err.contains(&format!("designcraft-cli {sub}")), "usage names {sub}: {err:?}"); + } + // An empty argument is a command nobody has, not a request for help. + run(&[""]).failed("an empty argument"); +} + +#[test] +fn help_goes_to_stdout_and_succeeds_in_all_three_spellings() { + let long = run(&["--help"]).succeeded("--help"); + assert!(long.starts_with("usage: designcraft-cli run"), "{long:?}"); + // The community links are under the usage block, for someone who has nowhere else to ask. + assert!(long.contains("Community:") && long.contains("discord"), "{long:?}"); + for spelling in ["-h", "help"] { + assert_eq!(run(&[spelling]).succeeded(spelling), long, "{spelling} prints the same help"); + } +} + +#[test] +fn an_unknown_command_fails_with_the_same_text_on_stderr() { + let usage = run(&["--help"]).succeeded("--help"); + for unknown in ["bogus", "-x", "--nope", "Run"] { + let err = run(&[unknown]).failed(unknown); + assert_eq!(err, usage, "{unknown}: the same usage, on stderr"); + // Asking for help about a command nobody has is still that command: ` --help` + // answered with the whole usage block on stdout and succeeded, which skipped the + // unknown-command failure entirely (noted in review). + for spelling in ["--help", "-h"] { + let err = run(&[unknown, spelling]).failed(&format!("{unknown} {spelling}")); + assert_eq!(err, usage, "{unknown} {spelling}: the same usage, on stderr"); + } + } + // A real subcommand still answers about itself, and only about itself. + for sub in SUBCOMMANDS.iter().filter(|s| **s != "script") { + let text = run(&[sub, "--help"]).succeeded(sub); + assert!(text.contains(&format!("designcraft-cli {sub}")), "{sub} --help describes {sub}: {text:?}"); + assert_ne!(text, usage, "{sub} --help is about {sub}, not the whole usage block"); + } +} + +#[test] +fn the_version_is_the_crate_version() { + let expected = format!("designcraft-cli {}\n", env!("CARGO_PKG_VERSION")); + for spelling in ["--version", "-V", "version"] { + assert_eq!(run(&[spelling]).succeeded(spelling), expected, "{spelling}"); + } +} + +/// ` --help` asks about that subcommand. It answers from the usage block, on stdout, and +/// nothing else happens: no export is written, no port is dialled, no measurement is taken, and a +/// file named earlier in the same line is not opened or complained about (photocraft#423). +#[test] +fn every_subcommand_answers_help_without_running_anything() { + let dir = temp_dir("help"); + let png = dir.join("ran.png"); + let dead = closed_port(); + let cases: [(&str, Vec<&str>); 10] = [ + ("run", vec!["run", "--sample", "--export", png.to_str().unwrap()]), + ("commands", vec!["commands"]), + ("describe", vec!["describe", "file.open"]), + ("script", vec!["script", "no-such-script.dcs"]), + ("app", vec!["app", "--port", &dead, "document.list"]), + ("mcp", vec!["mcp", "--connect", &dead]), + ("perf", vec!["perf", "--pages", "1", "--runs", "1"]), + ("bench", vec!["bench", "no-such-document.designcraft"]), + ("validate-pdf", vec!["validate-pdf", "no-such-file.pdf"]), + ("links", vec!["links"]), + ]; + for (sub, args) in cases { + for flag in ["--help", "-h"] { + let mut args = args.clone(); + args.push(flag); + let what = format!("{sub} {flag}"); + let out = run(&args).succeeded(&what); + assert!(out.contains(&format!("designcraft-cli {sub}")), "{what} names it: {out:?}"); + assert!(!out.contains("unknown option"), "{what}: {out:?}"); + // None of the work the rest of the line asks for was done. + assert!(!png.exists(), "{what} exported a file"); + assert!(!out.contains("cannot connect") && !out.contains("render threads"), "{what}: {out:?}"); + assert!(!out.contains("No such file"), "{what}: {out:?}"); + } + } + // `script`'s own help is longer than one usage line: it documents the script syntax, which is + // otherwise only in `describe script.run` and the docs. + let out = run(&["script", "--help"]).succeeded("script --help"); + assert!(out.contains("Script text, one step per line"), "{out:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The subcommands that have options refuse an option they do not know, and name it. +#[test] +fn an_unknown_option_is_refused_by_name() { + let cases: [Vec<&str>; 5] = [ + vec!["run", "--nope"], + vec!["script", "-", "--nope"], + vec!["mcp", "--nope"], + vec!["perf", "--nope"], + vec!["bench", "f.designcraft", "--nope"], + ]; + for args in cases { + let err = run(&args).failed(&format!("{args:?}")); + assert!(err.contains("--nope"), "{args:?}: {err:?}"); + assert!(err.contains("unknown"), "{args:?}: {err:?}"); + } +} + +/// The subcommands whose argument is a word, not an option, take an unknown option as that word: +/// `commands --nope` filters the command list by `--nope` and finds nothing. Each of these would +/// be an error under the rule photocraft#7071 settles on; today they are not, and a change of +/// mind shows up here. +#[test] +fn the_subcommands_that_take_a_word_read_an_unknown_option_as_that_word() { + // A filter that matches no command: an empty list, successfully. + assert_eq!(run(&["commands", "--nope"]).succeeded("commands --nope").trim(), "[]"); + // A command id nobody has. + let err = run(&["describe", "--nope"]).failed("describe --nope"); + assert!(err.contains("no command `--nope`"), "{err:?}"); + // A path nobody has. + let err = run(&["validate-pdf", "--nope"]).failed("validate-pdf --nope"); + assert!(err.contains("--nope") && err.contains("No such file"), "{err:?}"); + // A method name for the running app, so the error is about reaching the app. + let dead = closed_port(); + let err = run(&["app", "--port", &dead, "--nope"]).failed("app --nope"); + assert!(err.contains("cannot connect"), "{err:?}"); + // And `links`, which takes nothing, ignores what it is given. + let out = run(&["links", "--nope"]).succeeded("links --nope"); + assert_eq!(out, run(&["links"]).succeeded("links")); +} + +/// There is no `--opt=value` form. The two automation roots are the exception: they have one, +/// because a folder whose name starts with `-` has no other way in there. +#[test] +fn only_the_automation_roots_have_an_opt_equals_value_form() { + let cases: [(&str, Vec<&str>); 3] = [ + ("--scale=2", vec!["run", "--scale=2", "--sample"]), + ("--pages=2", vec!["perf", "--pages=2"]), + ("--save=out.designcraft", vec!["script", "-", "--save=out.designcraft"]), + ]; + for (token, args) in cases { + let err = run(&args).failed(&format!("{args:?}")); + assert!(err.contains("unknown"), "{args:?}: {err:?}"); + // The whole token is named, `=value` and all, so it is clear what was not understood. + assert!(err.contains(token), "{args:?}: {err:?}"); + } + // The roots read the value after `=`: an empty one is refused as a folder, which is the + // parser having taken it rather than ignoring the form. + let err = run(&["mcp", "--automation-read-root="]).failed("empty root"); + assert!(err.contains("--automation-read-root") && err.contains("folder"), "{err:?}"); + // A root given more than once adds another folder, in either spelling, rather than the last + // one winning or the repeat being refused: the roots are repeatable (`...` in the usage), and + // `mcp_automation_roots_take_several_folders` covers what the extra folder grants. This PR + // first pinned the older behaviour, where a second root was an error; upstream has made them + // repeatable since, so what is pinned here is today's. + // + // Checked by what fails rather than by letting the server start: the stray token after the + // roots is the error, which shows both roots were taken. + for second in [vec!["--automation-read-root=b"], vec!["--automation-read-root", "b"]] { + let mut args = vec!["mcp", "--automation-read-root=a"]; + args.extend(second.iter().copied()); + args.push("stray"); + let err = run(&args).failed(&format!("{second:?}")); + assert!(err.contains("stray"), "the stray token is what fails: {err:?}"); + assert!(!err.contains("twice"), "a repeated root is not refused any more: {err:?}"); + } +} + +/// An option that needs a value and has none says which option, and nothing runs. +#[test] +fn a_missing_value_names_its_option() { + let dir = temp_dir("missing"); + let png = dir.join("out.png"); + let cases: [(&str, Vec<&str>); 9] = [ + ("--export", vec!["run", "--sample", "--export"]), + ("--in", vec!["run", "--in"]), + ("--all-pages", vec!["run", "--sample", "--all-pages"]), + // Before an export, too: the order of the options is nothing to judge until this one has + // a value, so it is not reported as an export it is not in front of. + ("--scale", vec!["run", "--sample", "--scale", "--export", png.to_str().unwrap()]), + ("--page", vec!["run", "--sample", "--page"]), + ("--save", vec!["script", "-", "--save"]), + ("--connect", vec!["script", "-", "--connect"]), + ("--port", vec!["app", "--port"]), + ("--pages", vec!["perf", "--pages"]), + ]; + for (option, args) in cases { + let err = run(&args).failed(&format!("{args:?}")); + assert!(err.contains(option), "{args:?} names {option}: {err:?}"); + assert!(err.contains("needs"), "{args:?}: {err:?}"); + } + assert!(!png.exists(), "nothing is exported"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// An option that takes no value does not swallow the token after it: that token is read as the +/// next argument, and refused if it is not one. +#[test] +fn a_flag_that_takes_no_value_leaves_the_next_token_alone() { + let err = run(&["run", "--sample", "extra", "--export", "out.png"]).failed("run --sample extra"); + assert!(err.contains("extra"), "{err:?}"); + let err = run(&["perf", "--strict", "3"]).failed("perf --strict 3"); + assert!(err.contains('3'), "{err:?}"); +} + +/// A value flag given twice keeps the last value. (The automation roots are the exception, above.) +#[test] +fn a_repeated_value_flag_keeps_the_last_value() { + let dir = temp_dir("repeat"); + let at = |args: &[&str], name: &str| -> Vec { + let path = dir.join(name); + let mut full: Vec<&str> = vec!["run", "--sample"]; + full.extend_from_slice(args); + let out = path.to_str().unwrap(); + full.extend(["--export", out]); + let ran = run(&full); + assert_eq!(ran.code, Some(0), "{full:?}: {:?}", ran.err); + std::fs::read(&path).unwrap() + }; + // `--scale`: the size of the image says which value was used. + let one = at(&[], "1.png"); + let three = at(&["--scale", "3"], "3.png"); + assert_eq!(at(&["--scale", "2", "--scale", "3"], "23.png"), three, "the last --scale won"); + assert_ne!(three, one, "and --scale 3 is not --scale 1"); + // `--page`: which page was exported says it. + let second = at(&["--page", "1"], "p1.png"); + assert_ne!(second, one, "page 1 of the sample is not page 0"); + assert_eq!(at(&["--page", "1", "--page", "0"], "p10.png"), one, "the last --page won"); + // `--connect` and `--port`: the address the error names says it. + let (a, b) = (closed_port(), closed_port()); + for args in [vec!["mcp", "--connect", &a, "--connect", &b], vec!["app", "--port", &a, "--port", &b, "document.list"]] { + let err = run(&args).failed(&format!("{args:?}")); + assert!(err.contains(&format!("127.0.0.1:{b}")), "{args:?} dialled the last port: {err:?}"); + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// The flags that are meant to repeat each take effect, in order. +#[test] +fn the_repeatable_flags_all_take_effect() { + let dir = temp_dir("each"); + let (a, b) = (dir.join("a.png"), dir.join("b.png")); + let ran = run(&[ + "run", + "--sample", + "--cmd", + "document.list", + "--cmd", + "document.list", + "--export", + a.to_str().unwrap(), + "--export", + b.to_str().unwrap(), + ]); + assert_eq!(ran.code, Some(0), "{:?}", ran.err); + // One result line per `--cmd`, in the order given. + let results: Vec<&str> = ran.out.lines().collect(); + assert_eq!(results.len(), 2, "{results:?}"); + assert_eq!(results[0], results[1]); + // And one file per `--export`. + assert_eq!(std::fs::read(&a).unwrap(), std::fs::read(&b).unwrap()); + assert_eq!(ran.err.lines().filter(|l| l.starts_with("wrote ")).count(), 2, "{:?}", ran.err); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A subcommand given nothing to do does nothing, quietly or with its own usage line. `run` with +/// no arguments is the one that says nothing at all: there is no document to act on and nothing +/// was asked of it. +#[test] +fn a_subcommand_with_nothing_to_do_says_so_or_says_nothing() { + assert_eq!(run(&["run"]).succeeded("run"), ""); + // `script` with no file reads stdin, which is closed here: an empty script, run. + let out = run(&["script"]).succeeded("script"); + assert!(out.contains("\"completed\": 0"), "{out:?}"); + // The two that need an argument print the usage line for themselves. + for sub in ["describe", "bench", "validate-pdf"] { + let err = run(&[sub]).failed(sub); + assert!(err.contains(&format!("designcraft-cli {sub}")), "{sub}: {err:?}"); + } +} diff --git a/apps/designcraft-cli/tests/it/main.rs b/apps/designcraft-cli/tests/it/main.rs index 26710c101..e8761f4e1 100644 --- a/apps/designcraft-cli/tests/it/main.rs +++ b/apps/designcraft-cli/tests/it/main.rs @@ -1 +1,2 @@ +mod args; mod cli; From 2f403698e0e2a8db6b404afe30292f3e3d15ce81 Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 28 Oct 2026 18:53:45 +0500 Subject: [PATCH 0322/1349] An export says what text its pages had no room for (#1465) A page-based export leaves out the text its frames cannot fit, and said nothing about it: an imported 58-page form lost whole sentences -- a data-consent clause, a statutory rule, the last row of two tables -- with `warnings` empty while preflight reported 19 overset stories. The PDF and deck exports now report it, in the words preflight uses and with the same count, naming the page and the frame. A reflowable export carries the whole story, so it has nothing to report. Carries the review fix: a spread export puts the whole spread on the sheet, so choosing page 2 of a facing-pages document exports page 3 as well and page 3's overset is as absent from the file as page 2's would be. The selection is widened to the spreads it touches first. A page on another spread is still not reported, so the filter keeps doing what it is for. Rebased onto the post-split main: the PDF command is in export/pdf.rs, the deck one in export/formats.rs, and preflight.rs is unchanged by the split. The helper sits before export_pdf rather than between first_page_ref's doc comment and its function, which is where the pre-split patch had put it. --- crates/engine/src/cmd/export/formats.rs | 2 + crates/engine/src/cmd/export/pdf.rs | 123 +++++++++++++++++++++++- crates/engine/src/cmd/preflight.rs | 45 +++++++++ crates/engine/src/cmd/text.rs | 7 +- 4 files changed, 175 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/export/formats.rs b/crates/engine/src/cmd/export/formats.rs index 025bcdac4..dab0bb8d1 100644 --- a/crates/engine/src/cmd/export/formats.rs +++ b/crates/engine/src/cmd/export/formats.rs @@ -110,6 +110,8 @@ pub(super) fn export_pptx(s: &mut Session, p: &Value) -> Result { if rasterized > 0 { r.warnings.push(format!("{rasterized} object(s) went in as images")); } + // A slide has no room for the overset text either (#1465). + r.warnings.extend(crate::cmd::preflight::overset_warnings(s, opts.pages.as_deref())); match str_param(p, "path") { Some(path) => { #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/cmd/export/pdf.rs b/crates/engine/src/cmd/export/pdf.rs index 64011fa3c..12d5577ec 100644 --- a/crates/engine/src/cmd/export/pdf.rs +++ b/crates/engine/src/cmd/export/pdf.rs @@ -87,8 +87,27 @@ fn first_page_ref(pdf: &[u8]) -> Option { s[i..].split_whitespace().next()?.parse().ok() } +/// Every page sharing a spread with one of `pages` (0-based), for an export that puts whole +/// spreads on a sheet. The pages come back in document order. +fn with_their_spreads(s: &Session, pages: &[usize]) -> Vec { + let Some(st) = s.active() else { return pages.to_vec() }; + let d = &st.doc; + let spreads: std::collections::BTreeSet = pages.iter().filter_map(|p| d.page_loc(*p)).map(|(si, _)| si).collect(); + if spreads.is_empty() { + return pages.to_vec(); + } + (0..d.page_count()).filter(|p| d.page_loc(*p).is_some_and(|(si, _)| spreads.contains(&si))).collect() +} + pub(super) fn export_pdf(s: &mut Session, p: &Value) -> Result { - let r = pdf_export(s, p)?; + let mut r = pdf_export(s, p)?; + // Text the pages have no room for is not in the file: say so, as preflight does (#1465). + // A spread export puts the whole spread on the sheet, so choosing page 2 exports page 3 as + // well and page 3's overset is as absent from the file as page 2's would be. The selection + // is widened to the spreads it touches before the warnings are collected (noted in review). + let opts = options(p, s.doc()?.doc.page_count())?; + let warn_pages = opts.pages.as_deref().map(|pages| if opts.spreads { with_their_spreads(s, pages) } else { pages.to_vec() }); + r.warnings.extend(crate::cmd::preflight::overset_warnings(s, warn_pages.as_deref())); match str_param(p, "path") { Some(path) => { write_file(path, &r.bytes)?; @@ -461,3 +480,105 @@ mod page_list_tests { assert!(s.execute("file.exportPdf", &json!({"pages": []})).is_err()); } } + +#[cfg(test)] +mod overset_tests { + use serde_json::json; + + use crate::Session; + + /// A page-based export leaves out the text its frames have no room for, and said nothing + /// about it: an imported 58-page form lost whole sentences — a data-consent clause, a + /// statutory rule, the last row of two tables — with `warnings` empty while preflight + /// reported 19 overset stories (#1465). + #[test] + fn an_export_warns_about_the_text_the_pages_had_no_room_for() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200, "pages": 2, "facingPages": false, "margins": 0})).unwrap(); + let text = "First line is visible.\nSecond paragraph does not fit: this sentence carries the legal notice and must not vanish from the PDF without a warning."; + let frame = s.execute("frame.create", &json!({"rect": [20, 20, 280, 60], "content": "text", "text": text})).unwrap(); + let (id, sid) = (frame["id"].as_u64().unwrap(), frame["story"].clone()); + + // What preflight says about the same frame, for the warning to agree with. + let issues = s.execute("preflight.run", &json!({})).unwrap(); + let overset = issues["issues"].as_array().unwrap().iter().find(|i| i["kind"] == "overset").expect("preflight reports it").clone(); + assert_eq!(overset["message"], "Overset text: 76 characters"); + + for command in ["file.exportPdf", "file.exportPptx"] { + let r = s.execute(command, &json!({})).unwrap(); + let warnings = r["warnings"].as_array().expect("warnings").clone(); + let about: Vec<&str> = warnings.iter().filter_map(|w| w.as_str()).filter(|w| w.contains("not in the export")).collect(); + assert_eq!(about.len(), 1, "{command}: {warnings:?}"); + let w = about[0]; + assert!(w.contains("page 1"), "{command}: the page it is on: {w}"); + assert!(w.contains("76 character"), "{command}: the count preflight gives: {w}"); + assert!(w.contains(&format!("frame {id}")), "{command}: the frame: {w}"); + } + + // The pages being exported are the ones reported on: page 2 has no overset frame. + let r = s.execute("file.exportPdf", &json!({"pages": [2]})).unwrap(); + assert_eq!(r["warnings"], json!([]), "{r}"); + + // A reflowable export carries the whole story, so it has nothing to report. + let r = s.execute("file.exportHtml", &json!({})).unwrap(); + assert_eq!(r["warnings"], json!([]), "{r}"); + assert!(r["text"].as_str().unwrap().contains("must not vanish"), "the HTML has the text the PDF left out"); + + // `overset` is the index where the text stops fitting; `oversetChars` is how much is left, + // which is the number preflight reports. The two were read as the same thing. + let story = s.execute("story.get", &json!({"story": sid})).unwrap(); + assert_eq!(story["overset"], json!(68), "{story}"); + assert_eq!(story["oversetChars"], json!(76), "{story}"); + + // A frame the text fits: nothing is reported anywhere. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200, "pages": 1, "facingPages": false, "margins": 0})).unwrap(); + let frame = s.execute("frame.create", &json!({"rect": [20, 20, 280, 180], "content": "text", "text": "Short."})).unwrap(); + for command in ["file.exportPdf", "file.exportPptx"] { + assert_eq!(s.execute(command, &json!({})).unwrap()["warnings"], json!([]), "{command}"); + } + let story = s.execute("story.get", &json!({"story": frame["story"].clone()})).unwrap(); + assert!(story["overset"].is_null() && story["oversetChars"].is_null(), "{story}"); + } + + /// A spread export puts the whole spread on the sheet, so choosing one page of it exports its + /// partner too -- and that partner's overset is just as absent from the file. Reporting only + /// the pages that were named left it unmentioned (noted in review of #1465). + #[test] + fn a_spread_export_warns_about_the_pages_it_takes_with_it() { + let mut s = Session::new(); + // Facing pages: 2 and 3 share a spread, 1 is the cover on its own. + s.execute("file.new", &json!({"width": 200, "height": 200, "pages": 4, "facingPages": true, "margins": 0})).unwrap(); + let text = "First line is visible.\nSecond paragraph does not fit: this sentence carries the legal notice and must not vanish from the PDF without a warning."; + // A frame on page 3, whose text does not fit it. `frame.create` takes a spread and + // spread coordinates, so page 3's own bounds say where to put it. + let (si, b) = { + let d = &s.active().expect("a document").doc; + let (si, pi) = d.page_loc(2).expect("page 3 is there"); + (si, d.spreads[si].pages[pi].bounds()) + }; + let rect = json!([b.x0 + 20.0, b.y0 + 20.0, b.x0 + 180.0, b.y0 + 60.0]); + let frame = s.execute("frame.create", &json!({"spread": si, "rect": rect, "content": "text", "text": text})).unwrap(); + let id = frame["id"].as_u64().unwrap(); + let about = |r: &serde_json::Value| -> Vec { + r["warnings"] + .as_array() + .map(|w| w.iter().filter_map(|w| w.as_str()).filter(|w| w.contains("not in the export")).map(str::to_string).collect()) + .unwrap_or_default() + }; + + // Page by page, choosing page 2 reports nothing: page 2 holds no overset frame. + let r = s.execute("file.exportPdf", &json!({"pages": [2]})).unwrap(); + assert!(about(&r).is_empty(), "page 2 alone has nothing to report: {r}"); + + // As spreads, choosing page 2 exports page 3 with it, so page 3's overset is reported. + let r = s.execute("file.exportPdf", &json!({"pages": [2], "spreads": true})).unwrap(); + let w = about(&r); + assert_eq!(w.len(), 1, "the page that came along is reported too: {r}"); + assert!(w[0].contains("page 3") && w[0].contains(&format!("frame {id}")), "{}", w[0]); + + // And a page on another spread entirely is still not reported. + let r = s.execute("file.exportPdf", &json!({"pages": [1], "spreads": true})).unwrap(); + assert!(about(&r).is_empty(), "the cover's spread holds no overset frame: {r}"); + } +} diff --git a/crates/engine/src/cmd/preflight.rs b/crates/engine/src/cmd/preflight.rs index 390dc7118..b3a22d6ad 100644 --- a/crates/engine/src/cmd/preflight.rs +++ b/crates/engine/src/cmd/preflight.rs @@ -113,6 +113,51 @@ fn overset_location(s: &Session, target: designcraft_doc::ItemId) -> Option<(des None } +/// Text that is in the document but not in a page-based export (PDF, PowerPoint): the overset +/// part of a story, and a story with no frame at all. The export used to write the file and +/// report nothing, so whole sentences left an imported document without a hint anywhere (#1465). +/// +/// One line per story, naming the page and the frame as the preflight issue does. `pages` are the +/// 0-based pages being exported; a story whose overset is on a page that is not being exported is +/// not reported, and one with no page of its own always is. A reflowable export (EPUB, HTML) or a +/// text export carries the whole story, so neither calls this. +pub fn overset_warnings(s: &Session, pages: Option<&[usize]>) -> Vec { + let Some(st) = s.active() else { return vec![] }; + let d = &st.doc; + let mut out = Vec::new(); + for story in d.stories.values() { + let cs = s.cache.get(d, story.id, None); + if !cs.is_overset() { + continue; + } + let n = story.text.get(cs.overset_at.unwrap_or(0)..).unwrap_or("").chars().count(); + if n == 0 { + continue; + } + if story.frames.is_empty() { + out.push(format!("a story with no text frame: {n} character(s) of it are not in the export")); + continue; + } + let last = story.frames.last().copied(); + let location = last.and_then(|f| overset_location(s, f)); + let page = location.and_then(|(_, page)| page); + if let (Some(page), Some(pages)) = (page, pages) + && !pages.contains(&page) + { + continue; + } + let item = location.map(|(item, _)| item).or(last); + out.push(match (page, item) { + (Some(page), Some(item)) => { + format!("page {}: {n} character(s) of the story in frame {} do not fit it and are not in the export", page + 1, item.0) + } + (None, Some(item)) => format!("the story in frame {}: {n} character(s) do not fit and are not in the export", item.0), + _ => format!("{n} character(s) of a story do not fit their frame and are not in the export"), + }); + } + out +} + pub fn check(s: &Session, min_ppi: f64) -> Vec { let Some(st) = s.active() else { return vec![] }; let d = &st.doc; diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index 8e6038741..3e6dce9d5 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -191,12 +191,17 @@ pub fn specs() -> Vec { }) } ), - cmd!(query "story.get", "Get Story", [], None, "{story? | frame?} → text, frames, paragraphs, vertical, overset", has_doc, |s, p| { + cmd!(query "story.get", "Get Story", [], None, "{story? | frame?} → text, frames, paragraphs, vertical, lines, overset (the index in `text` where it stops fitting its frames, null when it all fits) and oversetChars (how many characters that leaves, as preflight reports them)", has_doc, |s, p| { let st = s.doc()?; let sid = story_of(s, p).ok_or_else(|| bad("story.get", "no story"))?; let mut v = st.doc.story_summary(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; let cs = s.cache.get(&st.doc, sid, None); + // `overset` is where the text stops fitting, not how much is left over: the two were + // read as the same number and disagreed with preflight's count (#1465). v["overset"] = json!(cs.overset_at); + v["oversetChars"] = json!(cs + .overset_at + .map(|at| st.doc.stories.get(&sid).and_then(|story| story.text.get(at..)).unwrap_or("").chars().count())); v["lines"] = json!(cs.line_count()); Ok(v) }), From 87b49d997376a3bdb3ce42ac7967efb0519c2c68 Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 28 Oct 2026 19:09:25 +0500 Subject: [PATCH 0323/1349] PDF export: SOURCE_DATE_EPOCH stands in for the clock, so exports repeat A PDF export recorded the second it was made in, so exporting one document twice gave different files although the pages matched -- and the instance id krilla derives from the bytes followed the timestamp, so nothing about the two files was comparable. SOURCE_DATE_EPOCH stands in for the clock when the export is given no date, as the reproducible-builds specification defines it. A date passed in still wins, and a value the PDF date format cannot hold -- malformed, negative, or past the range -- is ignored rather than refusing the export or writing a date no reader can parse. With the epoch pinned the two files are identical byte for byte. Rebased onto the post-split main: export_time and pinned_or live in export/metadata.rs beside now_unix, which they stand in front of, and the call site is in export/pipeline.rs. The ROADMAP keeps upstream's 2026-10-17 entry with this one above it. --- ROADMAP.md | 1 + crates/pdf/src/export/metadata.rs | 60 +++++++++++++++++++++++++++++++ crates/pdf/src/export/pipeline.rs | 4 +-- crates/pdf/src/lib.rs | 3 +- 4 files changed, 65 insertions(+), 3 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index c02176bab..68e286450 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -431,6 +431,7 @@ Newest first. - **2026-10-22** · macOS menu bar: the menus keep working after the interface language or Show CJK Features changes (a rebuilt menu bar lost every click, Quit included), and its key equivalents are the shortcuts in effect, so a shortcut moved in the Keyboard Shortcuts editor leaves its old menu item. No readiness percentage change. - **2026-10-22** · Paragraph rules: Rule Above's offset is measured from the first line's baseline to the rule's bottom edge, as in InDesign. Rules sat one ascent too high and crossed the previous paragraph's text (reported from an imported INDD document). No readiness percentage change. - **2026-10-21** · Ruler guides are selected like objects (#1282): a click with the Selection tools selects a guide (also where it crosses an object), Shift-click adds or removes one, a new guide from the rulers is selected, a marquee that touches no object selects the guides it crosses, and Edit › Select All Guides (⌥⌘G, `guide.selectAll`) selects every unlocked guide on the spread. Selected guides draw thicker in their layer's color, drag together (all of them shown moving), nudge with the arrow keys and go with Delete, each as one undo step (`guide.select`, `guide.deselect`, `guide.moveBy`, `guide.delete {}`). With one guide selected the Control bar's X (vertical guide) or Y (horizontal guide) field and Properties › Transform show where it is, as the rulers measure, and typing a value moves it there. No readiness percentage change. +- **2026-10-19** · A PDF export can repeat its bytes: it recorded the second it was made in, so exporting one document twice gave different files though the pages matched. `SOURCE_DATE_EPOCH` stands in for the clock when the export is given no date, as the reproducible-builds specification defines it; a date passed in still wins, and a malformed value is ignored rather than refusing the export. The timestamp was the only thing that differed, so the files are now identical byte for byte. No readiness percentage change. - **2026-10-17** · PDF/X-4 export warns about fonts drawing visible text without an embedded font program, including placed PDF forms; `validate-pdf` reports the font and page (#909). Invisible OCR text is exempt. Detection only: fonts are not embedded or outlined automatically. diff --git a/crates/pdf/src/export/metadata.rs b/crates/pdf/src/export/metadata.rs index 619a0f5a5..b5993453f 100644 --- a/crates/pdf/src/export/metadata.rs +++ b/crates/pdf/src/export/metadata.rs @@ -11,6 +11,27 @@ pub(super) fn now_unix() -> Option { None } +/// The date an exported file records, when the caller gives none: `SOURCE_DATE_EPOCH` if it holds +/// a non-negative whole number of seconds, else the clock. Pinning it makes an export repeat its +/// bytes, which is otherwise impossible -- the only thing that differs between two exports of one +/// document is the timestamp, and the instance id krilla derives from the bytes follows it. +/// +/// +pub(super) fn export_time() -> Option { + pinned_or(|name| std::env::var(name).ok(), now_unix) +} + +/// [`export_time`] with the environment and the clock given, so a test can show which wins. +fn pinned_or(get: impl Fn(&str) -> Option, clock: impl Fn() -> Option) -> Option { + let pinned = get("SOURCE_DATE_EPOCH").and_then(|v| v.trim().parse::().ok()).filter(|secs| PDF_DATES.contains(secs)); + pinned.or_else(clock) +} + +/// The dates a PDF can hold, as Unix seconds: `date_time` clamps the year to 0..=9999, so a value +/// outside this would be recorded as some other date rather than the one asked for. A value that +/// cannot be honoured is left to the clock, as a malformed one is. +const PDF_DATES: std::ops::RangeInclusive = 0..=253_402_300_799; + /// The document information from File Info (title, author, description, keywords). `title` and /// `author` from the export options replace File Info's. pub(super) fn file_info_metadata(doc: &Document, title: Option<&str>, author: Option<&str>) -> Metadata { @@ -49,3 +70,42 @@ pub(crate) fn civil(t: i64) -> (i64, u8, u8, u8, u8, u8) { let (y, t) = designcraft_doc::time::utc_parts(t, 0); (y, t.month() as u8, t.day() as u8, t.hour() as u8, t.minute() as u8, t.second() as u8) } + +#[cfg(test)] +mod export_time_tests { + use super::pinned_or; + + /// What an export records when the caller gives no date: `SOURCE_DATE_EPOCH` when it holds a + /// non-negative whole number of seconds, the clock whenever it does not. The environment and + /// the clock are given here rather than set, so no test changes this process's environment -- + /// that is `unsafe` under edition 2024 and would reach every test beside it. + #[test] + fn a_pinned_epoch_is_preferred_and_the_clock_answers_otherwise() { + let env = |v: Option<&'static str>| move |_: &str| v.map(str::to_owned); + let clock = || Some(1_000_000); + assert_eq!(pinned_or(env(Some("1791208980")), clock), Some(1_791_208_980), "the variable wins"); + assert_eq!(pinned_or(env(Some("0")), clock), Some(0), "the epoch itself counts"); + assert_eq!(pinned_or(env(Some(" 1791208980 ")), clock), Some(1_791_208_980), "spaces around it are allowed"); + // A date a PDF cannot hold is left to the clock too: `date_time` would clamp the year and + // record some other date. 253402300799 is 9999-12-31T23:59:59Z, the last one it can. + assert_eq!(pinned_or(env(Some("253402300799")), clock), Some(253_402_300_799), "the last date a PDF can hold"); + for ignored in [ + None, + Some(""), + Some(" "), + Some("-1"), + Some("later"), + Some("1791208980.5"), + Some("99999999999999999999"), + Some("253402300800"), + Some("9223372036854775807"), + ] { + assert_eq!(pinned_or(env(ignored), clock), Some(1_000_000), "{ignored:?} leaves it to the clock"); + } + // A platform with no clock and no variable records no date at all. + assert_eq!(pinned_or(env(None), || None), None); + assert_eq!(pinned_or(env(Some("1791208980")), || None), Some(1_791_208_980), "the variable needs no clock"); + // Only that variable is read. + assert_eq!(pinned_or(|name: &str| (name == "TZ").then(|| "1791208980".to_owned()), clock), Some(1_000_000)); + } +} diff --git a/crates/pdf/src/export/pipeline.rs b/crates/pdf/src/export/pipeline.rs index ca9d1a988..ffef45c87 100644 --- a/crates/pdf/src/export/pipeline.rs +++ b/crates/pdf/src/export/pipeline.rs @@ -1,6 +1,6 @@ use super::common::{tf, to_path}; use super::images::ImageContentCache; -use super::metadata::{date_time, file_info_metadata, now_unix}; +use super::metadata::{date_time, export_time, file_info_metadata}; use super::*; /// Export `doc` as PDF bytes. @@ -162,7 +162,7 @@ fn export_pdf_with_report_inner(doc: &Document, cache: &Cache, opts: &PdfOptions }; let settings = krilla::SerializeSettings { compress_content_streams: opts.compress, configuration, ..base }; let title = opts.title.clone().unwrap_or_else(|| doc.title.clone()); - let created = opts.created.or_else(now_unix); + let created = opts.created.or_else(export_time); let metadata = Metadata { created: created.map(date_time), ..file_info_metadata(doc, opts.title.as_deref(), opts.author.as_deref()) }; let mut writer = Writer::new(settings, metadata); let pdf = writer.document_mut(); diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 7d6682c6d..987e7ea97 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -136,7 +136,8 @@ pub struct PdfOptions { /// Title for the metadata; `None` = the document title. pub title: Option, pub author: Option, - /// Creation date as Unix seconds (UTC); `None` = now (native) / omitted (wasm). + /// Creation date as Unix seconds (UTC). `None` takes `SOURCE_DATE_EPOCH` when it names a date + /// a PDF can hold, else the clock (native) / omitted (wasm). pub created: Option, /// Tagged PDF: stories become paragraphs in reading order, graphics figures with their alt /// text, parent-page items and printer's marks artifacts. From 79b871b94fe03052a5f00eb10085ee2f31523a70 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 28 Oct 2026 15:18:35 +0000 Subject: [PATCH 0324/1349] Strip story marker characters from placed plain text files Found while testing crates/textimport/src/lib.rs:140 (plain) and crates/engine/src/cmd/place_text.rs:372 (place_text) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/links.rs | 10 ++++++++++ crates/textimport/src/lib.rs | 11 ++++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 7a6d3a001..9c19a9a10 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -1092,6 +1092,16 @@ mod text_link_tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn placed_plain_text_drops_story_markers() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let b64 = crate::cmd::base64_encode("a\u{E009}b\u{E000}c\u{E002}d".as_bytes()); + let r = s.execute("file.place", &json!({"base64": b64, "name": "n.txt", "rect": [72, 72, 300, 200]})).unwrap(); + let st = s.doc().unwrap().doc.story(StoryId(r["story"].as_u64().unwrap())).unwrap(); + assert_eq!(st.text, "abcd"); + } + #[test] fn create_links_when_placing_text_files_preference() { let dir = std::env::temp_dir().join(format!("dc-text-link-pref-{}", std::process::id())); diff --git a/crates/textimport/src/lib.rs b/crates/textimport/src/lib.rs index 56eac1a00..eb4189156 100644 --- a/crates/textimport/src/lib.rs +++ b/crates/textimport/src/lib.rs @@ -117,9 +117,12 @@ pub fn import(name: &str, bytes: &[u8]) -> Result { Ok(plain(&tagged::decode(bytes))) } -/// Plain text: line breaks become paragraphs (CRLF / CR normalised). +/// Plain text: line breaks become paragraphs (CRLF / CR normalised). The private-use characters +/// (U+E000–U+E1FF) that stories use as markers are dropped, since a stray one would be read as a +/// marker without its payload. pub fn plain(text: &str) -> Imported { let t = text.trim_start_matches('\u{FEFF}').replace("\r\n", "\n").replace('\r', "\n"); + let t: String = t.chars().filter(|c| !('\u{E000}'..='\u{E1FF}').contains(c)).collect(); let story = Story::with_text(designcraft_doc::StoryId(0), &t, Default::default()); Imported { story, para_styles: vec![], char_styles: vec![], warnings: vec![] } } @@ -137,6 +140,12 @@ mod tests { assert!(matches!(import("x.doc", b"\xD0\xCF"), Err(ImportError::Unsupported(_)))); } + #[test] + fn plain_text_drops_story_markers() { + let i = import("a.txt", "a\u{E009}b\u{E000}c\u{E002}d".as_bytes()).unwrap(); + assert_eq!(i.story.text, "abcd"); + } + #[test] fn plain_text_utf16() { let mut le = vec![0xFF, 0xFE]; From ae7e87ddd0cc162f27263a07d6b89f0cd39335be Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:22:28 +0100 Subject: [PATCH 0325/1349] =?UTF-8?q?Skip=20signed=20hex=20codes=20in=20Ta?= =?UTF-8?q?gged=20Text=20<0x=E2=80=A6>=20tags?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Found while testing crates/textimport/src/tagged.rs:~190 (the `n.starts_with("0x")` branch of import: `u32::from_str_radix(&n[2..], 16)`) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/textimport/src/tagged.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/textimport/src/tagged.rs b/crates/textimport/src/tagged.rs index 74806ae4c..e903e98fd 100644 --- a/crates/textimport/src/tagged.rs +++ b/crates/textimport/src/tagged.rs @@ -176,7 +176,10 @@ pub fn import(bytes: &[u8]) -> Result { let (name, value) = tag.split_once(':').map_or((tag.as_str(), ""), |(a, b)| (a, b)); match name { n if n.starts_with("0x") => { - if let Ok(u) = u32::from_str_radix(&n[2..], 16) + // `from_str_radix` accepts a leading '+', so check the digits first. + if let Some(digits) = n.get(2..) + && digits.bytes().all(|b| b.is_ascii_hexdigit()) + && let Ok(u) = u32::from_str_radix(digits, 16) && let Some(ch) = units.push(u) { push(&mut paras, ch, &fmt); @@ -278,6 +281,16 @@ mod tests { assert_eq!(import("\r\nA<0xD83D>B<0xDE00>C".as_bytes()).unwrap().story.text, "ABC"); } + /// `from_str_radix` accepts a leading `+`, so `<0x+41>` inserted an 'A'. A signed or empty + /// code is not a code point tag and is skipped. + #[test] + fn a_signed_hex_code_tag_is_skipped() { + for t in ["<0x+41>", "<0x-41>", "<0x>", "<0xZZ>"] { + let src = format!("\r\nA{t}B"); + assert_eq!(import(src.as_bytes()).unwrap().story.text, "AB", "{t}"); + } + } + /// A size does not have to be non-finite to be nonsense: a file can hold `1e300`, `0` or a /// negative, and tagged text took all three and set them on the text (#1593). They are now /// dropped, as RTF and DOCX already dropped them, so the text keeps its style's size. From 97b42e3476679d4c0da8cf0c6a1af40a811e4b0f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 19:03:09 +0000 Subject: [PATCH 0326/1349] Cross-references: the edited text's IDML export moves into its own method Keeps story_para under clippy's cognitive-complexity limit, which upstream now enforces. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CgGsJkVe5GYG9qK6VFdECa --- crates/idml/src/export/story.rs | 57 +++++++++++++++++---------------- 1 file changed, 29 insertions(+), 28 deletions(-) diff --git a/crates/idml/src/export/story.rs b/crates/idml/src/export/story.rs index 4a067e402..1fcefd659 100644 --- a/crates/idml/src/export/story.rs +++ b/crates/idml/src/export/story.rs @@ -327,6 +327,34 @@ impl<'a> Ex<'a> { segs } + /// A cross-reference source's text: `generated`, or the text typed over it, its page numbers + /// as InDesign's live cross-reference page number. + fn xref_content(&mut self, c: &mut El, x: &designcraft_doc::CrossRef, generated: String) { + let Some(t) = &x.text else { + let mut content = El::new("Content"); + content.children.push(Node::Text(generated)); + c.push(content); + return; + }; + let page = x.page.clone().unwrap_or_else(|| "?".into()); + for (n, part) in t.split(designcraft_doc::xref::PAGE_NUM_BLOCK).enumerate() { + if n > 0 { + c.push( + El::new("TextVariableInstance") + .attr("Self", self.fresh()) + .attr("Name", "TV XRefPageNumber") + .attr("ResultText", &page) + .attr("AssociatedTextVariable", "dTextVariablenTV XRefPageNumber"), + ); + } + if !part.is_empty() { + let mut content = El::new("Content"); + content.children.push(Node::Text(part.to_string())); + c.push(content); + } + } + } + fn story_para(&mut self, s: &Story, pi: usize, r: std::ops::Range, last: bool) -> El { let pf = s.paras.get(pi).cloned().unwrap_or_default(); let mut psr = self.psr_el(&pf); @@ -424,34 +452,7 @@ impl<'a> Ex<'a> { designcraft_doc::xref::expand(self.d.xref_format(&x.format).map_or("", |ff| ff.definition.as_str()), &v) }); let mut c = self.csr_el(&f); - match &x.text { - // Edited text as typed, its page numbers as InDesign's live - // cross-reference page number. - Some(t) => { - let page = x.page.clone().unwrap_or_else(|| "?".into()); - for (n, part) in t.split(designcraft_doc::xref::PAGE_NUM_BLOCK).enumerate() { - if n > 0 { - c.push( - El::new("TextVariableInstance") - .attr("Self", self.fresh()) - .attr("Name", "TV XRefPageNumber") - .attr("ResultText", &page) - .attr("AssociatedTextVariable", "dTextVariablenTV XRefPageNumber"), - ); - } - if !part.is_empty() { - let mut content = El::new("Content"); - content.children.push(Node::Text(part.to_string())); - c.push(content); - } - } - } - None => { - let mut content = El::new("Content"); - content.children.push(Node::Text(text)); - c.push(content); - } - } + self.xref_content(&mut c, x, text); let mut src = El::new("CrossReferenceSource") .attr("Self", &me) .attr("AppliedFormat", fmt) From b11913eb9cb21a654c2d0b457152364bfa4d6736 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 14:33:20 -0700 Subject: [PATCH 0327/1349] Layers: copied anchors in cells and notes get ids no other anchor has Duplicate Layer gave the text anchors in copied table cells and notes the document's next ids, which can equal the ids of anchors that cell and note stories number on their own. Each copy now skips every anchor id already in the document. The layer commands also import what they use since main moved them into their own module. --- crates/engine/src/cmd/layout.rs | 7 +-- crates/engine/src/cmd/layout/layers.rs | 86 +++++++++++++++++++++++--- 2 files changed, 79 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index fbb8b2a52..5ec6abb4d 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -1,11 +1,6 @@ //! Layout menu and Pages/Layers panels: pages, spreads, parents, margins & columns, layers. -use std::collections::HashMap; -use std::sync::Arc; - -use designcraft_doc::{ - Content, Guide, Hyperlink, HyperlinkSource, Item, ItemId, LAYER_COLORS, Layer, LayerId, Margins, SpreadId, SpreadRef, Story, StoryId, -}; +use designcraft_doc::{LAYER_COLORS, Layer, LayerId, Margins, SpreadId}; use serde_json::{Value, json}; use super::{CommandSpec, bad, cmd, has_doc, ok, str_param}; diff --git a/crates/engine/src/cmd/layout/layers.rs b/crates/engine/src/cmd/layout/layers.rs index 05bfa4c66..a527df660 100644 --- a/crates/engine/src/cmd/layout/layers.rs +++ b/crates/engine/src/cmd/layout/layers.rs @@ -1,4 +1,9 @@ -use super::{LAYER_COLORS, LayerId, Result, Session, Value, bad, ok}; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use designcraft_doc::{Content, Guide, Hyperlink, HyperlinkSource, Item, ItemId, SpreadRef, Story, StoryId}; + +use super::{LAYER_COLORS, Layer, LayerId, Result, Session, Value, bad, json, ok}; /// Layer Options: every field in one undo step; a bad name or colour changes nothing. pub(super) fn set_layer(s: &mut Session, p: &Value) -> Result { @@ -105,6 +110,10 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { // and those of the other copies point at, and tables with ids of their own, the tables in its cells and notes // included, allocated in story order. let mut anchors = HashMap::new(); + let mut used = HashSet::new(); + for st in d.stories.values() { + anchor_ids(st, &mut used); + } let mut order: Vec<(StoryId, StoryId)> = stories.iter().map(|(old, new)| (*old, *new)).collect(); order.sort_unstable_by_key(|(_, new)| *new); for (old, new) in &order { @@ -116,10 +125,11 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { for (k, a) in (1..).zip(st.anchors.iter_mut()) { let id = (new.0 << 24) + k; anchors.insert(a.id, id); + used.insert(id); Arc::make_mut(a).id = id; } renumber_tables(d, &mut st); - renumber_nested_anchors(d, &mut st, &mut anchors); + renumber_nested_anchors(d, &mut st, &mut anchors, &mut used); d.stories.insert(*new, Arc::new(st)); } for new in stories.values() { @@ -261,22 +271,40 @@ fn renumber_tables(d: &mut designcraft_doc::Document, st: &mut Story) { } } -fn renumber_nested_anchors(d: &mut designcraft_doc::Document, st: &mut Story, anchors: &mut HashMap) { - fn child(d: &mut designcraft_doc::Document, st: &mut Story, anchors: &mut HashMap) { +/// Add the ids of the text anchors in `st`, and in the stories of its table cells and notes at any depth, to `used`. +/// The walk keeps its own stack, so a story on another layer that nests deeper than [`too_deep`] allows is read too. +fn anchor_ids(st: &Story, used: &mut HashSet) { + let mut stack = vec![st]; + while let Some(st) = stack.pop() { + used.extend(st.anchors.iter().map(|a| a.id)); + stack.extend(st.tables.values().flat_map(|t| t.cells.iter().map(|c| &c.text))); + stack.extend(st.notes.iter().chain(st.endnotes.iter()).map(|n| &n.text)); + } +} + +/// Give the text anchors in the stories of the table cells and notes of `st` new ids from `d` that are not in `used` +/// (recorded in `anchors` and `used`). [`too_deep`] bounds the nesting. +fn renumber_nested_anchors(d: &mut designcraft_doc::Document, st: &mut Story, anchors: &mut HashMap, used: &mut HashSet) { + fn child(d: &mut designcraft_doc::Document, st: &mut Story, anchors: &mut HashMap, used: &mut HashSet) { for anchor in &mut st.anchors { - let id = d.alloc(); + let id = loop { + let id = d.alloc(); + if used.insert(id) { + break id; + } + }; anchors.insert(anchor.id, id); Arc::make_mut(anchor).id = id; } - renumber_nested_anchors(d, st, anchors); + renumber_nested_anchors(d, st, anchors, used); } for table in st.tables.values_mut() { for cell in &mut Arc::make_mut(table).cells { - child(d, &mut cell.text, anchors); + child(d, &mut cell.text, anchors, used); } } for note in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { - child(d, &mut Arc::make_mut(note).text, anchors); + child(d, &mut Arc::make_mut(note).text, anchors, used); } } @@ -797,6 +825,48 @@ mod layer_tests { assert_eq!(redone, after); } + #[test] + fn duplicate_layer_gives_copied_cell_anchors_ids_no_other_anchor_has() { + use std::sync::Arc; + + fn ids(st: &designcraft_doc::Story, out: &mut Vec) { + out.extend(st.anchors.iter().map(|a| a.id)); + for table in st.tables.values() { + for cell in &table.cells { + ids(&cell.text, out); + } + } + } + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Rows"})).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let table_id = d.alloc(); + // The cell's anchors take the ids the document hands out next, as anchors made in a cell story can. + let start = d.alloc(); + let mut table = designcraft_doc::Table::new(table_id, 1, 1, 0, 0, 40.0); + let cell = &mut table.cells[0].text; + for k in 1..=64 { + cell.insert_anchor(0, "Heading"); + Arc::make_mut(&mut cell.anchors[0]).id = start + k; + } + d.story_mut(sid).unwrap().insert_table(0, table); + let mut original = Vec::new(); + ids(d.story(sid).unwrap(), &mut original); + assert_eq!(original.len(), 64); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copied = on_layer(d, copy)[0].text_frame().unwrap().story; + let mut after = Vec::new(); + ids(d.story(copied).unwrap(), &mut after); + assert_eq!(after.len(), original.len()); + for id in &after { + assert!(!original.contains(id), "copied cell anchor {id} has the id of an original anchor"); + } + } + #[test] fn duplicate_layer_gives_copied_tables_their_own_ids() { let mut s = crate::Session::new(); From ba1ee2329b971bb2dc7dde669846f44618290be4 Mon Sep 17 00:00:00 2001 From: VoiceLessQ Date: Wed, 28 Oct 2026 21:10:50 -0200 Subject: [PATCH 0328/1349] Give anchored objects fresh ids when copying text frames (fixes #1522) Copying a text frame cloned its story but left the objects anchored in it with the original's item ids. Save does not validate, load runs Document::check and rejects duplicate ids, so a duplicated or pasted frame with an inline graphic produced a file that failed to open with "not a DesignCraft document: duplicate item id". renumber (Duplicate, Alt-drag copy, Paste, Paste into text, parent item overrides) and the data merge copy now give every anchored item in the copied story, its table cells, footnotes and endnotes a fresh id. Anchored text frames from IDML get their own story copy. Assets are not adopted again: the story copy already remapped them. The IDML export tests that relied on duplication to create shared ids now set the shared id explicitly, so the export guard stays covered. Files already saved with duplicate ids still do not open. --- ROADMAP.md | 4 + crates/engine/src/cmd/datamerge/fill.rs | 29 ++++++- crates/engine/src/cmd/datamerge/tests.rs | 16 ++++ crates/engine/src/cmd/interchange.rs | 35 +++++--- crates/engine/src/cmd/object.rs | 103 ++++++++++++++++++++++- 5 files changed, 166 insertions(+), 21 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index c02176bab..bdd8ec314 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -12,6 +12,10 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, open (documented JSON format + IDML), scriptable by agents (MCP), and available on the web. +- **2026-10-28** · Duplicate, paste, parent overrides and data merge give anchored objects in the + copied story fresh ids (#1522). Copies used to keep the original's ids, and the saved file then + failed to open with "duplicate item id". Files already saved that way still don't open; no + readiness percentage change. - **2026-10-25** · The application bar uses craft-window's shared title-bar code. A drag that starts on a floating panel over the bar moves the panel, not the window, and in full screen the bar no longer zooms or moves the window. No readiness percentage change. diff --git a/crates/engine/src/cmd/datamerge/fill.rs b/crates/engine/src/cmd/datamerge/fill.rs index 629258d6d..f2e60baae 100644 --- a/crates/engine/src/cmd/datamerge/fill.rs +++ b/crates/engine/src/cmd/datamerge/fill.rs @@ -71,11 +71,17 @@ pub fn copy_item( } fn renumber(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Document, it: &mut Item, maps: &mut Maps) { + renumber_in(dst, src, it, maps, true); +} + +/// `adopt` is false inside a story copy, whose asset references the copy has already adopted. +fn renumber_in(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Document, it: &mut Item, maps: &mut Maps, adopt: bool) { let old = it.id; let new_id = ItemId(dst.alloc()); maps.items.insert(old, new_id); it.id = new_id; - if let Some(m) = it.media.as_mut() + if adopt + && let Some(m) = it.media.as_mut() && let Some(p) = m.poster { m.poster = dst.adopt_asset(src, p).or(Some(p)); @@ -98,8 +104,10 @@ fn renumber(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Document } designcraft_doc::remap_story_assets(&mut st, &assets); st.frames.clear(); - dst.stories.insert(n, Arc::new(st)); + // Mapped first: the map is the seen-set that stops story recursion. maps.stories.insert(tf.story, n); + renumber_anchored(dst, src, &mut st, maps); + dst.stories.insert(n, Arc::new(st)); n }; tf.story = new_sid; @@ -108,19 +116,32 @@ fn renumber(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Document } } Content::Graphic(g) => { - if let Some(a) = dst.adopt_asset(src, g.asset) { + if adopt && let Some(a) = dst.adopt_asset(src, g.asset) { g.asset = a; } } Content::Group { items } => { for child in items.iter_mut() { - renumber(dst, src, Arc::make_mut(child), maps); + renumber_in(dst, src, Arc::make_mut(child), maps, adopt); } } Content::Unassigned => {} } } +/// Fresh ids for the objects anchored in story copy `st`, its table cells, footnotes and endnotes (#1522). +fn renumber_anchored(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Document, st: &mut Story, maps: &mut Maps) { + let mut fresh = |t: &mut Story| { + for o in &mut t.objects { + renumber_in(dst, src, &mut Arc::make_mut(o).item, maps, false); + } + }; + st.for_each_text_mut(&mut fresh); + for n in &mut st.endnotes { + Arc::make_mut(n).text.for_each_text_mut(&mut fresh); + } +} + struct Rep { story: StoryId, start: usize, diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index 79e16027e..2195bdf62 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -1198,3 +1198,19 @@ fn facing_pages_merge_tiles_short_blocks_without_stacking() { let unique: std::collections::BTreeSet<_> = origins.iter().collect(); assert_eq!(unique.len(), 3, "no two records may share a page and coordinates: {origins:?}"); } + +// #1522: each record's copy of an anchored object needs its own id, or the merged file won't reopen. +#[test] +fn merged_records_give_anchored_objects_their_own_ids() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name\nAda\nGrace\n"); + let made = text_frame(&mut s, [36.0, 36.0, 400.0, 80.0], "<> here", None); + let b = exec(&mut s, "frame.create", json!({"rect": [450, 450, 474, 490]})); + exec(&mut s, "anchored.insert", json!({"ids": [b["id"]], "story": made["story"], "pos": 2})); + assert_eq!(exec(&mut s, "data.merge", json!({}))["records"], 2); + let doc = &s.documents()[s.active_index().unwrap()].doc; + assert_eq!(doc.anchored_items().len(), 2); + doc.check().unwrap(); + designcraft_format::load(&designcraft_format::save(doc).unwrap()).unwrap(); +} diff --git a/crates/engine/src/cmd/interchange.rs b/crates/engine/src/cmd/interchange.rs index 0ddb6a1aa..152761fb1 100644 --- a/crates/engine/src/cmd/interchange.rs +++ b/crates/engine/src/cmd/interchange.rs @@ -74,7 +74,7 @@ fn with_pdf_layer_variants(doc: &Document, embed: bool) -> Result = doc.placed_items().into_iter().filter(|i| i.has_pdf_layer_override()).map(|i| i.id).collect(); - assert_eq!(with_choice, [chosen, chosen], "both placements share one id"); - assert!(doc.check().unwrap_err().to_string().contains(&format!("duplicate item id {chosen}"))); + assert_eq!(with_choice.len(), 2); + assert!(with_choice.contains(&chosen) && with_choice[0] != with_choice[1], "{with_choice:?}"); + doc.check().unwrap(); let result = s.execute("file.exportIdml", &json!({})).unwrap(); let imported = designcraft_idml::import_idml(&base64_decode(result["base64"].as_str().unwrap())).unwrap(); let mut layers: Vec<_> = @@ -831,8 +832,8 @@ mod nested_layer_tests { assert_eq!(layers, vec![states(false, true), states(true, false)]); } - // Shared anchored ids are a pre-existing duplication gap. Conflicting choices must not - // silently select one variant; this fixture changes only the copied anchor's choice. + // Duplication no longer shares anchored ids (#1522), so this fixture forces the shared id. + // Conflicting choices must not silently select one variant; only the copy's choice changes. #[test] fn shared_id_with_divergent_pdf_choices_is_rejected() { let mut s = Session::new(); @@ -840,23 +841,25 @@ mod nested_layer_tests { let pdf = designcraft_render::pdf_hide_layers(&super::super::pdflayers::tests::two_layer_pdf(), &["Red".into()]).unwrap(); let placed = s.execute("file.place", &json!({"base64": base64_encode(&pdf), "name": "layers.pdf"})).unwrap(); let control = ItemId(placed["id"].as_u64().unwrap()); - let frame = { + let (frame, anchored) = { let doc = Arc::make_mut(&mut s.doc_mut().unwrap().doc); let mut item = doc.item(control).unwrap().clone(); item.id = ItemId(doc.alloc()); item.pdf_hidden_layers = vec!["Blue".into()]; + let anchored = item.id; let layer = doc.default_layer(); let (frame, sid) = doc.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 200.0, 200.0), layer, "Body", Default::default()).unwrap(); doc.story_mut(sid).unwrap().insert_object(0, AnchoredObject { item, position: Default::default() }); - frame + (frame, anchored) }; s.execute("transform.move", &json!({"ids": [frame.0], "dx": 10, "dy": 10, "copy": true})).unwrap(); - // Change ONLY the copy in the newest story to explicit all-on. + // Give ONLY the copy in the newest story the original's id and explicit all-on. { let doc = Arc::make_mut(&mut s.doc_mut().unwrap().doc); let (_, st) = doc.stories.iter_mut().filter(|(_, st)| !st.objects.is_empty()).last().unwrap(); let o = &mut Arc::make_mut(st).objects[0]; let it = &mut Arc::make_mut(o).item; + it.id = anchored; it.pdf_hidden_layers.clear(); it.pdf_layer_override = true; } @@ -871,8 +874,8 @@ mod nested_layer_tests { assert!(Arc::ptr_eq(&before, &s.doc().unwrap().doc)); } - // Cross-document paste: the pasted frame's anchored placement keeps its source id, - // which can collide with an unrelated placement in the destination. + // Cross-document paste used to keep the anchored placement's source id (#1522), colliding + // with an unrelated placement in the destination. The fixture forces that collision. #[test] fn shared_id_with_different_pdf_assets_is_rejected() { let mut s = Session::new(); @@ -893,7 +896,13 @@ mod nested_layer_tests { .as_u64() .unwrap(); s.execute("edit.paste", &json!({})).unwrap(); - assert_eq!(a, b, "fresh documents allocate the same first placement id"); + { + let doc = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let (_, st) = doc.stories.iter_mut().find(|(_, st)| !st.objects.is_empty()).unwrap(); + let pasted = &mut Arc::make_mut(&mut Arc::make_mut(st).objects[0]).item; + assert_ne!(pasted.id.0, b, "paste gives the anchored placement a fresh id"); + pasted.id = ItemId(b); + } let before = s.doc().unwrap().doc.clone(); let graphics: Vec<_> = before.placed_items().into_iter().filter(|i| i.graphic().is_some()).collect(); assert_eq!(graphics.len(), 2); diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index ad8b25213..9ba95cf7c 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -1076,9 +1076,15 @@ fn adopt_or_dangle(dst: &mut Document, src: &Document, id: AssetId) -> AssetId { /// Give `it` (an item of `src`) fresh ids from `dst`, with copies of its stories and the assets it uses. pub(crate) fn renumber(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut HashMap) { + renumber_in(dst, src, it, stories, true); +} + +/// `adopt` is false inside a story copy, whose asset references the copy has already adopted. +fn renumber_in(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut HashMap, adopt: bool) { it.id = ItemId(dst.alloc()); let my_id = it.id; - if let Some(m) = it.media.as_mut() + if adopt + && let Some(m) = it.media.as_mut() && let Some(p) = m.poster { m.poster = Some(adopt_or_dangle(dst, src, p)); @@ -1100,8 +1106,10 @@ pub(crate) fn renumber(dst: &mut Document, src: &Document, it: &mut Item, storie } designcraft_doc::remap_story_assets(&mut st, &assets); st.frames.clear(); - dst.stories.insert(n, Arc::new(st)); + // Mapped first: the map is the seen-set that stops story recursion. stories.insert(tf.story, n); + renumber_anchored(dst, src, &mut st, stories); + dst.stories.insert(n, Arc::new(st)); n } }; @@ -1111,17 +1119,32 @@ pub(crate) fn renumber(dst: &mut Document, src: &Document, it: &mut Item, storie } } Content::Graphic(g) => { - g.asset = adopt_or_dangle(dst, src, g.asset); + if adopt { + g.asset = adopt_or_dangle(dst, src, g.asset); + } } Content::Group { items } => { for c in items.iter_mut() { - renumber(dst, src, Arc::make_mut(c), stories); + renumber_in(dst, src, Arc::make_mut(c), stories, adopt); } } Content::Unassigned => {} } } +/// Fresh ids for the objects anchored in story copy `st`, its table cells, footnotes and endnotes (#1522). +fn renumber_anchored(dst: &mut Document, src: &Document, st: &mut Story, stories: &mut HashMap) { + let mut fresh = |t: &mut Story| { + for o in &mut t.objects { + renumber_in(dst, src, &mut Arc::make_mut(o).item, stories, false); + } + }; + st.for_each_text_mut(&mut fresh); + for n in &mut st.endnotes { + Arc::make_mut(n).text.for_each_text_mut(&mut fresh); + } +} + fn transform_move(s: &mut Session, p: &Value) -> Result { let ids = targets(s, p)?; let (dx, dy) = (f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0)); @@ -5701,3 +5724,75 @@ mod frame_baseline_grid_tests { assert_eq!(grid(&s), None); } } + +#[cfg(test)] +mod anchored_copy_tests { + use super::*; + use designcraft_doc::AnchoredObject; + + /// A text frame with an inline rectangle; returns the frame and the anchored item's id. + fn frame_with_inline_box(s: &mut Session) -> (ItemId, ItemId) { + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Before after."})).unwrap(); + let frame = ItemId(r["id"].as_u64().unwrap()); + let sid = s.doc().unwrap().doc.item(frame).unwrap().text_frame().unwrap().story; + let b = s.execute("frame.create", &json!({"rect": [450, 450, 474, 490]})).unwrap(); + s.execute("anchored.insert", &json!({"ids": [b["id"]], "story": sid.0, "pos": 7})).unwrap(); + (frame, s.doc().unwrap().doc.story(sid).unwrap().objects[0].item.id) + } + + fn assert_reopens(doc: &Document) { + doc.check().unwrap(); + designcraft_format::load(&designcraft_format::save(doc).unwrap()).unwrap(); + } + + // #1522: the copy kept the anchored object's id, and the saved file no longer opened. + #[test] + fn duplicating_a_frame_with_an_anchored_object_saves_a_file_that_reopens() { + let mut s = Session::new(); + let (frame, anchored) = frame_with_inline_box(&mut s); + s.execute("transform.move", &json!({"ids": [frame.0], "dx": 10, "dy": 10, "copy": true})).unwrap(); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.anchored_items().iter().filter(|(_, i)| i.id == anchored).count(), 1); + assert_eq!(doc.anchored_items().len(), 2); + assert_reopens(doc); + } + + #[test] + fn pasting_a_frame_with_an_anchored_object_twice_keeps_ids_unique() { + let mut s = Session::new(); + let (frame, _) = frame_with_inline_box(&mut s); + s.execute("selection.set", &json!({"ids": [frame.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.anchored_items().len(), 3); + assert_reopens(doc); + } + + // IDML import can anchor a text frame; its story is copied too, with the copy in its thread. + #[test] + fn an_anchored_text_frame_gets_its_own_story_copy() { + let mut d = Document::new(&designcraft_doc::build::NewDocument::default()); + let layer = d.default_layer(); + let (host, host_sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 300.0, 300.0), layer, "Host", ParaFormat::default()).unwrap(); + let (inner, inner_sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 50.0, 50.0), layer, "Inner", ParaFormat::default()).unwrap(); + let item = d.item(inner).unwrap().clone(); + let inner_story = d.stories.get(&inner_sid).unwrap().clone(); + d.remove_item(inner).unwrap(); + d.stories.insert(inner_sid, inner_story); + d.story_mut(host_sid).unwrap().insert_object(0, AnchoredObject { item, position: Default::default() }); + d.check().unwrap(); + let src = d.clone(); + let copy = duplicate_from(&mut d, &src, &[host], SpreadRef::Doc(0), Vec2::new(10.0, 10.0)).unwrap(); + let copy_sid = d.item(copy[0]).unwrap().text_frame().unwrap().story; + let anchored = &d.story(copy_sid).unwrap().objects[0].item; + assert_ne!(anchored.id, inner); + let anchored_sid = anchored.text_frame().unwrap().story; + assert_ne!(anchored_sid, inner_sid); + assert_eq!(d.story(anchored_sid).unwrap().frames, [anchored.id]); + assert_eq!(d.story(inner_sid).unwrap().frames, [inner]); + assert_reopens(&d); + } +} From e248b631659c79b169413d2005290bc38256b9f4 Mon Sep 17 00:00:00 2001 From: VoiceLessQ Date: Wed, 28 Oct 2026 21:46:56 -0200 Subject: [PATCH 0329/1349] Autoflow: a frame a Start Paragraph option ends early sets no fill rate (fixes #1209) fit() counted the frame before a paragraph that starts on the next column, frame, page or odd/even page as a full frame. With a short title before such a paragraph, autoflow estimated a page per few bytes left and added up to 2000 pages before removing them again: placing 2000 words took 35.6 s in the app, now 0.36 s, with the same pages. The option is resolved through the paragraph style, so an imported Word style counts the same as a local override. --- ROADMAP.md | 1 + crates/engine/src/cmd/place_text.rs | 15 ++++++--- crates/engine/src/cmd/place_text/tests.rs | 37 +++++++++++++++++++++++ 3 files changed, 49 insertions(+), 4 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index c02176bab..20525e4a6 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -380,6 +380,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-10-28** · Autoflow no longer sizes the rest of a story by a frame that a Start Paragraph option (next column, frame, page, or odd or even page) ends early (#1209). With a title before a chapter that starts on the next odd page, it estimated a page per few characters, added up to 2000 pages (the autoflow limit) and removed them again: placing 2000 words took 36 s in the app, now 0.4 s, with the same pages. No readiness percentage change. - **2026-10-27** · An iconic panel's flyout stays open while you work in the canvas or a text field: Auto-Collapse Iconic Panels is off by default, and preferences saved with it on start with it off. Preferences › Interface › Panels holds the setting next to the column bar's menu item. No readiness percentage change. - **2026-10-24** · Column rules run from the top line's ascent to the bottom line's descent, as InDesign draws them, instead of from the top to the bottom of the columns, on screen, in PDF and in PowerPoint export. The top and bottom insets shorten the rule from those lines. Existing documents draw their column rules at the new length. No readiness percentage change. - **2026-10-20** · Edit › Keyboard Shortcuts is craft-keymap's shared dialog: commands grouped by menu with Show and Filter, recording that asks before taking a key from another command, undo and redo, named shortcut sets (edits of Default become Custom; an imported set becomes a set of its own), an on-screen US keyboard, InDesign Show Set files reviewed before they apply, JSON export and an HTML summary. ui.json keeps the `shortcuts` map earlier versions read, for the active set. No readiness percentage change. diff --git a/crates/engine/src/cmd/place_text.rs b/crates/engine/src/cmd/place_text.rs index 4f9aaf1aa..7932a185c 100644 --- a/crates/engine/src/cmd/place_text.rs +++ b/crates/engine/src/cmd/place_text.rs @@ -3,7 +3,7 @@ //! until the whole story fits (InDesign's Shift-click with a loaded text cursor). use designcraft_doc::{ - CharacterStyle, Content, Document, ParaFormat, ParagraphStyle, SpreadRef, Story, StoryId, TextDirection, TextFileLink, TextSel, + CharacterStyle, Content, Document, ParaFormat, ParagraphStyle, SpreadRef, StartParagraph, Story, StoryId, TextDirection, TextFileLink, TextSel, }; use designcraft_geom::Rect; use serde_json::{Value, json}; @@ -199,14 +199,21 @@ pub(crate) fn reimport( /// Is the story overset in its frames, and how much text do its full frames hold (bytes, frames)? /// A frame a column, frame or page break ends early is left out: it says nothing about how much -/// a frame holds. +/// a frame holds. So is one a Start Paragraph option ends early (#1209). fn fit(d: &Document, sid: StoryId) -> (Option, usize, usize) { let cs = designcraft_compose::compose_story(d, sid, &Default::default()); - let text = d.story(sid).map_or("", |s| s.text.as_str()); + let Some(story) = d.story(sid) else { return (cs.overset_at, 0, 0) }; + let text = story.text.as_str(); + // A frame's range stops before the paragraph's return. + let moved_on = |end: usize| { + let next = if text.as_bytes().get(end) == Some(&b'\n') { end.saturating_add(1) } else { end }; + next.checked_sub(1).is_some_and(|i| text.as_bytes().get(i) == Some(&b'\n')) + && story.paras.get(story.para_at(next)).is_some_and(|p| d.styles.resolve_para(p).0.start_paragraph != StartParagraph::Anywhere) + }; let (mut held, mut full) = (0, 0); for f in &cs.frames { let Some(shown) = text.get(f.range.clone()) else { continue }; - if !shown.is_empty() && !shown.chars().any(designcraft_doc::is_break_char) { + if !shown.is_empty() && !shown.chars().any(designcraft_doc::is_break_char) && !moved_on(f.range.end) { held += shown.len(); full += 1; } diff --git a/crates/engine/src/cmd/place_text/tests.rs b/crates/engine/src/cmd/place_text/tests.rs index 006762ab2..bdce2a975 100644 --- a/crates/engine/src/cmd/place_text/tests.rs +++ b/crates/engine/src/cmd/place_text/tests.rs @@ -307,3 +307,40 @@ fn autoflow_adds_the_pages_odd_and_even_page_breaks_ask_for() { assert_eq!(designcraft_compose::compose_story(&d, sid, &Default::default()).overset_at, None, "{brk:?}"); } } + +#[test] +fn autoflow_sizes_no_frame_by_one_a_start_option_ends_early() { + // Regression (#1209): the title frame a start option ends early isn't a frame's worth of text. + use std::io::Write; + const W: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#; + let para = |style: &str, text: &str| format!(r#"{text}"#); + let body = [para("Title", "Front"), para("Chapter", "Chapter one"), para("Body", "lorem ipsum dolor sit amet ".repeat(60).trim())].concat(); + let styles: String = ["Title", "Chapter", "Body"] + .iter() + .map(|s| format!(r#""#)) + .collect(); + let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let o = zip::write::SimpleFileOptions::default(); + for (n, c) in [ + ("word/document.xml", format!(r#"{body}"#)), + ("word/styles.xml", format!(r#"{styles}"#)), + ] { + w.start_file(n, o).unwrap(); + w.write_all(c.as_bytes()).unwrap(); + } + let docx = w.finish().unwrap().into_inner(); + for (start, pages) in [("nextOddPage", 5), ("nextEvenPage", 4)] { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 3, "facingPages": true})).unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Chapter", "para": {"startParagraph": start}})).unwrap(); + let ids = s.doc().unwrap().doc.next_id; + let r = s + .execute("file.place", &json!({"base64": super::super::file::base64_encode(&docx), "name": "front.docx", "page": 3, "autoflow": true})) + .unwrap(); + assert_eq!(r["overset"], false, "{start}: {r}"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.page_count(), pages, "{start}: {r}"); + // A few ids per page it keeps, not hundreds for pages it builds and removes. + assert!(d.next_id - ids < 100, "{start}: {} ids", d.next_id - ids); + } +} From ca85be89d2c3a4a1df225a807be9eb4fe2ab8ab7 Mon Sep 17 00:00:00 2001 From: VoiceLessQ Date: Wed, 28 Oct 2026 22:32:07 -0200 Subject: [PATCH 0330/1349] Autoflow: skip deleted paragraphs and ask for every forced frame at once (#1209) The start option lookup now reads the next paragraph composing places, past tracked-deleted ones. Frames that start options and breaks force are counted and asked for in one round, so a story with a paragraph per page no longer gets one frame per round. --- ROADMAP.md | 2 +- crates/compose/src/lib.rs | 4 +-- crates/engine/src/cmd/place_text.rs | 34 ++++++++++++++++------- crates/engine/src/cmd/place_text/tests.rs | 33 ++++++++++++++++++++++ 4 files changed, 60 insertions(+), 13 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 20525e4a6..deda0dc4f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -380,7 +380,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. -- **2026-10-28** · Autoflow no longer sizes the rest of a story by a frame that a Start Paragraph option (next column, frame, page, or odd or even page) ends early (#1209). With a title before a chapter that starts on the next odd page, it estimated a page per few characters, added up to 2000 pages (the autoflow limit) and removed them again: placing 2000 words took 36 s in the app, now 0.4 s, with the same pages. No readiness percentage change. +- **2026-10-28** · Autoflow no longer sizes the rest of a story by a frame that a Start Paragraph option (next column, frame, page, or odd or even page) ends early (#1209). With a title before a chapter that starts on the next odd page, it estimated a page per few characters, added up to 2000 pages (the autoflow limit) and removed them again: placing 2000 words took 36 s in the app, now 0.4 s, with the same pages. It looks past tracked-deleted paragraphs for the option, as composing does, and asks for every frame that start options and breaks force in one round: 200 one-line chapters on their own pages take 9 ms (58 ms before). No readiness percentage change. - **2026-10-27** · An iconic panel's flyout stays open while you work in the canvas or a text field: Auto-Collapse Iconic Panels is off by default, and preferences saved with it on start with it off. Preferences › Interface › Panels holds the setting next to the column bar's menu item. No readiness percentage change. - **2026-10-24** · Column rules run from the top line's ascent to the bottom line's descent, as InDesign draws them, instead of from the top to the bottom of the columns, on screen, in PDF and in PowerPoint export. The top and bottom insets shorten the rule from those lines. Existing documents draw their column rules at the new length. No readiness percentage change. - **2026-10-20** · Edit › Keyboard Shortcuts is craft-keymap's shared dialog: commands grouped by menu with Show and Filter, recording that asks before taking a key from another command, undo and redo, named shortcut sets (edits of Default become Custom; an imported set becomes a set of its own), an on-screen US keyboard, InDesign Show Set files reviewed before they apply, JSON export and an HTML summary. ui.json keeps the `shortcuts` map earlier versions read, for the active set. No readiness percentage change. diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 88becd85f..131e5273c 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -3483,8 +3483,8 @@ fn rewind( } /// Paragraphs that tracked changes delete: all their text is deleted, and so is their return or -/// the return before them (then they join a paragraph and add nothing to it). -fn deleted_paras(story: &Story, ranges: &[Range]) -> Vec { +/// the return before them (then they join a paragraph and add nothing to it). Composing skips them. +pub fn deleted_paras(story: &Story, ranges: &[Range]) -> Vec { let mut spans: Vec> = Vec::new(); for (r, f) in story.runs() { if f.over.change != Some(designcraft_doc::ChangeMark::Deleted) { diff --git a/crates/engine/src/cmd/place_text.rs b/crates/engine/src/cmd/place_text.rs index 7932a185c..961f6f630 100644 --- a/crates/engine/src/cmd/place_text.rs +++ b/crates/engine/src/cmd/place_text.rs @@ -197,18 +197,24 @@ pub(crate) fn reimport( Ok(imp.warnings) } -/// Is the story overset in its frames, and how much text do its full frames hold (bytes, frames)? +/// Is the story overset in its frames, how much text do its full frames hold (bytes, frames), and +/// how many frames does the overset text start on its own (breaks, Start Paragraph options)? /// A frame a column, frame or page break ends early is left out: it says nothing about how much /// a frame holds. So is one a Start Paragraph option ends early (#1209). -fn fit(d: &Document, sid: StoryId) -> (Option, usize, usize) { +fn fit(d: &Document, sid: StoryId) -> (Option, usize, usize, usize) { let cs = designcraft_compose::compose_story(d, sid, &Default::default()); - let Some(story) = d.story(sid) else { return (cs.overset_at, 0, 0) }; + let Some(story) = d.story(sid) else { return (cs.overset_at, 0, 0, 0) }; let text = story.text.as_str(); - // A frame's range stops before the paragraph's return. + let deleted = designcraft_compose::deleted_paras(story, &story.para_ranges()); + let starts = |p: usize| { + !deleted.get(p).copied().unwrap_or(false) + && story.paras.get(p).is_some_and(|pf| d.styles.resolve_para(pf).0.start_paragraph != StartParagraph::Anywhere) + }; + // A frame's range stops before the paragraph's return; composing skips deleted paragraphs. let moved_on = |end: usize| { let next = if text.as_bytes().get(end) == Some(&b'\n') { end.saturating_add(1) } else { end }; next.checked_sub(1).is_some_and(|i| text.as_bytes().get(i) == Some(&b'\n')) - && story.paras.get(story.para_at(next)).is_some_and(|p| d.styles.resolve_para(p).0.start_paragraph != StartParagraph::Anywhere) + && (story.para_at(next)..story.paras.len()).find(|&p| !deleted.get(p).copied().unwrap_or(false)).is_some_and(starts) }; let (mut held, mut full) = (0, 0); for f in &cs.frames { @@ -218,7 +224,14 @@ fn fit(d: &Document, sid: StoryId) -> (Option, usize, usize) { full += 1; } } - (cs.overset_at, held, full) + let forced = cs.overset_at.map_or(0, |at| { + let first = story.para_at(at); + // The paragraph the overset text starts with counts when it starts there. + let from = if at.checked_sub(1).is_none_or(|i| text.as_bytes().get(i) == Some(&b'\n')) { first } else { first.saturating_add(1) }; + let breaks = text.get(at..).map_or(0, |t| t.chars().filter(|&c| designcraft_doc::is_break_char(c)).count()); + (from..story.paras.len()).filter(|&p| starts(p)).count().saturating_add(breaks) + }); + (cs.overset_at, held, full, forced) } /// The frames autoflow sets on a page: one per column inside the margins, in the order a story @@ -263,12 +276,13 @@ pub(crate) fn autoflow(d: &mut Document, sid: StoryId, max_pages: usize, cmd: &s // The next page of the document autoflow may set frames on; it only moves forward. let mut following = 0; loop { - let (overset, held, full) = fit(d, sid); + let (overset, held, full, forced) = fit(d, sid); let Some(at) = overset else { break }; let len = d.story(sid).map_or(0, |s| s.len()); - // Frames still needed at the rate the full ones are filled (at least one); with no full - // frame to go by yet, one more. - let want = held.checked_div(full).map_or(1, |per_frame| len.saturating_sub(at).div_ceil(per_frame.max(1))).max(1); + // Frames still needed at the rate the full ones are filled, plus one per frame the text + // starts on its own (at least one); with neither to go by yet, one more. + let rate = held.checked_div(full).map_or(0, |per_frame| len.saturating_sub(at).div_ceil(per_frame.max(1))); + let want = rate.saturating_add(forced).max(1); let last = *d.story(sid).and_then(|s| s.frames.last()).ok_or_else(|| bad(cmd, "the story has no frame"))?; let page = d.page_of_item(last).unwrap_or(d.page_count().saturating_sub(1)); let layer = d.default_layer(); diff --git a/crates/engine/src/cmd/place_text/tests.rs b/crates/engine/src/cmd/place_text/tests.rs index bdce2a975..183a46074 100644 --- a/crates/engine/src/cmd/place_text/tests.rs +++ b/crates/engine/src/cmd/place_text/tests.rs @@ -344,3 +344,36 @@ fn autoflow_sizes_no_frame_by_one_a_start_option_ends_early() { assert!(d.next_id - ids < 100, "{start}: {} ids", d.next_id - ids); } } + +#[test] +fn autoflow_looks_past_a_deleted_paragraph_for_the_start_option() { + // The title frame ends before a tracked deletion; the chapter after it starts on an odd page. + use designcraft_doc::{ChangeMark, build::NewDocument}; + let mut d = Document::new(&NewDocument { pages: 1, facing_pages: false, primary_text_frame: true, ..Default::default() }); + let sid = d.settings.primary_story.unwrap(); + let st = d.story_mut(sid).unwrap(); + st.insert(0, &format!("Front\nGone\nChapter one\n{}", "lorem ipsum dolor sit amet ".repeat(400).trim())); + st.paras[2].para.start_paragraph = Some(StartParagraph::NextOddPage); + st.format_chars(6..11, |f| f.over.change = Some(ChangeMark::Deleted)); + let ids = d.next_id; + assert_eq!(autoflow(&mut d, sid, 2000, "file.place", false).unwrap(), 4); + assert_eq!(designcraft_compose::compose_story(&d, sid, &Default::default()).overset_at, None); + assert!(d.next_id - ids < 100, "{} ids", d.next_id - ids); +} + +#[test] +fn autoflow_asks_for_every_frame_the_start_options_ask_for_at_once() { + // A paragraph per page: no frame sets a fill rate, yet one round shouldn't add one frame. + use designcraft_doc::build::NewDocument; + let mut d = Document::new(&NewDocument { pages: 1, facing_pages: false, primary_text_frame: true, ..Default::default() }); + let sid = d.settings.primary_story.unwrap(); + let st = d.story_mut(sid).unwrap(); + st.insert(0, (0..200).map(|i| format!("Chapter {i}\n")).collect::().trim_end()); + for p in &mut st.paras { + p.para.start_paragraph = Some(StartParagraph::NextPage); + } + let ids = d.next_id; + assert_eq!(autoflow(&mut d, sid, 2000, "file.place", false).unwrap(), 199); + assert_eq!(designcraft_compose::compose_story(&d, sid, &Default::default()).overset_at, None); + assert!(d.next_id - ids < 2000, "{} ids", d.next_id - ids); +} From ed88f3e4b5f6775a92e2ab4a2e7fa7d993477ff6 Mon Sep 17 00:00:00 2001 From: KnottyDyes <47539659+KnottyDyes@users.noreply.github.com> Date: Wed, 28 Oct 2026 01:52:25 -0600 Subject: [PATCH 0331/1349] Compose: tables clear the footnote area Reserve column and spanning footnotes when fitting inline table row groups. Continue rows in the next column or frame when the remaining space is too small, and include cell-local footnotes in measured row height. Fixes #1901 Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 4 + crates/compose/src/lib.rs | 15 +++- crates/compose/src/table.rs | 29 ++++-- crates/compose/src/tests.rs | 172 ++++++++++++++++++++++++++++++++++++ 4 files changed, 211 insertions(+), 9 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index c02176bab..7cc6acf73 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -12,6 +12,10 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, open (documented JSON format + IDML), scriptable by agents (MCP), and available on the web. +- **2026-10-28** · Inline table rows leave room for column and spanning footnotes, continuing in + the next column or frame when needed (#1901). Cell-local footnotes contribute to row height + and sit inside the cell rather than outside its measuring frame. Vertical justification keeps + paragraphs and table fragments above the footnote area. No readiness percentage change. - **2026-10-25** · The application bar uses craft-window's shared title-bar code. A drag that starts on a floating panel over the bar moves the panel, not the window, and in full screen the bar no longer zooms or moves the window. No readiness percentage change. diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 88becd85f..58454b228 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -1099,7 +1099,7 @@ fn place_table_paragraph(input: TableParagraphInput<'_>) -> TableParagraphResult } let at_top = cursor.last_baseline.is_none(); let start_at = (cursor.fi, cursor.col); - if !table::place_table(doc, table, anchor, paragraph, props, frames, columns, cursor, out, opts) { + if !table::place_table(doc, table, anchor, paragraph, props, frames, columns, cursor, out, notes, opts) { if let Some(j) = trial_failed(trial, limits, *balance_runs < balance_budget) { *balance_runs += 1; rewind(j, snaps, note_snaps, notes, out, cursor, list_counter, force_col, line_cap, no_hyph); @@ -3108,7 +3108,7 @@ fn finish_composition(input: FinishInput<'_>) -> ComposedStory { let before: Vec = ft.tables.iter().map(|t| ft.lines.get(t.line).map_or(0.0, |l| l.baseline)).collect(); let spanned = ft.columns.len() > 1 && ft.lines.iter().any(|l| span_paras.get(l.para) == Some(&true)) || ft.lines.iter().any(|l| split_paras.get(l.para) == Some(&true)); - vertical_justify(ft, f, spanned); + vertical_justify(ft, f, spanned, &doc.footnote_options); for (t, b) in ft.tables.iter_mut().zip(before) { let now = ft.lines.get(t.line).map_or(b, |l| l.baseline); t.shift(now - b); @@ -5320,7 +5320,7 @@ fn hyphenation_points( } /// `spanned`: a paragraph spans the frame's columns, so the lines move together. -fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool) { +fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &designcraft_doc::FootnoteOptions) { if ft.lines.is_empty() || f.opts.vertical_justification == VerticalJustification::Top { return; } @@ -5333,7 +5333,14 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool) { let idx: Vec = ft.lines.iter().enumerate().filter(|(_, l)| spanned || l.column == c).map(|(i, _)| i).collect(); let (Some(&a), Some(_)) = (idx.first(), idx.last()) else { continue }; let bottom = idx.iter().map(|&i| ft.lines[i].baseline + ft.lines[i].descent).fold(f64::NEG_INFINITY, f64::max); - let space = f.area.y1 - bottom; + let bottom = ft.tables.iter().filter(|t| spanned || t.column == c).map(|t| t.rect.y1).fold(bottom, f64::max); + let limit = ft + .notes + .iter() + .filter(|n| spanned || notes.span_columns || n.column == c) + .map(|n| n.rect.y0 - notes.space_before) + .fold(f.area.y1, f64::min); + let space = limit - bottom; if space <= 0.0 { continue; } diff --git a/crates/compose/src/table.rs b/crates/compose/src/table.rs index c620622a3..dc579d8a7 100644 --- a/crates/compose/src/table.rs +++ b/crates/compose/src/table.rs @@ -122,7 +122,7 @@ impl CellLineExtent { /// Compose a cell story at width `w` (content space, top-left at the origin). fn compose_cell(doc: &Document, cell: &Cell, w: f64, opts: &ComposeOptions, (left_page, right_page): (bool, bool)) -> CellLayout { - let spec = FrameSpec { + let mut spec = FrameSpec { id: ItemId(0), area: Rect::new(0.0, 0.0, w.max(1.0), 1.0e6), opts: TextFrameOptions { first_baseline: cell.first_baseline, first_baseline_min: cell.first_baseline_min, ..TextFrameOptions::default() }, @@ -137,7 +137,15 @@ fn compose_cell(doc: &Document, cell: &Cell, w: f64, opts: &ComposeOptions, (lef right_page, page_rect: None, }; - let cs = crate::compose(doc, &cell.text, std::slice::from_ref(&spec), opts); + let mut cs = crate::compose(doc, &cell.text, std::slice::from_ref(&spec), opts); + // The measuring frame is deliberately tall. Recompose at the actual content height so + // cell-local footnotes sit inside the row rather than at the measuring frame's bottom. + if let Some(frame) = cs.frames.first().filter(|f| !f.notes.is_empty()) { + let body = frame.lines.iter().map(|l| l.baseline + l.descent).fold(0.0, f64::max); + let note_top = frame.notes.first().map_or(spec.area.y1, |n| n.rect.y0); + spec.area.y1 = body + doc.footnote_options.space_before + (spec.area.y1 - note_top); + cs = crate::compose(doc, &cell.text, std::slice::from_ref(&spec), opts); + } let line_heights: Vec = cs .frames .first() @@ -157,7 +165,8 @@ fn compose_cell(doc: &Document, cell: &Cell, w: f64, opts: &ComposeOptions, (lef .unwrap_or_default(); // Check all lines: a large descender or lowered inline object on an earlier line can // extend below the final baseline when leading is fixed. - let content_h = line_heights.iter().copied().fold(0.0, f64::max); + let note_bottom = cs.frames.first().map_or(0.0, |f| f.notes.iter().map(|n| n.rect.y1).fold(0.0, f64::max)); + let content_h = line_heights.iter().copied().fold(note_bottom, f64::max); CellLayout { text: Arc::new(cs), content_h, line_heights } } @@ -174,6 +183,7 @@ pub(crate) fn place_table( cols: &[Vec], cur: &mut Cursor, out: &mut ComposedStory, + notes: &mut crate::notes::Notes, opts: &ComposeOptions, ) -> bool { if cur.fi >= frames.len() || table.nrows() == 0 || table.ncols() == 0 { @@ -292,6 +302,13 @@ pub(crate) fn place_table( } }; place_rows(0..header, &mut y, false, &mut frag_rows); + // Table rows do not add story footnotes; cell-local notes are composed separately. + let column_reserve = |notes: &mut crate::notes::Notes, cur: &Cursor, col: Rect| { + let note_w = notes.area(&cols[cur.fi], cur.col).map_or(col.width(), |a| a.width()); + let column = crate::notes::NoteColumn { frame_index: cur.fi, column_index: cur.col, width: note_w, frame: &frames[cur.fi] }; + notes.reserve(doc, column, &[], opts) + }; + let mut reserve = column_reserve(notes, cur, col); let mut r = header; loop { if r >= body_end { @@ -299,9 +316,10 @@ pub(crate) fn place_table( } let ge = group_end[r].min(body_end).max(r + 1); let gh = sum(r, ge); + let bottom = col.y1 - reserve; let at_col_top = cur.last_baseline.is_none() && (top - col.y0).abs() < 1e-6; - if y + gh + footer_h <= col.y1 + 0.01 || (body_placed == 0 && at_col_top) { - if y + gh + footer_h > col.y1 + 0.01 && body_placed == 0 && at_col_top && y + gh > col.y1 + 0.01 { + if y + gh + footer_h <= bottom + 0.01 || (body_placed == 0 && at_col_top && reserve == 0.0) { + if y + gh + footer_h > bottom + 0.01 && body_placed == 0 && at_col_top && y + gh > bottom + 0.01 { // A row group taller than an empty column can never fit. return false; } @@ -324,6 +342,7 @@ pub(crate) fn place_table( return false; } col = col_rect(cur); + reserve = column_reserve(notes, cur, col); y = col.y0; top = y; frag_rows.clear(); diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 3083261fb..2f66eca93 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -1994,6 +1994,178 @@ fn footnotes_sit_at_the_column_bottom_and_push_text() { assert!(note_caret(&cs, n.id, 0).is_some()); } +fn justified_content_clears_footnotes(mode: designcraft_doc::VerticalJustification, table: bool) { + for span in [false, true] { + let (mut d, sid, fid) = doc_with("First paragraph.\nSecond paragraph.", Rect::new(0.0, 0.0, 420.0, 240.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2; + d.footnote_options.span_columns = span; + d.footnote_options.space_before = 60.0; + let st = d.story_mut(sid).unwrap(); + st.insert_note(5, "Synthetic footnote.", ParaFormat::default()); + if table { + let mut t = designcraft_doc::Table::new(77, 1, 1, 0, 0, 180.0); + t.rows[0].mode = designcraft_doc::RowHeightMode::Exactly; + t.rows[0].height = 90.0; + st.insert_table(st.len(), t); + } + let top = compose_story(&d, sid, &ComposeOptions::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = mode; + + let cs = compose_story(&d, sid, &ComposeOptions::default()); + + assert!(!cs.is_overset()); + let ft = cs.frame(fid).unwrap(); + let original = top.frame(fid).unwrap(); + assert_eq!(ft.notes.len(), 1); + assert_eq!(ft.notes[0].rect, original.notes[0].rect, "footnotes must not move"); + let limit = ft.notes[0].rect.y0 - d.footnote_options.space_before; + assert!(ft.lines.iter().all(|l| l.baseline + l.descent <= limit + 0.01), "lines overlap footnotes in {mode:?}, span {span}"); + assert!(ft.tables.iter().flat_map(|t| &t.cells).all(|c| c.rect.y1 <= limit + 0.01), "cells overlap footnotes in {mode:?}, span {span}"); + assert!(ft.lines.last().unwrap().baseline > original.lines.last().unwrap().baseline + 0.01, "content must still move down"); + if table { + assert_eq!(ft.tables.len(), 1); + assert!(ft.tables[0].rect.y1 > original.tables[0].rect.y1 + 0.01, "table must still move down"); + } + } +} + +#[test] +fn bottom_justified_paragraphs_clear_footnotes() { + justified_content_clears_footnotes(designcraft_doc::VerticalJustification::Bottom, false); +} + +#[test] +fn bottom_justified_tables_clear_footnotes() { + justified_content_clears_footnotes(designcraft_doc::VerticalJustification::Bottom, true); +} + +#[test] +fn center_justified_tables_clear_footnotes() { + justified_content_clears_footnotes(designcraft_doc::VerticalJustification::Center, true); +} + +#[test] +fn vertically_justified_tables_clear_footnotes() { + justified_content_clears_footnotes(designcraft_doc::VerticalJustification::Justify, true); +} + +#[test] +fn vertical_justification_counts_table_fragment_bottoms() { + use designcraft_doc::VerticalJustification::{Bottom, Center, Justify}; + let (mut d, sid, fid) = doc_with("Reference.", Rect::new(0.0, 0.0, 200.0, 240.0), ParaAttrs::default()); + let st = d.story_mut(sid).unwrap(); + st.insert_note(5, "Synthetic footnote.", ParaFormat::default()); + let mut table = designcraft_doc::Table::new(77, 1, 1, 0, 0, 180.0); + table.rows[0].mode = designcraft_doc::RowHeightMode::Exactly; + table.rows[0].height = 120.0; + st.insert_table(st.len(), table); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + for mode in [Bottom, Center, Justify] { + let mut ft = cs.frame(fid).unwrap().clone(); + let t = &ft.tables[0]; + let (anchor, bottom, baseline) = (t.line, t.rect.y1, t.rect.y0); + // Exercise a fragment extending below its anchor, without a later text line hiding it. + ft.lines.truncate(anchor + 1); + ft.lines[anchor].baseline = baseline; + let mut spec = frame_specs(&d, sid).remove(0); + spec.opts.vertical_justification = mode; + + vertical_justify(&mut ft, &spec, false, &d.footnote_options); + + let moved = ft.lines[anchor].baseline - baseline; + let limit = ft.notes[0].rect.y0 - d.footnote_options.space_before; + assert!(moved > 0.01); + assert!(bottom + moved <= limit + 0.01, "fragment overlaps footnotes in {mode:?}"); + } +} + +#[test] +fn table_rows_clear_footnotes_and_continue_in_the_next_column() { + for span in [false, true] { + for row_height in [24.0, 150.0] { + let (mut d, sid, fid) = doc_with("First paragraph.\nSecond paragraph.", Rect::new(0.0, 0.0, 420.0, 200.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2; + d.footnote_options.span_columns = span; + let st = d.story_mut(sid).unwrap(); + st.insert_note(5, "First synthetic footnote.", ParaFormat::default()); + st.insert_note(25, "Second synthetic footnote.", ParaFormat::default()); + let mut table = designcraft_doc::Table::new(77, 8, 1, 0, 0, 180.0); + for row in &mut table.rows { + row.mode = designcraft_doc::RowHeightMode::Exactly; + row.height = row_height; + } + st.insert_table(st.len(), table); + let (next, _) = + d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 220.0, 420.0, 1720.0), d.default_layer(), "", ParaFormat::default()).unwrap(); + d.thread(fid, next).unwrap(); + + let cs = compose_story(&d, sid, &ComposeOptions::default()); + + assert!(!cs.is_overset()); + let ft = cs.frame(fid).unwrap(); + assert_eq!(ft.notes.len(), 2); + let top = ft.notes[0].rect.y0 - d.footnote_options.space_before; + for frag in &ft.tables { + if span || frag.column == 0 { + assert!(frag.cells.iter().all(|c| c.rect.y1 <= top + 0.01), "rows overlap footnotes: {:?}, top {top}", frag.rect); + } + } + assert!(cs.frames.iter().skip(1).any(|f| !f.tables.is_empty()) || ft.tables.iter().any(|t| t.column == 1)); + let rows: Vec<_> = cs.frames.iter().flat_map(|f| &f.tables).flat_map(|t| &t.cells).filter(|c| !c.repeated).map(|c| c.row).collect(); + assert_eq!(rows, (0..8).collect::>()); + if row_height == 150.0 { + assert!(!ft.tables.iter().any(|t| t.column == 0), "the whole table moves when no row fits"); + } + } + } +} + +#[test] +fn table_reports_overset_when_every_remaining_column_has_footnotes() { + let (mut d, sid, fid) = doc_with("Reference.", Rect::new(0.0, 0.0, 420.0, 200.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 3; + d.footnote_options.span_columns = true; + d.footnote_options.space_before = 40.0; + let st = d.story_mut(sid).unwrap(); + st.insert_note(5, "Synthetic spanning footnote.", ParaFormat::default()); + let mut table = designcraft_doc::Table::new(77, 2, 1, 0, 0, 100.0); + for row in &mut table.rows { + row.mode = designcraft_doc::RowHeightMode::Exactly; + row.height = 90.0; + } + table.cells[0].row_span = 2; + let anchor = st.insert_table(st.len(), table); + + let cs = compose_story(&d, sid, &ComposeOptions::default()); + + assert!(cs.is_overset()); + assert_eq!(cs.overset_at, Some(anchor)); + let ft = cs.frame(fid).unwrap(); + assert_eq!(ft.notes.len(), 1); + assert!(ft.notes[0].rect.y0 - d.footnote_options.space_before < 180.0); + assert!(cs.frames.iter().all(|f| f.tables.is_empty()), "the unplaced row group must remain overset"); +} + +#[test] +fn table_cell_footnotes_fit_inside_the_row() { + let (mut d, sid, _) = doc_with("", Rect::new(0.0, 0.0, 200.0, 200.0), ParaAttrs::default()); + let mut table = designcraft_doc::Table::new(77, 1, 1, 0, 0, 180.0); + let cell = &mut table.cells[0]; + cell.text.insert(0, "Cell reference."); + cell.text.insert_note(5, "Synthetic cell footnote.", ParaFormat::default()); + d.story_mut(sid).unwrap().insert_table(0, table); + + let cs = compose_story(&d, sid, &ComposeOptions::default()); + + let cell = &cs.frames[0].tables[0].cells[0]; + assert!(!cell.overset); + let frame = &cell.text.frames[0]; + assert_eq!(frame.notes.len(), 1); + let note = &frame.notes[0]; + assert!(cell.origin.y + note.rect.y1 <= cell.clip.y1 + 0.01, "cell footnote must remain within the row"); + assert!(frame.lines.iter().all(|l| l.baseline + l.descent <= note.rect.y0 - d.footnote_options.space_before + 0.01)); +} + #[test] fn footnotes_stack_baseline_to_baseline() { // Single-line footnotes read as one text: consecutive baselines sit one leading (plus From 5eddc821ecffc265b8c66e1ed1458d5413c71c5b Mon Sep 17 00:00:00 2001 From: VoiceLessQ Date: Wed, 28 Oct 2026 22:50:39 -0200 Subject: [PATCH 0332/1349] Images: refuse a raster that would decode past 1 GiB of RGBA (fixes #1586) decode_rgba relied on the image crate's 512 MiB limit, which bounds only the decoder's own output. A gray or 1-bit image just under it expanded four times to RGBA, and render made a premultiplied copy on top: a 288 KB PNG of 23,000 x 23,000 pixels froze the first draw for 9 s and took the app to 4.5 GB. The size is now read from the header and anything past 256 Mpx is refused before decoding. It draws as an empty frame, and PDF export skips it with a warning. A 300 ppi scan of an A0 sheet (about 139 Mpx) still opens. --- ROADMAP.md | 1 + crates/images/src/lib.rs | 7 +++++++ crates/images/src/tests.rs | 38 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+) diff --git a/ROADMAP.md b/ROADMAP.md index c02176bab..16fb72145 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -380,6 +380,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-10-28** · A placed image whose pixels would decode past 1 GiB of RGBA (256 Mpx) is refused from its header, before decoding (#1586). A 288 KB 23,000 px gray PNG used to hang the first draw for 9 s and take the app to 4.5 GB; it now draws as an empty frame, and PDF export skips it with a warning. A 300 ppi A0 scan still fits. No readiness percentage change. - **2026-10-27** · An iconic panel's flyout stays open while you work in the canvas or a text field: Auto-Collapse Iconic Panels is off by default, and preferences saved with it on start with it off. Preferences › Interface › Panels holds the setting next to the column bar's menu item. No readiness percentage change. - **2026-10-24** · Column rules run from the top line's ascent to the bottom line's descent, as InDesign draws them, instead of from the top to the bottom of the columns, on screen, in PDF and in PowerPoint export. The top and bottom insets shorten the rule from those lines. Existing documents draw their column rules at the new length. No readiness percentage change. - **2026-10-20** · Edit › Keyboard Shortcuts is craft-keymap's shared dialog: commands grouped by menu with Show and Filter, recording that asks before taking a key from another command, undo and redo, named shortcut sets (edits of Default become Custom; an imported set becomes a set of its own), an on-screen US keyboard, InDesign Show Set files reviewed before they apply, JSON export and an HTML summary. ui.json keeps the `shortcuts` map earlier versions read, for the active set. No readiness percentage change. diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 817aa7829..117017502 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -324,10 +324,17 @@ pub fn pixel_size(bytes: &[u8]) -> Option<(u32, u32)> { .or_else(|| tiff_decoder(bytes)?.dimensions().ok()) } +/// The largest decoded raster, in RGBA bytes: 256 Mpx, a 300 ppi scan of an A0 sheet fits. +const MAX_RGBA_BYTES: u64 = 1 << 30; + /// Straight (non-premultiplied) RGBA8 of a raster in display sRGB: an embedded ICC profile is /// applied, and CMYK goes through its own profile or the working CMYK space ([`colour`]). pub fn decode_rgba(bytes: &[u8]) -> Option { use colour::{DisplayColour, Pixels, to_display_rgba}; + // `image` limits only its own output, which can be a quarter of the RGBA copy or less. + if pixel_size(bytes).is_some_and(|(w, h)| u64::from(w).saturating_mul(u64::from(h)).saturating_mul(4) > MAX_RGBA_BYTES) { + return None; + } if is_psd(bytes) { return psd::decode(bytes); } diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index ba6e032eb..54a173cd1 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -401,3 +401,41 @@ fn bmp_decodes() { assert_eq!(pixel_size(&bmp), Some((3, 2))); assert_eq!(decode_rgba(&bmp).unwrap().get_pixel(1, 1).0, [0, 0, 255, 255]); } + +/// A 1-bit gray PNG of `side` x `side` blank pixels, written row by row so the test stays small. +fn blank_png(side: u32) -> Vec { + use std::io::Write; + let chunk = |out: &mut Vec, kind: &[u8; 4], data: &[u8]| { + out.extend((data.len() as u32).to_be_bytes()); + let mut crc = flate2::Crc::new(); + crc.update(kind); + crc.update(data); + out.extend(kind); + out.extend(data); + out.extend(crc.sum().to_be_bytes()); + }; + let row = vec![0u8; 1 + side.div_ceil(8) as usize]; + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast()); + for _ in 0..side { + z.write_all(&row).unwrap(); + } + let mut ihdr = [side.to_be_bytes(), side.to_be_bytes()].concat(); + ihdr.extend([1, 0, 0, 0, 0]); + let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); + chunk(&mut png, b"IHDR", &ihdr); + chunk(&mut png, b"IDAT", &z.finish().unwrap()); + chunk(&mut png, b"IEND", &[]); + png +} + +/// A small file that expands past 1 GiB of RGBA is refused from its header (#1586). +#[test] +fn rasters_past_the_rgba_budget_are_refused_before_decoding() { + let png = blank_png(16_385); + assert!(png.len() < 1 << 20, "{} bytes", png.len()); + assert_eq!(pixel_size(&png), Some((16_385, 16_385))); + assert_eq!(natural_size(&png), Some((16_385.0, 16_385.0))); + assert!(decode_rgba(&png).is_none()); + let small = decode_rgba(&blank_png(9)).expect("decodes"); + assert_eq!(small.get_pixel(8, 8).0, [0, 0, 0, 255]); +} From 50b5936b78cbcdfb56bc12968f353659d2d12d51 Mon Sep 17 00:00:00 2001 From: Henrique Cabral Date: Wed, 28 Oct 2026 21:07:42 -0400 Subject: [PATCH 0333/1349] IDML export: write the document's default StoryPreference InDesign always writes a document-level StoryPreference in Resources/Preferences.xml; DesignCraft only wrote one per story. IDML readers that take the spread reading order from the document's preference, such as Okapi's IDML filter, failed on DesignCraft's files without it. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 1 + crates/idml/src/export/fonts_prefs.rs | 10 ++++++++++ crates/idml/src/tests.rs | 8 ++++++++ 3 files changed, 19 insertions(+) diff --git a/ROADMAP.md b/ROADMAP.md index c02176bab..7070bb62a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -380,6 +380,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-10-28** · IDML export writes the document's default `StoryPreference` in `Resources/Preferences.xml`, as InDesign does. Only each story carried one, and IDML readers that take the spread reading order from the document's (Okapi's IDML filter) failed on DesignCraft's files. No readiness percentage change. - **2026-10-27** · An iconic panel's flyout stays open while you work in the canvas or a text field: Auto-Collapse Iconic Panels is off by default, and preferences saved with it on start with it off. Preferences › Interface › Panels holds the setting next to the column bar's menu item. No readiness percentage change. - **2026-10-24** · Column rules run from the top line's ascent to the bottom line's descent, as InDesign draws them, instead of from the top to the bottom of the columns, on screen, in PDF and in PowerPoint export. The top and bottom insets shorten the rule from those lines. Existing documents draw their column rules at the new length. No readiness percentage change. - **2026-10-20** · Edit › Keyboard Shortcuts is craft-keymap's shared dialog: commands grouped by menu with Show and Filter, recording that asks before taking a key from another command, undo and redo, named shortcut sets (edits of Default become Custom; an imported set becomes a set of its own), an on-screen US keyboard, InDesign Show Set files reviewed before they apply, JSON export and an HTML summary. ui.json keeps the `shortcuts` map earlier versions read, for the active set. No readiness percentage change. diff --git a/crates/idml/src/export/fonts_prefs.rs b/crates/idml/src/export/fonts_prefs.rs index fac86af33..2e8daa565 100644 --- a/crates/idml/src/export/fonts_prefs.rs +++ b/crates/idml/src/export/fonts_prefs.rs @@ -169,6 +169,16 @@ impl<'a> Ex<'a> { .attr("SubscriptSize", num(a.subscript_size)) .attr("SubscriptPosition", num(a.subscript_position)), ); + // InDesign always writes the document's default story preference; readers such as Okapi's IDML + // filter take the spread reading order from it and fail without it. + root.push( + El::new("StoryPreference") + .attr("OpticalMarginAlignment", "false") + .attr("OpticalMarginSize", "12") + .attr("FrameType", "TextFrameType") + .attr("StoryOrientation", "Horizontal") + .attr("StoryDirection", "LeftToRightDirection"), + ); document(&root) } } diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs index 0d078c63c..b5b5a1cd8 100644 --- a/crates/idml/src/tests.rs +++ b/crates/idml/src/tests.rs @@ -554,6 +554,14 @@ fn basic_paragraph_is_normal_paragraph_style() { assert_eq!(back.styles.paragraph.iter().filter(|p| p.name == st::BASIC_PARAGRAPH).count(), 1); } +/// Like InDesign, the export carries the document's default story preference, which IDML readers expect. +#[test] +fn export_writes_the_document_story_preference() { + let d = import_idml_with(&fixture(), &|_| None).unwrap(); + let prefs = zip_text(&export_idml(&d), "Resources/Preferences.xml"); + assert!(prefs.contains(r#""#), "{prefs}"); +} + /// Page items, frames, tables and preferences an IDML file leaves unset are InDesign's defaults /// for a new document. #[test] From 89ccfbb18c9e21e0bc4a222f2dfb051019e5a123 Mon Sep 17 00:00:00 2001 From: VoiceLessQ Date: Wed, 28 Oct 2026 23:08:41 -0200 Subject: [PATCH 0334/1349] Autoflow: count each forced move once, and only visible breaks (#1209) fit() counted every break character in the overset text and every Start Paragraph option. A break followed by a paragraph whose option it already meets moved the text once but asked for two frames, and breaks that tracked changes delete or a hidden condition hides asked for frames that composing never uses. Autoflow added those pages and removed them again: 200 chapters that end in page breaks and start on the next page took 61095 ids and 430 ms, now 798 ids and 16 ms. Each paragraph composing places now counts once, when a visible break ends the paragraph before it or its start option sends it on; after a break it is at the top of a frame, where the option only fixes odd or even page parity. A visible break inside a paragraph counts once more. previous_visible_break and the new visible_break in designcraft-compose are public, so the estimate and the composer use one rule. --- ROADMAP.md | 2 +- crates/compose/src/lib.rs | 21 +++++++---- crates/engine/src/cmd/place_text.rs | 35 +++++++++++++----- crates/engine/src/cmd/place_text/tests.rs | 44 +++++++++++++++++++++++ 4 files changed, 86 insertions(+), 16 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index deda0dc4f..435dd5d39 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -380,7 +380,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. -- **2026-10-28** · Autoflow no longer sizes the rest of a story by a frame that a Start Paragraph option (next column, frame, page, or odd or even page) ends early (#1209). With a title before a chapter that starts on the next odd page, it estimated a page per few characters, added up to 2000 pages (the autoflow limit) and removed them again: placing 2000 words took 36 s in the app, now 0.4 s, with the same pages. It looks past tracked-deleted paragraphs for the option, as composing does, and asks for every frame that start options and breaks force in one round: 200 one-line chapters on their own pages take 9 ms (58 ms before). No readiness percentage change. +- **2026-10-28** · Autoflow no longer sizes the rest of a story by a frame that a Start Paragraph option (next column, frame, page, or odd or even page) ends early (#1209). With a title before a chapter that starts on the next odd page, it estimated a page per few characters, added up to 2000 pages (the autoflow limit) and removed them again: placing 2000 words took 36 s in the app, now 0.4 s, with the same pages. It looks past tracked-deleted paragraphs for the option, as composing does, and asks for every frame that start options and breaks force in one round: 200 one-line chapters on their own pages take 9 ms (58 ms before). A break and the start option it meets count once, and breaks that tracked changes delete or a hidden condition hides don't count. No readiness percentage change. - **2026-10-27** · An iconic panel's flyout stays open while you work in the canvas or a text field: Auto-Collapse Iconic Panels is off by default, and preferences saved with it on start with it off. Preferences › Interface › Panels holds the setting next to the column bar's menu item. No readiness percentage change. - **2026-10-24** · Column rules run from the top line's ascent to the bottom line's descent, as InDesign draws them, instead of from the top to the bottom of the columns, on screen, in PDF and in PowerPoint export. The top and bottom insets shorten the rule from those lines. Existing documents draw their column rules at the new length. No readiness percentage change. - **2026-10-20** · Edit › Keyboard Shortcuts is craft-keymap's shared dialog: commands grouped by menu with Show and Filter, recording that asks before taking a key from another command, undo and redo, named shortcut sets (edits of Default become Custom; an imported set becomes a set of its own), an on-screen US keyboard, InDesign Show Set files reviewed before they apply, JSON export and an HTML summary. ui.json keeps the `shortcuts` map earlier versions read, for the active set. No readiness percentage change. diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 131e5273c..177733f99 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -930,18 +930,25 @@ fn line_has_wrapping_exclusion(frame: &FrameSpec, range: Range, column: R }) } -fn previous_visible_break(doc: &Document, story: &Story, ranges: &[Range], deleted: &[bool], pi: usize) -> Option { +/// The visible break ending the last placed paragraph before `pi`, which sends `pi` on. +pub fn previous_visible_break(doc: &Document, story: &Story, ranges: &[Range], deleted: &[bool], pi: usize) -> Option { (0..pi).rev().find(|&p| !deleted.get(p).copied().unwrap_or(false)).and_then(|p| { let range = ranges.get(p)?; - let (index, character) = story.text.get(range.clone())?.char_indices().next_back()?; - let start = break_start(character)?; - let (_, chars) = doc.styles.resolve_para(story.paras.get(p)?); - let props = doc.styles.resolve_char(&chars, story.char_format_at(range.start + index + character.len_utf8())); - let gone = props.change == designcraft_doc::ChangeMark::Deleted || doc.conditions_hide(&props.conditions); - (!gone).then_some(start) + let (index, _) = story.text.get(range.clone())?.char_indices().next_back()?; + visible_break(doc, story, p, range.start + index) }) } +/// The start option of the break at byte `at` in paragraph `p`, unless deleted or hidden. +pub fn visible_break(doc: &Document, story: &Story, p: usize, at: usize) -> Option { + let character = story.text.get(at..)?.chars().next()?; + let start = break_start(character)?; + let (_, chars) = doc.styles.resolve_para(story.paras.get(p)?); + let props = doc.styles.resolve_char(&chars, story.char_format_at(at + character.len_utf8())); + let gone = props.change == designcraft_doc::ChangeMark::Deleted || doc.conditions_hide(&props.conditions); + (!gone).then_some(start) +} + fn named_list_labels(doc: &Document, story: &Story, ranges: &[Range], deleted: &[bool]) -> Vec> { let mut counters: std::collections::HashMap = std::collections::HashMap::new(); story diff --git a/crates/engine/src/cmd/place_text.rs b/crates/engine/src/cmd/place_text.rs index 961f6f630..852db171e 100644 --- a/crates/engine/src/cmd/place_text.rs +++ b/crates/engine/src/cmd/place_text.rs @@ -205,16 +205,15 @@ fn fit(d: &Document, sid: StoryId) -> (Option, usize, usize, usize) { let cs = designcraft_compose::compose_story(d, sid, &Default::default()); let Some(story) = d.story(sid) else { return (cs.overset_at, 0, 0, 0) }; let text = story.text.as_str(); - let deleted = designcraft_compose::deleted_paras(story, &story.para_ranges()); - let starts = |p: usize| { - !deleted.get(p).copied().unwrap_or(false) - && story.paras.get(p).is_some_and(|pf| d.styles.resolve_para(pf).0.start_paragraph != StartParagraph::Anywhere) - }; + let ranges = story.para_ranges(); + let deleted = designcraft_compose::deleted_paras(story, &ranges); + let placed = |p: usize| !deleted.get(p).copied().unwrap_or(false); + let starts = |p: usize| placed(p) && story.paras.get(p).is_some_and(|pf| d.styles.resolve_para(pf).0.start_paragraph != StartParagraph::Anywhere); // A frame's range stops before the paragraph's return; composing skips deleted paragraphs. let moved_on = |end: usize| { let next = if text.as_bytes().get(end) == Some(&b'\n') { end.saturating_add(1) } else { end }; next.checked_sub(1).is_some_and(|i| text.as_bytes().get(i) == Some(&b'\n')) - && (story.para_at(next)..story.paras.len()).find(|&p| !deleted.get(p).copied().unwrap_or(false)).is_some_and(starts) + && (story.para_at(next)..story.paras.len()).find(|&p| placed(p)).is_some_and(starts) }; let (mut held, mut full) = (0, 0); for f in &cs.frames { @@ -228,8 +227,28 @@ fn fit(d: &Document, sid: StoryId) -> (Option, usize, usize, usize) { let first = story.para_at(at); // The paragraph the overset text starts with counts when it starts there. let from = if at.checked_sub(1).is_none_or(|i| text.as_bytes().get(i) == Some(&b'\n')) { first } else { first.saturating_add(1) }; - let breaks = text.get(at..).map_or(0, |t| t.chars().filter(|&c| designcraft_doc::is_break_char(c)).count()); - (from..story.paras.len()).filter(|&p| starts(p)).count().saturating_add(breaks) + // Once per paragraph: after a break, its start option only fixes odd or even page parity. + let sent = (from..ranges.len()) + .filter(|&p| starts(p) || (placed(p) && designcraft_compose::previous_visible_break(d, story, &ranges, &deleted, p).is_some())) + .count(); + // A break inside a paragraph moves the rest of it. + let inside: usize = (first..ranges.len()) + .filter(|&p| placed(p)) + .filter_map(|p| Some((p, ranges.get(p)?.clone()))) + .map(|(p, r)| { + let Some(t) = text.get(r.clone()) else { return 0 }; + let last = t.char_indices().next_back().map(|(i, _)| i); + t.char_indices() + .filter(|&(i, c)| { + designcraft_doc::is_break_char(c) + && Some(i) != last + && r.start.saturating_add(i) >= at + && designcraft_compose::visible_break(d, story, p, r.start.saturating_add(i)).is_some() + }) + .count() + }) + .sum(); + sent.saturating_add(inside) }); (cs.overset_at, held, full, forced) } diff --git a/crates/engine/src/cmd/place_text/tests.rs b/crates/engine/src/cmd/place_text/tests.rs index 183a46074..8275e7ab2 100644 --- a/crates/engine/src/cmd/place_text/tests.rs +++ b/crates/engine/src/cmd/place_text/tests.rs @@ -377,3 +377,47 @@ fn autoflow_asks_for_every_frame_the_start_options_ask_for_at_once() { assert_eq!(designcraft_compose::compose_story(&d, sid, &Default::default()).overset_at, None); assert!(d.next_id - ids < 2000, "{} ids", d.next_id - ids); } + +#[test] +fn autoflow_asks_no_frame_for_a_deleted_or_hidden_break() { + // Composing skips breaks in the overset text that tracked changes delete or a condition hides. + use designcraft_doc::{ChangeMark, Condition, PAGE_BREAK, build::NewDocument}; + for hide in [false, true] { + let mut d = Document::new(&NewDocument { pages: 1, facing_pages: false, primary_text_frame: true, ..Default::default() }); + d.conditions.push(Condition { name: "Hidden".into(), color: [0, 0, 0], visible: false }); + let sid = d.settings.primary_story.unwrap(); + let st = d.story_mut(sid).unwrap(); + let body = "lorem ipsum dolor sit amet ".repeat(300); + let gone = format!("x{PAGE_BREAK}\n").repeat(200); + st.insert(0, &format!("{}\n{gone}{}", body.trim(), body.trim())); + let at = body.trim().len() + 1; + if hide { + for (i, _) in gone.match_indices(PAGE_BREAK) { + st.format_chars(at + i..at + i + PAGE_BREAK.len_utf8(), |f| f.over.conditions = Some(vec!["Hidden".into()])); + } + } else { + st.format_chars(at..at + gone.len(), |f| f.over.change = Some(ChangeMark::Deleted)); + } + let ids = d.next_id; + autoflow(&mut d, sid, 2000, "file.place", false).unwrap(); + assert_eq!(designcraft_compose::compose_story(&d, sid, &Default::default()).overset_at, None, "hide {hide}"); + assert!(d.next_id - ids < 100, "hide {hide}: {} pages, {} ids", d.page_count(), d.next_id - ids); + } +} + +#[test] +fn autoflow_counts_a_break_and_the_start_option_it_meets_once() { + // Each chapter ends in a page break and starts on the next page: one new page each, not two. + use designcraft_doc::{PAGE_BREAK, build::NewDocument}; + let mut d = Document::new(&NewDocument { pages: 1, facing_pages: false, primary_text_frame: true, ..Default::default() }); + let sid = d.settings.primary_story.unwrap(); + let st = d.story_mut(sid).unwrap(); + st.insert(0, (0..200).map(|i| format!("Chapter {i}{PAGE_BREAK}\n")).collect::().trim_end()); + for p in &mut st.paras { + p.para.start_paragraph = Some(StartParagraph::NextPage); + } + let ids = d.next_id; + assert_eq!(autoflow(&mut d, sid, 2000, "file.place", false).unwrap(), 199); + assert_eq!(designcraft_compose::compose_story(&d, sid, &Default::default()).overset_at, None); + assert!(d.next_id - ids < 2000, "{} ids", d.next_id - ids); +} From d5f07d30eb9c67671ee037c869009a6e5ce7f618 Mon Sep 17 00:00:00 2001 From: VoiceLessQ Date: Wed, 28 Oct 2026 23:28:11 -0200 Subject: [PATCH 0335/1349] PDF: check the RGBA budget before recompressing an image (#1586) With compressImages on, PDF export re-encodes rasters as JPEG in recompress, which decoded with the image crate directly. A gray PNG that decode_rgba refuses still decoded there, was copied and encoded as JPEG, and only then dropped: krilla refuses a JPEG wider or taller than 16,384 px, and every raster past the budget is. Exporting the 23,000 px PNG that way took 4.2 s and 1 GB more memory, for a PDF without the image. recompress now asks too_large_to_decode first, the check decode_rgba uses, so the export skips the image with the same warning at once. --- Cargo.lock | 1 + crates/images/src/lib.rs | 9 +++++-- crates/images/src/tests.rs | 2 ++ crates/pdf/Cargo.toml | 1 + crates/pdf/src/export/images.rs | 7 ++++-- crates/pdf/src/tests.rs | 42 +++++++++++++++++++++++++++++++++ 6 files changed, 58 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1c361aef2..037448dbb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1535,6 +1535,7 @@ dependencies = [ "designcraft-fonts", "designcraft-geom", "designcraft-images", + "flate2", "hayro-cmap", "hayro-interpret", "hayro-syntax", diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 117017502..dfe4166b7 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -327,12 +327,17 @@ pub fn pixel_size(bytes: &[u8]) -> Option<(u32, u32)> { /// The largest decoded raster, in RGBA bytes: 256 Mpx, a 300 ppi scan of an A0 sheet fits. const MAX_RGBA_BYTES: u64 = 1 << 30; +/// Whether a raster's header gives it more pixels than [`decode_rgba`] decodes. +pub fn too_large_to_decode(bytes: &[u8]) -> bool { + // `image` limits only its own output, which can be a quarter of the RGBA copy or less. + pixel_size(bytes).is_some_and(|(w, h)| u64::from(w).saturating_mul(u64::from(h)).saturating_mul(4) > MAX_RGBA_BYTES) +} + /// Straight (non-premultiplied) RGBA8 of a raster in display sRGB: an embedded ICC profile is /// applied, and CMYK goes through its own profile or the working CMYK space ([`colour`]). pub fn decode_rgba(bytes: &[u8]) -> Option { use colour::{DisplayColour, Pixels, to_display_rgba}; - // `image` limits only its own output, which can be a quarter of the RGBA copy or less. - if pixel_size(bytes).is_some_and(|(w, h)| u64::from(w).saturating_mul(u64::from(h)).saturating_mul(4) > MAX_RGBA_BYTES) { + if too_large_to_decode(bytes) { return None; } if is_psd(bytes) { diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index 54a173cd1..9ca9fe14f 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -435,7 +435,9 @@ fn rasters_past_the_rgba_budget_are_refused_before_decoding() { assert!(png.len() < 1 << 20, "{} bytes", png.len()); assert_eq!(pixel_size(&png), Some((16_385, 16_385))); assert_eq!(natural_size(&png), Some((16_385.0, 16_385.0))); + assert!(too_large_to_decode(&png)); assert!(decode_rgba(&png).is_none()); + assert!(!too_large_to_decode(&blank_png(16_384))); let small = decode_rgba(&blank_png(9)).expect("decodes"); assert_eq!(small.get_pixel(8, 8).0, [0, 0, 0, 255]); } diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index 2b4275da3..3df877c5c 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -31,4 +31,5 @@ hayro-interpret = { version = "0.7.0", default-features = false, features = ["em hayro-cmap = "0.1" kurbo = { workspace = true } tiff = { workspace = true } +flate2 = "1" designcraft-fonts = { workspace = true, features = ["testing"] } diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index a164a6948..8a2b803cf 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -161,9 +161,12 @@ pub(super) fn cmyk_tiff(data: &[u8], mode: RasterMode) -> Option { Image::from_custom(CmykImage(Arc::new(r)), mode.interpolate).ok() } -/// Opaque raster → JPEG (quality 90). `None` when the image has transparency or can't be decoded. -/// With `tag_rgb`, the JPEG keeps the source's RGB profile, or gets sRGB. +/// Opaque raster → JPEG (quality 90). `None` when the image has transparency, is too large or +/// can't be decoded. With `tag_rgb`, the JPEG keeps the source's RGB profile, or gets sRGB. pub(super) fn recompress(data: &[u8], mode: RasterMode) -> Option { + if designcraft_images::too_large_to_decode(data) { + return None; + } let img = image::load_from_memory(data).ok()?; if img.color().has_alpha() && img.to_rgba8().pixels().any(|p| p[3] < 255) { return None; diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 2accc79fa..8fcc15547 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -257,6 +257,32 @@ fn cmyk_tiff() -> (Vec, Vec) { (b, px) } +/// A black `side`² 1-bit grey PNG: well under 1 MB, it decodes to `side`² bytes. +fn blank_png(side: u32) -> Vec { + use std::io::Write; + let chunk = |out: &mut Vec, kind: &[u8; 4], data: &[u8]| { + out.extend((data.len() as u32).to_be_bytes()); + let mut crc = flate2::Crc::new(); + crc.update(kind); + crc.update(data); + out.extend(kind); + out.extend(data); + out.extend(crc.sum().to_be_bytes()); + }; + let row = vec![0u8; 1 + side.div_ceil(8) as usize]; + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast()); + for _ in 0..side { + z.write_all(&row).unwrap(); + } + let mut ihdr = [side.to_be_bytes(), side.to_be_bytes()].concat(); + ihdr.extend([1, 0, 0, 0, 0]); + let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); + chunk(&mut png, b"IHDR", &ihdr); + chunk(&mut png, b"IDAT", &z.finish().unwrap()); + chunk(&mut png, b"IEND", &[]); + png +} + fn place(d: &mut Document, data: Vec, px: (u32, u32)) { let asset = designcraft_doc::AssetId(d.alloc()); let mime = designcraft_images::mime(&data).into(); @@ -328,6 +354,22 @@ fn a_cut_off_image_is_skipped_not_fatal() { } } +/// A raster past the RGBA budget is skipped undecoded, also when images are recompressed (#1586). +#[test] +fn an_image_past_the_decode_budget_is_skipped_undecoded() { + let side = 16_385; + let mut d = doc_with_text("still here"); + place(&mut d, blank_png(side), (side, side)); + for compress_images in [false, true] { + let started = std::time::Instant::now(); + let r = export_pdf_with_report(&d, &Cache::new(), &PdfOptions { compress_images, ..Default::default() }).unwrap(); + let took = started.elapsed(); + assert!(took < std::time::Duration::from_secs(1), "compress_images {compress_images}: took {took:?}"); + assert!(r.warnings.iter().any(|w| w.contains("could not be decoded and was skipped")), "compress_images {compress_images}: {:?}", r.warnings); + assert!(image_xobjects(&r.bytes).is_empty(), "compress_images {compress_images}"); + } +} + /// Every image XObject in a PDF: its /ColorSpace name (`?` when not a name) and decoded samples. fn image_xobjects(bytes: &[u8]) -> Vec<(String, Vec)> { use hayro_syntax::object::Name; From 30a0f08698b45047498da78670baccfe6a7b155b Mon Sep 17 00:00:00 2001 From: VoiceLessQ Date: Thu, 29 Oct 2026 00:08:22 -0200 Subject: [PATCH 0336/1349] Story: copy a paragraph's format for all new returns at once (#1588) insert_with_raw gave each return in the inserted text its own Vec::insert of the paragraph's format, and each insert moves every format after it. A ParaFormat is 2,888 bytes, so the time grew with the square of the returns: Story::with_text took 2.2 s for 10,000 returns, 15.8 s for 20,000 and 90 s for 40,000. Placing a plain-text file goes through it. The copies now go in with one splice. --- ROADMAP.md | 1 + crates/doc/src/story.rs | 23 ++++++++++++++++++----- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index c02176bab..3887ecda8 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -380,6 +380,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-10-29** · Inserting text with many returns no longer takes time that grows with their square (part of #1588): each return copied its paragraph's format with its own insert, moving every format after it. Splitting 20,000 returns into paragraphs took 15.8 s; placing a text file of them now takes 0.2 s, and one of a million returns 5.5 s. No readiness percentage change. - **2026-10-27** · An iconic panel's flyout stays open while you work in the canvas or a text field: Auto-Collapse Iconic Panels is off by default, and preferences saved with it on start with it off. Preferences › Interface › Panels holds the setting next to the column bar's menu item. No readiness percentage change. - **2026-10-24** · Column rules run from the top line's ascent to the bottom line's descent, as InDesign draws them, instead of from the top to the bottom of the columns, on screen, in PDF and in PowerPoint export. The top and bottom insets shorten the rule from those lines. Existing documents draw their column rules at the new length. No readiness percentage change. - **2026-10-20** · Edit › Keyboard Shortcuts is craft-keymap's shared dialog: commands grouped by menu with Show and Filter, recording that asks before taking a key from another command, undo and redo, named shortcut sets (edits of Default become Custom; an imported set becomes a set of its own), an on-screen US keyboard, InDesign Show Set files reviewed before they apply, JSON export and an HTML summary. ui.json keeps the `shortcuts` map earlier versions read, for the active set. No readiness percentage change. diff --git a/crates/doc/src/story.rs b/crates/doc/src/story.rs index 05adcb35f..bb56505f7 100644 --- a/crates/doc/src/story.rs +++ b/crates/doc/src/story.rs @@ -385,11 +385,11 @@ impl Story { // Paragraph formats: each new '\n' splits the current paragraph; the new paragraphs copy it. let pi = self.para_at(pos); let newlines = text.bytes().filter(|b| *b == b'\n').count(); - if newlines > 0 { - let f = self.paras[pi].clone(); - for _ in 0..newlines { - self.paras.insert(pi + 1, f.clone()); - } + if newlines > 0 + && let Some(f) = self.paras.get(pi).cloned() + { + // All at once: an insert per return made many returns quadratic (#1588). + self.paras.splice(pi + 1..pi + 1, std::iter::repeat_n(f, newlines)); } self.text.insert_str(pos, text); // Character runs. @@ -669,6 +669,19 @@ mod tests { assert_eq!(s.para_ranges(), vec![0..6]); } + /// Each return inserted its paragraph format on its own, quadratic in the returns (#1588). + #[test] + fn many_returns_split_a_paragraph_at_once() { + let para = ParaFormat { style: "Body".into(), ..ParaFormat::default() }; + let started = std::time::Instant::now(); + let s = Story::with_text(StoryId(1), &"\n".repeat(20_000), para.clone()); + let took = started.elapsed(); + assert!(took < std::time::Duration::from_secs(1), "took {took:?}"); + assert_eq!(s.paras.len(), 20_001); + assert!(s.paras.iter().all(|p| *p == para)); + s.check().unwrap(); + } + #[test] fn char_formats_split_and_merge() { let mut s = st("hello world"); From 033fc2e17e5410921aba283ab6966eef2aa703a0 Mon Sep 17 00:00:00 2001 From: VoiceLessQ Date: Thu, 29 Oct 2026 00:12:33 -0200 Subject: [PATCH 0337/1349] PDF: count recompress decodes in the oversized-image test (#1586) The test for a raster past the RGBA budget showed that recompress skips the decode only through a one-second limit, which a slow CI runner could fail and a fast machine could pass without the fix. recompress now counts its decodes in a test-only per-thread counter, and a unit test checks that the 16,385 px PNG doesn't reach the decode while a 9 px one does. The export test keeps its output checks and drops the time limit. --- crates/pdf/src/export/images.rs | 27 +++++++++++++++++++++++++++ crates/pdf/src/tests.rs | 9 +++------ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 8a2b803cf..ec7c76fd6 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -161,12 +161,22 @@ pub(super) fn cmyk_tiff(data: &[u8], mode: RasterMode) -> Option { Image::from_custom(CmykImage(Arc::new(r)), mode.interpolate).ok() } +#[cfg(test)] +thread_local! { + /// Rasters `recompress` has decoded on this thread. + static RECOMPRESS_DECODES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Opaque raster → JPEG (quality 90). `None` when the image has transparency, is too large or /// can't be decoded. With `tag_rgb`, the JPEG keeps the source's RGB profile, or gets sRGB. pub(super) fn recompress(data: &[u8], mode: RasterMode) -> Option { if designcraft_images::too_large_to_decode(data) { return None; } + #[cfg(test)] + { + RECOMPRESS_DECODES.with(|n| n.set(n.get() + 1)); + } let img = image::load_from_memory(data).ok()?; if img.color().has_alpha() && img.to_rgba8().pixels().any(|p| p[3] < 255) { return None; @@ -539,3 +549,20 @@ mod eps_tests { assert_eq!(civil(i64::MIN), (-292277022657, 1, 27, 8, 29, 52)); } } + +#[cfg(test)] +mod recompress_tests { + use super::*; + + /// A raster past the RGBA budget is refused before `recompress` decodes it (#1586). + #[test] + fn a_raster_past_the_budget_is_not_decoded() { + let mode = RasterMode { interpolate: false, tag_rgb: false }; + let decodes = || RECOMPRESS_DECODES.with(std::cell::Cell::get); + let start = decodes(); + assert!(recompress(&crate::tests::blank_png(16_385), mode).is_none()); + assert_eq!(decodes(), start); + assert!(recompress(&crate::tests::blank_png(9), mode).is_some()); + assert_eq!(decodes(), start + 1); + } +} diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 8fcc15547..160fa38b2 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -258,7 +258,7 @@ fn cmyk_tiff() -> (Vec, Vec) { } /// A black `side`² 1-bit grey PNG: well under 1 MB, it decodes to `side`² bytes. -fn blank_png(side: u32) -> Vec { +pub(crate) fn blank_png(side: u32) -> Vec { use std::io::Write; let chunk = |out: &mut Vec, kind: &[u8; 4], data: &[u8]| { out.extend((data.len() as u32).to_be_bytes()); @@ -354,17 +354,14 @@ fn a_cut_off_image_is_skipped_not_fatal() { } } -/// A raster past the RGBA budget is skipped undecoded, also when images are recompressed (#1586). +/// A raster past the RGBA budget is skipped with a warning, also when images are recompressed (#1586). #[test] -fn an_image_past_the_decode_budget_is_skipped_undecoded() { +fn an_image_past_the_decode_budget_is_skipped_with_a_warning() { let side = 16_385; let mut d = doc_with_text("still here"); place(&mut d, blank_png(side), (side, side)); for compress_images in [false, true] { - let started = std::time::Instant::now(); let r = export_pdf_with_report(&d, &Cache::new(), &PdfOptions { compress_images, ..Default::default() }).unwrap(); - let took = started.elapsed(); - assert!(took < std::time::Duration::from_secs(1), "compress_images {compress_images}: took {took:?}"); assert!(r.warnings.iter().any(|w| w.contains("could not be decoded and was skipped")), "compress_images {compress_images}: {:?}", r.warnings); assert!(image_xobjects(&r.bytes).is_empty(), "compress_images {compress_images}"); } From 5aba8cb01747da9690b501401dcdbda314cd1c5b Mon Sep 17 00:00:00 2001 From: Zaxaerith Date: Thu, 29 Oct 2026 11:09:07 +0800 Subject: [PATCH 0338/1349] docs: complete README architecture layer table (#1979) --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index cd0f56479..47dbd6ee0 100644 --- a/README.md +++ b/README.md @@ -250,11 +250,11 @@ egui frontend is a separate crate, so the UI can be swapped without touching the |---|---| | L0 | `geom` (paths, units & measurement parsing, corner options) · `color` (CMYK/RGB/Lab, swatches, tints, gradients) | | L1 | `doc` (spreads, pages, parents, layers, frames, stories, styles) · `fonts` (font DB, shaping, outlines) | -| L2 | `compose` (the text engine) | -| L3 | `render` (vello_cpu) | +| L2 | `compose` (the text engine) · `images` | +| L3 | `render` (vello_cpu) · `pdf` · `idml` · `epub` · `pptx` · `textimport` · `format` | | L4 | `tools` (pointer events → commands + overlays) | | L5 | `engine` (session, history, command registry) | -| L6 | `ui-egui` (publishing UI, control channel) | +| L6 | `ui-egui` (publishing UI, control channel) · `mcp` | | L7 | `apps/designcraft`, `apps/designcraft-cli`, `apps/designcraft-web` | - **Status and milestones:** [ROADMAP.md](ROADMAP.md) (stage: pre-alpha); feature assessment: [`docs/target-app-parity.md`](docs/target-app-parity.md); known gaps: [`docs/gaps.md`](docs/gaps.md) From 53d4d9862a3193655907e9cd3e6eb4a51702e533 Mon Sep 17 00:00:00 2001 From: Zaxaerith Date: Thu, 29 Oct 2026 11:12:23 +0800 Subject: [PATCH 0339/1349] docs: correct sample document menu path (#1978) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cd0f56479..33dde275d 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ ## The sample magazine Every page below was laid out by DesignCraft from code (`crates/engine/src/sample.rs`) and exported -by its own renderer. Try it yourself with `File → New → Sample Document`, or start the app with +by its own renderer. Try it yourself with `Help → Sample Document`, or start the app with `--sample`.
From d7bc6633e763656ac53179f7ffb12b5c46eef6b4 Mon Sep 17 00:00:00 2001 From: KnottyDyes <47539659+KnottyDyes@users.noreply.github.com> Date: Wed, 28 Oct 2026 20:26:06 -0600 Subject: [PATCH 0340/1349] Compose: honor discretionary hyphens in single-line composition Recognize U+00AD independently of automatic hyphenation in the greedy breaker, reusing the existing visible hyphen output. Cover both composers, zero-width unbroken soft hyphens, pattern suppression, and tagged and untagged PDF text extraction. Fixes #1955 Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 1 + crates/compose/src/breaker.rs | 10 +++- crates/compose/src/tests.rs | 100 +++++++++++++++++++++++++++++----- crates/pdf/src/tests.rs | 22 ++++++++ docs/typography-parity.md | 2 +- 5 files changed, 120 insertions(+), 15 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index c02176bab..6c49d77e7 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -380,6 +380,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-10-28** · Discretionary hyphens (U+00AD) break in the single-line composer with automatic hyphenation on or off, matching the paragraph composer. Unbroken soft hyphens remain invisible and zero-width, and words containing them keep only their discretionary break points (#1955). No readiness percentage change. - **2026-10-27** · An iconic panel's flyout stays open while you work in the canvas or a text field: Auto-Collapse Iconic Panels is off by default, and preferences saved with it on start with it off. Preferences › Interface › Panels holds the setting next to the column bar's menu item. No readiness percentage change. - **2026-10-24** · Column rules run from the top line's ascent to the bottom line's descent, as InDesign draws them, instead of from the top to the bottom of the columns, on screen, in PDF and in PowerPoint export. The top and bottom insets shorten the rule from those lines. Existing documents draw their column rules at the new length. No readiness percentage change. - **2026-10-20** · Edit › Keyboard Shortcuts is craft-keymap's shared dialog: commands grouped by menu with Show and Filter, recording that asks before taking a key from another command, undo and redo, named shortcut sets (edits of Default become Custom; an imported set becomes a set of its own), an on-screen US keyboard, InDesign Show Set files reviewed before they apply, JSON export and an HTML summary. ui.json keeps the `shortcuts` map earlier versions read, for the active set. No readiness percentage change. diff --git a/crates/compose/src/breaker.rs b/crates/compose/src/breaker.rs index 9b453ff0a..6f62542d7 100644 --- a/crates/compose/src/breaker.rs +++ b/crates/compose/src/breaker.rs @@ -972,7 +972,15 @@ pub fn greedy( x += adv; shrink += sp.box_elastic(g).1.iter().sum::(); if i + 1 < n && !glyphs[i + 1].is_space() && !g.no_break && g.break_after != Some(false) { - if matches!(g.ch, '-' | '\u{2010}' | '\u{2013}' | '\u{2014}' | '/') + if g.ch == SOFT_HYPHEN { + if may_hyphenate(hyphens) { + let hw = hyphen_width(g, &mut hy_cache); + let hy = (hw - hyphen_hang(g, hw, sp)).max(0.0); + if x + hy <= w + shrink + FIT_EPS { + last_ok = Some((i + 1, true)); + } + } + } else if matches!(g.ch, '-' | '\u{2010}' | '\u{2013}' | '\u{2014}' | '/') || g.break_after.unwrap_or_else(|| cjk_break(g, &glyphs[i + 1], sp)) { last_ok = Some((i + 1, false)); diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 3083261fb..3128da3a7 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -1103,21 +1103,95 @@ fn hyphenate_across_column_off_keeps_nested_line_styles_on_their_lines() { } #[test] -fn discretionary_hyphen_replaces_automatic_points() { - let text = "aaaa bbbb cccc extraordi\u{AD}narily dddd eeee"; - let para = ParaAttrs { align: Some(Align::Left), ..Default::default() }; - let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 120.0, 1000.0), para); - let cs = compose_story(&d, sid, &ComposeOptions::default()); - let soft = text.find('\u{AD}').unwrap(); - for l in all_lines(&cs) { - if l.hyphenated { - let last = l.glyphs.iter().rfind(|g| g.len > 0).unwrap(); - assert!(last.byte + last.len >= soft && last.byte <= soft + 2, "{:?}", &text[l.range.clone()]); +fn discretionary_hyphen_breaks_with_both_composers_and_hyphenation_settings() { + let text = "Wir möchten uns ganz besonders herzlich bei folgenden Personen bedanken, die auf unterschied\u{ad}lichste Weise zur Entstehung dieses Lehrbuches beigetragen haben:"; + let soft_end = text.find('\u{ad}').unwrap() + '\u{ad}'.len_utf8(); + for composer in [Composer::SingleLine, Composer::Paragraph] { + for hyphenate in [false, true] { + let para = ParaAttrs { composer: Some(composer), hyphenate: Some(hyphenate), ..Default::default() }; + let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 430.0, 1000.0), para); + d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.size = Some(9.5)); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let first = all_lines(&cs)[0]; + assert_eq!(first.range.end, soft_end, "{composer:?}, hyphenate={hyphenate}: {:?}", &text[first.range.clone()]); + assert!(first.hyphenated); + let hyphen = first.glyphs.last().unwrap(); + assert!(hyphen.visible && hyphen.len == 0 && hyphen.adv > 0.0); } } - // Hyphenation points of the word itself: none besides the discretionary one. - let lines = all_lines(&cs); - assert!(lines.iter().filter(|l| l.hyphenated).count() <= 1); +} + +#[test] +fn discretionary_hyphen_before_cjk_single_line() { + discretionary_hyphen_before_cjk(Composer::SingleLine); +} + +#[test] +fn discretionary_hyphen_before_cjk_paragraph() { + discretionary_hyphen_before_cjk(Composer::Paragraph); +} + +fn discretionary_hyphen_before_cjk(composer: Composer) { + let text = "abc\u{ad}\u{65e5}\u{672c}\u{8a9e}\u{65e5}\u{672c}\u{8a9e}"; + let soft_end = text.find('\u{ad}').unwrap() + '\u{ad}'.len_utf8(); + for hyphenate in [false, true] { + let para = ParaAttrs { composer: Some(composer), hyphenate: Some(hyphenate), ..Default::default() }; + let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 24.0, 1000.0), para); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let first = all_lines(&cs)[0]; + assert_eq!(first.range.end, soft_end, "{composer:?}, hyphenate={hyphenate}: {:?}", &text[first.range.clone()]); + assert!(first.hyphenated, "{composer:?}, hyphenate={hyphenate}"); + let hyphen = first.glyphs.last().unwrap(); + assert!(hyphen.visible && hyphen.len == 0 && hyphen.adv > 0.0); + } +} + +#[test] +fn discretionary_hyphen_is_invisible_and_zero_width_when_unbroken() { + for composer in [Composer::SingleLine, Composer::Paragraph] { + let mut widths = Vec::new(); + for text in ["unterschiedlichste", "unterschied\u{ad}lichste"] { + let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 1000.0, 100.0), ParaAttrs { composer: Some(composer), ..Default::default() }); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + assert_eq!(lines.len(), 1); + assert!(!lines[0].hyphenated); + if let Some(soft) = text.find('\u{ad}') { + let glyph = lines[0].glyphs.iter().find(|g| g.byte == soft).unwrap(); + assert!(!glyph.visible && glyph.adv == 0.0); + } + widths.push(lines[0].end_x); + } + assert!((widths[0] - widths[1]).abs() < 1e-6, "{composer:?}: {widths:?}"); + } +} + +#[test] +fn discretionary_hyphen_replaces_automatic_points() { + let text = "aaaa bbbb cccc extraordi\u{AD}narily dddd eeee"; + let soft = text.find('\u{AD}').unwrap(); + for composer in [Composer::SingleLine, Composer::Paragraph] { + let mut discretionary_breaks = 0; + let mut automatic_breaks = 0; + for width in (90..181).step_by(10) { + for discretionary in [false, true] { + let source = if discretionary { text.to_string() } else { text.replace('\u{AD}', "") }; + let para = ParaAttrs { composer: Some(composer), hyphenate: Some(true), align: Some(Align::Left), ..Default::default() }; + let (d, sid, _) = doc_with(&source, Rect::new(0.0, 0.0, f64::from(width), 1000.0), para); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + for l in all_lines(&cs).into_iter().filter(|l| l.hyphenated) { + if discretionary { + assert_eq!(l.range.end, soft + '\u{AD}'.len_utf8(), "{composer:?}: {:?}", &source[l.range.clone()]); + discretionary_breaks += 1; + } else { + automatic_breaks += 1; + } + } + } + } + assert!(discretionary_breaks > 0, "{composer:?}: discretionary breaks exercised"); + assert!(automatic_breaks > 0, "{composer:?}: pattern breaks exercised without U+00AD"); + } } #[test] diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 2accc79fa..f913854aa 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -76,6 +76,28 @@ fn exports_valid_pdf_with_one_page_per_page() { assert_eq!(pdf.pages().len(), 2); } +#[test] +fn discretionary_hyphen_pdf_text_follows_visible_breaks() { + let text = "Wir möchten uns ganz besonders herzlich bei folgenden Personen bedanken, die auf unterschied\u{ad}lichste Weise zur Entstehung dieses Lehrbuches beigetragen haben:"; + for composer in [designcraft_doc::Composer::SingleLine, designcraft_doc::Composer::Paragraph] { + for (width, expected) in [(430.0, "unterschied-lichste"), (540.0, "unterschiedlichste")] { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let para = designcraft_doc::ParaAttrs { composer: Some(composer), hyphenate: Some(false), ..Default::default() }; + let (_, sid) = d + .add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 36.0 + width, 400.0), lid, text, ParaFormat { para, ..Default::default() }) + .unwrap(); + d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.size = Some(9.5)); + for tagged in [false, true] { + let bytes = export_pdf(&d, &Cache::new(), &PdfOptions { tagged, ..Default::default() }).unwrap(); + let extracted = extract_text(&bytes).concat(); + assert!(extracted.contains(expected), "{composer:?}, width={width}, tagged={tagged}: {extracted:?}"); + assert!(!extracted.contains('\u{ad}')); + } + } + } +} + #[test] fn text_is_real_text() { let d = doc_with_text("Hello DesignCraft — efficient affine"); diff --git a/docs/typography-parity.md b/docs/typography-parity.md index 8c92e8dfa..9b4c2591a 100644 --- a/docs/typography-parity.md +++ b/docs/typography-parity.md @@ -36,7 +36,7 @@ Fidelity: **unmeasured** unless stated. | Single-line Composer | greedy | greedy with the same ranges | ✓ | | | World-Ready composers | Paragraph / Single-line World-Ready | RTL, Arabic and bidi in the main composer | ~ | Indic scripts (Devanagari etc.) shape through harfrust but are untested | | Justification | word/letter spacing, glyph scaling min/desired/max, single-word, last line | all of these | ✓ | a justified line with a tab justifies after the tab (#284); set per paragraph in Type › Justification… and the Paragraph panel menu (#531) | -| Hyphenation | per-language dictionaries (~40), zone, limits, capitalized, last word, across columns | Liang patterns: English (trained from the public-domain Moby list), Spanish (Bezos), Portuguese (hyph-pt), Norwegian (hyph-no) and Greek (hyph-el-monoton); zone, limits, exceptions in the user dictionary; Hyphenate Across Column off keeps automatic hyphens off the last line of a column or frame | ~ | other languages don't hyphenate (#87 reported "doesn't work") | +| Hyphenation | per-language dictionaries (~40), zone, limits, capitalized, last word, across columns | Liang patterns: English (trained from the public-domain Moby list), Spanish (Bezos), Portuguese (hyph-pt), Norwegian (hyph-no) and Greek (hyph-el-monoton); zone, limits, exceptions in the user dictionary; Hyphenate Across Column off keeps automatic hyphens off the last line of a column or frame; discretionary U+00AD breaks with both composers regardless of automatic hyphenation and replaces pattern points within its word (#1955) | ~ | other languages don't hyphenate (#87 reported "doesn't work") | | Spelling | per-language dictionaries | English (Moby) + document/user dictionary | ~ | | | Kerning | Metrics, Optical, manual, none | Metrics, Optical (outline-based: pairs pulled towards the font's stem gap, `crates/compose/src/optical.rs`), manual, none | ~ | Optical is an approximation of Adobe's algorithm (#181), not a match: imported display text can still break differently | | Tracking, scale, skew, baseline shift | ✓ | ✓ | ✓ | | From 4d88c0899e88a4b05d554985acfdf8ccb2f7ce4e Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:21:20 +0100 Subject: [PATCH 0341/1349] Keep stroke styles from joining the subpaths of a compound path Found while testing crates/geom/src/stroke_style.rs:24-31 (offset_path: `(MoveTo(p), 0, true) => out.line_to(p)`; also samples/wavy at :58-98) Co-Authored-By: Claude Opus 5.5 --- crates/geom/src/stroke_style.rs | 63 +++++++++++++++++++++++++++------ 1 file changed, 53 insertions(+), 10 deletions(-) diff --git a/crates/geom/src/stroke_style.rs b/crates/geom/src/stroke_style.rs index 63c632ea2..d018667f2 100644 --- a/crates/geom/src/stroke_style.rs +++ b/crates/geom/src/stroke_style.rs @@ -9,6 +9,28 @@ pub fn offset_path(bp: &BezPath, d: f64, tol: f64) -> BezPath { return bp.clone(); } let mut out = BezPath::new(); + for sub in subpaths(bp) { + offset_subpath(&sub, d, tol, &mut out); + } + out +} + +/// `bp` split at each `MoveTo` into its subpaths. +fn subpaths(bp: &BezPath) -> Vec { + let mut out: Vec = Vec::new(); + for el in bp.elements() { + if matches!(el, kurbo::PathEl::MoveTo(_)) || out.is_empty() { + out.push(BezPath::new()); + } + if let Some(sub) = out.last_mut() { + sub.push(*el); + } + } + out +} + +/// One subpath offset by `d`, its segments joined into one line, appended to `out`. +fn offset_subpath(bp: &BezPath, d: f64, tol: f64, out: &mut BezPath) { let mut started = false; for seg in bp.segments() { let c = match seg { @@ -30,7 +52,6 @@ pub fn offset_path(bp: &BezPath, d: f64, tol: f64) -> BezPath { } started = true; } - out } /// Bands (start, width) across a stroke, as fractions of the weight from its left edge. @@ -54,8 +75,13 @@ pub fn stripes(bp: &BezPath, weight: f64, bands: &Bands, tol: f64) -> BezPath { out } -/// Points along `bp` every `step` of arc length, with the unit tangent there. -fn samples(bp: &BezPath, step: f64) -> Vec<(Point, Vec2)> { +/// Points along each subpath of `bp` every `step` of arc length, with the unit tangent there. +fn samples(bp: &BezPath, step: f64) -> Vec> { + subpaths(bp).iter().map(|sub| subpath_samples(sub, step)).collect() +} + +/// Points along one subpath every `step` of arc length, with the unit tangent there. +fn subpath_samples(bp: &BezPath, step: f64) -> Vec<(Point, Vec2)> { let mut out = Vec::new(); let mut carry = 0.0; for seg in bp.segments() { @@ -85,13 +111,14 @@ fn samples(bp: &BezPath, step: f64) -> Vec<(Point, Vec2)> { /// A wavy stroke: the line swings `weight` wide, drawn a third of the weight thick. pub fn wavy(bp: &BezPath, weight: f64, tol: f64) -> BezPath { let wavelength = (weight * 4.0).max(2.0); - let pts = samples(bp, wavelength / 16.0); let mut line = BezPath::new(); - for (i, (p, t)) in pts.iter().enumerate() { - let normal = Vec2::new(-t.y, t.x); - let phase = i as f64 / 16.0 * std::f64::consts::TAU; - let q = *p + normal * (phase.sin() * weight * 0.33); - if i == 0 { line.move_to(q) } else { line.line_to(q) } + for pts in samples(bp, wavelength / 16.0) { + for (i, (p, t)) in pts.iter().enumerate() { + let normal = Vec2::new(-t.y, t.x); + let phase = i as f64 / 16.0 * std::f64::consts::TAU; + let q = *p + normal * (phase.sin() * weight * 0.33); + if i == 0 { line.move_to(q) } else { line.line_to(q) } + } } let s = Stroke::new(weight / 3.0).with_join(kurbo::Join::Round); kurbo::stroke(line.iter(), &s, &kurbo::StrokeOpts::default(), tol) @@ -100,7 +127,7 @@ pub fn wavy(bp: &BezPath, weight: f64, tol: f64) -> BezPath { /// A straight-hash stroke: short ticks across the path, as wide as the weight. pub fn hashed(bp: &BezPath, weight: f64, tol: f64) -> BezPath { let mut ticks = BezPath::new(); - for (p, t) in samples(bp, (weight * 0.6).max(1.0)) { + for (p, t) in samples(bp, (weight * 0.6).max(1.0)).into_iter().flatten() { let normal = Vec2::new(-t.y, t.x) * (weight / 2.0); ticks.move_to(p - normal); ticks.line_to(p + normal); @@ -141,4 +168,20 @@ mod tests { let h = hashed(&line(), 8.0, 0.01).bounding_box(); assert!((h.height() - 8.0).abs() < 0.5 && h.width() > 90.0, "{h:?}"); } + + #[test] + fn styled_strokes_keep_subpaths_apart() { + // Two separate lines, 50 pt apart, in one compound path. + let mut b = line(); + b.move_to((0.0, 50.0)); + b.line_to((100.0, 50.0)); + let moves = |p: &BezPath| p.elements().iter().filter(|e| matches!(e, kurbo::PathEl::MoveTo(_))).count(); + assert_eq!(moves(&offset_path(&b, 3.0, 0.01)), 2, "one offset subpath per input subpath"); + let s = stripes(&b, 12.0, &[(0.0, 0.5), (0.75, 0.25)], 0.01); + assert!(!s.contains(Point::new(50.0, 25.0)), "stripe bridges the subpaths: {:?}", s.bounding_box()); + assert!(s.contains(Point::new(50.0, 46.0)), "second line is still striped"); + let w = wavy(&b, 4.0, 0.01); + let bridged = (0..=2000).map(|i| f64::from(i) * 0.05).filter(|&x| w.contains(Point::new(x, 25.0))).count(); + assert_eq!(bridged, 0, "wavy bridges the subpaths: {:?}", w.bounding_box()); + } } From f11f5f3b11ac06be32c142b1d681bdb912c6bd10 Mon Sep 17 00:00:00 2001 From: Hamza Date: Thu, 29 Oct 2026 13:51:49 +0500 Subject: [PATCH 0342/1349] cli: a missing value is found before anything runs Review caught a consequence of the previous commit. Standing the order check aside so a missing value could be reported meant the value was reported later -- after the exports before it had already been written. `run --export first.png --scale --export second.png` wrote first.png and only then failed, so an invocation that fails could overwrite a file that was already there. `values_present` checks every option that takes a value before the order check and before any export, so the line is refused as a whole. The test writes a file at the export path first and asserts its bytes are unchanged. --- apps/designcraft-cli/src/main.rs | 21 +++++++++++++++++++++ apps/designcraft-cli/tests/it/cli.rs | 14 ++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/apps/designcraft-cli/src/main.rs b/apps/designcraft-cli/src/main.rs index 98c9b32d2..46e4a7c8c 100644 --- a/apps/designcraft-cli/src/main.rs +++ b/apps/designcraft-cli/src/main.rs @@ -379,7 +379,28 @@ impl Export { } } +/// Every option that takes a value has one, checked before anything runs. Found later, a missing +/// value is reported only after the exports before it have been written -- and `run --export +/// first.png --scale --export second.png` would then have overwritten an existing `first.png` on +/// an invocation that fails (noted in review). +fn values_present(args: &[String]) -> Result<(), String> { + let mut i = 0; + while let Some(a) = args.get(i) { + i += 1; + if !matches!(a.as_str(), "--in" | "--cmd" | "--export" | "--all-pages" | "--page" | "--scale" | "--pdf-options") { + continue; + } + value(a, args.get(i))?; + // Step over the value, so one that looks like an option is not checked as one. + i += 1; + } + Ok(()) +} + fn run(args: &[String]) -> Result<(), String> { + // Before the order check and before any export: a value error is about the line as written, + // and reporting it must not cost a file that was already there. + values_present(args)?; if let Some(opt) = option_after_last_export(args) { return Err(format!( "{opt} has no --export or --all-pages after it; options apply to the exports that follow them, so put it before its --export" diff --git a/apps/designcraft-cli/tests/it/cli.rs b/apps/designcraft-cli/tests/it/cli.rs index 87e5b58fd..a2c909e38 100644 --- a/apps/designcraft-cli/tests/it/cli.rs +++ b/apps/designcraft-cli/tests/it/cli.rs @@ -592,6 +592,20 @@ fn the_argument_parser_refuses_what_it_cannot_mean() { assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); assert!(dir.join("-dash.png").is_file(), "{:?}", std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name()).collect::>()); + // A missing value is found before anything runs, so an export earlier on the line does not + // happen: reported later, `--export first.png --scale --export second.png` wrote first.png + // and only then failed, overwriting a file that was already there (noted in review). + let first = dir.join("first.png"); + std::fs::write(&first, b"older file").unwrap(); + let out = + cli().current_dir(&dir).args(["run", "--sample", "--export", first.to_str().unwrap(), "--scale", "--export", "second.png"]).output().unwrap(); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err:?}"); + assert!(err.contains("--scale needs a value"), "{err:?}"); + assert_eq!(std::fs::read(&first).unwrap(), b"older file", "the file that was already there is untouched"); + assert!(!dir.join("second.png").exists(), "and nothing else is written"); + std::fs::remove_file(&first).unwrap(); + // A missing value is still a missing value, with the message it had. let out = cli().args(["run", "--sample", "--export"]).output().unwrap(); assert!(!out.status.success()); From 2b0d8a4c105ce1c3eac31d574f8fd999027cde44 Mon Sep 17 00:00:00 2001 From: Hamza Date: Thu, 29 Oct 2026 13:53:11 +0500 Subject: [PATCH 0343/1349] test(cli): don't assert the operating system's wording for a missing file Review caught a test that cannot pass on Windows: it asserted the error for `validate-pdf --nope` contains "No such file", which is the unix phrasing. Windows says "The system cannot find the file specified", so the assertion failed there even when the command refused the path correctly -- the same mistake as the `\\?\C:\` one on #1909, and in a test whose point is to run everywhere. It asserts the error names the path; `failed()` already checks the exit code and the stream. The companion check that a ` --help` run did not open a file now looks for either operating system's wording, so it catches that on Windows too rather than only on unix. --- apps/designcraft-cli/tests/it/args.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/apps/designcraft-cli/tests/it/args.rs b/apps/designcraft-cli/tests/it/args.rs index bbbde4867..7c27a8e8e 100644 --- a/apps/designcraft-cli/tests/it/args.rs +++ b/apps/designcraft-cli/tests/it/args.rs @@ -153,7 +153,9 @@ fn every_subcommand_answers_help_without_running_anything() { // None of the work the rest of the line asks for was done. assert!(!png.exists(), "{what} exported a file"); assert!(!out.contains("cannot connect") && !out.contains("render threads"), "{what}: {out:?}"); - assert!(!out.contains("No such file"), "{what}: {out:?}"); + // Either operating system's wording, so this catches a file the help path opened on + // Windows as well as on unix. + assert!(!out.contains("No such file") && !out.contains("cannot find the file"), "{what}: {out:?}"); } } // `script`'s own help is longer than one usage line: it documents the script syntax, which is @@ -193,7 +195,11 @@ fn the_subcommands_that_take_a_word_read_an_unknown_option_as_that_word() { assert!(err.contains("no command `--nope`"), "{err:?}"); // A path nobody has. let err = run(&["validate-pdf", "--nope"]).failed("validate-pdf --nope"); - assert!(err.contains("--nope") && err.contains("No such file"), "{err:?}"); + // The error names the path. Not the operating system's wording for a missing file: Windows + // says "The system cannot find the file specified", so asserting the Unix phrasing failed + // there even when the command refused correctly (noted in review). `failed` already checks + // the exit code and the stream. + assert!(err.contains("--nope"), "{err:?}"); // A method name for the running app, so the error is about reaching the app. let dead = closed_port(); let err = run(&["app", "--port", &dead, "--nope"]).failed("app --nope"); From 5a53a3807c08d156722ba8dce3f034d03b411181 Mon Sep 17 00:00:00 2001 From: Hamza Date: Thu, 29 Oct 2026 14:17:21 +0500 Subject: [PATCH 0344/1349] Check a parent page's frame on the pages that show it The warnings composed every story once with no page. For a frame on a parent page that is wrong twice over, and I measured both: exportPdf {"pages": [2]} ["the story in frame 9: 76 character(s) do not fit and are not in the export"] Page 2 used no parent at all, so nothing of that frame was in its export to be missing -- and the warning named no page, because a parent frame has no document page of its own. It now resolves the pages that draw the parent page and reports only those: {"pages": [1]} ["page 1: 76 character(s) ... frame 9 ..."] {"pages": [2]} [] The second half is page-dependent text. A parent frame 112 pt wide holding "Continued on page " fits while the number is one digit and does not once it is two, so composing it once could not tell: {"pages": [1]} [] {"pages": [9]} [] {"pages": [10]} ["page 10: 1 character(s) ..."] {} ["pages 10, 11, 12: 1 character(s) ..."] Each page that shows the parent is composed as that page, and the pages are grouped by how much they lose, so a story still gets one line. Also from review: `story.get` now says `overset` is a UTF-8 byte offset into `text`, not a character index. A test measures the difference on French text, where the offset runs ahead of the character count. --- crates/engine/src/cmd/export/pdf.rs | 70 +++++++++++++++++++++++++++++ crates/engine/src/cmd/preflight.rs | 63 +++++++++++++++++++++++++- crates/engine/src/cmd/text.rs | 2 +- 3 files changed, 132 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/export/pdf.rs b/crates/engine/src/cmd/export/pdf.rs index 12d5577ec..b5f16c110 100644 --- a/crates/engine/src/cmd/export/pdf.rs +++ b/crates/engine/src/cmd/export/pdf.rs @@ -541,6 +541,76 @@ mod overset_tests { assert!(story["overset"].is_null() && story["oversetChars"].is_null(), "{story}"); } + /// `overset` indexes `text` in UTF-8 bytes, not characters: a client that slices a JavaScript + /// string at it cuts the wrong place once the text is not ASCII (noted in review). + #[test] + fn overset_is_a_byte_offset_into_the_text() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200, "pages": 1, "facingPages": false, "margins": 0})).unwrap(); + // Accented letters are two bytes each, so the byte offset runs ahead of the character index. + let text = "Réservé à l'évaluation détaillée des éléments.\nCette phrase dépasse le cadre et n'est pas dans le PDF exporté du tout."; + let frame = s.execute("frame.create", &json!({"rect": [20, 20, 280, 40], "content": "text", "text": text})).unwrap(); + let story = s.execute("story.get", &json!({"story": frame["story"].clone()})).unwrap(); + let at = story["overset"].as_u64().expect("it oversets") as usize; + assert!(text.is_char_boundary(at), "a byte offset that splits no character: {at}"); + assert!(at > text[..at].chars().count(), "ahead of the character index: {at} bytes, {} characters", text[..at].chars().count()); + // And `oversetChars` counts characters, which is why the two numbers differ. + assert_eq!(story["oversetChars"], json!(text[at..].chars().count()), "{story}"); + } + + /// A parent page's frame is composed once per page that shows it: its page number marker is + /// that page's, so the same frame fits on page 1 and oversets on page 10 -- and a parent page + /// no exported page uses puts nothing in the file to be missing. Composing it once with no + /// page reported neither: every selection got the same unpaged warning (noted in review). + #[test] + fn a_parent_frame_is_checked_on_the_pages_that_show_it() { + let about = |r: &serde_json::Value| -> Vec { + r["warnings"] + .as_array() + .map(|w| w.iter().filter_map(|w| w.as_str()).filter(|w| w.contains("not in the export")).map(str::to_string).collect()) + .unwrap_or_default() + }; + + // A parent page that only page 1 uses. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200, "pages": 2, "facingPages": false, "margins": 0})).unwrap(); + s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": null})).unwrap(); + let text = "First line is visible.\nSecond paragraph does not fit: this sentence carries the legal notice and must not vanish from the PDF without a warning."; + let frame = s + .execute("frame.create", &json!({"spread": {"kind": "parent", "index": 0}, "rect": [20, 20, 280, 60], "content": "text", "text": text})) + .unwrap(); + let id = frame["id"].as_u64().unwrap(); + + let w = about(&s.execute("file.exportPdf", &json!({"pages": [1]})).unwrap()); + assert_eq!(w.len(), 1, "page 1 shows the parent: {w:?}"); + assert!(w[0].contains("page 1") && w[0].contains(&format!("frame {id}")) && w[0].contains("76 character"), "{}", w[0]); + + // Page 2 has no parent, so nothing of that frame is in its export to be missing. + let r = s.execute("file.exportPdf", &json!({"pages": [2]})).unwrap(); + assert!(about(&r).is_empty(), "page 2 does not use the parent: {r}"); + + // Page-dependent text: the marker is one digit up to page 9 and two from page 10, and the + // wider line no longer fits. 112 pt is the width where that is the only difference. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200, "pages": 12, "facingPages": false, "margins": 0})).unwrap(); + let text = format!("Continued on page {}", designcraft_doc::story::PAGE_NUMBER); + s.execute("frame.create", &json!({"spread": {"kind": "parent", "index": 0}, "rect": [20, 20, 132, 36], "content": "text", "text": text})) + .unwrap(); + + for page in [1, 9] { + let r = s.execute("file.exportPdf", &json!({"pages": [page]})).unwrap(); + assert!(about(&r).is_empty(), "page {page} fits one digit: {r}"); + } + let w = about(&s.execute("file.exportPdf", &json!({"pages": [10]})).unwrap()); + assert_eq!(w.len(), 1, "two digits do not fit: {w:?}"); + assert!(w[0].contains("page 10"), "{}", w[0]); + + // The whole document: one line naming every page it happens on, not one line per page. + let w = about(&s.execute("file.exportPdf", &json!({})).unwrap()); + assert_eq!(w.len(), 1, "one line for the story: {w:?}"); + assert!(w[0].starts_with("pages 10, 11, 12:"), "{}", w[0]); + } + /// A spread export puts the whole spread on the sheet, so choosing one page of it exports its /// partner too -- and that partner's overset is just as absent from the file. Reporting only /// the pages that were named left it unmentioned (noted in review of #1465). diff --git a/crates/engine/src/cmd/preflight.rs b/crates/engine/src/cmd/preflight.rs index b3a22d6ad..bf98f9ab9 100644 --- a/crates/engine/src/cmd/preflight.rs +++ b/crates/engine/src/cmd/preflight.rs @@ -121,16 +121,76 @@ fn overset_location(s: &Session, target: designcraft_doc::ItemId) -> Option<(des /// 0-based pages being exported; a story whose overset is on a page that is not being exported is /// not reported, and one with no page of its own always is. A reflowable export (EPUB, HTML) or a /// text export carries the whole story, so neither calls this. +/// Pages a single warning names before "and N more". +const MAX_WARNED_PAGES: usize = 10; + +/// How the pages one warning covers are named: "page 3", "pages 3, 4", "pages 3, 4 and 6 more". +fn page_list(pages: &[usize]) -> String { + let shown: Vec = pages.iter().take(MAX_WARNED_PAGES).map(|p| (p + 1).to_string()).collect(); + let rest = pages.len() - shown.len(); + let list = shown.join(", "); + match (pages.len(), rest) { + (1, _) => format!("page {list}"), + (_, 0) => format!("pages {list}"), + _ => format!("pages {list} and {rest} more"), + } +} + +/// The parent spread and the page of it a frame sits on, or `None` for a frame on a document page. +fn parent_page_of(d: &Document, target: designcraft_doc::ItemId) -> Option<(usize, usize)> { + let loc = d.find(target)?; + let SpreadRef::Parent(pi) = loc.spread else { return None }; + let bounds = d.parent_xf(&loc).transform_rect_bbox(d.item(target)?.bounds()); + Some((pi, d.spread(loc.spread)?.page_at_x(bounds.center().x).unwrap_or(0))) +} + +/// Document pages that draw parent page `pp` of parent spread `pi`, in document order. +fn pages_showing(d: &Document, (pi, pp): (usize, usize)) -> Vec { + (0..d.page_count()) + .filter(|p| d.page_loc(*p).is_some_and(|(si, pgi)| d.shown_parent_pages(SpreadRef::Doc(si), pgi).contains(&(pi, pp)))) + .collect() +} + +/// Characters of `story` that `cs` had no room for. +fn overset_chars(story: &designcraft_doc::Story, cs: &ComposedStory) -> usize { + story.text.get(cs.overset_at.unwrap_or(0)..).unwrap_or("").chars().count() +} + pub fn overset_warnings(s: &Session, pages: Option<&[usize]>) -> Vec { let Some(st) = s.active() else { return vec![] }; let d = &st.doc; let mut out = Vec::new(); for story in d.stories.values() { + let last = story.frames.last().copied(); + // A story on a parent page is composed once per page that shows it: its page number + // markers and variables are that page's, so the same frame can fit on one page and + // overset on another, and a parent page no exported page uses puts nothing in the file + // to be missing. Composing it once with no page reported neither (noted in review). + if let Some(parent) = last.and_then(|f| parent_page_of(d, f)) { + let mut by_count: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for page in pages_showing(d, parent) { + if pages.is_some_and(|sel| !sel.contains(&page)) { + continue; + } + let cs = s.cache.get(d, story.id, Some(page)); + let n = overset_chars(story, &cs); + if cs.is_overset() && n > 0 { + by_count.entry(n).or_default().push(page); + } + } + let item = last.map_or(0, |f| f.0); + out.extend( + by_count.into_iter().map(|(n, ps)| { + format!("{}: {n} character(s) of the story in frame {item} do not fit it and are not in the export", page_list(&ps)) + }), + ); + continue; + } let cs = s.cache.get(d, story.id, None); if !cs.is_overset() { continue; } - let n = story.text.get(cs.overset_at.unwrap_or(0)..).unwrap_or("").chars().count(); + let n = overset_chars(story, &cs); if n == 0 { continue; } @@ -138,7 +198,6 @@ pub fn overset_warnings(s: &Session, pages: Option<&[usize]>) -> Vec { out.push(format!("a story with no text frame: {n} character(s) of it are not in the export")); continue; } - let last = story.frames.last().copied(); let location = last.and_then(|f| overset_location(s, f)); let page = location.and_then(|(_, page)| page); if let (Some(page), Some(pages)) = (page, pages) diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index 3e6dce9d5..01abf0e6e 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -191,7 +191,7 @@ pub fn specs() -> Vec { }) } ), - cmd!(query "story.get", "Get Story", [], None, "{story? | frame?} → text, frames, paragraphs, vertical, lines, overset (the index in `text` where it stops fitting its frames, null when it all fits) and oversetChars (how many characters that leaves, as preflight reports them)", has_doc, |s, p| { + cmd!(query "story.get", "Get Story", [], None, "{story? | frame?} → text, frames, paragraphs, vertical, lines, overset (the UTF-8 byte offset into `text` where it stops fitting its frames, not a character index, null when it all fits) and oversetChars (how many characters that leaves, as preflight reports them)", has_doc, |s, p| { let st = s.doc()?; let sid = story_of(s, p).ok_or_else(|| bad("story.get", "no story"))?; let mut v = st.doc.story_summary(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; From fd7d8dfb77c29b4203503196a287130c1550aa4c Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 12:08:10 +0100 Subject: [PATCH 0345/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/tools/src/select.rs | 134 ++++++++++++++++++------------------- 1 file changed, 67 insertions(+), 67 deletions(-) diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 096944828..f254cdf33 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -789,51 +789,51 @@ impl SelectionTool { && let Some((id, si, ai, handle)) = anchor_at(cx, p) { let at = anchor_spread_point(cx, id, si, ai); - let mut out = vec![]; - let mut others = vec![]; - if handle.is_none() { - // InDesign's anchor point selection: a click selects the point, Shift+click - // adds it or takes it away, and dragging a selected point moves all of them. - let me = (ItemId(id), si, ai); - let mut points = cx.selection.anchors.clone(); - let was = points.contains(&me); - if ev.mods.shift && was { - // Kept selected so a Shift-drag can constrain it; a click still takes it - // away, on release, as for objects. - self.anchor_release = Some(me); - } else if ev.mods.shift { - points.push(me); - } else if !was { - points = vec![me]; - } - if points != cx.selection.anchors { - out.push(Action::Exec("selection.set".into(), anchor_selection(cx, &points))); - } - others = points.iter().filter(|a| **a != me).map(|(i, s, a)| (i.0, *s, *a)).collect(); - } - let label = if handle.is_some() { - "Move Direction Handle" - } else if others.is_empty() { - "Move Anchor" - } else { - "Move Anchors" - }; - self.drag = Drag::Anchor { id, si, ai, handle, start: p, at, others }; - out.push(Action::Begin(label.into())); - return out; + let mut out = vec![]; + let mut others = vec![]; + if handle.is_none() { + // InDesign's anchor point selection: a click selects the point, Shift+click + // adds it or takes it away, and dragging a selected point moves all of them. + let me = (ItemId(id), si, ai); + let mut points = cx.selection.anchors.clone(); + let was = points.contains(&me); + if ev.mods.shift && was { + // Kept selected so a Shift-drag can constrain it; a click still takes it + // away, on release, as for objects. + self.anchor_release = Some(me); + } else if ev.mods.shift { + points.push(me); + } else if !was { + points = vec![me]; } - // As in InDesign, the Direct Selection tool pressed on a corner or anchor of an object - // that isn't selected selects it and moves just that point (Chris Nielsen's "The - // InDesign Toolbox", 10:10: click outside, then pull a frame's corner). - if self.direct - && !ev.mods.shift - && let Some((_, hit)) = cx.hit(p) - && !cx.selection.contains(hit) - && let Some((id, si, ai, None)) = anchor_at_in(cx, &[hit], p) - { - let at = anchor_spread_point(cx, id, si, ai); - self.drag = Drag::Anchor { id, si, ai, handle: None, start: p, at, others: vec![] }; - return vec![Action::Exec("selection.set".into(), json!({"ids": [id], "content": true})), Action::Begin("Move Anchor".into())]; + if points != cx.selection.anchors { + out.push(Action::Exec("selection.set".into(), anchor_selection(cx, &points))); + } + others = points.iter().filter(|a| **a != me).map(|(i, s, a)| (i.0, *s, *a)).collect(); + } + let label = if handle.is_some() { + "Move Direction Handle" + } else if others.is_empty() { + "Move Anchor" + } else { + "Move Anchors" + }; + self.drag = Drag::Anchor { id, si, ai, handle, start: p, at, others }; + out.push(Action::Begin(label.into())); + return out; + } + // As in InDesign, the Direct Selection tool pressed on a corner or anchor of an object + // that isn't selected selects it and moves just that point (Chris Nielsen's "The + // InDesign Toolbox", 10:10: click outside, then pull a frame's corner). + if self.direct + && !ev.mods.shift + && let Some((_, hit)) = cx.hit(p) + && !cx.selection.contains(hit) + && let Some((id, si, ai, None)) = anchor_at_in(cx, &[hit], p) + { + let at = anchor_spread_point(cx, id, si, ai); + self.drag = Drag::Anchor { id, si, ai, handle: None, start: p, at, others: vec![] }; + return vec![Action::Exec("selection.set".into(), json!({"ids": [id], "content": true})), Action::Begin("Move Anchor".into())]; } // A selected placed graphic's own handles resize it inside its frame (the // frame's anchors, under Direct Selection, come first). @@ -1172,18 +1172,18 @@ impl SelectionTool { // Screen y points down: a positive screen angle is clockwise. vec![Action::Preview("transform.rotate".into(), json!({"angle": -a}))] } - Drag::Anchor { id, si, ai, handle, start, at, others } => { - let mut d = p - start; - if d.hypot() >= cx.tol(3.0) { - self.anchor_release = None; - } else if self.anchor_release.is_some() { - // A Shift-press on a selected point is still a click: nothing moves yet. - return vec![]; - } - // Shift: horizontal, vertical or at 45°. - if ev.mods.shift { - d = constrain_45(d); - } + Drag::Anchor { id, si, ai, handle, start, at, others } => { + let mut d = p - start; + if d.hypot() >= cx.tol(3.0) { + self.anchor_release = None; + } else if self.anchor_release.is_some() { + // A Shift-press on a selected point is still a click: nothing moves yet. + return vec![]; + } + // Shift: horizontal, vertical or at 45°. + if ev.mods.shift { + d = constrain_45(d); + } let mut dx = d.x; let mut dy = d.y; self.guides.clear(); @@ -1211,23 +1211,23 @@ impl SelectionTool { }, ); // dx and dy stay in canvas space. Snap.delta is spread space. - let mut corr = spread_delta_to_canvas(cx.layout.xf(spread), hit.delta); - corr = Vec2::new(if corr.x.is_finite() { corr.x } else { 0.0 }, if corr.y.is_finite() { corr.y } else { 0.0 }); - // Shift: the snap moves the points along the constrained direction only. - if ev.mods.shift && d.hypot() > 1e-9 { - let dir = d / d.hypot(); - corr = dir * corr.dot(dir); + let mut corr = spread_delta_to_canvas(cx.layout.xf(spread), hit.delta); + corr = Vec2::new(if corr.x.is_finite() { corr.x } else { 0.0 }, if corr.y.is_finite() { corr.y } else { 0.0 }); + // Shift: the snap moves the points along the constrained direction only. + if ev.mods.shift && d.hypot() > 1e-9 { + let dir = d / d.hypot(); + corr = dir * corr.dot(dir); } - dx += corr.x; - dy += corr.y; + dx += corr.x; + dy += corr.y; self.guides = hit.guides; } let mut params = json!({"id": id, "anchors": [[si, ai]], "dx": dx, "dy": dy}); if let Some(h) = handle { params["handle"] = json!(h); - } else if !others.is_empty() { - let points: Vec = std::iter::once((id, si, ai)).chain(others).map(|(i, s, a)| json!([i, s, a])).collect(); - params = json!({"points": points, "dx": dx, "dy": dy}); + } else if !others.is_empty() { + let points: Vec = std::iter::once((id, si, ai)).chain(others).map(|(i, s, a)| json!([i, s, a])).collect(); + params = json!({"points": points, "dx": dx, "dy": dy}); } vec![Action::Preview("path.moveAnchors".into(), params)] } From 9114b51de258926b6806de348496a6c4e28a5a31 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 12:13:28 +0100 Subject: [PATCH 0346/1349] Eyedropper test: the ink limit is the Separations view's on main, not the canvas texture's Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/tests.rs | 9 --------- 1 file changed, 9 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 71cc94a4a..165727cf8 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3506,15 +3506,6 @@ fn guide_counts(app: &DesignApp) -> Vec { let proofed = sample(&mut h); assert_eq!(proofed, shown(plain, &|img| designcraft_render::proof_view(img, &setup))); assert_ne!(proofed, plain, "the proof changes this green"); - // The composite ink-limit preview: a blue over a 100% limit shows (and samples) the warning. - h.state_mut().ui.proof_colors = false; - h.state_mut().run("object.fill", json!({"ids": [id], "swatch": "C=100 M=90 Y=10 K=0"})).unwrap(); - h.run_steps(3); - let blue = sample(&mut h); - h.state_mut().ui.ink_limit = Some(1.0); - let limited = sample(&mut h); - assert_eq!(limited, shown(blue, &|img| designcraft_render::separation_view(img, None, Some(1.0)))); - assert_eq!(limited, [230, 40, 40]); } #[test] From e96baa7f7f33de500e847047753844106bb3f4e1 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 12:19:19 +0100 Subject: [PATCH 0347/1349] Table keys: the selection helpers by their paths on main's split modules Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/table.rs | 2 +- crates/engine/src/cmd/table/registry.rs | 2 +- crates/engine/src/cmd/table/selection.rs | 2 +- crates/engine/src/cmd/text/edit.rs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/table.rs b/crates/engine/src/cmd/table.rs index 2a124e7a9..7c2f182ea 100644 --- a/crates/engine/src/cmd/table.rs +++ b/crates/engine/src/cmd/table.rs @@ -28,4 +28,4 @@ mod styles; mod target; pub use registry::specs; -pub(crate) use selection::step_cell; +pub(crate) use selection::{one_selected_cell_to_text, step_cell}; diff --git a/crates/engine/src/cmd/table/registry.rs b/crates/engine/src/cmd/table/registry.rs index 19cad9907..ee782609c 100644 --- a/crates/engine/src/cmd/table/registry.rs +++ b/crates/engine/src/cmd/table/registry.rs @@ -1,7 +1,7 @@ use super::cell::{get_cell_stroke, set_cell}; use super::content::{drop_cells, place_graphic, sort_rows}; use super::options::{get, options}; -use super::selection::{move_rc, select, step_cell}; +use super::selection::{move_rc, select, step_cell, toggle_selection}; use super::sizing::{distribute_cols, distribute_rows, resize_border, set_col_width, set_row_height}; use super::structure::{ can_convert_rows, convert_from_text, convert_rows, convert_to_text, delete_cols, delete_rows, delete_table, insert, insert_col, insert_row, diff --git a/crates/engine/src/cmd/table/selection.rs b/crates/engine/src/cmd/table/selection.rs index 00582fb4d..656dfdd78 100644 --- a/crates/engine/src/cmd/table/selection.rs +++ b/crates/engine/src/cmd/table/selection.rs @@ -84,7 +84,7 @@ pub(crate) fn one_selected_cell_to_text(s: &mut Session) -> Result<()> { /// Esc in a table: text in a cell becomes that cell's selection, and selected cells the text of /// the first one (InDesign toggles between the two). -fn toggle_selection(s: &mut Session) -> Result { +pub(super) fn toggle_selection(s: &mut Session) -> Result { const ID: &str = "table.toggleSelection"; let st = s.doc_mut()?; let t = st.selection.text.ok_or_else(|| bad(ID, "no caret"))?; diff --git a/crates/engine/src/cmd/text/edit.rs b/crates/engine/src/cmd/text/edit.rs index 7d896c999..21888cb22 100644 --- a/crates/engine/src/cmd/text/edit.rs +++ b/crates/engine/src/cmd/text/edit.rs @@ -18,7 +18,7 @@ pub(super) fn insert(s: &mut Session, p: &Value) -> Result { return crate::cmd::table::step_cell(s, true); } // Typing with one cell selected replaces its text, as InDesign. - super::table::one_selected_cell_to_text(s)?; + crate::cmd::table::one_selected_cell_to_text(s)?; let raw = p.get("raw").and_then(Value::as_bool).unwrap_or(false); let text = if s.prefs.typographers_quotes && !raw { smart_quotes(s, &text) } else { text }; let tracking = s.doc()?.doc.settings.track_changes; From e779d9eea2a0d34a8502de686c71f505a679766e Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 12:19:27 +0100 Subject: [PATCH 0348/1349] Hidden characters: the test reaches frame_hidden_marks in its new module Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/canvas/text_overlay.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 3a1f8c733..5c0926b44 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -56,7 +56,7 @@ use scroll::{mods, navigation_space, scrollbars, spring_zoom_mode}; pub use text_overlay::selected_text; use text_overlay::{draw_dynamic_spelling, draw_hidden_characters}; #[cfg(test)] -use text_overlay::{draw_text_selection, hidden_marks}; +use text_overlay::{draw_text_selection, frame_hidden_marks, hidden_marks}; use tool_overlays::draw_tool_overlays; pub(crate) use view::page_in_view; use view::present_fit; diff --git a/crates/ui-egui/src/canvas/text_overlay.rs b/crates/ui-egui/src/canvas/text_overlay.rs index 6af92d842..ebf2a6349 100644 --- a/crates/ui-egui/src/canvas/text_overlay.rs +++ b/crates/ui-egui/src/canvas/text_overlay.rs @@ -288,7 +288,7 @@ pub(super) fn draw_hidden_characters(app: &DesignApp, painter: &egui::Painter, x /// the line's ascent): its lines' marks, then its tables' — each text cell's own marks (nested /// tables included) with its # where its text ends, and a table paragraph's ¶ after the last /// row's bottom right corner. A table's own glyph-less line has no marks: its ¶ is that one. -fn frame_hidden_marks(text: &str, ft: &compose::FrameText) -> Vec<(Point, &'static str, bool, f64)> { +pub(super) fn frame_hidden_marks(text: &str, ft: &compose::FrameText) -> Vec<(Point, &'static str, bool, f64)> { let table_lines: Vec = ft.tables.iter().map(|t| t.line).collect(); let mut out: Vec<_> = ft .lines From d4ecb552f5a0aacebf9f428a4f4a1adcc174403a Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 12:38:46 +0100 Subject: [PATCH 0349/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/pages/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/pages/tests.rs b/crates/ui-egui/src/panels/pages/tests.rs index 037ef6a89..b0dcafb06 100644 --- a/crates/ui-egui/src/panels/pages/tests.rs +++ b/crates/ui-egui/src/panels/pages/tests.rs @@ -343,7 +343,7 @@ fn the_panel_menu_follows_indesigns_order() { assert_eq!(h.state().session.doc().unwrap().doc.page_count(), 3); h.get_by_label("Insert Pages…").click(); h.run_steps(3); - assert!(h.state().ui.dialog.as_ref().is_some_and(|d| d.id == "insertPages")); + assert!(h.state().ui.dialog.as_ref().is_some_and(|d| d.id == "insertPages")); } #[test] From 08e954515e79fd635ca62791558510aefb067d44 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 12:43:14 +0100 Subject: [PATCH 0350/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/chrome/tests.rs | 82 +++++++++++++++--------------- 1 file changed, 41 insertions(+), 41 deletions(-) diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 48f79c819..eb84e74ca 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -180,48 +180,48 @@ fn status_bar_error_count_opens_the_preflight_panel() { assert!(crate::panel_docking::showing(&h.state().app, "preflight")); } - /// The course's chapter 25: while a parent is shown, the status bar's page box names it - /// ("A-Parent"), as InDesign's. Its menu lists the pages, then the parents: a parent shows - /// that parent, a page leaves the parents for that page. - #[test] - fn the_page_box_names_the_parent_in_view_and_lists_the_parents() { - use egui::accesskit::Role; - let mut app = app(); - app.run("file.new", serde_json::json!({"pages": 4, "facingPages": true})).unwrap(); - app.run("layout.parents.new", serde_json::json!({"prefix": "B", "name": "Cover"})).unwrap(); - app.ui.dock_tab = "properties".into(); - let mut h = test_window::open(app, vec2(1200.0, 700.0)); - let shown = |h: &egui_kittest::Harness<'static, test_window::Window>| { - let b = h.get_by(|n| n.role() == Role::ComboBox && n.label().as_deref() == Some("Page")); - b.value().unwrap_or_default() - }; - assert_eq!(shown(&h), "1"); - h.state_mut().app.run("layout.parents.edit", serde_json::json!({"on": true})).unwrap(); - h.run_steps(6); - assert_eq!(shown(&h), "A-Parent"); - // The menu: a parent. - h.get_by(|n| n.role() == Role::ComboBox && n.label().as_deref() == Some("Page")).click(); - h.run_steps(3); - for name in ["1", "2", "3", "4", "A-Parent"] { - assert!(h.query_by_label(name).is_some(), "{name} is listed"); - } - h.get_by_label("B-Cover").click(); - h.run_steps(6); - assert_eq!(shown(&h), "B-Cover"); - assert_eq!(crate::canvas::current_parent_page(&h.state().app).map(|(i, _)| i), Some(1)); - // A page: the parents are left. - h.get_by(|n| n.role() == Role::ComboBox && n.label().as_deref() == Some("Page")).click(); - h.run_steps(3); - h.get_by_label("3").click(); - h.run_steps(6); - assert!(!h.state().app.session.active().unwrap().editing_parents); - assert_eq!(crate::canvas::current_page(&h.state().app), Some(2)); - assert_eq!(shown(&h), "3"); - // Its accessible name is in the interface's language. - h.state_mut().app.ui.language = "de".into(); - h.run_steps(3); - assert!(h.query_by(|n| n.role() == Role::ComboBox && n.label().as_deref() == Some("Seite")).is_some(), "the page box is Seite"); +/// The course's chapter 25: while a parent is shown, the status bar's page box names it +/// ("A-Parent"), as InDesign's. Its menu lists the pages, then the parents: a parent shows +/// that parent, a page leaves the parents for that page. +#[test] +fn the_page_box_names_the_parent_in_view_and_lists_the_parents() { + use egui::accesskit::Role; + let mut app = app(); + app.run("file.new", serde_json::json!({"pages": 4, "facingPages": true})).unwrap(); + app.run("layout.parents.new", serde_json::json!({"prefix": "B", "name": "Cover"})).unwrap(); + app.ui.dock_tab = "properties".into(); + let mut h = test_window::open(app, vec2(1200.0, 700.0)); + let shown = |h: &egui_kittest::Harness<'static, test_window::Window>| { + let b = h.get_by(|n| n.role() == Role::ComboBox && n.label().as_deref() == Some("Page")); + b.value().unwrap_or_default() + }; + assert_eq!(shown(&h), "1"); + h.state_mut().app.run("layout.parents.edit", serde_json::json!({"on": true})).unwrap(); + h.run_steps(6); + assert_eq!(shown(&h), "A-Parent"); + // The menu: a parent. + h.get_by(|n| n.role() == Role::ComboBox && n.label().as_deref() == Some("Page")).click(); + h.run_steps(3); + for name in ["1", "2", "3", "4", "A-Parent"] { + assert!(h.query_by_label(name).is_some(), "{name} is listed"); } + h.get_by_label("B-Cover").click(); + h.run_steps(6); + assert_eq!(shown(&h), "B-Cover"); + assert_eq!(crate::canvas::current_parent_page(&h.state().app).map(|(i, _)| i), Some(1)); + // A page: the parents are left. + h.get_by(|n| n.role() == Role::ComboBox && n.label().as_deref() == Some("Page")).click(); + h.run_steps(3); + h.get_by_label("3").click(); + h.run_steps(6); + assert!(!h.state().app.session.active().unwrap().editing_parents); + assert_eq!(crate::canvas::current_page(&h.state().app), Some(2)); + assert_eq!(shown(&h), "3"); + // Its accessible name is in the interface's language. + h.state_mut().app.ui.language = "de".into(); + h.run_steps(3); + assert!(h.query_by(|n| n.role() == Role::ComboBox && n.label().as_deref() == Some("Seite")).is_some(), "the page box is Seite"); +} /// As in InDesign, double-clicking the preflight count (or its light) shows the panel. #[test] From 18f2dc2bdea4e8d9d028a4c267352240240d8a44 Mon Sep 17 00:00:00 2001 From: Hamza Date: Thu, 29 Oct 2026 16:43:49 +0500 Subject: [PATCH 0351/1349] A spent cell budget stops reading tables, rather than keeping one each Keeping a 1 x 1 table for every further `
` was unbounded in the one direction the budget exists to close. `
` is fifteen bytes, so the 512 MiB a part may decompress to holds some 36 million of them, and a `Cell` is 1,360 bytes: tens of gigabytes, with every table inside both caps. The test I wrote said as much without my noticing -- its invariant was `reserved <= MAX + tables`, and `tables` had no bound. `budgeted_size` now returns `None` once the budget is spent and the table is not read at all, so the cells one import reserves are at most the budget, exactly. The invariant is now `reserved <= MAX_IMPORT_TABLE_CELLS`, with no term that grows with the file. The warnings needed the same treatment, for the same reason: a file of 400,000 tables each claiming one row and two columns got a line about every one of them. At most 20 are named, then one line saying the rest were the same, and the file is told once that its tables ran out of cells between them. --- crates/idml/src/import.rs | 7 +++ crates/idml/src/import/story.rs | 7 ++- crates/idml/src/import/table.rs | 104 +++++++++++++++++++++----------- 3 files changed, 81 insertions(+), 37 deletions(-) diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs index c8e0512b5..ae7364647 100644 --- a/crates/idml/src/import.rs +++ b/crates/idml/src/import.rs @@ -142,6 +142,11 @@ struct Importer<'r> { /// Cells every table in this import has reserved. One table is capped, but a file chooses /// how many tables it has, so the cap has to be document-wide as well (noted in review). table_cells: usize, + /// Tables whose size the file claimed and did not get, warned about so far. A file chooses + /// how many tables it has, so a line each is its own flood (noted in review). + table_warnings: usize, + /// Whether the file has already been told its tables ran out of cells between them. + table_budget_spent: bool, settings: DocSettings, default_margins: Option<(Margins, Columns)>, swatches: Vec, @@ -229,6 +234,8 @@ impl<'r> Importer<'r> { previews, next_id: 0, table_cells: 0, + table_warnings: 0, + table_budget_spent: false, settings: DocSettings::default(), default_margins: None, swatches: specials, diff --git a/crates/idml/src/import/story.rs b/crates/idml/src/import/story.rs index 694a2dbbd..72cde49b1 100644 --- a/crates/idml/src/import/story.rs +++ b/crates/idml/src/import/story.rs @@ -168,8 +168,11 @@ impl<'r> Importer<'r> { b.fresh = true; } "Table" => { - let t = self.table(c); - b.push_table(t, pf, cf); + // `None` once the file-wide cell budget is spent: the table is not read + // at all rather than kept as a 1 x 1 (noted in review). + if let Some(t) = self.table(c) { + b.push_table(t, pf, cf); + } } "HyperlinkTextDestination" | "ParagraphDestination" => { b.anchors.push((c.get("Self").unwrap_or("").to_string(), c.get("Name").unwrap_or("Anchor").to_string())); diff --git a/crates/idml/src/import/table.rs b/crates/idml/src/import/table.rs index 3b1051b66..91ac287f9 100644 --- a/crates/idml/src/import/table.rs +++ b/crates/idml/src/import/table.rs @@ -7,22 +7,31 @@ use super::*; /// importer collects at most. const MAX_IMPORT_TABLE_CELLS: usize = 400_000; +/// Clamp warnings one import writes before it says the rest were the same. +const MAX_TABLE_WARNINGS: usize = 20; + /// How large a table of `rows` x `cols` may be read when `reserved` cells have already been -/// taken, and whether the file-wide budget is what cut it down. +/// taken, and whether the file-wide budget is what cut it down -- or `None` when the budget is +/// spent and the table is not read at all. /// /// The per-table cap leaves a file free to hold many capped tables, so each is also clamped -/// against what is left. One row and one column are always kept: the table is then still in the -/// document, still says where its text went, and a file pays one cell for a table it really -/// does contain -- which its own size already bounds. -fn budgeted_size(rows: usize, cols: usize, reserved: usize) -> (usize, usize, bool) { +/// against what is left. While there is budget, one row and one column are always kept: the table +/// is then still in the document, still says where its text went, and a file pays one cell for a +/// table it really does contain. +/// +/// Past that there is nothing left to pay with. Keeping a 1 x 1 table for every further `` +/// was unbounded in the one direction the budget was meant to close: `
` is fifteen +/// bytes, so the 512 MiB a part may decompress to holds some 36 million of them, and a `Cell` +/// each is tens of gigabytes with every table inside both caps (noted in review). +fn budgeted_size(rows: usize, cols: usize, reserved: usize) -> Option<(usize, usize, bool)> { let (mut nr, mut nc) = designcraft_doc::table::clamped_size(rows, cols); - let left = MAX_IMPORT_TABLE_CELLS.saturating_sub(reserved); + let left = MAX_IMPORT_TABLE_CELLS.checked_sub(reserved).filter(|left| *left > 0)?; let over_budget = nr.saturating_mul(nc) > left; if over_budget { - nc = nc.min(left.max(1)); + nc = nc.min(left); nr = nr.min((left / nc).max(1)); } - (nr, nc, over_budget) + Some((nr, nc, over_budget)) } /// Preserve the legacy uniform field only when all four sides explicitly specify every @@ -45,8 +54,7 @@ pub(super) fn uniform_cell_stroke(edges: &[designcraft_doc::CellStrokeAttrs; 4]) impl<'r> Importer<'r> { /// ``: rows, columns and cells (cell `Name` is `column:row`). - pub(super) fn table(&mut self, e: &El) -> Table { - let id = self.alloc(); + pub(super) fn table(&mut self, e: &El) -> Option
{ let rows: Vec<&El> = e.find_all("Row").collect(); let cols: Vec<&El> = e.find_all("Column").collect(); // A file's row and column counts are its claim, and a table of them is allocated whole: a @@ -57,12 +65,31 @@ impl<'r> Importer<'r> { // // Reserved before `Table::new`, so a cell's own story cannot spend the budget this table // is counting on. - let (nr, nc, over_budget) = budgeted_size(rows.len().max(1), cols.len().max(1), self.table_cells); + let Some((nr, nc, over_budget)) = budgeted_size(rows.len().max(1), cols.len().max(1), self.table_cells) else { + // Said once: the file that reaches this is the one with millions of tables in it. + if !self.table_budget_spent { + self.table_budget_spent = true; + self.warnings.push(format!( + "the tables in this file claim more than {MAX_IMPORT_TABLE_CELLS} cells between them: the rest of them were not read" + )); + } + return None; + }; self.table_cells = self.table_cells.saturating_add(nr.saturating_mul(nc)); if nr < rows.len() || nc < cols.len() { let why = if over_budget { "more than the tables in one file can hold between them" } else { "more than a table can hold" }; - self.warnings.push(format!("a table of {} rows and {} columns was read as {nr} x {nc}: {why}", rows.len(), cols.len())); + self.table_warnings += 1; + match self.table_warnings.cmp(&MAX_TABLE_WARNINGS) { + std::cmp::Ordering::Less => { + self.warnings.push(format!("a table of {} rows and {} columns was read as {nr} x {nc}: {why}", rows.len(), cols.len())) + } + std::cmp::Ordering::Equal => { + self.warnings.push(format!("more than {MAX_TABLE_WARNINGS} tables were read smaller than this file claims")) + } + std::cmp::Ordering::Greater => {} + } } + let id = self.alloc(); let rows = &rows[..nr.min(rows.len())]; let cols = &cols[..nc.min(cols.len())]; let mut t = Table::new(id, nr, nc, 0, 0, 0.0); @@ -151,7 +178,7 @@ impl<'r> Importer<'r> { for rg in regions { let _ = t.merge(rg); } - t + Some(t) } /// A cell's local fill, insets, alignment, rotation and edge strokes. @@ -207,45 +234,52 @@ mod budget_tests { fn the_tables_in_one_file_are_capped_between_them() { let mut reserved = 0; let mut sizes = Vec::new(); - for _ in 0..3 { - let (nr, nc, over) = budgeted_size(500, 1000, reserved); - reserved += nr * nc; - sizes.push((nr, nc, over)); + for _ in 0..4 { + let size = budgeted_size(500, 1000, reserved); + if let Some((nr, nc, _)) = size { + reserved += nr * nc; + } + sizes.push(size); } - assert_eq!(sizes[0], (250, 1000, false), "the first table is held by the per-table cap alone"); - assert_eq!(sizes[1], (150, 1000, true), "the second gets what is left of the file's budget"); - assert_eq!(sizes[2], (1, 1, true), "and the third is kept, so its text still has somewhere to be"); - assert_eq!(reserved, MAX_IMPORT_TABLE_CELLS + 1, "400,000 cells and the one the last table keeps"); + assert_eq!(sizes[0], Some((250, 1000, false)), "the first table is held by the per-table cap alone"); + assert_eq!(sizes[1], Some((150, 1000, true)), "the second gets what is left of the file's budget"); + assert_eq!(sizes[2], None, "and the third is not read: there is nothing left to pay for it"); + assert_eq!(sizes[3], None, "nor any after it"); + assert_eq!(reserved, MAX_IMPORT_TABLE_CELLS, "the budget is spent exactly, not overspent"); } - /// The budget holds for any sequence of claimed sizes, and a table is never read as nothing: - /// a 0 x n table has no cells to hold the text the file puts in it. + /// The budget is a hard limit, not a floor: keeping one cell for every further table was + /// unbounded in the one direction the budget exists to close, since a `
` is + /// fifteen bytes and a part may decompress to 512 MiB (noted in review). #[test] - fn a_table_is_never_read_as_empty_and_the_budget_always_holds() { + fn a_spent_budget_stops_reading_tables_altogether() { let claims = [(0, 0), (1, 1), (7, 3), (usize::MAX, usize::MAX), (1, usize::MAX), (usize::MAX, 1), (10_000, 1_000), (2, 0)]; let mut reserved = 0usize; - let mut tables = 0usize; + let mut read = 0usize; + let mut skipped = 0usize; // Every claim, several times over, in an order that exhausts the budget part way through. for _ in 0..4 { for (rows, cols) in claims { - let (nr, nc, _) = budgeted_size(rows.max(1), cols.max(1), reserved); - assert!(nr >= 1 && nc >= 1, "{rows} x {cols} was read as {nr} x {nc}"); - reserved += nr * nc; - tables += 1; - assert!( - reserved <= MAX_IMPORT_TABLE_CELLS + tables, - "{tables} tables reserved {reserved} cells, past the budget by more than the one cell each keeps" - ); + match budgeted_size(rows.max(1), cols.max(1), reserved) { + Some((nr, nc, _)) => { + assert!(nr >= 1 && nc >= 1, "{rows} x {cols} was read as {nr} x {nc}: a table has nowhere to put its text"); + reserved += nr * nc; + read += 1; + } + None => skipped += 1, + } + assert!(reserved <= MAX_IMPORT_TABLE_CELLS, "{read} tables reserved {reserved} cells, past the budget"); } } - assert!(reserved >= MAX_IMPORT_TABLE_CELLS, "this sequence does reach the budget: {reserved}"); + assert_eq!(reserved, MAX_IMPORT_TABLE_CELLS, "this sequence does reach the budget"); + assert!(skipped > 0, "and does go on asking after it: {skipped} tables were not read"); } /// Below the budget nothing is clamped by it, so an ordinary file is read exactly as before. #[test] fn an_ordinary_file_is_not_touched_by_the_budget() { for (rows, cols) in [(1, 1), (2, 3), (50, 20), (250, 1000)] { - assert_eq!(budgeted_size(rows, cols, 0), (rows, cols, false), "{rows} x {cols}"); + assert_eq!(budgeted_size(rows, cols, 0), Some((rows, cols, false)), "{rows} x {cols}"); } } } From 3de3efccafdf84725588e4bec78a08f20e6eb9ed Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 12:50:00 +0100 Subject: [PATCH 0352/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/properties/tests.rs | 112 +++++++++--------- 1 file changed, 56 insertions(+), 56 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 91004afa9..96a1b14b6 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -638,65 +638,65 @@ fn clicking_a_swatch_chip_in_the_appearance_fill_menu_applies_it() { assert_eq!(after, name, "clicking the swatch chip applies it"); } - /// The course's chapter 23: a double-click on Properties › Appearance › Fill opens the Color - /// Picker with the fill's colour, as InDesign's (a click opens the swatches). For selected - /// text, the text's Fill chip opens it for the text. - #[test] - fn double_clicking_a_fill_chip_opens_the_color_picker() { - let double_click = |h: &mut Harness<'_, DesignApp>, label: &str| { - let at = h.get_by_label(label).rect().center(); - h.hover_at(at); +/// The course's chapter 23: a double-click on Properties › Appearance › Fill opens the Color +/// Picker with the fill's colour, as InDesign's (a click opens the swatches). For selected +/// text, the text's Fill chip opens it for the text. +#[test] +fn double_clicking_a_fill_chip_opens_the_color_picker() { + let double_click = |h: &mut Harness<'_, DesignApp>, label: &str| { + let at = h.get_by_label(label).rect().center(); + h.hover_at(at); + h.step(); + for pressed in [true, false, true, false] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); h.step(); - for pressed in [true, false, true, false] { - h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); - h.step(); - } - h.run_steps(3); - }; - // Frames 1 ms apart, so two clicks make a double-click. - let panel = |app: DesignApp| { - let mut h = Harness::builder().with_size(vec2(320.0, 1400.0)).with_step_dt(0.001).build_ui_state( - |ui, app: &mut DesignApp| { - let id = egui::Id::new("test_fonts"); - if ui.data(|d| d.get_temp::(id)).is_none() { - crate::theme::install_fonts(ui.ctx(), ""); - ui.data_mut(|d| d.insert_temp(id, true)); - return; - } - show(app, ui); - }, - app, - ); - h.run_steps(3); - h - }; - let frame = || { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let id = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap(); - app.run("selection.set", json!({"ids": [id]})).unwrap(); - app.run("object.fill", json!({"swatch": "C=0 M=0 Y=100 K=0"})).unwrap(); - app - }; - let mut h = panel(frame()); - double_click(&mut h, "Fill swatch"); - assert!(h.query_by_label("Tint:").is_none(), "the swatches popup isn't left open too"); - let d = h.state().ui.dialog.clone().expect("the Color Picker"); - assert_eq!((d.id.as_str(), d.s("target"), d.s("model"), d.b("text")), ("colorPicker", "fill".into(), "cmyk".into(), false)); - assert_eq!(d.fields["cmyk"], json!([0.0, 0.0, 100.0, 0.0])); - let mut h = panel(frame()); - double_click(&mut h, "Stroke swatch"); - assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.s("target")), Some("stroke".into())); - // Selected text: its own Fill chip. + } + h.run_steps(3); + }; + // Frames 1 ms apart, so two clicks make a double-click. + let panel = |app: DesignApp| { + let mut h = Harness::builder().with_size(vec2(320.0, 1400.0)).with_step_dt(0.001).build_ui_state( + |ui, app: &mut DesignApp| { + let id = egui::Id::new("test_fonts"); + if ui.data(|d| d.get_temp::(id)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(id, true)); + return; + } + show(app, ui); + }, + app, + ); + h.run_steps(3); + h + }; + let frame = || { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({})).unwrap(); - let f = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "Lemon"})).unwrap(); - app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 5})).unwrap(); - let mut h = panel(app); - double_click(&mut h, "Text fill swatch"); - let d = h.state().ui.dialog.clone().expect("the Color Picker"); - assert_eq!((d.id.as_str(), d.s("target"), d.b("text")), ("colorPicker", "fill".into(), true)); - } + let id = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + app.run("object.fill", json!({"swatch": "C=0 M=0 Y=100 K=0"})).unwrap(); + app + }; + let mut h = panel(frame()); + double_click(&mut h, "Fill swatch"); + assert!(h.query_by_label("Tint:").is_none(), "the swatches popup isn't left open too"); + let d = h.state().ui.dialog.clone().expect("the Color Picker"); + assert_eq!((d.id.as_str(), d.s("target"), d.s("model"), d.b("text")), ("colorPicker", "fill".into(), "cmyk".into(), false)); + assert_eq!(d.fields["cmyk"], json!([0.0, 0.0, 100.0, 0.0])); + let mut h = panel(frame()); + double_click(&mut h, "Stroke swatch"); + assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.s("target")), Some("stroke".into())); + // Selected text: its own Fill chip. + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let f = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "Lemon"})).unwrap(); + app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 5})).unwrap(); + let mut h = panel(app); + double_click(&mut h, "Text fill swatch"); + let d = h.state().ui.dialog.clone().expect("the Color Picker"); + assert_eq!((d.id.as_str(), d.s("target"), d.b("text")), ("colorPicker", "fill".into(), true)); +} fn panel(app: DesignApp) -> Harness<'static, DesignApp> { let mut h = Harness::builder().with_size(vec2(320.0, 1400.0)).build_ui_state( From f56aa76ada740497a97e0c524549bd43b9dcde03 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 12:50:08 +0100 Subject: [PATCH 0353/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/properties/tests.rs | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 74fd68ba7..d8b965fb5 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -655,21 +655,21 @@ fn panel(app: DesignApp) -> Harness<'static, DesignApp> { h } - /// The course's chapter 21: Properties › Bullets and Numbering › Options opens the Bullets - /// and Numbering dialog, as InDesign's, not the Paragraph panel. - #[test] - fn bullets_options_open_the_bullets_and_numbering_dialog() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let f = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "4 eggs"})).unwrap(); - app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 6})).unwrap(); - let mut h = panel(app); - h.get_by_label("Options").click(); - h.run_steps(3); - let d = h.state().ui.dialog.clone().expect("a dialog"); - assert_eq!((d.id.as_str(), d.s("section").as_str()), ("paragraphLocal", "bullets")); - assert_ne!(h.state().ui.open_panel.as_deref(), Some("paragraph")); - } +/// The course's chapter 21: Properties › Bullets and Numbering › Options opens the Bullets +/// and Numbering dialog, as InDesign's, not the Paragraph panel. +#[test] +fn bullets_options_open_the_bullets_and_numbering_dialog() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let f = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "4 eggs"})).unwrap(); + app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 6})).unwrap(); + let mut h = panel(app); + h.get_by_label("Options").click(); + h.run_steps(3); + let d = h.state().ui.dialog.clone().expect("a dialog"); + assert_eq!((d.id.as_str(), d.s("section").as_str()), ("paragraphLocal", "bullets")); + assert_ne!(h.state().ui.open_panel.as_deref(), Some("paragraph")); +} /// The course's chapter 21: Properties' Bulleted List button gives the selected paragraphs /// bullets with InDesign's hanging indent; pressed again, both go. From e9d7a199943d8926370f1f939de6e0109a35a92a Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Thu, 29 Oct 2026 11:58:54 +0000 Subject: [PATCH 0354/1349] Keep leading and trailing spaces in Tagged Text style names Found while testing crates/textimport/src/tagged.rs:~190-205 (the ParaStyle and CharStyle branches of import: `unescape_value(value.trim())`) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/textimport/src/tagged.rs | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/crates/textimport/src/tagged.rs b/crates/textimport/src/tagged.rs index 74806ae4c..28929c985 100644 --- a/crates/textimport/src/tagged.rs +++ b/crates/textimport/src/tagged.rs @@ -184,7 +184,7 @@ pub fn import(bytes: &[u8]) -> Result { } "ParaStyle" => { started = true; - let v = unescape_value(value.trim()); + let v = unescape_value(value); if !v.is_empty() && !para_styles.contains(&v) { para_styles.push(v.clone()); } @@ -193,7 +193,7 @@ pub fn import(bytes: &[u8]) -> Result { } } "CharStyle" => { - let v = unescape_value(value.trim()); + let v = unescape_value(value); fmt.style = if v.is_empty() { NO_CHAR_STYLE.into() } else { v.clone() }; if !v.is_empty() && !char_styles.contains(&v) { char_styles.push(v); @@ -205,7 +205,7 @@ pub fn import(bytes: &[u8]) -> Result { // keeps its style's size (#1593). "cSize" => fmt.over.size = value.trim().parse().ok().and_then(designcraft_doc::attrs::imported_type_size), "DefineParaStyle" | "DefineCharStyle" => { - let nm = value.split('=').next().unwrap_or("").trim().to_string(); + let nm = value.split('=').next().unwrap_or("").to_string(); let list = if name == "DefineParaStyle" { &mut para_styles } else { &mut char_styles }; if !nm.is_empty() && !list.contains(&nm) { list.push(nm); @@ -278,6 +278,28 @@ mod tests { assert_eq!(import("\r\nA<0xD83D>B<0xDE00>C".as_bytes()).unwrap().story.text, "ABC"); } + /// A style name is read back exactly as the exporter wrote it, spaces included. + #[test] + fn style_names_keep_leading_and_trailing_spaces() { + let i = import("\r\n\r\nHello".as_bytes()).unwrap(); + assert_eq!(i.story.paras[0].style, "Body "); + assert_eq!(i.story.char_format_at(2).style, " Em "); + assert_eq!(i.para_styles[0].name, "Body "); + assert_eq!(i.char_styles[0].name, " Em "); + } + + /// A style defined with spaces in its name keeps them, so a paragraph that uses the name matches. + #[test] + fn defined_style_names_keep_leading_and_trailing_spaces() { + let src = + "\r\n>>Hello"; + let i = import(src.as_bytes()).unwrap(); + assert_eq!(i.para_styles.len(), 1); + assert_eq!(i.para_styles[0].name, "Body "); + assert_eq!(i.char_styles.len(), 1); + assert_eq!(i.char_styles[0].name, " Em "); + } + /// A size does not have to be non-finite to be nonsense: a file can hold `1e300`, `0` or a /// negative, and tagged text took all three and set them on the text (#1593). They are now /// dropped, as RTF and DOCX already dropped them, so the text keeps its style's size. From 299a65c89042e8f0f14fc963c3b3be4984da9827 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 13:16:00 +0100 Subject: [PATCH 0355/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/menus/tests.rs | 46 +++++++++++++++---------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index d65a99afc..a4d907e7a 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -29,29 +29,29 @@ fn view_items_are_in_the_view_menu_as_in_indesign() { assert_eq!(ui_label("view.togglePreview").and_then(|c| c.1), Some("W")); } - /// Object › Fitting in InDesign's groups: the proportional fits, the frame and content fits, - /// Clear Frame Fitting Options, then the dialog. - #[test] - fn the_fitting_menu_is_grouped_as_indesigns() { - let items = MENUS.iter().find(|(t, _)| *t == "Object").map(|(_, items)| *items).unwrap(); - let start = items.iter().position(|e| *e == ">Fitting").unwrap() + 1; - let end = start + items[start..].iter().position(|e| *e == "<").unwrap(); - assert_eq!( - &items[start..end], - [ - "ui:fit.fillFrameProportionally", - "ui:fit.contentProportionally", - "-", - "ui:fit.frameToContent", - "ui:fit.contentToFrame", - "ui:fit.centerContent", - "-", - "cmd:object.clearFittingOptions", - "-", - "ui:app.fittingOptions", - ] - ); - } +/// Object › Fitting in InDesign's groups: the proportional fits, the frame and content fits, +/// Clear Frame Fitting Options, then the dialog. +#[test] +fn the_fitting_menu_is_grouped_as_indesigns() { + let items = MENUS.iter().find(|(t, _)| *t == "Object").map(|(_, items)| *items).unwrap(); + let start = items.iter().position(|e| *e == ">Fitting").unwrap() + 1; + let end = start + items[start..].iter().position(|e| *e == "<").unwrap(); + assert_eq!( + &items[start..end], + [ + "ui:fit.fillFrameProportionally", + "ui:fit.contentProportionally", + "-", + "ui:fit.frameToContent", + "ui:fit.contentToFrame", + "ui:fit.centerContent", + "-", + "cmd:object.clearFittingOptions", + "-", + "ui:app.fittingOptions", + ] + ); +} /// The submenu paths of a menu bar menu ("View/Screen Mode"), as Edit › Menus keys them. fn submenu_paths(title: &str) -> Vec { From 4a71ee5d83f5a733dec7a36446bc0a93baa5ef15 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 13:22:55 +0100 Subject: [PATCH 0356/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/tools/src/select.rs | 140 ++++++++--------- crates/ui-egui/src/panels/properties/tests.rs | 146 +++++++++--------- 2 files changed, 143 insertions(+), 143 deletions(-) diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index d94b72560..e1161fce9 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -782,51 +782,51 @@ impl SelectionTool { && let Some((id, si, ai, handle)) = anchor_at(cx, p) { let at = anchor_spread_point(cx, id, si, ai); - let mut out = vec![]; - let mut others = vec![]; - if handle.is_none() { - // InDesign's anchor point selection: a click selects the point, Shift+click - // adds it or takes it away, and dragging a selected point moves all of them. - let me = (ItemId(id), si, ai); - let mut points = cx.selection.anchors.clone(); - let was = points.contains(&me); - if ev.mods.shift && was { - // Kept selected so a Shift-drag can constrain it; a click still takes it - // away, on release, as for objects. - self.anchor_release = Some(me); - } else if ev.mods.shift { - points.push(me); - } else if !was { - points = vec![me]; - } - if points != cx.selection.anchors { - out.push(Action::Exec("selection.set".into(), anchor_selection(cx, &points, ev.mods.shift))); - } - others = points.iter().filter(|a| **a != me).map(|(i, s, a)| (i.0, *s, *a)).collect(); - } - let label = if handle.is_some() { - "Move Direction Handle" - } else if others.is_empty() { - "Move Anchor" - } else { - "Move Anchors" - }; - self.drag = Drag::Anchor { id, si, ai, handle, start: p, at, others }; - out.push(Action::Begin(label.into())); - return out; + let mut out = vec![]; + let mut others = vec![]; + if handle.is_none() { + // InDesign's anchor point selection: a click selects the point, Shift+click + // adds it or takes it away, and dragging a selected point moves all of them. + let me = (ItemId(id), si, ai); + let mut points = cx.selection.anchors.clone(); + let was = points.contains(&me); + if ev.mods.shift && was { + // Kept selected so a Shift-drag can constrain it; a click still takes it + // away, on release, as for objects. + self.anchor_release = Some(me); + } else if ev.mods.shift { + points.push(me); + } else if !was { + points = vec![me]; } - // As in InDesign, the Direct Selection tool pressed on a corner or anchor of an object - // that isn't selected selects it and moves just that point (Chris Nielsen's "The - // InDesign Toolbox", 10:10: click outside, then pull a frame's corner). - if self.direct - && !ev.mods.shift - && let Some((_, hit)) = cx.hit(p) - && !cx.selection.contains(hit) - && let Some((id, si, ai, None)) = anchor_at_in(cx, &[hit], p) - { - let at = anchor_spread_point(cx, id, si, ai); - self.drag = Drag::Anchor { id, si, ai, handle: None, start: p, at, others: vec![] }; - return vec![Action::Exec("selection.set".into(), json!({"ids": [id], "content": true})), Action::Begin("Move Anchor".into())]; + if points != cx.selection.anchors { + out.push(Action::Exec("selection.set".into(), anchor_selection(cx, &points, ev.mods.shift))); + } + others = points.iter().filter(|a| **a != me).map(|(i, s, a)| (i.0, *s, *a)).collect(); + } + let label = if handle.is_some() { + "Move Direction Handle" + } else if others.is_empty() { + "Move Anchor" + } else { + "Move Anchors" + }; + self.drag = Drag::Anchor { id, si, ai, handle, start: p, at, others }; + out.push(Action::Begin(label.into())); + return out; + } + // As in InDesign, the Direct Selection tool pressed on a corner or anchor of an object + // that isn't selected selects it and moves just that point (Chris Nielsen's "The + // InDesign Toolbox", 10:10: click outside, then pull a frame's corner). + if self.direct + && !ev.mods.shift + && let Some((_, hit)) = cx.hit(p) + && !cx.selection.contains(hit) + && let Some((id, si, ai, None)) = anchor_at_in(cx, &[hit], p) + { + let at = anchor_spread_point(cx, id, si, ai); + self.drag = Drag::Anchor { id, si, ai, handle: None, start: p, at, others: vec![] }; + return vec![Action::Exec("selection.set".into(), json!({"ids": [id], "content": true})), Action::Begin("Move Anchor".into())]; } // A selected placed graphic's own handles resize it inside its frame (the // frame's anchors, under Direct Selection, come first). @@ -1165,18 +1165,18 @@ impl SelectionTool { // Screen y points down: a positive screen angle is clockwise. vec![Action::Preview("transform.rotate".into(), json!({"angle": -a}))] } - Drag::Anchor { id, si, ai, handle, start, at, others } => { - let mut d = p - start; - if d.hypot() >= cx.tol(3.0) { - self.anchor_release = None; - } else if self.anchor_release.is_some() { - // A Shift-press on a selected point is still a click: nothing moves yet. - return vec![]; - } - // Shift: horizontal, vertical or at 45°. - if ev.mods.shift { - d = constrain_45(d); - } + Drag::Anchor { id, si, ai, handle, start, at, others } => { + let mut d = p - start; + if d.hypot() >= cx.tol(3.0) { + self.anchor_release = None; + } else if self.anchor_release.is_some() { + // A Shift-press on a selected point is still a click: nothing moves yet. + return vec![]; + } + // Shift: horizontal, vertical or at 45°. + if ev.mods.shift { + d = constrain_45(d); + } let mut dx = d.x; let mut dy = d.y; self.guides.clear(); @@ -1204,25 +1204,25 @@ impl SelectionTool { }, ); // dx and dy stay in canvas space. Snap.delta is spread space. - let mut corr = spread_delta_to_canvas(cx.layout.xf(spread), hit.delta); - corr = Vec2::new(if corr.x.is_finite() { corr.x } else { 0.0 }, if corr.y.is_finite() { corr.y } else { 0.0 }); - // Shift: the snap moves the points along the constrained direction only. - if ev.mods.shift && d.hypot() > 1e-9 { - let dir = d / d.hypot(); - corr = dir * corr.dot(dir); + let mut corr = spread_delta_to_canvas(cx.layout.xf(spread), hit.delta); + corr = Vec2::new(if corr.x.is_finite() { corr.x } else { 0.0 }, if corr.y.is_finite() { corr.y } else { 0.0 }); + // Shift: the snap moves the points along the constrained direction only. + if ev.mods.shift && d.hypot() > 1e-9 { + let dir = d / d.hypot(); + corr = dir * corr.dot(dir); } - dx += corr.x; - dy += corr.y; + dx += corr.x; + dy += corr.y; self.guides = hit.guides; } - // The command moves in spread space: each point by the drag in its own spread. - let own = at.map_or(Vec2::new(dx, dy), |(spread, _)| cx.layout.delta_to_spread(spread, Vec2::new(dx, dy))); - let mut params = json!({"id": id, "anchors": [[si, ai]], "dx": own.x, "dy": own.y}); + // The command moves in spread space: each point by the drag in its own spread. + let own = at.map_or(Vec2::new(dx, dy), |(spread, _)| cx.layout.delta_to_spread(spread, Vec2::new(dx, dy))); + let mut params = json!({"id": id, "anchors": [[si, ai]], "dx": own.x, "dy": own.y}); if let Some(h) = handle { params["handle"] = json!(h); - } else if !others.is_empty() { - let points = std::iter::once((id, si, ai)).chain(others).map(|(i, s, a)| (ItemId(i), s, a)); - params = json!({"points": moved_points(cx, points, Vec2::new(dx, dy))}); + } else if !others.is_empty() { + let points = std::iter::once((id, si, ai)).chain(others).map(|(i, s, a)| (ItemId(i), s, a)); + params = json!({"points": moved_points(cx, points, Vec2::new(dx, dy))}); } vec![Action::Preview("path.moveAnchors".into(), params)] } diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 025368deb..ef4519688 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -786,82 +786,82 @@ fn apply_to_text_colours_a_text_frames_text_not_the_frame() { assert_eq!(doc.item(designcraft_doc::ids::ItemId(id)).unwrap().fill.swatch, "[None]", "the frame isn't"); } - /// Points selected with Direct Selection: InDesign's "Anchor Point(s)" panel, with Convert - /// Points and the Delete Point(s) quick action, as in the Zero2Graphic tutorial (1:25). - #[test] - fn selected_points_show_convert_points_and_delete_points() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let a = app.run("frame.create", json!({"rect": [72, 72, 172, 172]})).unwrap()["id"].as_u64().unwrap(); - let b = app.run("frame.create", json!({"rect": [200, 72, 300, 172]})).unwrap()["id"].as_u64().unwrap(); - app.run("selection.set", json!({"anchors": [[a, 0, 0], [b, 0, 0]]})).unwrap(); - assert_eq!(selection_title(&app, &super::super::sel_info(&app)), "Anchor Point(s)"); - let mut h = panel(app); - // The four point types (Appearance has a Corner row too). - for tip in ["Plain", "Corner", "Smooth", "Symmetrical"] { - assert!(h.get_all_by_label(tip).next().is_some(), "{tip}"); - } - assert!(h.query_by_label("Align").is_none(), "only the sections InDesign shows for points"); - h.get_by_label("Delete Point(s)").click(); - h.run_steps(3); - let d = &h.state().session.active().unwrap().doc; - for id in [a, b] { - assert_eq!(d.item(designcraft_doc::ids::ItemId(id)).unwrap().path.subpaths[0].anchors.len(), 3, "one point gone from each"); - } +/// Points selected with Direct Selection: InDesign's "Anchor Point(s)" panel, with Convert +/// Points and the Delete Point(s) quick action, as in the Zero2Graphic tutorial (1:25). +#[test] +fn selected_points_show_convert_points_and_delete_points() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let a = app.run("frame.create", json!({"rect": [72, 72, 172, 172]})).unwrap()["id"].as_u64().unwrap(); + let b = app.run("frame.create", json!({"rect": [200, 72, 300, 172]})).unwrap()["id"].as_u64().unwrap(); + app.run("selection.set", json!({"anchors": [[a, 0, 0], [b, 0, 0]]})).unwrap(); + assert_eq!(selection_title(&app, &super::super::sel_info(&app)), "Anchor Point(s)"); + let mut h = panel(app); + // The four point types (Appearance has a Corner row too). + for tip in ["Plain", "Corner", "Smooth", "Symmetrical"] { + assert!(h.get_all_by_label(tip).next().is_some(), "{tip}"); } + assert!(h.query_by_label("Align").is_none(), "only the sections InDesign shows for points"); + h.get_by_label("Delete Point(s)").click(); + h.run_steps(3); + let d = &h.state().session.active().unwrap().doc; + for id in [a, b] { + assert_eq!(d.item(designcraft_doc::ids::ItemId(id)).unwrap().path.subpaths[0].anchors.len(), 3, "one point gone from each"); + } +} - /// With points selected, Transform measures and moves the points: one corner of a frame shows - /// that corner, not the frame, and X moves the corner alone; W spreads two points apart. - #[test] - fn transform_measures_and_moves_the_selected_points() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let a = app.run("frame.create", json!({"rect": [72, 72, 172, 172]})).unwrap()["id"].as_u64().unwrap(); - let corner = |app: &DesignApp, i: usize| { - let d = &app.session.active().unwrap().doc; - let it = d.item(designcraft_doc::ids::ItemId(a)).unwrap(); - it.xf * it.path.subpaths[0].anchors[i].p - }; - let first = corner(&app, 0); - app.run("selection.set", json!({"anchors": [[a, 0, 0]]})).unwrap(); - let i = super::super::sel_info(&app).unwrap(); - assert_eq!((i.page_rect.width(), i.page_rect.height()), (0.0, 0.0), "a point, not the frame"); - app.ui.ref_point = 0; - transform_anchors(&mut app, &json!({"x": i.page_rect.x0 + 10.0})).unwrap(); - assert_eq!(corner(&app, 0), first + designcraft_geom::Vec2::new(10.0, 0.0), "the corner moved"); - assert_eq!(corner(&app, 2), designcraft_geom::Point::new(172.0, 172.0), "the opposite corner stayed"); - // Two points 100 pt apart, W 200 from the left: the right one goes 100 further. - app.run("selection.set", json!({"anchors": [[a, 0, 2], [a, 0, 3]]})).unwrap(); - let (p2, p3) = (corner(&app, 2), corner(&app, 3)); - let w = super::super::sel_info(&app).unwrap().page_rect.width(); - transform_anchors(&mut app, &json!({"width": w * 2.0})).unwrap(); - let (left, right) = if p2.x < p3.x { (2, 3) } else { (3, 2) }; - let (pl, pr) = if left == 2 { (p2, p3) } else { (p3, p2) }; - assert_eq!(corner(&app, left), pl, "the reference side stays"); - assert!((corner(&app, right).x - (pr.x + w)).abs() < 1e-9, "spread to twice the width"); - } +/// With points selected, Transform measures and moves the points: one corner of a frame shows +/// that corner, not the frame, and X moves the corner alone; W spreads two points apart. +#[test] +fn transform_measures_and_moves_the_selected_points() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let a = app.run("frame.create", json!({"rect": [72, 72, 172, 172]})).unwrap()["id"].as_u64().unwrap(); + let corner = |app: &DesignApp, i: usize| { + let d = &app.session.active().unwrap().doc; + let it = d.item(designcraft_doc::ids::ItemId(a)).unwrap(); + it.xf * it.path.subpaths[0].anchors[i].p + }; + let first = corner(&app, 0); + app.run("selection.set", json!({"anchors": [[a, 0, 0]]})).unwrap(); + let i = super::super::sel_info(&app).unwrap(); + assert_eq!((i.page_rect.width(), i.page_rect.height()), (0.0, 0.0), "a point, not the frame"); + app.ui.ref_point = 0; + transform_anchors(&mut app, &json!({"x": i.page_rect.x0 + 10.0})).unwrap(); + assert_eq!(corner(&app, 0), first + designcraft_geom::Vec2::new(10.0, 0.0), "the corner moved"); + assert_eq!(corner(&app, 2), designcraft_geom::Point::new(172.0, 172.0), "the opposite corner stayed"); + // Two points 100 pt apart, W 200 from the left: the right one goes 100 further. + app.run("selection.set", json!({"anchors": [[a, 0, 2], [a, 0, 3]]})).unwrap(); + let (p2, p3) = (corner(&app, 2), corner(&app, 3)); + let w = super::super::sel_info(&app).unwrap().page_rect.width(); + transform_anchors(&mut app, &json!({"width": w * 2.0})).unwrap(); + let (left, right) = if p2.x < p3.x { (2, 3) } else { (3, 2) }; + let (pl, pr) = if left == 2 { (p2, p3) } else { (p3, p2) }; + assert_eq!(corner(&app, left), pl, "the reference side stays"); + assert!((corner(&app, right).x - (pr.x + w)).abs() < 1e-9, "spread to twice the width"); +} - /// One point has no size: W and H show its frame's, greyed out, as InDesign; two points - /// measure (and set) their own. - #[test] - fn one_selected_point_shows_its_frames_size_greyed() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let a = app.run("frame.create", json!({"rect": [72, 72, 172, 222]})).unwrap()["id"].as_u64().unwrap(); - app.run("selection.set", json!({"anchors": [[a, 0, 0]]})).unwrap(); - assert_eq!(super::super::sel_info(&app).unwrap().object_size, (100.0, 150.0)); - let mut h = panel(app); - h.run_steps(2); - let greyed = |h: &Harness<'_, DesignApp>| { - h.query_all_by(|n| n.role() == egui::accesskit::Role::TextInput && n.is_disabled()).filter_map(|n| n.value()).collect::>() - }; - let u = units(h.state()); - let f = |v| designcraft_geom::units::format_measure(v, u); - assert_eq!(greyed(&h), [f(100.0), f(150.0)], "the frame's W and H, greyed"); - h.state_mut().run("selection.set", json!({"anchors": [[a, 0, 0], [a, 0, 2]]})).unwrap(); - h.run_steps(2); - assert!(greyed(&h).is_empty(), "two points have a size of their own"); - } +/// One point has no size: W and H show its frame's, greyed out, as InDesign; two points +/// measure (and set) their own. +#[test] +fn one_selected_point_shows_its_frames_size_greyed() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let a = app.run("frame.create", json!({"rect": [72, 72, 172, 222]})).unwrap()["id"].as_u64().unwrap(); + app.run("selection.set", json!({"anchors": [[a, 0, 0]]})).unwrap(); + assert_eq!(super::super::sel_info(&app).unwrap().object_size, (100.0, 150.0)); + let mut h = panel(app); + h.run_steps(2); + let greyed = |h: &Harness<'_, DesignApp>| { + h.query_all_by(|n| n.role() == egui::accesskit::Role::TextInput && n.is_disabled()).filter_map(|n| n.value()).collect::>() + }; + let u = units(h.state()); + let f = |v| designcraft_geom::units::format_measure(v, u); + assert_eq!(greyed(&h), [f(100.0), f(150.0)], "the frame's W and H, greyed"); + h.state_mut().run("selection.set", json!({"anchors": [[a, 0, 0], [a, 0, 2]]})).unwrap(); + h.run_steps(2); + assert!(greyed(&h).is_empty(), "two points have a size of their own"); +} #[test] fn transform_flips_and_rotates_from_properties() { From 03d6404dcf11d38f5f032dc8403c6b066a3af3f0 Mon Sep 17 00:00:00 2001 From: Youssef Azriouil Date: Thu, 15 Oct 2026 11:38:44 +0200 Subject: [PATCH 0357/1349] Contributors: credit Y-az --- contributors/people.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index 79acd86b0..ec7a75f01 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -71,3 +71,7 @@ real_name = "Paul Gemignani" [people.skylartaylor] display_name = "skylartaylor" + +[people.Y-az] +real_name = "Youssef Azriouil" +display_name = "youssef" From dccda2cd4ca67629cad35dd2c71debf715d0641a Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 13:31:57 +0100 Subject: [PATCH 0358/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/tests.rs | 114 ++++++++++++++--------------- 1 file changed, 57 insertions(+), 57 deletions(-) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 836fd37cd..b96133c76 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -86,65 +86,65 @@ fn bleed_and_slug_are_preview_modes_that_show_their_area() { } } - /// An empty graphic frame's X joins its corners: a rectangle's, and a frame slanted by - /// moving its top points, as in the Zero2Graphic tutorial's row of parallelograms. - #[test] - fn an_empty_frames_x_follows_its_corners() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let id = app.run("frame.create", json!({"rect": [100, 100, 200, 160]})).unwrap()["id"].as_u64().unwrap(); - let x = |app: &DesignApp| { - let it = app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().clone(); - let m = it.xf; - frame_x(&it).map(|(a, b)| { - let (a, b) = (m * a, m * b); - [(a.x.round(), a.y.round()), (b.x.round(), b.y.round())] - }) - }; - let mut lines = x(&app).to_vec(); - lines.iter_mut().for_each(|l| l.sort_by(|a, b| a.partial_cmp(b).unwrap())); - lines.sort_by(|a, b| a.partial_cmp(b).unwrap()); - assert_eq!(lines, vec![[(100.0, 100.0), (200.0, 160.0)], [(100.0, 160.0), (200.0, 100.0)]], "corner to corner"); - // Slant it: the two top points move 30 pt right. +/// An empty graphic frame's X joins its corners: a rectangle's, and a frame slanted by +/// moving its top points, as in the Zero2Graphic tutorial's row of parallelograms. +#[test] +fn an_empty_frames_x_follows_its_corners() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [100, 100, 200, 160]})).unwrap()["id"].as_u64().unwrap(); + let x = |app: &DesignApp| { let it = app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().clone(); - let top: Vec = - it.path.subpaths[0].anchors.iter().enumerate().filter(|(_, a)| (it.xf * a.p).y < 130.0).map(|(k, _)| json!([0, k])).collect(); - assert_eq!(top.len(), 2); - app.run("path.moveAnchors", json!({"id": id, "anchors": top, "dx": 30, "dy": 0})).unwrap(); - let mut lines = x(&app).to_vec(); - lines.iter_mut().for_each(|l| l.sort_by(|a, b| a.partial_cmp(b).unwrap())); - lines.sort_by(|a, b| a.partial_cmp(b).unwrap()); - assert_eq!(lines, vec![[(100.0, 160.0), (230.0, 100.0)], [(130.0, 100.0), (200.0, 160.0)]], "the slanted corners"); - // An ellipse frame (four smooth anchors) keeps the X across its bounds, not a plus. - let e = app.run("frame.create", json!({"rect": [300, 100, 400, 160], "shape": "ellipse"})).unwrap()["id"].as_u64().unwrap(); - let it = app.session.active().unwrap().doc.item(designcraft_doc::ItemId(e)).unwrap().clone(); - let mut lines: Vec<[(f64, f64); 2]> = frame_x(&it) - .map(|(a, b)| { - let (a, b) = (it.xf * a, it.xf * b); - [(a.x.round(), a.y.round()), (b.x.round(), b.y.round())] - }) - .to_vec(); - lines.iter_mut().for_each(|l| l.sort_by(|a, b| a.partial_cmp(b).unwrap())); - lines.sort_by(|a, b| a.partial_cmp(b).unwrap()); - assert_eq!(lines, vec![[(300.0, 100.0), (400.0, 160.0)], [(300.0, 160.0), (400.0, 100.0)]], "the ellipse's bounds"); - // So does a four-sided polygon frame (a diamond): its corners would cross as a plus. - let mut diamond = it.clone(); - diamond.shape = designcraft_doc::Shape::Polygon; - for a in &mut diamond.path.subpaths[0].anchors { - (a.h_in, a.h_out) = (a.p, a.p); - } - let lines: Vec<_> = frame_x(&diamond).to_vec(); - assert!(lines.iter().all(|(a, b)| (a.x - b.x).abs() > 1e-6 && (a.y - b.y).abs() > 1e-6), "diagonals, not a plus: {lines:?}"); - // Still after one of its points moves (which makes it a path). - let p = app.run("frame.create", json!({"rect": [300, 200, 400, 260], "shape": "polygon", "sides": 4, "starInset": 0})).unwrap()["id"] - .as_u64() - .unwrap(); - app.run("path.moveAnchors", json!({"id": p, "anchors": [[0, 0]], "dx": 5, "dy": 0})).unwrap(); - let it = app.session.active().unwrap().doc.item(designcraft_doc::ItemId(p)).unwrap().clone(); - assert_eq!(it.shape, designcraft_doc::Shape::Path); - let lines: Vec<_> = frame_x(&it).to_vec(); - assert!(lines.iter().all(|(a, b)| (a.x - b.x).abs() > 1e-6 && (a.y - b.y).abs() > 1e-6), "an edited diamond: {lines:?}"); + let m = it.xf; + frame_x(&it).map(|(a, b)| { + let (a, b) = (m * a, m * b); + [(a.x.round(), a.y.round()), (b.x.round(), b.y.round())] + }) + }; + let mut lines = x(&app).to_vec(); + lines.iter_mut().for_each(|l| l.sort_by(|a, b| a.partial_cmp(b).unwrap())); + lines.sort_by(|a, b| a.partial_cmp(b).unwrap()); + assert_eq!(lines, vec![[(100.0, 100.0), (200.0, 160.0)], [(100.0, 160.0), (200.0, 100.0)]], "corner to corner"); + // Slant it: the two top points move 30 pt right. + let it = app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().clone(); + let top: Vec = + it.path.subpaths[0].anchors.iter().enumerate().filter(|(_, a)| (it.xf * a.p).y < 130.0).map(|(k, _)| json!([0, k])).collect(); + assert_eq!(top.len(), 2); + app.run("path.moveAnchors", json!({"id": id, "anchors": top, "dx": 30, "dy": 0})).unwrap(); + let mut lines = x(&app).to_vec(); + lines.iter_mut().for_each(|l| l.sort_by(|a, b| a.partial_cmp(b).unwrap())); + lines.sort_by(|a, b| a.partial_cmp(b).unwrap()); + assert_eq!(lines, vec![[(100.0, 160.0), (230.0, 100.0)], [(130.0, 100.0), (200.0, 160.0)]], "the slanted corners"); + // An ellipse frame (four smooth anchors) keeps the X across its bounds, not a plus. + let e = app.run("frame.create", json!({"rect": [300, 100, 400, 160], "shape": "ellipse"})).unwrap()["id"].as_u64().unwrap(); + let it = app.session.active().unwrap().doc.item(designcraft_doc::ItemId(e)).unwrap().clone(); + let mut lines: Vec<[(f64, f64); 2]> = frame_x(&it) + .map(|(a, b)| { + let (a, b) = (it.xf * a, it.xf * b); + [(a.x.round(), a.y.round()), (b.x.round(), b.y.round())] + }) + .to_vec(); + lines.iter_mut().for_each(|l| l.sort_by(|a, b| a.partial_cmp(b).unwrap())); + lines.sort_by(|a, b| a.partial_cmp(b).unwrap()); + assert_eq!(lines, vec![[(300.0, 100.0), (400.0, 160.0)], [(300.0, 160.0), (400.0, 100.0)]], "the ellipse's bounds"); + // So does a four-sided polygon frame (a diamond): its corners would cross as a plus. + let mut diamond = it.clone(); + diamond.shape = designcraft_doc::Shape::Polygon; + for a in &mut diamond.path.subpaths[0].anchors { + (a.h_in, a.h_out) = (a.p, a.p); } + let lines: Vec<_> = frame_x(&diamond).to_vec(); + assert!(lines.iter().all(|(a, b)| (a.x - b.x).abs() > 1e-6 && (a.y - b.y).abs() > 1e-6), "diagonals, not a plus: {lines:?}"); + // Still after one of its points moves (which makes it a path). + let p = app.run("frame.create", json!({"rect": [300, 200, 400, 260], "shape": "polygon", "sides": 4, "starInset": 0})).unwrap()["id"] + .as_u64() + .unwrap(); + app.run("path.moveAnchors", json!({"id": p, "anchors": [[0, 0]], "dx": 5, "dy": 0})).unwrap(); + let it = app.session.active().unwrap().doc.item(designcraft_doc::ItemId(p)).unwrap().clone(); + assert_eq!(it.shape, designcraft_doc::Shape::Path); + let lines: Vec<_> = frame_x(&it).to_vec(); + assert!(lines.iter().all(|(a, b)| (a.x - b.x).abs() > 1e-6 && (a.y - b.y).abs() > 1e-6), "an edited diamond: {lines:?}"); +} /// Each preview mode's shown area: Preview stops at the trim, Bleed reaches the bleed box and /// Slug the slug box. A slug narrower than the bleed never pulls the edge back in. From 7a3e69e20a345d957311c9b616b6f90b999795ee Mon Sep 17 00:00:00 2001 From: Youssef Azriouil Date: Wed, 14 Oct 2026 18:35:04 +0200 Subject: [PATCH 0359/1349] Hyphenation: bundle the Dutch patterns Enable hypher's "dutch" feature: Piet Tutelaers's hyph-nl.tex 1.1 from hyph-utf8, MIT licensed (added to NOTICE). Dutch text, including InDesign's nl_NL_2005, now hyphenates instead of never breaking a word. --- NOTICE | 14 ++++++++++++++ crates/compose/Cargo.toml | 2 +- crates/compose/src/hyphen.rs | 26 ++++++++++++++++++++++---- docs/gaps.md | 2 +- docs/localization-parity.md | 2 +- docs/target-app-parity.md | 4 ++-- docs/typography-parity.md | 2 +- 7 files changed, 42 insertions(+), 10 deletions(-) diff --git a/NOTICE b/NOTICE index fc46bcdf3..6f7cb28eb 100644 --- a/NOTICE +++ b/NOTICE @@ -32,6 +32,20 @@ list (author, source, license) is in ASSETS.md. 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. +- Dutch hyphenation patterns, embedded through the hypher crate (feature "dutch"): + hyph-nl.tex 1.1 from hyph-utf8, https://github.com/hyphenation/tex-hyphen. + Copyright (C) 1996 Piet Tutelaers. MIT License: + 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. - Portuguese hyphenation patterns, embedded through the hypher crate (feature "portuguese"): hyph-pt.tex 1.4 from hyph-utf8, https://github.com/hyphenation/tex-hyphen. Copyright (C) 1987, 1994, 1996, 2015 Pedro J. de Rezende, 1996, 2015 J. Joao Dias Almeida, diff --git a/crates/compose/Cargo.toml b/crates/compose/Cargo.toml index b7017f80f..126416a1d 100644 --- a/crates/compose/Cargo.toml +++ b/crates/compose/Cargo.toml @@ -21,7 +21,7 @@ log = { workspace = true } regex = { workspace = true } fancy-regex = { workspace = true } miniz_oxide = "0.8" -hypher = { version = "0.1.8", default-features = false, features = ["alloc", "greek", "portuguese", "spanish", "norwegian"] } +hypher = { version = "0.1.8", default-features = false, features = ["alloc", "greek", "portuguese", "spanish", "norwegian", "dutch"] } [dev-dependencies] designcraft-fonts = { workspace = true, features = ["testing"] } diff --git a/crates/compose/src/hyphen.rs b/crates/compose/src/hyphen.rs index 3f07f4b40..37f7ae598 100644 --- a/crates/compose/src/hyphen.rs +++ b/crates/compose/src/hyphen.rs @@ -2,10 +2,11 @@ //! Liang patterns compiled into `hypher`, one cargo feature per language: Spanish is Javier Bezos's //! `hyph-es.tex` 5.0 from hyph-utf8, MIT; Portuguese is `hyph-pt.tex` 1.4 from hyph-utf8 (Pedro J. //! de Rezende, J. Joao Dias Almeida, Leonardo Araujo, Aline Benevides), BSD-3-Clause; Norwegian is -//! `hyph-no.tex` from hyph-utf8 (Rune Kleveland, Ole Michael Selberg), permissive (see NOTICE); -//! Greek is `hyph-el-monoton.tex` 5.0 from hyph-utf8 (Dimitrios Filippou), LPPL or MIT, taken -//! under MIT. Those are the **monotonic** patterns, which is what `hypher` maps `el` to, so -//! polytonic text hyphenates by them as well. +//! `hyph-no.tex` from hyph-utf8 (Rune Kleveland, Ole Michael Selberg), permissive; Dutch is Piet +//! Tutelaers's `hyph-nl.tex` 1.1 from hyph-utf8, MIT (see NOTICE); Greek is `hyph-el-monoton.tex` +//! 5.0 from hyph-utf8 (Dimitrios Filippou), LPPL or MIT, taken under MIT. Those are the +//! **monotonic** patterns, which is what `hypher` maps `el` to, so polytonic text hyphenates by +//! them as well. //! //! English lookup order for each word: //! 1. the **dictionary** ([`Dictionary::en_us`]) — the public-domain Moby Hyphenator II word list @@ -435,6 +436,23 @@ mod tests { assert_eq!(h("beveger"), "be-ve-ger"); } + #[test] + fn dutch_uses_the_hyph_nl_patterns() { + let nl = Lang::for_language("Dutch").unwrap(); + // InDesign writes the 2005 spelling as `nl_NL_2005`. + assert_eq!(nl, Lang::for_language("nl_NL_2005").unwrap()); + assert_ne!(nl, Lang::for_language("Spanish").unwrap()); + let h = |w: &str| { + let pts = hyphen_points_in(w, &Limits::default(), nl); + w.chars().enumerate().map(|(i, c)| if pts.contains(&i) { format!("-{c}") } else { c.to_string() }).collect::() + }; + assert_eq!(h("uitspraak"), "uit-spraak"); + assert_eq!(h("kinderen"), "kin-de-ren"); + assert_eq!(h("leesvaardigheid"), "lees-vaar-dig-heid"); + assert_eq!(h("zelfvertrouwen"), "zelf-ver-trou-wen"); + assert_eq!(h("Ontwikkelen"), "Ont-wik-ke-len"); + } + #[test] fn heuristic_fallback() { let c: Vec = "happen".chars().collect(); diff --git a/docs/gaps.md b/docs/gaps.md index ea9cafd40..c0cbfa847 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -156,7 +156,7 @@ Kind: **F** feature · **U** UI/UX · **T** typography · **FF** file format · - **Estimate:** 25–40 h. ### 13. Hyphenation and spelling languages (T, L) -- **Missing:** hyphenation patterns for every language but English, Spanish, Portuguese, Norwegian and Greek; spelling for +- **Missing:** hyphenation patterns for every language but English, Spanish, Portuguese, Norwegian, Greek and Dutch; spelling for every language but English. InDesign ships dictionaries for ~40 languages. - **Estimate:** 30–60 h (permissively licensed patterns exist for most; spelling word lists need licence review). **Doc:** [typography-parity.md](typography-parity.md) diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 404cf13a7..599358c61 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -68,7 +68,7 @@ eight of the twelve (cs, da, el, en_GB, fi, hu, it, nb, nl, pl, ro, ru, sq, sv, ## Document languages InDesign 2026 hyphenates and spell-checks ~40 languages (Hunspell and Duden dictionaries). -DesignCraft hyphenates **English, Spanish, Portuguese and Norwegian** and spell-checks **English** only. Text language +DesignCraft hyphenates **English, Spanish, Portuguese, Norwegian and Dutch** and spell-checks **English** only. Text language can be set per paragraph and character (Properties, Character panel) and drives quotes and locale shaping. See [typography-parity.md](typography-parity.md). diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3443ca8e6..2bed89817 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -59,7 +59,7 @@ they receive, setting type exactly, and basic editing that never fails. | Dimension | Weight | Ready | Remaining (Opus 5.5 h) | Evidence | Doc | |---|---|---|---|---|---| | Features (depth of each area) | 25% | 55% | 250–400 | 275 catalogue rows exist; many lack options (e.g. Books is 258 lines of engine code, Liquid Layout 329); see the area table | this file | -| Typography and composition fidelity | 15% | 45% | 120–200 | Knuth–Plass composer, keeps, grids, CJK, Arabic all exist; no comparison with InDesign's line breaks; optical kerning falls back to metrics (#181); overset rule differs (#180); hyphenation patterns for English, Spanish, Portuguese, Norwegian and Greek only | [typography-parity.md](typography-parity.md) | +| Typography and composition fidelity | 15% | 45% | 120–200 | Knuth–Plass composer, keeps, grids, CJK, Arabic all exist; no comparison with InDesign's line breaks; optical kerning falls back to metrics (#181); overset rule differs (#180); hyphenation patterns for English, Spanish, Portuguese, Norwegian, Greek and Dutch only | [typography-parity.md](typography-parity.md) | | File formats | 20% | 40% | 150–250 (+10–30 for an INDD corpus) | INDD and INDT open through indd-utils, measured on synthetic bytes only (#21); IDML both ways and verified in InDesign 2026, but real-file bugs open (#193, #338, #339, #340); PDF export strong; PDF/X-4 only | [file-format-parity.md](file-format-parity.md) | | UI/UX fidelity | 15% | 45% | 120–180 | Measured InDesign 2026 look; but users report object copy/paste (#351, #348, #185, #164), right-click menus (#238, #187, #160), out-port threading (#352, #194, #165) failing | [ui-parity.md](ui-parity.md) | | Stability | 10% | 45% | 60–100 | Never-crash rules and last-resort guards; startup failures on some GPUs and machines (#334, #273, #220, #192, #167, #166); no CI runs the tests on pull requests | [gaps.md](gaps.md) | @@ -362,7 +362,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - Linked stories (Edit ▸ Place and Link, `story.placeAndLink/links/updateLink/unlink`): child stories copy a parent, show out of date in the Links panel and update. - Edit ▸ Menus (`window.hideMenuItem`): hide menu items; menus with hidden items end in Show All Menu Items. - View ▸ Separations Preview (`view.separations`, Window ▸ Output ▸ Separations Preview, `ink.separations`): the plates the print PDF puts on film, spot plates included. Each visible spread is exported as Export PDF writes it and separated with craft-prepress, so the Ink Manager's aliases and spots to process, overprint and the flattener show as printed. All inks as printed, one plate as film, or an ink limit in red over gray; the panel lists the plates with each ink's percentage under the pointer. -- Language (Character panel ▸ Language, Properties ▸ Character, `type.char {language}`): text in other languages isn't hyphenated or spell-checked with the English dictionaries, typographer's quotes follow the language (German „…“, French and Russian «…», Swiss, Spanish, Dutch, Nordic, Japanese and Traditional Chinese 「…」, Simplified Chinese “…”), the font's localized forms (OpenType `locl`: Turkish i, Bulgarian Cyrillic, Japanese / Chinese / Korean glyph variants) follow it too, and so does the fallback for CJK characters the font lacks (with Draw Missing Glyphs from Fallback Fonts on): Japanese, Simplified Chinese, Traditional Chinese and Korean each try their own installed system fonts (Japanese starts with the craft-fonts Japanese faces, Mincho first, when built with them; Hangul, kana and Bopomofo pick their language's fonts whatever the language). Language names from IDML keep their spelling; locale codes as InDesign writes them for some languages (`de_DE_2006`, `nl_NL_2005`; any `ll`, `ll_CC`, `ll-CC`) are their language and region for all of the above, and Chinese is also recognised in its common spellings ("Simplified Chinese", "Chinese (Traditional)", `zh_CN`, `zh-Hant`). Spanish is hyphenated with Javier Bezos's Liang patterns (`hyph-es.tex` 5.0, MIT), Portuguese with hyph-utf8's `hyph-pt.tex` 1.4 (BSD-3-Clause) and Norwegian with hyph-utf8's `hyph-no.tex` (permissive), all through the `hypher` crate; hyphenation for other languages isn't bundled yet. +- Language (Character panel ▸ Language, Properties ▸ Character, `type.char {language}`): text in other languages isn't hyphenated or spell-checked with the English dictionaries, typographer's quotes follow the language (German „…“, French and Russian «…», Swiss, Spanish, Dutch, Nordic, Japanese and Traditional Chinese 「…」, Simplified Chinese “…”), the font's localized forms (OpenType `locl`: Turkish i, Bulgarian Cyrillic, Japanese / Chinese / Korean glyph variants) follow it too, and so does the fallback for CJK characters the font lacks (with Draw Missing Glyphs from Fallback Fonts on): Japanese, Simplified Chinese, Traditional Chinese and Korean each try their own installed system fonts (Japanese starts with the craft-fonts Japanese faces, Mincho first, when built with them; Hangul, kana and Bopomofo pick their language's fonts whatever the language). Language names from IDML keep their spelling; locale codes as InDesign writes them for some languages (`de_DE_2006`, `nl_NL_2005`; any `ll`, `ll_CC`, `ll-CC`) are their language and region for all of the above, and Chinese is also recognised in its common spellings ("Simplified Chinese", "Chinese (Traditional)", `zh_CN`, `zh-Hant`). Spanish is hyphenated with Javier Bezos's Liang patterns (`hyph-es.tex` 5.0, MIT), Portuguese with hyph-utf8's `hyph-pt.tex` 1.4 (BSD-3-Clause), Norwegian with hyph-utf8's `hyph-no.tex` (permissive) and Dutch with Piet Tutelaers's `hyph-nl.tex` 1.1 (MIT), all through the `hypher` crate; hyphenation for other languages isn't bundled yet. - Books (`book.new/open/add/remove/list/styleSource/paginate/syncStyles/exportPdf`, Book panel): `.dcbook` files, continuous page numbering, chapter numbers resolved in book order (Automatic, Start Chapter Numbering at, Same as Previous Document; `layout.chapterNumbering`, with a style for Chapter Number variables and cross-references), style sync from a style source, one merged PDF. Section prefixes follow InDesign's rule (up to 8 characters, no + or comma). - Numbering & Section Options window as in InDesign (Start Section, automatic or explicit page numbering up to 99999, prefix, style, marker, Include Prefix; the document's chapter numbering and its book); OK applies both in one undo step (`layout.numberingOptions`). - Book numbering/style updates validate and serialize all targets before changing the first chapter. They write only closed native chapters, checking canonical paths for open aliases; IDML remains a read-only style source and PDF input. Snapshots are staged on disk with at most 4,096 chapter records in memory. Each replacement is atomic; a later write failure explicitly lists completed chapters rather than claiming whole-book rollback. Import/serialization memory limits and advanced book TOC/index work remain separate. diff --git a/docs/typography-parity.md b/docs/typography-parity.md index 8c92e8dfa..e9d5d20f5 100644 --- a/docs/typography-parity.md +++ b/docs/typography-parity.md @@ -36,7 +36,7 @@ Fidelity: **unmeasured** unless stated. | Single-line Composer | greedy | greedy with the same ranges | ✓ | | | World-Ready composers | Paragraph / Single-line World-Ready | RTL, Arabic and bidi in the main composer | ~ | Indic scripts (Devanagari etc.) shape through harfrust but are untested | | Justification | word/letter spacing, glyph scaling min/desired/max, single-word, last line | all of these | ✓ | a justified line with a tab justifies after the tab (#284); set per paragraph in Type › Justification… and the Paragraph panel menu (#531) | -| Hyphenation | per-language dictionaries (~40), zone, limits, capitalized, last word, across columns | Liang patterns: English (trained from the public-domain Moby list), Spanish (Bezos), Portuguese (hyph-pt), Norwegian (hyph-no) and Greek (hyph-el-monoton); zone, limits, exceptions in the user dictionary; Hyphenate Across Column off keeps automatic hyphens off the last line of a column or frame | ~ | other languages don't hyphenate (#87 reported "doesn't work") | +| Hyphenation | per-language dictionaries (~40), zone, limits, capitalized, last word, across columns | Liang patterns: English (trained from the public-domain Moby list), Spanish (Bezos), Portuguese (hyph-pt), Norwegian (hyph-no), Greek (hyph-el-monoton) and Dutch (Tutelaers); zone, limits, exceptions in the user dictionary; Hyphenate Across Column off keeps automatic hyphens off the last line of a column or frame | ~ | other languages don't hyphenate (#87 reported "doesn't work") | | Spelling | per-language dictionaries | English (Moby) + document/user dictionary | ~ | | | Kerning | Metrics, Optical, manual, none | Metrics, Optical (outline-based: pairs pulled towards the font's stem gap, `crates/compose/src/optical.rs`), manual, none | ~ | Optical is an approximation of Adobe's algorithm (#181), not a match: imported display text can still break differently | | Tracking, scale, skew, baseline shift | ✓ | ✓ | ✓ | | From 5fc74966297d2bbd579c845d598c5bef0137ddbb Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 13:43:42 +0100 Subject: [PATCH 0360/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/tools/src/select.rs | 134 ++++++++++++++++++------------------- 1 file changed, 67 insertions(+), 67 deletions(-) diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 2cc3f0078..3fdf457d3 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -768,51 +768,51 @@ impl SelectionTool { && let Some((id, si, ai, handle)) = anchor_at(cx, p) { let at = anchor_spread_point(cx, id, si, ai); - let mut out = vec![]; - let mut others = vec![]; - if handle.is_none() { - // InDesign's anchor point selection: a click selects the point, Shift+click - // adds it or takes it away, and dragging a selected point moves all of them. - let me = (ItemId(id), si, ai); - let mut points = cx.selection.anchors.clone(); - let was = points.contains(&me); - if ev.mods.shift && was { - // Kept selected so a Shift-drag can constrain it; a click still takes it - // away, on release, as for objects. - self.anchor_release = Some(me); - } else if ev.mods.shift { - points.push(me); - } else if !was { - points = vec![me]; - } - if points != cx.selection.anchors { - out.push(Action::Exec("selection.set".into(), anchor_selection(cx, &points))); - } - others = points.iter().filter(|a| **a != me).map(|(i, s, a)| (i.0, *s, *a)).collect(); - } - let label = if handle.is_some() { - "Move Direction Handle" - } else if others.is_empty() { - "Move Anchor" - } else { - "Move Anchors" - }; - self.drag = Drag::Anchor { id, si, ai, handle, start: p, at, others }; - out.push(Action::Begin(label.into())); - return out; + let mut out = vec![]; + let mut others = vec![]; + if handle.is_none() { + // InDesign's anchor point selection: a click selects the point, Shift+click + // adds it or takes it away, and dragging a selected point moves all of them. + let me = (ItemId(id), si, ai); + let mut points = cx.selection.anchors.clone(); + let was = points.contains(&me); + if ev.mods.shift && was { + // Kept selected so a Shift-drag can constrain it; a click still takes it + // away, on release, as for objects. + self.anchor_release = Some(me); + } else if ev.mods.shift { + points.push(me); + } else if !was { + points = vec![me]; } - // As in InDesign, the Direct Selection tool pressed on a corner or anchor of an object - // that isn't selected selects it and moves just that point (Chris Nielsen's "The - // InDesign Toolbox", 10:10: click outside, then pull a frame's corner). - if self.direct - && !ev.mods.shift - && let Some((_, hit)) = cx.hit(p) - && !cx.selection.contains(hit) - && let Some((id, si, ai, None)) = anchor_at_in(cx, &[hit], p) - { - let at = anchor_spread_point(cx, id, si, ai); - self.drag = Drag::Anchor { id, si, ai, handle: None, start: p, at, others: vec![] }; - return vec![Action::Exec("selection.set".into(), json!({"ids": [id], "content": true})), Action::Begin("Move Anchor".into())]; + if points != cx.selection.anchors { + out.push(Action::Exec("selection.set".into(), anchor_selection(cx, &points))); + } + others = points.iter().filter(|a| **a != me).map(|(i, s, a)| (i.0, *s, *a)).collect(); + } + let label = if handle.is_some() { + "Move Direction Handle" + } else if others.is_empty() { + "Move Anchor" + } else { + "Move Anchors" + }; + self.drag = Drag::Anchor { id, si, ai, handle, start: p, at, others }; + out.push(Action::Begin(label.into())); + return out; + } + // As in InDesign, the Direct Selection tool pressed on a corner or anchor of an object + // that isn't selected selects it and moves just that point (Chris Nielsen's "The + // InDesign Toolbox", 10:10: click outside, then pull a frame's corner). + if self.direct + && !ev.mods.shift + && let Some((_, hit)) = cx.hit(p) + && !cx.selection.contains(hit) + && let Some((id, si, ai, None)) = anchor_at_in(cx, &[hit], p) + { + let at = anchor_spread_point(cx, id, si, ai); + self.drag = Drag::Anchor { id, si, ai, handle: None, start: p, at, others: vec![] }; + return vec![Action::Exec("selection.set".into(), json!({"ids": [id], "content": true})), Action::Begin("Move Anchor".into())]; } // A selected placed graphic's own handles resize it inside its frame (the // frame's anchors, under Direct Selection, come first). @@ -1151,18 +1151,18 @@ impl SelectionTool { // Screen y points down: a positive screen angle is clockwise. vec![Action::Preview("transform.rotate".into(), json!({"angle": -a}))] } - Drag::Anchor { id, si, ai, handle, start, at, others } => { - let mut d = p - start; - if d.hypot() >= cx.tol(3.0) { - self.anchor_release = None; - } else if self.anchor_release.is_some() { - // A Shift-press on a selected point is still a click: nothing moves yet. - return vec![]; - } - // Shift: horizontal, vertical or at 45°. - if ev.mods.shift { - d = constrain_45(d); - } + Drag::Anchor { id, si, ai, handle, start, at, others } => { + let mut d = p - start; + if d.hypot() >= cx.tol(3.0) { + self.anchor_release = None; + } else if self.anchor_release.is_some() { + // A Shift-press on a selected point is still a click: nothing moves yet. + return vec![]; + } + // Shift: horizontal, vertical or at 45°. + if ev.mods.shift { + d = constrain_45(d); + } let mut dx = d.x; let mut dy = d.y; self.guides.clear(); @@ -1190,23 +1190,23 @@ impl SelectionTool { }, ); // dx and dy stay in canvas space. Snap.delta is spread space. - let mut corr = spread_delta_to_canvas(cx.layout.xf(spread), hit.delta); - corr = Vec2::new(if corr.x.is_finite() { corr.x } else { 0.0 }, if corr.y.is_finite() { corr.y } else { 0.0 }); - // Shift: the snap moves the points along the constrained direction only. - if ev.mods.shift && d.hypot() > 1e-9 { - let dir = d / d.hypot(); - corr = dir * corr.dot(dir); + let mut corr = spread_delta_to_canvas(cx.layout.xf(spread), hit.delta); + corr = Vec2::new(if corr.x.is_finite() { corr.x } else { 0.0 }, if corr.y.is_finite() { corr.y } else { 0.0 }); + // Shift: the snap moves the points along the constrained direction only. + if ev.mods.shift && d.hypot() > 1e-9 { + let dir = d / d.hypot(); + corr = dir * corr.dot(dir); } - dx += corr.x; - dy += corr.y; + dx += corr.x; + dy += corr.y; self.guides = hit.guides; } let mut params = json!({"id": id, "anchors": [[si, ai]], "dx": dx, "dy": dy}); if let Some(h) = handle { params["handle"] = json!(h); - } else if !others.is_empty() { - let points: Vec = std::iter::once((id, si, ai)).chain(others).map(|(i, s, a)| json!([i, s, a])).collect(); - params = json!({"points": points, "dx": dx, "dy": dy}); + } else if !others.is_empty() { + let points: Vec = std::iter::once((id, si, ai)).chain(others).map(|(i, s, a)| json!([i, s, a])).collect(); + params = json!({"points": points, "dx": dx, "dy": dy}); } vec![Action::Preview("path.moveAnchors".into(), params)] } From 35e2f8e66c8dfcee1c45516fc6ea95e2553c3488 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 13:51:04 +0100 Subject: [PATCH 0361/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/menus/tests.rs | 140 +++++++++++++++--------------- 1 file changed, 70 insertions(+), 70 deletions(-) diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 60455a4fc..5f7f5b93d 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -6,80 +6,80 @@ fn menu_ids(title: &str) -> Vec<&'static str> { items.iter().filter_map(|e| e.split_once(':').map(|(_, rest)| rest.split('|').next().unwrap_or(rest))).collect() } - /// The Object menu's top level in InDesign's order and groups (as InDesign 2023 shows it in - /// Learn Skills Daily's course), with Paths holding Join, Open and Close Path, Convert Shape - /// only shapes, and a Convert Point submenu. - #[test] - fn the_object_menu_is_in_indesigns_order() { - let items = MENUS.iter().find(|(t, _)| *t == "Object").map(|(_, items)| *items).unwrap(); - // The top-level entries: submenus by name, separators as "-", items by command id. - let mut top = Vec::new(); - let mut depth = 0; - for e in items { - match *e { - "<" => depth -= 1, - e if e.starts_with('>') => { - if depth == 0 { - top.push(e.trim_start_matches('>')); - } - depth += 1; +/// The Object menu's top level in InDesign's order and groups (as InDesign 2023 shows it in +/// Learn Skills Daily's course), with Paths holding Join, Open and Close Path, Convert Shape +/// only shapes, and a Convert Point submenu. +#[test] +fn the_object_menu_is_in_indesigns_order() { + let items = MENUS.iter().find(|(t, _)| *t == "Object").map(|(_, items)| *items).unwrap(); + // The top-level entries: submenus by name, separators as "-", items by command id. + let mut top = Vec::new(); + let mut depth = 0; + for e in items { + match *e { + "<" => depth -= 1, + e if e.starts_with('>') => { + if depth == 0 { + top.push(e.trim_start_matches('>')); } - e if depth == 0 => top.push(e.split_once(':').map_or(e, |(_, r)| r.split('|').next().unwrap_or(r))), - _ => {} + depth += 1; } + e if depth == 0 => top.push(e.split_once(':').map_or(e, |(_, r)| r.split('|').next().unwrap_or(r))), + _ => {} } - assert_eq!( - top, - [ - "Transform", - "Transform Again", - "Arrange", - "Select", - "-", - "object.group", - "object.ungroup", - "object.lock", - "object.unlockAll", - "object.hide", - "object.showAll", - "-", - "app.qrCode", - "-", - "object.textFrameOptions", - "object.primaryTextFrame", - "Anchored Object", - "-", - "Fitting", - "Content", - "-", - "Effects", - "object.cornerOptions", - "-", - "app.layerOptions", - "object.exportOptions", - "Captions", - "Clipping Path", - "-", - "Flex Layout", - "-", - "Paths", - "Pathfinder", - "Convert Shape", - "Convert Point", - ] - ); - let ids = menu_ids("Object"); - for id in ["path.join", "path.reverse", "path.convertPoints"] { - assert!(ids.contains(&id), "{id}"); - } - let sub = |name: &str| { - let i = items.iter().position(|e| *e == format!(">{name}")).unwrap(); - items[i + 1..].iter().take_while(|e| **e != "<").copied().collect::>() - }; - assert!(sub("Paths").iter().any(|e| e.contains("|Open Path|")) && sub("Paths").iter().any(|e| e.contains("|Close Path|"))); - assert!(!sub("Convert Shape").iter().any(|e| e.contains("openPath") || e.contains("closedPath")), "shapes only"); - assert_eq!(sub("Convert Point").len(), 4); } + assert_eq!( + top, + [ + "Transform", + "Transform Again", + "Arrange", + "Select", + "-", + "object.group", + "object.ungroup", + "object.lock", + "object.unlockAll", + "object.hide", + "object.showAll", + "-", + "app.qrCode", + "-", + "object.textFrameOptions", + "object.primaryTextFrame", + "Anchored Object", + "-", + "Fitting", + "Content", + "-", + "Effects", + "object.cornerOptions", + "-", + "app.layerOptions", + "object.exportOptions", + "Captions", + "Clipping Path", + "-", + "Flex Layout", + "-", + "Paths", + "Pathfinder", + "Convert Shape", + "Convert Point", + ] + ); + let ids = menu_ids("Object"); + for id in ["path.join", "path.reverse", "path.convertPoints"] { + assert!(ids.contains(&id), "{id}"); + } + let sub = |name: &str| { + let i = items.iter().position(|e| *e == format!(">{name}")).unwrap(); + items[i + 1..].iter().take_while(|e| **e != "<").copied().collect::>() + }; + assert!(sub("Paths").iter().any(|e| e.contains("|Open Path|")) && sub("Paths").iter().any(|e| e.contains("|Close Path|"))); + assert!(!sub("Convert Shape").iter().any(|e| e.contains("openPath") || e.contains("closedPath")), "shapes only"); + assert_eq!(sub("Convert Point").len(), 4); +} #[test] fn view_items_are_in_the_view_menu_as_in_indesign() { From e7a29a8ad5968f873b5bbbdb9fa5b26cf0413b6a Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 13:55:33 +0100 Subject: [PATCH 0362/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/tests.rs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 900407f5e..7d1f217b7 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3469,20 +3469,20 @@ fn guide_counts(app: &DesignApp) -> Vec { } #[test] - fn create_guides_dialog_covers_the_spread_in_view() { +fn create_guides_dialog_covers_the_spread_in_view() { let mut app = facing_app(6); - // As in InDesign, both pages of the facing spread in view get the guides. + // As in InDesign, both pages of the facing spread in view get the guides. crate::canvas::go_to_page(&mut app, 1); crate::menus::activate(&mut app, "layout.createGuides", &Value::Null); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("target"), "spread"); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("target"), "spread"); ctl(&mut app, "ui.dialog.set", json!({"field": "columns", "value": "2"})); - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); - assert_eq!(guide_counts(&app), vec![0, 2, 2, 0, 0, 0]); - // "This page" narrows them to the page in view. - crate::canvas::go_to_page(&mut app, 4); - crate::menus::activate(&mut app, "layout.createGuides", &Value::Null); - ctl(&mut app, "ui.dialog.set", json!({"field": "columns", "value": "3"})); - ctl(&mut app, "ui.dialog.set", json!({"field": "target", "value": "page"})); + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); + assert_eq!(guide_counts(&app), vec![0, 2, 2, 0, 0, 0]); + // "This page" narrows them to the page in view. + crate::canvas::go_to_page(&mut app, 4); + crate::menus::activate(&mut app, "layout.createGuides", &Value::Null); + ctl(&mut app, "ui.dialog.set", json!({"field": "columns", "value": "3"})); + ctl(&mut app, "ui.dialog.set", json!({"field": "target", "value": "page"})); assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); assert_eq!(guide_counts(&app), vec![0, 2, 2, 0, 4, 0]); } From 07a4696a9fdbe0fd6bedd565ef60e941241fee86 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 13:59:35 +0100 Subject: [PATCH 0363/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/tools/src/snap/tests.rs | 74 +++++++++++++++++----------------- 1 file changed, 37 insertions(+), 37 deletions(-) diff --git a/crates/tools/src/snap/tests.rs b/crates/tools/src/snap/tests.rs index f59558ff9..5ac86076b 100644 --- a/crates/tools/src/snap/tests.rs +++ b/crates/tools/src/snap/tests.rs @@ -683,43 +683,43 @@ fn centering_needs_smart_spacing() { assert_eq!(hit.delta.x, 0.0); } - /// A frame drawn on an A4 landscape page from the top margin down to the middle of the page - /// stops at the page's centre line (297.6 pt), not at the hidden baseline grid line 1.4 pt - /// further down (300 pt), as InDesign's smart guides do. - #[test] - fn a_drawn_edge_snaps_to_the_page_centre() { - let a4 = NewDocument { width: 841.89, height: 595.276, ..NewDocument::default() }; - let doc = with_baseline_grid(Document::new(&a4)); - let cache = Cache::new(); - let layout = CanvasLayout::new(&doc, false); - let sel = Selection::default(); - let cx = ctx_on(&doc, &sel, &cache, &layout); - let create = |gesture, y_edges, rect| SnapRequest { - spread: SpreadRef::Doc(0), - gesture, - rect, - x_edges: [false, false, false], - y_edges, - exclude: &[], - exclude_guides: &[], - copying: false, - lengths: [None, None], - angle: None, - radius: 0.0, - pointer: Point::new(0.0, 0.0), - }; - let centre = 595.276 / 2.0; - let hit = snap(&cx, create(Gesture::Create, [false, false, true], Rect::new(500.0, 42.52, 800.0, 298.6))); - assert!((hit.delta.y - (centre - 298.6)).abs() < 1e-6, "{}", hit.delta.y); - // Drawn upwards, the top edge meets it too; a resized edge does as well. - let hit = snap(&cx, create(Gesture::Create, [true, false, false], Rect::new(500.0, 296.0, 800.0, 552.0))); - assert!((hit.delta.y - (centre - 296.0)).abs() < 1e-6, "{}", hit.delta.y); - let hit = snap(&cx, create(Gesture::Resize, [false, false, true], Rect::new(500.0, 42.52, 800.0, 298.6))); - assert!((hit.delta.y - (centre - 298.6)).abs() < 1e-6, "{}", hit.delta.y); - // A moved frame still lines up by its centre only: its bottom edge goes to the baseline. - let hit = snap(&cx, create(Gesture::Move, [true, false, true], Rect::new(500.0, 42.52, 800.0, 298.6))); - assert!((hit.delta.y - 1.4).abs() < 1e-6, "{}", hit.delta.y); - } +/// A frame drawn on an A4 landscape page from the top margin down to the middle of the page +/// stops at the page's centre line (297.6 pt), not at the hidden baseline grid line 1.4 pt +/// further down (300 pt), as InDesign's smart guides do. +#[test] +fn a_drawn_edge_snaps_to_the_page_centre() { + let a4 = NewDocument { width: 841.89, height: 595.276, ..NewDocument::default() }; + let doc = with_baseline_grid(Document::new(&a4)); + let cache = Cache::new(); + let layout = CanvasLayout::new(&doc, false); + let sel = Selection::default(); + let cx = ctx_on(&doc, &sel, &cache, &layout); + let create = |gesture, y_edges, rect| SnapRequest { + spread: SpreadRef::Doc(0), + gesture, + rect, + x_edges: [false, false, false], + y_edges, + exclude: &[], + exclude_guides: &[], + copying: false, + lengths: [None, None], + angle: None, + radius: 0.0, + pointer: Point::new(0.0, 0.0), + }; + let centre = 595.276 / 2.0; + let hit = snap(&cx, create(Gesture::Create, [false, false, true], Rect::new(500.0, 42.52, 800.0, 298.6))); + assert!((hit.delta.y - (centre - 298.6)).abs() < 1e-6, "{}", hit.delta.y); + // Drawn upwards, the top edge meets it too; a resized edge does as well. + let hit = snap(&cx, create(Gesture::Create, [true, false, false], Rect::new(500.0, 296.0, 800.0, 552.0))); + assert!((hit.delta.y - (centre - 296.0)).abs() < 1e-6, "{}", hit.delta.y); + let hit = snap(&cx, create(Gesture::Resize, [false, false, true], Rect::new(500.0, 42.52, 800.0, 298.6))); + assert!((hit.delta.y - (centre - 298.6)).abs() < 1e-6, "{}", hit.delta.y); + // A moved frame still lines up by its centre only: its bottom edge goes to the baseline. + let hit = snap(&cx, create(Gesture::Move, [true, false, true], Rect::new(500.0, 42.52, 800.0, 298.6))); + assert!((hit.delta.y - 1.4).abs() < 1e-6, "{}", hit.delta.y); +} #[test] fn create_does_not_match_spacing() { From 142498f2ca5ed9d1005657d61c0db299c26945a6 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 14:00:45 +0100 Subject: [PATCH 0364/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/properties/tests.rs | 58 +++++++++---------- 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 2ae3bd3ac..e87d359e0 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -710,35 +710,35 @@ fn several_shapes_show_pathfinder_and_intersect_combines_them() { assert!((r.x0 - 200.0).abs() < 0.5 && (r.y1 - 200.0).abs() < 0.5 && (r.x1 - 300.0).abs() < 0.5, "{r:?}"); } - /// Properties › Frame Fitting has Auto-Fit and an Options button, as InDesign's: ticking - /// Auto-Fit makes the picture refit when its frame is resized. - #[test] - fn properties_frame_fitting_sets_auto_fit_and_opens_its_options() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let id = app.run("frame.create", json!({"rect": [72, 72, 272, 172]})).unwrap()["id"].as_u64().unwrap(); - let png = designcraft_render::Rendered { width: 40, height: 20, pixels: vec![200; 40 * 20 * 4] }.to_png(); - app.run("file.place", json!({"base64": designcraft_engine::cmd::base64_encode(&png), "name": "p.png", "frame": id})).unwrap(); - app.run("selection.set", json!({"ids": [id]})).unwrap(); - let graphic = |app: &DesignApp| app.session.active().unwrap().doc.item(designcraft_doc::ids::ItemId(id)).unwrap().graphic().unwrap().clone(); - assert_eq!(graphic(&app).auto_fit, designcraft_doc::Fitting::None); - let mut h = panel(app); - // A checkbox its section disables says so: Invert, with no text wrap. - use egui_kittest::kittest::NodeT; - assert!(h.get_by_label("Invert").accesskit_node().is_disabled()); - assert!(!h.get_by_label("Auto-Fit").accesskit_node().is_disabled()); - h.get_by_label("Auto-Fit").click(); - h.run_steps(3); - assert_ne!(graphic(h.state()).auto_fit, designcraft_doc::Fitting::None, "Auto-Fit is on"); - // The frame resized: the picture follows it. - h.state_mut().run("transform.resize", json!({"from": [72, 72, 272, 172], "to": [72, 72, 372, 272]})).unwrap(); - let g = graphic(h.state()); - let r = g.xf.transform_rect_bbox(designcraft_geom::Rect::new(0.0, 0.0, g.size.0, g.size.1)); - assert!(r.width() > 250.0, "refitted to the larger frame: {r:?}"); - h.get_by_label("Options").click(); - h.run_steps(3); - assert!(h.state().ui.dialog.is_some(), "Frame Fitting Options opens"); - } +/// Properties › Frame Fitting has Auto-Fit and an Options button, as InDesign's: ticking +/// Auto-Fit makes the picture refit when its frame is resized. +#[test] +fn properties_frame_fitting_sets_auto_fit_and_opens_its_options() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [72, 72, 272, 172]})).unwrap()["id"].as_u64().unwrap(); + let png = designcraft_render::Rendered { width: 40, height: 20, pixels: vec![200; 40 * 20 * 4] }.to_png(); + app.run("file.place", json!({"base64": designcraft_engine::cmd::base64_encode(&png), "name": "p.png", "frame": id})).unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + let graphic = |app: &DesignApp| app.session.active().unwrap().doc.item(designcraft_doc::ids::ItemId(id)).unwrap().graphic().unwrap().clone(); + assert_eq!(graphic(&app).auto_fit, designcraft_doc::Fitting::None); + let mut h = panel(app); + // A checkbox its section disables says so: Invert, with no text wrap. + use egui_kittest::kittest::NodeT; + assert!(h.get_by_label("Invert").accesskit_node().is_disabled()); + assert!(!h.get_by_label("Auto-Fit").accesskit_node().is_disabled()); + h.get_by_label("Auto-Fit").click(); + h.run_steps(3); + assert_ne!(graphic(h.state()).auto_fit, designcraft_doc::Fitting::None, "Auto-Fit is on"); + // The frame resized: the picture follows it. + h.state_mut().run("transform.resize", json!({"from": [72, 72, 272, 172], "to": [72, 72, 372, 272]})).unwrap(); + let g = graphic(h.state()); + let r = g.xf.transform_rect_bbox(designcraft_geom::Rect::new(0.0, 0.0, g.size.0, g.size.1)); + assert!(r.width() > 250.0, "refitted to the larger frame: {r:?}"); + h.get_by_label("Options").click(); + h.run_steps(3); + assert!(h.state().ui.dialog.is_some(), "Frame Fitting Options opens"); +} const CYAN: &str = "C=100 M=0 Y=0 K=0"; From 3b86c0ca06b347659f8415255864cb988c51d7da Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 14:06:07 +0100 Subject: [PATCH 0365/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/tools/src/snap/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tools/src/snap/tests.rs b/crates/tools/src/snap/tests.rs index 300d5ad05..f97c637c1 100644 --- a/crates/tools/src/snap/tests.rs +++ b/crates/tools/src/snap/tests.rs @@ -64,7 +64,7 @@ fn ctx_on<'a>(doc: &'a Document, sel: &'a Selection, cache: &'a Cache, layout: & snap: SnapView::FACTORY, unit: Unit::Points, stroke_in_front: false, - loaded: None, + loaded: None, } } From 5e2af169ef84d40dd60854c9ab0a8c191cef5147 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 14:08:04 +0100 Subject: [PATCH 0366/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/properties/tests.rs | 130 ++++++++---------- 1 file changed, 61 insertions(+), 69 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 40226fa84..1ac82ab9f 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -710,78 +710,70 @@ fn several_shapes_show_pathfinder_and_intersect_combines_them() { assert!((r.x0 - 200.0).abs() < 0.5 && (r.y1 - 200.0).abs() < 0.5 && (r.x1 - 300.0).abs() < 0.5, "{r:?}"); } - /// Properties › Text Wrap shows the four offsets under the wrap buttons, as InDesign's - /// Properties panel does: linked at first, so one value sets all four; unlinked, one side. - #[test] - fn properties_text_wrap_shows_and_sets_the_offsets() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let id = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "shape": "rectangle"})).unwrap()["id"].as_u64().unwrap(); - app.run("selection.set", json!({"ids": [id]})).unwrap(); - app.run("object.textWrap", json!({"mode": "boundingBox", "offset": 0})).unwrap(); - let offsets = |app: &DesignApp| app.session.active().unwrap().doc.item(designcraft_doc::ids::ItemId(id)).unwrap().wrap.offsets; - let mut h = panel(app); - // The fields between the Text Wrap heading and Quick Actions: Top, Left, Bottom, Right. - let fields = |h: &Harness<'_, DesignApp>| { - let (top, bottom) = (h.get_by_label("Text Wrap").rect().bottom(), h.get_by_label("Quick Actions").rect().top()); - let mut v: Vec = h - .get_all_by_role(egui::accesskit::Role::TextInput) - .map(|n| n.rect()) - .filter(|r| r.center().y > top && r.center().y < bottom) - .collect(); - v.sort_by(|a, b| (a.top(), a.left()).partial_cmp(&(b.top(), b.left())).unwrap()); - v - }; - let f = fields(&h); - assert_eq!(f.len(), 4, "four offsets: {f:?}"); - let type_in = |h: &mut Harness<'_, DesignApp>, at: egui::Rect, text: &str| { - h.hover_at(at.center()); - h.drag_at(at.center()); - h.drop_at(at.center()); - h.run_steps(2); - h.event(egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }); - h.event(egui::Event::Text(text.into())); - h.key_press(egui::Key::Enter); - h.run_steps(3); - }; - // Linked: the top offset sets all four. - type_in(&mut h, f[0], "12pt"); - assert_eq!(offsets(h.state()), [12.0; 4]); - // Unlinked: the bottom one alone. +/// Properties › Text Wrap shows the four offsets under the wrap buttons, as InDesign's +/// Properties panel does: linked at first, so one value sets all four; unlinked, one side. +#[test] +fn properties_text_wrap_shows_and_sets_the_offsets() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "shape": "rectangle"})).unwrap()["id"].as_u64().unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + app.run("object.textWrap", json!({"mode": "boundingBox", "offset": 0})).unwrap(); + let offsets = |app: &DesignApp| app.session.active().unwrap().doc.item(designcraft_doc::ids::ItemId(id)).unwrap().wrap.offsets; + let mut h = panel(app); + // The fields between the Text Wrap heading and Quick Actions: Top, Left, Bottom, Right. + let fields = |h: &Harness<'_, DesignApp>| { let (top, bottom) = (h.get_by_label("Text Wrap").rect().bottom(), h.get_by_label("Quick Actions").rect().top()); - h.get_all_by_label("Make all settings the same").find(|n| n.rect().center().y > top && n.rect().center().y < bottom).unwrap().click(); + let mut v: Vec = + h.get_all_by_role(egui::accesskit::Role::TextInput).map(|n| n.rect()).filter(|r| r.center().y > top && r.center().y < bottom).collect(); + v.sort_by(|a, b| (a.top(), a.left()).partial_cmp(&(b.top(), b.left())).unwrap()); + v + }; + let f = fields(&h); + assert_eq!(f.len(), 4, "four offsets: {f:?}"); + let type_in = |h: &mut Harness<'_, DesignApp>, at: egui::Rect, text: &str| { + h.hover_at(at.center()); + h.drag_at(at.center()); + h.drop_at(at.center()); h.run_steps(2); - let f = fields(&h); - type_in(&mut h, f[2], "6pt"); - assert_eq!(offsets(h.state()), [12.0, 12.0, 6.0, 12.0], "[top, left, bottom, right]"); - // Two objects with different offsets: a side typed in changes that side on each, and - // each keeps its other three. - let other = h.state_mut().run("frame.create", json!({"rect": [72, 300, 300, 400], "shape": "rectangle"})).unwrap()["id"].as_u64().unwrap(); - h.state_mut().run("object.textWrap", json!({"mode": "contour", "offset": [3, 4, 5, 6], "ids": [other]})).unwrap(); - let of = |h: &Harness<'_, DesignApp>, id: u64| { - h.state().session.active().unwrap().doc.item(designcraft_doc::ids::ItemId(id)).unwrap().wrap.offsets - }; - h.state_mut().run("selection.set", json!({"ids": [id, other]})).unwrap(); + h.event(egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }); + h.event(egui::Event::Text(text.into())); + h.key_press(egui::Key::Enter); h.run_steps(3); - let f = fields(&h); - type_in(&mut h, f[0], "9pt"); - assert_eq!((of(&h, id), of(&h, other)), ([9.0, 12.0, 6.0, 12.0], [9.0, 4.0, 5.0, 6.0]), "the top alone, on each"); - let mode = - |h: &Harness<'_, DesignApp>, id: u64| h.state().session.active().unwrap().doc.item(designcraft_doc::ids::ItemId(id)).unwrap().wrap.mode; - assert_eq!( - (mode(&h, id), mode(&h, other)), - (designcraft_doc::WrapMode::BoundingBox, designcraft_doc::WrapMode::Contour), - "each keeps its mode" - ); - // An object whose offsets are the same starts linked, though the link was off before. - let third = h.state_mut().run("frame.create", json!({"rect": [320, 72, 500, 200], "shape": "rectangle"})).unwrap()["id"].as_u64().unwrap(); - h.state_mut().run("object.textWrap", json!({"mode": "boundingBox", "offset": 4, "ids": [third]})).unwrap(); - h.state_mut().run("selection.set", json!({"ids": [third]})).unwrap(); - h.run_steps(3); - let f = fields(&h); - type_in(&mut h, f[2], "8pt"); - assert_eq!(of(&h, third), [8.0; 4], "linked again for this selection"); - } + }; + // Linked: the top offset sets all four. + type_in(&mut h, f[0], "12pt"); + assert_eq!(offsets(h.state()), [12.0; 4]); + // Unlinked: the bottom one alone. + let (top, bottom) = (h.get_by_label("Text Wrap").rect().bottom(), h.get_by_label("Quick Actions").rect().top()); + h.get_all_by_label("Make all settings the same").find(|n| n.rect().center().y > top && n.rect().center().y < bottom).unwrap().click(); + h.run_steps(2); + let f = fields(&h); + type_in(&mut h, f[2], "6pt"); + assert_eq!(offsets(h.state()), [12.0, 12.0, 6.0, 12.0], "[top, left, bottom, right]"); + // Two objects with different offsets: a side typed in changes that side on each, and + // each keeps its other three. + let other = h.state_mut().run("frame.create", json!({"rect": [72, 300, 300, 400], "shape": "rectangle"})).unwrap()["id"].as_u64().unwrap(); + h.state_mut().run("object.textWrap", json!({"mode": "contour", "offset": [3, 4, 5, 6], "ids": [other]})).unwrap(); + let of = + |h: &Harness<'_, DesignApp>, id: u64| h.state().session.active().unwrap().doc.item(designcraft_doc::ids::ItemId(id)).unwrap().wrap.offsets; + h.state_mut().run("selection.set", json!({"ids": [id, other]})).unwrap(); + h.run_steps(3); + let f = fields(&h); + type_in(&mut h, f[0], "9pt"); + assert_eq!((of(&h, id), of(&h, other)), ([9.0, 12.0, 6.0, 12.0], [9.0, 4.0, 5.0, 6.0]), "the top alone, on each"); + let mode = + |h: &Harness<'_, DesignApp>, id: u64| h.state().session.active().unwrap().doc.item(designcraft_doc::ids::ItemId(id)).unwrap().wrap.mode; + assert_eq!((mode(&h, id), mode(&h, other)), (designcraft_doc::WrapMode::BoundingBox, designcraft_doc::WrapMode::Contour), "each keeps its mode"); + // An object whose offsets are the same starts linked, though the link was off before. + let third = h.state_mut().run("frame.create", json!({"rect": [320, 72, 500, 200], "shape": "rectangle"})).unwrap()["id"].as_u64().unwrap(); + h.state_mut().run("object.textWrap", json!({"mode": "boundingBox", "offset": 4, "ids": [third]})).unwrap(); + h.state_mut().run("selection.set", json!({"ids": [third]})).unwrap(); + h.run_steps(3); + let f = fields(&h); + type_in(&mut h, f[2], "8pt"); + assert_eq!(of(&h, third), [8.0; 4], "linked again for this selection"); +} const CYAN: &str = "C=100 M=0 Y=0 K=0"; From 8cb63ce5f57d2a36ba2dd8dd290387b3e7dba95d Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 14:12:43 +0100 Subject: [PATCH 0367/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/properties/object.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/properties/object.rs b/crates/ui-egui/src/panels/properties/object.rs index ea0fff6aa..3795bcd8a 100644 --- a/crates/ui-egui/src/panels/properties/object.rs +++ b/crates/ui-egui/src/panels/properties/object.rs @@ -555,7 +555,7 @@ fn wrap_offsets(app: &mut DesignApp, ui: &mut Ui, i: &SelInfo) { ] { let ir = sub(b, x, y + 2.0, 17.0, 17.0); icons::paint(ui.painter(), ir, icon, if enabled { t.icon } else { t.text_dim }); - ui.interact(ir, ui.id().with(("prop_wrap_off", k)), Sense::hover()).on_hover_ui(|ui| { + ui.interact(ir, ui.scope_id().with(("prop_wrap_off", k)), Sense::hover()).on_hover_ui(|ui| { crate::rtl::label(ui, tr(tip)); }); let nv = place(ui, sub(b, x + 20.0, y, 76.0, FIELD_H), |ui| { From f1f7ed1fab6985ada5877f74f69d41cc90f06543 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 14:15:30 +0100 Subject: [PATCH 0368/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/properties/tests.rs | 102 +++++++++--------- 1 file changed, 51 insertions(+), 51 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 2af713820..2858392f0 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -710,59 +710,59 @@ fn several_shapes_show_pathfinder_and_intersect_combines_them() { assert!((r.x0 - 200.0).abs() < 0.5 && (r.y1 - 200.0).abs() < 0.5 && (r.x1 - 300.0).abs() < 0.5, "{r:?}"); } - /// The arrow beside Opacity opens a slider, as in InDesign: a drag shows the opacity live and - /// is one undo step; the Opacity link still opens the Effects panel. - #[test] - fn the_opacity_arrow_opens_a_slider_and_a_drag_is_one_undo_step() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let id = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "shape": "rectangle"})).unwrap()["id"].as_u64().unwrap(); - app.run("selection.set", json!({"ids": [id]})).unwrap(); - let opacity = |app: &DesignApp| app.session.active().unwrap().doc.item(designcraft_doc::ids::ItemId(id)).unwrap().opacity; - let steps = undo_steps(&app); - let mut h = Harness::builder().with_size(vec2(320.0, 1400.0)).build_ui_state( - |ui, app: &mut DesignApp| { - let id = egui::Id::new("test_fonts"); - if ui.data(|d| d.get_temp::(id)).is_none() { - crate::theme::install_fonts(ui.ctx(), ""); - ui.data_mut(|d| d.insert_temp(id, true)); - return; - } - app.settle_live_preview(); - show(app, ui); - }, - app, - ); - h.run_steps(3); - assert!(h.query_by_role(egui::accesskit::Role::Slider).is_none()); - h.get_by(|n| n.role() == egui::accesskit::Role::Button && n.label().as_deref() == Some("Opacity")).click(); - h.run_steps(3); - assert!( - h.query_by(|n| n.role() == egui::accesskit::Role::Slider && n.label().as_deref() == Some("Opacity")).is_some(), - "assistive technology names the slider" - ); - let track = h.get_by_role(egui::accesskit::Role::Slider).rect(); - let y = track.center().y; - h.hover_at(egui::pos2(track.right() - 1.0, y)); +/// The arrow beside Opacity opens a slider, as in InDesign: a drag shows the opacity live and +/// is one undo step; the Opacity link still opens the Effects panel. +#[test] +fn the_opacity_arrow_opens_a_slider_and_a_drag_is_one_undo_step() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "shape": "rectangle"})).unwrap()["id"].as_u64().unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + let opacity = |app: &DesignApp| app.session.active().unwrap().doc.item(designcraft_doc::ids::ItemId(id)).unwrap().opacity; + let steps = undo_steps(&app); + let mut h = Harness::builder().with_size(vec2(320.0, 1400.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let id = egui::Id::new("test_fonts"); + if ui.data(|d| d.get_temp::(id)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(id, true)); + return; + } + app.settle_live_preview(); + show(app, ui); + }, + app, + ); + h.run_steps(3); + assert!(h.query_by_role(egui::accesskit::Role::Slider).is_none()); + h.get_by(|n| n.role() == egui::accesskit::Role::Button && n.label().as_deref() == Some("Opacity")).click(); + h.run_steps(3); + assert!( + h.query_by(|n| n.role() == egui::accesskit::Role::Slider && n.label().as_deref() == Some("Opacity")).is_some(), + "assistive technology names the slider" + ); + let track = h.get_by_role(egui::accesskit::Role::Slider).rect(); + let y = track.center().y; + h.hover_at(egui::pos2(track.right() - 1.0, y)); + h.run_steps(1); + h.drag_at(egui::pos2(track.right() - 1.0, y)); + h.run_steps(1); + for k in 1..=5 { + h.hover_at(egui::pos2(track.right() - track.width() * 0.05 * k as f32, y)); h.run_steps(1); - h.drag_at(egui::pos2(track.right() - 1.0, y)); - h.run_steps(1); - for k in 1..=5 { - h.hover_at(egui::pos2(track.right() - track.width() * 0.05 * k as f32, y)); - h.run_steps(1); - assert_eq!(undo_steps(h.state()), steps, "no undo step while dragging"); - } - let previewed = opacity(h.state()); - assert!(previewed < 0.9 && previewed > 0.5, "the drag shows the opacity live: {previewed}"); - // Let go further along than the last move: the release frame changes the value too. - h.drop_at(egui::pos2(track.right() - track.width() * 0.3, y)); - h.run_steps(3); - assert_eq!(undo_steps(h.state()), steps + 1, "the whole drag is one undo step"); - assert!(opacity(h.state()) < previewed, "the release position is applied: {previewed} → {}", opacity(h.state())); - assert_ne!(h.state().ui.open_panel.as_deref(), Some("effects"), "the arrow doesn't open Effects"); - h.state_mut().run("edit.undo", json!({})).unwrap(); - assert_eq!(opacity(h.state()), 1.0); + assert_eq!(undo_steps(h.state()), steps, "no undo step while dragging"); } + let previewed = opacity(h.state()); + assert!(previewed < 0.9 && previewed > 0.5, "the drag shows the opacity live: {previewed}"); + // Let go further along than the last move: the release frame changes the value too. + h.drop_at(egui::pos2(track.right() - track.width() * 0.3, y)); + h.run_steps(3); + assert_eq!(undo_steps(h.state()), steps + 1, "the whole drag is one undo step"); + assert!(opacity(h.state()) < previewed, "the release position is applied: {previewed} → {}", opacity(h.state())); + assert_ne!(h.state().ui.open_panel.as_deref(), Some("effects"), "the arrow doesn't open Effects"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(opacity(h.state()), 1.0); +} const CYAN: &str = "C=100 M=0 Y=0 K=0"; From 888b8a2d901ebaab75d5218828918aca77b20f02 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 14:32:08 +0100 Subject: [PATCH 0369/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/pages.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/pages.rs b/crates/ui-egui/src/panels/pages.rs index 128e51496..6834e56a2 100644 --- a/crates/ui-egui/src/panels/pages.rs +++ b/crates/ui-egui/src/panels/pages.rs @@ -484,7 +484,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { Stroke::NONE, )); let marker = - ui.interact(egui::Rect::from_center_size(c, vec2(12.0, 8.0)), ui.id().with(("section", abs)), Sense::click()); + ui.interact(egui::Rect::from_center_size(c, vec2(12.0, 8.0)), ui.scope_id().with(("section", abs)), Sense::click()); let label = format!( "{}: {}", crate::i18n::tr(&app.ui.language, "Numbering & Section Options…").trim_end_matches('…'), @@ -551,7 +551,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { ui.painter().rect_filled(br, 0.0, BADGE); } ui.painter().galley(c - g.size() / 2.0, g, Color32::WHITE); - let lr = ui.interact(br, ui.id().with(("spread_label", si)), Sense::click()); + let lr = ui.interact(br, ui.scope_id().with(("spread_label", si)), Sense::click()); lr.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, &label)); if lr.clicked() { if editing_parents { From 90185deb8287604d7b87b801dade64b22ab0b793 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 14:35:23 +0100 Subject: [PATCH 0370/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/tests.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 408d56ff2..3d1ef0acc 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -2401,7 +2401,7 @@ fn find_scope_dialog_domain_and_object_changes_release_original_range() { #[test] fn dialog_title_and_actions_fit_scaled_viewports() { for language in ["en", "ar"] { - for size in [egui::vec2(1178.0, 814.0), egui::vec2(589.0, 407.0), egui::vec2(392.0, 271.0), egui::vec2(360.0, 280.0)] { + for size in [egui::vec2(1178.0, 814.0), egui::vec2(589.0, 407.0), egui::vec2(392.0, 271.0), egui::vec2(360.0, 280.0)] { for (command, title, ok, cancel) in [("app.preferences", "Preferences", "OK", "Cancel"), ("app.newDocumentDialog", "New Document", "Create", "Close")] { @@ -2528,7 +2528,7 @@ fn preferences_horizontal_scroll_reaches_clipped_options() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); app.run("app.preferences", json!({})).unwrap(); let ctx = dialog_context("en"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(360.0, 280.0)); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(360.0, 280.0)); for _ in 0..3 { dialog_frame(&mut app, &ctx, screen, vec![]); } @@ -2587,7 +2587,7 @@ fn new_document_vertical_scroll_reaches_every_field_and_preset() { #[test] fn arabic_new_document_fields_remain_reachable_and_editable() { - for size in [egui::vec2(392.0, 271.0), egui::vec2(360.0, 280.0), egui::vec2(1178.0, 814.0)] { + for size in [egui::vec2(392.0, 271.0), egui::vec2(360.0, 280.0), egui::vec2(1178.0, 814.0)] { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); app.ui.language = "ar".into(); app.run("app.newDocumentDialog", json!({})).unwrap(); From 68d96f3ec97740be9bee3af96f8fdcb28a4806b6 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 14:35:28 +0100 Subject: [PATCH 0371/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 32cd4f690..ef4814347 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -6930,7 +6930,7 @@ fn toc_dialog(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { // 200 pt, reserved: a desired width alone is squeezed by the grid to a few characters. // Narrower when the dialog is, so the style selector beside it stays in view. let w = 200.0_f32.min(title_room.max(80.0)); - if ui.add_sized([w, ui.spacing().interact_size.y], egui::TextEdit::singleline(&mut title).horizontal_align(egui::Align::Min)).changed() { + if ui.add_sized([w, ui.spacing().interact_size.y], egui::TextEdit::singleline(&mut title).align(egui::Align2::LEFT_TOP)).changed() { d.fields.insert("title".into(), json!(title)); } crate::rtl::label(ui, tr("Style:")); From 93bbbad231ea12ad39902037a3fed71f67fbe964 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 14:47:56 +0100 Subject: [PATCH 0372/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/new_document/tests.rs | 72 ++++++++++++------------ 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/crates/ui-egui/src/new_document/tests.rs b/crates/ui-egui/src/new_document/tests.rs index 0a364c277..bf63b9c87 100644 --- a/crates/ui-egui/src/new_document/tests.rs +++ b/crates/ui-egui/src/new_document/tests.rs @@ -216,42 +216,42 @@ fn enter_in_the_preset_popup_saves_the_preset_and_keeps_the_dialog() { assert!(!egui::Popup::is_any_open(&h.ctx), "the popup closed"); } - #[test] - fn saved_preset_delete_buttons_keep_the_preview_and_never_create_a_document() { - use egui_kittest::kittest::Queryable as _; - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.savePreset", json!({"name":"Portrait draft","pages":3,"facingPages":false})).unwrap(); - app.run("file.savePreset", json!({"name":"Landscape draft","width":792,"height":612,"pages":2})).unwrap(); - app.run("app.newDocumentDialog", json!({})).unwrap(); - let mut h = crate::test_window::open(app, vec2(1440.0, 900.0)); - h.run_steps(4); - let saved = h.get_by_label("Saved").rect().center(); - crate::test_window::click_at(&mut h, saved); - let portrait = h.get_by_label("Portrait draft").rect().center(); - crate::test_window::click_at(&mut h, portrait); - h.get_by_label("Preview").click(); - h.run_steps(20); - assert!(h.query_by_label("Delete Preset: Portrait draft").is_some(), "the selected preset has its action"); - assert!(h.query_by_label("Delete Preset: [Default]").is_none(), "the factory card cannot be deleted"); - let before = h.state().app.session.active().unwrap().doc.clone(); - let preview = h.state().app.session.new_document_preview(); - let count = h.state().app.session.documents().len(); - let fields = params(h.state().app.ui.dialog.as_ref().unwrap()); - let landscape = h.get_by_label("Landscape draft").rect().center(); - h.event(egui::Event::PointerMoved(landscape)); - h.run_steps(3); - let remove = h.get_by_label("Delete Preset: Landscape draft").rect().center(); - crate::test_window::click_at(&mut h, remove); - assert_eq!(h.state().app.session.prefs.document_presets.iter().map(|p| p.title.as_str()).collect::>(), ["Portrait draft"]); - let remove = h.get_by_label("Delete Preset: Portrait draft").rect().center(); - crate::test_window::click_at(&mut h, remove); - let app = &h.state().app; - assert!(app.session.prefs.document_presets.is_empty()); - assert_eq!(app.session.new_document_preview(), preview); - assert_eq!(app.session.documents().len(), count); - assert_eq!(*app.session.active().unwrap().doc, *before); - assert_eq!(params(app.ui.dialog.as_ref().unwrap()), fields, "deletion does not select another preset or create the preview"); - } +#[test] +fn saved_preset_delete_buttons_keep_the_preview_and_never_create_a_document() { + use egui_kittest::kittest::Queryable as _; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.savePreset", json!({"name":"Portrait draft","pages":3,"facingPages":false})).unwrap(); + app.run("file.savePreset", json!({"name":"Landscape draft","width":792,"height":612,"pages":2})).unwrap(); + app.run("app.newDocumentDialog", json!({})).unwrap(); + let mut h = crate::test_window::open(app, vec2(1440.0, 900.0)); + h.run_steps(4); + let saved = h.get_by_label("Saved").rect().center(); + crate::test_window::click_at(&mut h, saved); + let portrait = h.get_by_label("Portrait draft").rect().center(); + crate::test_window::click_at(&mut h, portrait); + h.get_by_label("Preview").click(); + h.run_steps(20); + assert!(h.query_by_label("Delete Preset: Portrait draft").is_some(), "the selected preset has its action"); + assert!(h.query_by_label("Delete Preset: [Default]").is_none(), "the factory card cannot be deleted"); + let before = h.state().app.session.active().unwrap().doc.clone(); + let preview = h.state().app.session.new_document_preview(); + let count = h.state().app.session.documents().len(); + let fields = params(h.state().app.ui.dialog.as_ref().unwrap()); + let landscape = h.get_by_label("Landscape draft").rect().center(); + h.event(egui::Event::PointerMoved(landscape)); + h.run_steps(3); + let remove = h.get_by_label("Delete Preset: Landscape draft").rect().center(); + crate::test_window::click_at(&mut h, remove); + assert_eq!(h.state().app.session.prefs.document_presets.iter().map(|p| p.title.as_str()).collect::>(), ["Portrait draft"]); + let remove = h.get_by_label("Delete Preset: Portrait draft").rect().center(); + crate::test_window::click_at(&mut h, remove); + let app = &h.state().app; + assert!(app.session.prefs.document_presets.is_empty()); + assert_eq!(app.session.new_document_preview(), preview); + assert_eq!(app.session.documents().len(), count); + assert_eq!(*app.session.active().unwrap().doc, *before); + assert_eq!(params(app.ui.dialog.as_ref().unwrap()), fields, "deletion does not select another preset or create the preview"); +} #[test] fn escape_in_the_preset_popup_closes_only_the_popup() { From b92070c4e8746934ed718af66199e1eb541c0181 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 14:50:52 +0100 Subject: [PATCH 0373/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/new_document.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/new_document.rs b/crates/ui-egui/src/new_document.rs index 1fb2b3807..54fa76a33 100644 --- a/crates/ui-egui/src/new_document.rs +++ b/crates/ui-egui/src/new_document.rs @@ -508,7 +508,7 @@ fn presets(app: &mut DesignApp, ui: &mut Ui, d: &mut Dialog) -> bool { if current == c.key || ui.rect_contains_pointer(resp.rect) { let x = if rtl { resp.rect.left() + 4.0 } else { resp.rect.right() - 26.0 }; let rect = Rect::from_min_size(pos2(x, resp.rect.top() + 4.0), vec2(22.0, 22.0)); - let button = ui.interact(rect, ui.id().with(("delete-preset", &c.key)), Sense::click()); + let button = ui.interact(rect, ui.scope_id().with(("delete-preset", &c.key)), Sense::click()); let label = format!("{}: {}", crate::i18n::tr(&lang, "Delete Preset"), c.label); button.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label.as_str())); if button.hovered() { From 4ebc675164538a7a814553272107a26c24df074b Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 14:53:46 +0100 Subject: [PATCH 0374/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/format/src/tests.rs | 56 +++++++++++++++++++------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/crates/format/src/tests.rs b/crates/format/src/tests.rs index 170e8be9a..0e7ba0d3b 100644 --- a/crates/format/src/tests.rs +++ b/crates/format/src/tests.rs @@ -555,14 +555,14 @@ fn r7a_nullable_document(local_clear: bool, style_clear: bool) -> Document { underline_offset: Some(Some(1.0)), strikethrough_weight: Some(Some(2.0)), strikethrough_offset: Some(Some(1.0)), - kenten_size: Some(Some(14.0)), - kenten_fill_tint: Some(Some(0.3)), - kenten_stroke_tint: Some(Some(0.4)), - kenten_stroke_weight: Some(Some(2.0)), - ruby_font_size: Some(Some(14.0)), - ruby_fill_tint: Some(Some(0.3)), - ruby_stroke_tint: Some(Some(0.4)), - ruby_stroke_weight: Some(Some(2.0)), + kenten_size: Some(Some(14.0)), + kenten_fill_tint: Some(Some(0.3)), + kenten_stroke_tint: Some(Some(0.4)), + kenten_stroke_weight: Some(Some(2.0)), + ruby_font_size: Some(Some(14.0)), + ruby_fill_tint: Some(Some(0.3)), + ruby_stroke_tint: Some(Some(0.4)), + ruby_stroke_weight: Some(Some(2.0)), ..Default::default() }; // Legacy JSON loads as format 1, whose upgrade pins Keep Lines Together and Align Left @@ -572,7 +572,7 @@ fn r7a_nullable_document(local_clear: bool, style_clear: bool) -> Document { start_at: Some(Some(7)), paragraph_kashida_width: Some(Some(0.5)), kinsoku: Some(Some(Default::default())), - list_tab: Some(Some(36.0)), + list_tab: Some(Some(36.0)), keep_all_lines: Some(true), drop_cap_align_left: Some(true), ..Default::default() @@ -587,18 +587,18 @@ fn r7a_nullable_document(local_clear: bool, style_clear: bool) -> Document { underline_offset: Some(None), strikethrough_weight: Some(None), strikethrough_offset: Some(None), - kenten_size: Some(None), - kenten_fill_tint: Some(None), - kenten_stroke_tint: Some(None), - kenten_stroke_weight: Some(None), - ruby_font_size: Some(None), - ruby_fill_tint: Some(None), - ruby_stroke_tint: Some(None), - ruby_stroke_weight: Some(None), + kenten_size: Some(None), + kenten_fill_tint: Some(None), + kenten_stroke_tint: Some(None), + kenten_stroke_weight: Some(None), + ruby_font_size: Some(None), + ruby_fill_tint: Some(None), + ruby_stroke_tint: Some(None), + ruby_stroke_weight: Some(None), ..Default::default() }; - let clear_para = - ParaAttrs { start_at: Some(None), paragraph_kashida_width: Some(None), kinsoku: Some(None), list_tab: Some(None), ..Default::default() }; + let clear_para = + ParaAttrs { start_at: Some(None), paragraph_kashida_width: Some(None), kinsoku: Some(None), list_tab: Some(None), ..Default::default() }; let selected = if style_clear { std::sync::Arc::make_mut(&mut d.styles).paragraph.push(designcraft_doc::styles::ParagraphStyle { name: "Defaults".into(), @@ -639,15 +639,15 @@ fn r7a_assert_nullable_defaults_survive(d: &Document) { assert_eq!(expected.0.paragraph_kashida_width, None); assert_eq!(expected.0.kinsoku, None); assert_eq!(expected.1.leading_aki, None); - assert_eq!(expected.0.list_tab, None); - assert_eq!(expected.1.kenten_size, None); - assert_eq!(expected.1.kenten_fill_tint, None); - assert_eq!(expected.1.kenten_stroke_tint, None); - assert_eq!(expected.1.kenten_stroke_weight, None); - assert_eq!(expected.1.ruby_font_size, None); - assert_eq!(expected.1.ruby_fill_tint, None); - assert_eq!(expected.1.ruby_stroke_tint, None); - assert_eq!(expected.1.ruby_stroke_weight, None); + assert_eq!(expected.0.list_tab, None); + assert_eq!(expected.1.kenten_size, None); + assert_eq!(expected.1.kenten_fill_tint, None); + assert_eq!(expected.1.kenten_stroke_tint, None); + assert_eq!(expected.1.kenten_stroke_weight, None); + assert_eq!(expected.1.ruby_font_size, None); + assert_eq!(expected.1.ruby_fill_tint, None); + assert_eq!(expected.1.ruby_stroke_tint, None); + assert_eq!(expected.1.ruby_stroke_weight, None); // Legacy JSON is format 1: its upgrade pins older defaults on the other styles, so only // the native ZIP compares as the whole document. for (bytes, native) in [(save(d).unwrap(), true), (serde_json::to_vec(d).unwrap(), false)] { From 11ef2cc8404c42ff83fd811d84dd8e51f04300f8 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 15:01:01 +0100 Subject: [PATCH 0375/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/tools/src/select.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index cd47a0338..ff5d0320e 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -776,8 +776,8 @@ impl SelectionTool { } else { out.push(Action::Exec("selection.toggle".into(), json!({"id": id.0}))); } - } else if !cx.selection.contains(id) || (self.direct && !cx.selection.content && cx.doc.item(id).is_some_and(holds_content)) { - // Direct Selection on a selected frame selects its content (a graphic or pasted-in items). + } else if !cx.selection.contains(id) || (self.direct && !cx.selection.content && cx.doc.item(id).is_some_and(holds_content)) { + // Direct Selection on a selected frame selects its content (a graphic or pasted-in items). out.push(Action::Exec("selection.set".into(), json!({"ids": [id.0], "content": self.direct}))); } else if !self.direct && cx.selection.items.len() > 1 { // InDesign: a click on one of several selected objects makes it the From 785c49a1d4e4a5669578397289f07e56fe0d26fd Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 15:08:12 +0100 Subject: [PATCH 0376/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/tools/src/select.rs | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index f073d063e..f6b42377d 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -703,19 +703,19 @@ impl SelectionTool { self.drag = Drag::Anchor { id, si, ai, handle, start: p, at }; return vec![Action::Begin(if handle.is_some() { "Move Direction Handle".into() } else { "Move Anchor".into() })]; } - // As in InDesign, the Direct Selection tool pressed on a corner or anchor of an object - // that isn't selected selects it and moves just that point (Chris Nielsen's "The - // InDesign Toolbox", 10:10: click outside, then pull a frame's corner). - if self.direct - && !ev.mods.shift - && let Some((_, hit)) = cx.hit(p) - && !cx.selection.contains(hit) - && let Some((id, si, ai, None)) = anchor_at_in(cx, &[hit], p) - { - let at = anchor_spread_point(cx, id, si, ai); - self.drag = Drag::Anchor { id, si, ai, handle: None, start: p, at }; - return vec![Action::Exec("selection.set".into(), json!({"ids": [id], "content": true})), Action::Begin("Move Anchor".into())]; - } + // As in InDesign, the Direct Selection tool pressed on a corner or anchor of an object + // that isn't selected selects it and moves just that point (Chris Nielsen's "The + // InDesign Toolbox", 10:10: click outside, then pull a frame's corner). + if self.direct + && !ev.mods.shift + && let Some((_, hit)) = cx.hit(p) + && !cx.selection.contains(hit) + && let Some((id, si, ai, None)) = anchor_at_in(cx, &[hit], p) + { + let at = anchor_spread_point(cx, id, si, ai); + self.drag = Drag::Anchor { id, si, ai, handle: None, start: p, at }; + return vec![Action::Exec("selection.set".into(), json!({"ids": [id], "content": true})), Action::Begin("Move Anchor".into())]; + } // A selected placed graphic's own handles resize it inside its frame (the // frame's anchors, under Direct Selection, come first). if let Some((id, h)) = content_handle_at(cx, p) From 5f96d2b3ffa3410695a0fff0bbe0d3029cdc4345 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 15:14:53 +0100 Subject: [PATCH 0377/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/pages.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/pages.rs b/crates/ui-egui/src/panels/pages.rs index ae951787c..10a53e175 100644 --- a/crates/ui-egui/src/panels/pages.rs +++ b/crates/ui-egui/src/panels/pages.rs @@ -533,7 +533,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { ui.painter().rect_filled(br, 0.0, BADGE); } ui.painter().galley(c - g.size() / 2.0, g, ink); - let lr = ui.interact(br, ui.id().with(("spread_label", si)), Sense::click()); + let lr = ui.interact(br, ui.scope_id().with(("spread_label", si)), Sense::click()); // A click goes to the spread, so assistive technology hears a button. lr.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &label)); if lr.clicked() { From 5363ef8a4c40f312802c718c6b5e42983282c993 Mon Sep 17 00:00:00 2001 From: Youssef Azriouil Date: Thu, 29 Oct 2026 15:26:14 +0100 Subject: [PATCH 0378/1349] Docs: Greek in the localization hyphenation list Greek patterns are bundled on main; the localization parity list now names them next to Dutch. --- docs/localization-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 599358c61..d300a0b22 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -68,7 +68,7 @@ eight of the twelve (cs, da, el, en_GB, fi, hu, it, nb, nl, pl, ro, ru, sq, sv, ## Document languages InDesign 2026 hyphenates and spell-checks ~40 languages (Hunspell and Duden dictionaries). -DesignCraft hyphenates **English, Spanish, Portuguese, Norwegian and Dutch** and spell-checks **English** only. Text language +DesignCraft hyphenates **English, Spanish, Portuguese, Norwegian, Greek and Dutch** and spell-checks **English** only. Text language can be set per paragraph and character (Properties, Character panel) and drives quotes and locale shaping. See [typography-parity.md](typography-parity.md). From 3959cafd12e5cd965a73367f06c23b615faaa25b Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 15:26:16 +0100 Subject: [PATCH 0379/1349] Tests: the branch's dialog tests beside main's dialog test helpers (dialogs/tests.rs) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 49 ----------------------------- crates/ui-egui/src/dialogs/tests.rs | 49 +++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 49 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 4801278db..ef6869f95 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -186,55 +186,6 @@ fn color_theme(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { mod color_theme_tests { use super::*; - #[test] - fn on_a_page_without_a_section_the_window_is_new_section() { - // Chris Nielsen's "Numbering Page Sections" (4:43): page 3 selected, the Pages panel menu's - // Numbering & Section Options opens New Section with Start Section on and 1 offered. - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"pages": 6, "facingPages": true})).unwrap(); - app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 800.0))); - crate::canvas::go_to_page(&mut app, 2); - crate::menus::activate(&mut app, "layout.section", &Value::Null); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!( - (d.n("page"), d.b("newSection"), d.b("startSection"), d.b("automatic"), d.s("startNumber")), - (Some(3.0), true, true, true, "1".into()) - ); - let ctx = dialog_context("en"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0)); - for _ in 0..3 { - dialog_frame(&mut app, &ctx, screen, vec![]); - } - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - visible_label(&labels, screen, "New Section"); - // Typing a number in the field chooses Start Page Numbering at; OK: page 3 is page 5 (odd, - // so a facing page stays on the right). - let field = visible_label(&labels, screen, "1"); - click_dialog(&mut app, &ctx, screen, field.center()); - dialog_frame( - &mut app, - &ctx, - screen, - vec![ - egui::Event::Key { key: egui::Key::End, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }, - egui::Event::Key { key: egui::Key::Backspace, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }, - egui::Event::Text("5".into()), - ], - ); - assert!(!app.ui.dialog.as_ref().unwrap().b("automatic"), "typing chose Start Page Numbering at"); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "OK").center()); - assert!(app.ui.dialog.is_none()); - assert_eq!(app.session.active().unwrap().doc.page_name(2), "5"); - // Opened again on that page, it is Numbering & Section Options, showing the section. - crate::menus::activate(&mut app, "layout.section", &Value::Null); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.b("newSection"), d.b("startSection"), d.b("automatic"), d.s("startNumber")), (false, true, false, "5".into())); - let labels = (0..4).map(|_| dialog_frame(&mut app, &ctx, screen, vec![])).last().unwrap(); - visible_label(&labels, screen, "Numbering & Section Options"); - assert!(!labels.iter().any(|(t, _, _)| t == "New Section")); - } - #[test] fn color_theme_cancel_is_read_only_and_confirm_adds_the_preview() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 84cbf3bea..23bc23ef9 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3521,3 +3521,52 @@ fn character_style_options_set_the_digits() { assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi)); } + +#[test] +fn on_a_page_without_a_section_the_window_is_new_section() { + // Chris Nielsen's "Numbering Page Sections" (4:43): page 3 selected, the Pages panel menu's + // Numbering & Section Options opens New Section with Start Section on and 1 offered. + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 6, "facingPages": true})).unwrap(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 800.0))); + crate::canvas::go_to_page(&mut app, 2); + crate::menus::activate(&mut app, "layout.section", &Value::Null); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!( + (d.n("page"), d.b("newSection"), d.b("startSection"), d.b("automatic"), d.s("startNumber")), + (Some(3.0), true, true, true, "1".into()) + ); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0)); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + visible_label(&labels, screen, "New Section"); + // Typing a number in the field chooses Start Page Numbering at; OK: page 3 is page 5 (odd, + // so a facing page stays on the right). + let field = visible_label(&labels, screen, "1"); + click_dialog(&mut app, &ctx, screen, field.center()); + dialog_frame( + &mut app, + &ctx, + screen, + vec![ + egui::Event::Key { key: egui::Key::End, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }, + egui::Event::Key { key: egui::Key::Backspace, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }, + egui::Event::Text("5".into()), + ], + ); + assert!(!app.ui.dialog.as_ref().unwrap().b("automatic"), "typing chose Start Page Numbering at"); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "OK").center()); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.active().unwrap().doc.page_name(2), "5"); + // Opened again on that page, it is Numbering & Section Options, showing the section. + crate::menus::activate(&mut app, "layout.section", &Value::Null); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.b("newSection"), d.b("startSection"), d.b("automatic"), d.s("startNumber")), (false, true, false, "5".into())); + let labels = (0..4).map(|_| dialog_frame(&mut app, &ctx, screen, vec![])).last().unwrap(); + visible_label(&labels, screen, "Numbering & Section Options"); + assert!(!labels.iter().any(|(t, _, _)| t == "New Section")); +} From b0c1bc47479a8582163a50c7f693c82aaf23ced5 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 15:26:17 +0100 Subject: [PATCH 0380/1349] Tests: the branch's dialog tests beside main's dialog test helpers (dialogs/tests.rs) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 113 ---------------------------- crates/ui-egui/src/dialogs/tests.rs | 113 ++++++++++++++++++++++++++++ 2 files changed, 113 insertions(+), 113 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 1eccf0ac3..4704cc870 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -186,119 +186,6 @@ fn color_theme(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { mod color_theme_tests { use super::*; - #[test] - fn corner_options_dialog_sets_each_corner_with_preview_and_one_undo_step() { - use designcraft_geom::corners::CornerShape; - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let id = app.run("frame.create", json!({"rect": [72, 72, 360, 360]})).unwrap()["id"].as_u64().unwrap(); - app.run("selection.set", json!({"ids": [id]})).unwrap(); - let corners = |app: &DesignApp| app.session.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().corners.corners; - let undo = |app: &DesignApp| app.session.doc().unwrap().history.undo.len(); - let set = |app: &mut DesignApp, k: &str, v: Value| { - app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v); - }; - let u0 = undo(&app); - let ctx = dialog_context("en"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0)); - // Object › Corner Options… opens InDesign's dialog, not a form of the command's params. - crate::menus::activate(&mut app, "object.cornerOptions", &Value::Null); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some(CORNER_OPTIONS)); - dialog_frame(&mut app, &ctx, screen, vec![]); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - for expected in ["Corner Options", "Corner Size and Shape:", "Preview", "OK", "Cancel"] { - visible_label(&labels, screen, expected); - } - assert!(!labels.iter().any(|(t, _, _)| t.trim() == "Ids"), "no raw command fields"); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.s("size1"), d.s("shape1"), d.b("link")), ("0p0".into(), "none".into(), true), "seeded from the frame, linked"); - // Linked: a corner changed is all four. - set(&mut app, "size0", json!("1p0")); - dialog_frame(&mut app, &ctx, screen, vec![]); - assert_eq!(app.ui.dialog.as_ref().unwrap().s("size2"), "1p0"); - // Unlinked, only the top-right corner rounds, as in the tutorial. - set(&mut app, "link", json!(false)); - for k in 0..4 { - set(&mut app, &format!("size{k}"), json!("0")); - } - set(&mut app, "size1", json!("3 cm")); - set(&mut app, "shape1", json!("rounded")); - set(&mut app, "preview", json!(true)); - dialog_frame(&mut app, &ctx, screen, vec![]); - assert_eq!(corners(&app)[1].shape, CornerShape::Rounded, "Preview shows it"); - assert_eq!(undo(&app), u0, "without an undo step"); - set(&mut app, "preview", json!(false)); - dialog_frame(&mut app, &ctx, screen, vec![]); - assert_eq!(corners(&app)[1].shape, CornerShape::None, "Preview off puts it back"); - set(&mut app, "preview", json!(true)); - dialog_frame(&mut app, &ctx, screen, vec![]); - confirm(&mut app).unwrap(); - let c = corners(&app); - assert_eq!(c.map(|c| c.shape), [CornerShape::None, CornerShape::Rounded, CornerShape::None, CornerShape::None]); - assert!((c[1].size - 3.0 / 2.54 * 72.0).abs() < 1e-6, "{}", c[1].size); - assert_eq!(undo(&app), u0 + 1, "one undo step"); - // Reopened, it shows the frame's corners, no longer linked. - crate::menus::activate(&mut app, "object.cornerOptions", &Value::Null); - dialog_frame(&mut app, &ctx, screen, vec![]); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.s("shape1"), d.s("shape0"), d.b("link")), ("rounded".into(), "none".into(), false)); - // A size that does not parse keeps the dialog open with the error; so does a shape the - // dialog doesn't offer (rather than another shape taking its place). - set(&mut app, "size0", json!("abc")); - assert!(confirm(&mut app).is_err()); - assert!(app.ui.dialog.is_some()); - set(&mut app, "size0", json!("0")); - set(&mut app, "shape0", json!("spiky")); - assert!(confirm(&mut app).is_err()); - assert!(app.ui.dialog.is_some()); - cancel(&mut app); - assert_eq!(corners(&app), c); - } - - /// Several objects: the dialog shows the first one's corners, and OK sets only the corners - /// edited; the others keep each object's own. A linked edit sets all four. - #[test] - fn corner_options_keep_each_objects_untouched_corners() { - use designcraft_geom::corners::CornerShape; - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let a = app.run("frame.create", json!({"rect": [72, 72, 200, 200]})).unwrap()["id"].as_u64().unwrap(); - let b = app.run("frame.create", json!({"rect": [272, 72, 400, 200]})).unwrap()["id"].as_u64().unwrap(); - app.run("object.cornerOptions", json!({"ids": [b], "shape": "bevel", "size": 12})).unwrap(); - app.run("selection.set", json!({"ids": [a, b]})).unwrap(); - let corners = |app: &DesignApp, id: u64| app.session.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().corners.corners; - let set = |app: &mut DesignApp, k: &str, v: Value| { - app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v); - }; - let ctx = dialog_context("en"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0)); - let b0 = corners(&app, b); - // Unlinked: only the top-right corner rounds, on both. - crate::menus::activate(&mut app, "object.cornerOptions", &Value::Null); - dialog_frame(&mut app, &ctx, screen, vec![]); - set(&mut app, "link", json!(false)); - set(&mut app, "size1", json!("1p0")); - set(&mut app, "shape1", json!("rounded")); - dialog_frame(&mut app, &ctx, screen, vec![]); - confirm(&mut app).unwrap(); - let (ca, cb) = (corners(&app, a), corners(&app, b)); - assert_eq!(ca.map(|c| c.shape), [CornerShape::None, CornerShape::Rounded, CornerShape::None, CornerShape::None]); - assert_eq!(cb.map(|c| c.shape), [CornerShape::Bevel, CornerShape::Rounded, CornerShape::Bevel, CornerShape::Bevel], "b keeps its others"); - assert_eq!((cb[0], cb[2], cb[3]), (b0[0], b0[2], b0[3])); - assert_eq!(ca[1], cb[1]); - // Linked: a corner set to the first object's own value still sets all four, on both. - crate::menus::activate(&mut app, "object.cornerOptions", &Value::Null); - dialog_frame(&mut app, &ctx, screen, vec![]); - set(&mut app, "link", json!(true)); - dialog_frame(&mut app, &ctx, screen, vec![]); - set(&mut app, "size0", json!("0p6")); - dialog_frame(&mut app, &ctx, screen, vec![]); - confirm(&mut app).unwrap(); - let (ca, cb) = (corners(&app, a), corners(&app, b)); - assert_eq!(ca, cb, "all four, on both"); - assert!(ca.iter().all(|c| c.shape == CornerShape::None && (c.size - 6.0).abs() < 1e-6), "{ca:?}"); - } - #[test] fn color_theme_cancel_is_read_only_and_confirm_adds_the_preview() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 84cbf3bea..7d91c4533 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3521,3 +3521,116 @@ fn character_style_options_set_the_digits() { assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi)); } + +#[test] +fn corner_options_dialog_sets_each_corner_with_preview_and_one_undo_step() { + use designcraft_geom::corners::CornerShape; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [72, 72, 360, 360]})).unwrap()["id"].as_u64().unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + let corners = |app: &DesignApp| app.session.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().corners.corners; + let undo = |app: &DesignApp| app.session.doc().unwrap().history.undo.len(); + let set = |app: &mut DesignApp, k: &str, v: Value| { + app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v); + }; + let u0 = undo(&app); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0)); + // Object › Corner Options… opens InDesign's dialog, not a form of the command's params. + crate::menus::activate(&mut app, "object.cornerOptions", &Value::Null); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some(CORNER_OPTIONS)); + dialog_frame(&mut app, &ctx, screen, vec![]); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + for expected in ["Corner Options", "Corner Size and Shape:", "Preview", "OK", "Cancel"] { + visible_label(&labels, screen, expected); + } + assert!(!labels.iter().any(|(t, _, _)| t.trim() == "Ids"), "no raw command fields"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.s("size1"), d.s("shape1"), d.b("link")), ("0p0".into(), "none".into(), true), "seeded from the frame, linked"); + // Linked: a corner changed is all four. + set(&mut app, "size0", json!("1p0")); + dialog_frame(&mut app, &ctx, screen, vec![]); + assert_eq!(app.ui.dialog.as_ref().unwrap().s("size2"), "1p0"); + // Unlinked, only the top-right corner rounds, as in the tutorial. + set(&mut app, "link", json!(false)); + for k in 0..4 { + set(&mut app, &format!("size{k}"), json!("0")); + } + set(&mut app, "size1", json!("3 cm")); + set(&mut app, "shape1", json!("rounded")); + set(&mut app, "preview", json!(true)); + dialog_frame(&mut app, &ctx, screen, vec![]); + assert_eq!(corners(&app)[1].shape, CornerShape::Rounded, "Preview shows it"); + assert_eq!(undo(&app), u0, "without an undo step"); + set(&mut app, "preview", json!(false)); + dialog_frame(&mut app, &ctx, screen, vec![]); + assert_eq!(corners(&app)[1].shape, CornerShape::None, "Preview off puts it back"); + set(&mut app, "preview", json!(true)); + dialog_frame(&mut app, &ctx, screen, vec![]); + confirm(&mut app).unwrap(); + let c = corners(&app); + assert_eq!(c.map(|c| c.shape), [CornerShape::None, CornerShape::Rounded, CornerShape::None, CornerShape::None]); + assert!((c[1].size - 3.0 / 2.54 * 72.0).abs() < 1e-6, "{}", c[1].size); + assert_eq!(undo(&app), u0 + 1, "one undo step"); + // Reopened, it shows the frame's corners, no longer linked. + crate::menus::activate(&mut app, "object.cornerOptions", &Value::Null); + dialog_frame(&mut app, &ctx, screen, vec![]); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.s("shape1"), d.s("shape0"), d.b("link")), ("rounded".into(), "none".into(), false)); + // A size that does not parse keeps the dialog open with the error; so does a shape the + // dialog doesn't offer (rather than another shape taking its place). + set(&mut app, "size0", json!("abc")); + assert!(confirm(&mut app).is_err()); + assert!(app.ui.dialog.is_some()); + set(&mut app, "size0", json!("0")); + set(&mut app, "shape0", json!("spiky")); + assert!(confirm(&mut app).is_err()); + assert!(app.ui.dialog.is_some()); + cancel(&mut app); + assert_eq!(corners(&app), c); +} + +/// Several objects: the dialog shows the first one's corners, and OK sets only the corners +/// edited; the others keep each object's own. A linked edit sets all four. +#[test] +fn corner_options_keep_each_objects_untouched_corners() { + use designcraft_geom::corners::CornerShape; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let a = app.run("frame.create", json!({"rect": [72, 72, 200, 200]})).unwrap()["id"].as_u64().unwrap(); + let b = app.run("frame.create", json!({"rect": [272, 72, 400, 200]})).unwrap()["id"].as_u64().unwrap(); + app.run("object.cornerOptions", json!({"ids": [b], "shape": "bevel", "size": 12})).unwrap(); + app.run("selection.set", json!({"ids": [a, b]})).unwrap(); + let corners = |app: &DesignApp, id: u64| app.session.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().corners.corners; + let set = |app: &mut DesignApp, k: &str, v: Value| { + app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v); + }; + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0)); + let b0 = corners(&app, b); + // Unlinked: only the top-right corner rounds, on both. + crate::menus::activate(&mut app, "object.cornerOptions", &Value::Null); + dialog_frame(&mut app, &ctx, screen, vec![]); + set(&mut app, "link", json!(false)); + set(&mut app, "size1", json!("1p0")); + set(&mut app, "shape1", json!("rounded")); + dialog_frame(&mut app, &ctx, screen, vec![]); + confirm(&mut app).unwrap(); + let (ca, cb) = (corners(&app, a), corners(&app, b)); + assert_eq!(ca.map(|c| c.shape), [CornerShape::None, CornerShape::Rounded, CornerShape::None, CornerShape::None]); + assert_eq!(cb.map(|c| c.shape), [CornerShape::Bevel, CornerShape::Rounded, CornerShape::Bevel, CornerShape::Bevel], "b keeps its others"); + assert_eq!((cb[0], cb[2], cb[3]), (b0[0], b0[2], b0[3])); + assert_eq!(ca[1], cb[1]); + // Linked: a corner set to the first object's own value still sets all four, on both. + crate::menus::activate(&mut app, "object.cornerOptions", &Value::Null); + dialog_frame(&mut app, &ctx, screen, vec![]); + set(&mut app, "link", json!(true)); + dialog_frame(&mut app, &ctx, screen, vec![]); + set(&mut app, "size0", json!("0p6")); + dialog_frame(&mut app, &ctx, screen, vec![]); + confirm(&mut app).unwrap(); + let (ca, cb) = (corners(&app, a), corners(&app, b)); + assert_eq!(ca, cb, "all four, on both"); + assert!(ca.iter().all(|c| c.shape == CornerShape::None && (c.size - 6.0).abs() < 1e-6), "{ca:?}"); +} From 9ffc1ae379bdfe5e000b7a60ab92343a74d46fab Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 15:26:17 +0100 Subject: [PATCH 0381/1349] Tests: the branch's dialog tests beside main's dialog test helpers (dialogs/tests.rs) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 54 ----------------------------- crates/ui-egui/src/dialogs/tests.rs | 54 +++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 54 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a2265c288..858f08a22 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -186,60 +186,6 @@ fn color_theme(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { mod color_theme_tests { use super::*; - /// With no document open, Preferences has Units & Increments, as InDesign's: OK keeps them - /// for new documents, and New Document opens in them (Lollo's inches, set once). - #[test] - fn preferences_with_no_document_set_the_units_of_new_documents() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - crate::menus::activate(&mut app, "app.preferences", &Value::Null); - let mut d = app.ui.dialog.take().expect("Preferences"); - assert!(d.b("defaults"), "for new documents"); - let ctx = dialog_context("en"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0)); - app.ui.dialog = Some(d.clone()); - let mut labels = vec![]; - for _ in 0..3 { - labels = dialog_frame(&mut app, &ctx, screen, vec![]); - } - assert!(labels.iter().any(|(t, _, _)| t == "Units & Increments"), "listed with no document: {labels:?}"); - d.fields.insert("horizontalUnits".into(), json!("inches")); - d.fields.insert("verticalUnits".into(), json!("inches")); - d.fields.insert("keyboardIncrement".into(), json!("0.5 pt")); - app.ui.dialog = Some(d); - confirm(&mut app).unwrap(); - let du = app.session.prefs.default_units; - assert_eq!((du.horizontal_units, du.vertical_units, du.keyboard_increment), (Unit::Inches, Unit::Inches, 0.5)); - assert!(app.session.active().is_none(), "no document made"); - // A Cursor Key of 0 or text that isn't a measure is refused, keeping the dialog open and - // the saved values, the other preferences' too; a Kerning/Tracking of 0.5 is kept as it is. - let scale = app.session.prefs.scale_strokes; - for bad in [json!({"keyboardIncrement": "0 pt"}), json!({"keyboardIncrement": "wide"}), json!({"kerningIncrement": "lots"})] { - let mut d = Dialog::new("preferences", json!({"defaults": true, "horizontalUnits": "inches", "scaleStrokes": !scale})); - for (k, v) in bad.as_object().unwrap() { - d.fields.insert(k.clone(), v.clone()); - } - app.ui.dialog = Some(d); - assert!(confirm(&mut app).is_err(), "{bad}"); - assert!(app.ui.dialog.as_ref().is_some_and(|d| d.id == "preferences"), "still open: {bad}"); - assert_eq!(app.session.prefs.default_units.keyboard_increment, 0.5, "{bad}"); - assert_eq!(app.session.prefs.scale_strokes, scale, "no other preference saved: {bad}"); - } - app.ui.dialog = Some(Dialog::new("preferences", json!({"defaults": true, "horizontalUnits": "inches", "kerningIncrement": "0.5"}))); - confirm(&mut app).unwrap(); - assert_eq!(app.session.prefs.default_units.kerning_increment, 0.5, "not rounded up to 1"); - // New Document opens in inches, and the document it makes has inch rulers. - crate::menus::activate(&mut app, "app.newDocumentDialog", &Value::Null); - let nd = app.ui.dialog.clone().expect("New Document"); - assert_eq!(nd.fields["units"], json!("inches")); - assert_eq!(nd.s("width"), designcraft_geom::format_measure(612.0, Unit::Inches)); - confirm(&mut app).unwrap(); - let st = &app.session.doc().unwrap().doc.settings; - assert_eq!((st.horizontal_units, st.vertical_units, st.keyboard_increment), (Unit::Inches, Unit::Inches, 0.5)); - // With the document open, Preferences edits that document's units, not the defaults. - crate::menus::activate(&mut app, "app.preferences", &Value::Null); - assert!(!app.ui.dialog.as_ref().unwrap().b("defaults")); - } - #[test] fn color_theme_cancel_is_read_only_and_confirm_adds_the_preview() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 84cbf3bea..7b0c8b5ba 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3521,3 +3521,57 @@ fn character_style_options_set_the_digits() { assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi)); } + +/// With no document open, Preferences has Units & Increments, as InDesign's: OK keeps them +/// for new documents, and New Document opens in them (Lollo's inches, set once). +#[test] +fn preferences_with_no_document_set_the_units_of_new_documents() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + crate::menus::activate(&mut app, "app.preferences", &Value::Null); + let mut d = app.ui.dialog.take().expect("Preferences"); + assert!(d.b("defaults"), "for new documents"); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0)); + app.ui.dialog = Some(d.clone()); + let mut labels = vec![]; + for _ in 0..3 { + labels = dialog_frame(&mut app, &ctx, screen, vec![]); + } + assert!(labels.iter().any(|(t, _, _)| t == "Units & Increments"), "listed with no document: {labels:?}"); + d.fields.insert("horizontalUnits".into(), json!("inches")); + d.fields.insert("verticalUnits".into(), json!("inches")); + d.fields.insert("keyboardIncrement".into(), json!("0.5 pt")); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + let du = app.session.prefs.default_units; + assert_eq!((du.horizontal_units, du.vertical_units, du.keyboard_increment), (Unit::Inches, Unit::Inches, 0.5)); + assert!(app.session.active().is_none(), "no document made"); + // A Cursor Key of 0 or text that isn't a measure is refused, keeping the dialog open and + // the saved values, the other preferences' too; a Kerning/Tracking of 0.5 is kept as it is. + let scale = app.session.prefs.scale_strokes; + for bad in [json!({"keyboardIncrement": "0 pt"}), json!({"keyboardIncrement": "wide"}), json!({"kerningIncrement": "lots"})] { + let mut d = Dialog::new("preferences", json!({"defaults": true, "horizontalUnits": "inches", "scaleStrokes": !scale})); + for (k, v) in bad.as_object().unwrap() { + d.fields.insert(k.clone(), v.clone()); + } + app.ui.dialog = Some(d); + assert!(confirm(&mut app).is_err(), "{bad}"); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.id == "preferences"), "still open: {bad}"); + assert_eq!(app.session.prefs.default_units.keyboard_increment, 0.5, "{bad}"); + assert_eq!(app.session.prefs.scale_strokes, scale, "no other preference saved: {bad}"); + } + app.ui.dialog = Some(Dialog::new("preferences", json!({"defaults": true, "horizontalUnits": "inches", "kerningIncrement": "0.5"}))); + confirm(&mut app).unwrap(); + assert_eq!(app.session.prefs.default_units.kerning_increment, 0.5, "not rounded up to 1"); + // New Document opens in inches, and the document it makes has inch rulers. + crate::menus::activate(&mut app, "app.newDocumentDialog", &Value::Null); + let nd = app.ui.dialog.clone().expect("New Document"); + assert_eq!(nd.fields["units"], json!("inches")); + assert_eq!(nd.s("width"), designcraft_geom::format_measure(612.0, Unit::Inches)); + confirm(&mut app).unwrap(); + let st = &app.session.doc().unwrap().doc.settings; + assert_eq!((st.horizontal_units, st.vertical_units, st.keyboard_increment), (Unit::Inches, Unit::Inches, 0.5)); + // With the document open, Preferences edits that document's units, not the defaults. + crate::menus::activate(&mut app, "app.preferences", &Value::Null); + assert!(!app.ui.dialog.as_ref().unwrap().b("defaults")); +} From f713e97a7f7b2af46f8d51df75d729f458f4761b Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 15:26:17 +0100 Subject: [PATCH 0382/1349] Tests: the branch's dialog tests beside main's dialog test helpers (dialogs/tests.rs) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 19 ------------------- crates/ui-egui/src/dialogs/tests.rs | 19 +++++++++++++++++++ 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 0506af15f..45ffc593b 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -186,25 +186,6 @@ fn color_theme(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { mod color_theme_tests { use super::*; - /// Preferences › File Handling shows the number of recent items as a whole number, as - /// InDesign's does ("20"; it read "20.0"). - #[test] - fn file_handling_shows_the_recent_items_count_as_a_whole_number() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("app.preferences", json!({})).unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("section".into(), json!("files")); - let ctx = dialog_context("en"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 700.0)); - dialog_frame(&mut app, &ctx, screen, vec![]); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - visible_label(&labels, screen, "Number of Recent Items to Display:"); - let count = app.ui.dialog.as_ref().unwrap().n("recentFilesMax").unwrap(); - assert_eq!(count, 20.0, "InDesign's default"); - visible_label(&labels, screen, &format!("{count}")); - assert!(!labels.iter().any(|(t, _, _)| t.trim() == format!("{count:.1}")), "no decimal shown"); - } - #[test] fn color_theme_cancel_is_read_only_and_confirm_adds_the_preview() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 84cbf3bea..167158d84 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3521,3 +3521,22 @@ fn character_style_options_set_the_digits() { assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi)); } + +/// Preferences › File Handling shows the number of recent items as a whole number, as +/// InDesign's does ("20"; it read "20.0"). +#[test] +fn file_handling_shows_the_recent_items_count_as_a_whole_number() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("app.preferences", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("section".into(), json!("files")); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 700.0)); + dialog_frame(&mut app, &ctx, screen, vec![]); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + visible_label(&labels, screen, "Number of Recent Items to Display:"); + let count = app.ui.dialog.as_ref().unwrap().n("recentFilesMax").unwrap(); + assert_eq!(count, 20.0, "InDesign's default"); + visible_label(&labels, screen, &format!("{count}")); + assert!(!labels.iter().any(|(t, _, _)| t.trim() == format!("{count:.1}")), "no decimal shown"); +} From 788061a9ae8350c69c45eb5d725272d75b7df5d6 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 15:26:18 +0100 Subject: [PATCH 0383/1349] Tests: the branch's dialog tests beside main's dialog test helpers (dialogs/tests.rs) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 58 ----------------------------- crates/ui-egui/src/dialogs/tests.rs | 58 +++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 58 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index cdcccc954..85ad65dce 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -186,64 +186,6 @@ fn color_theme(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { mod color_theme_tests { use super::*; - /// Collapsing advanced TOC controls changes visibility without discarding their values. - #[test] - fn toc_more_options_preserves_hidden_settings() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.newSample", json!({})).unwrap(); - open_toc(&mut app); - app.ui.dialog.as_mut().unwrap().fields.insert( - "included".into(), - json!([{ - "style": "Headline", "level": 3, "separator": " ^t", "pageNumber": "before", - "pageNumberStyle": "Accent", "separatorStyle": "Emphasis", "sort": true - }]), - ); - let before = toc_params(&app, app.ui.dialog.as_ref().unwrap()); - let revision = app.session.doc().unwrap().revision; - let ctx = dialog_context("en"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); - for _ in 0..3 { - dialog_frame(&mut app, &ctx, screen, vec![]); - } - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - visible_label(&labels, screen, "Between Entry and Number:"); - click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "Fewer Options").center()); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - assert!(!labels.iter().any(|(text, _, _)| text == "Between Entry and Number:")); - visible_label(&labels, screen, "Entry Style:"); - assert_eq!(toc_params(&app, app.ui.dialog.as_ref().unwrap()), before); - click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "More Options").center()); - for _ in 0..3 { - dialog_frame(&mut app, &ctx, screen, vec![]); - } - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - visible_label(&labels, screen, "Between Entry and Number:"); - assert_eq!(toc_params(&app, app.ui.dialog.as_ref().unwrap()), before); - assert_eq!(app.session.doc().unwrap().revision, revision); - } - - /// Enter on the focused Fewer Options / More Options button toggles the options; it doesn't - /// also make the table of contents. - #[test] - fn enter_on_the_toc_options_toggle_only_toggles() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.newSample", json!({})).unwrap(); - open_toc(&mut app); - let revision = app.session.doc().unwrap().revision; - let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(|ui, app: &mut DesignApp| show(app, ui.ctx()), app); - h.run_steps(3); - h.get_by_label("Fewer Options").focus(); - h.run_steps(2); - h.key_press(egui::Key::Enter); - h.run_steps(3); - let d = h.state().ui.dialog.as_ref().expect("the dialog stays open"); - assert_eq!((d.id.as_str(), d.b("moreOptions")), (TOC, false), "the options are fewer"); - assert_eq!(h.state().session.doc().unwrap().revision, revision, "no table of contents made"); - assert!(h.query_by_label("More Options").is_some()); - } - #[test] fn color_theme_cancel_is_read_only_and_confirm_adds_the_preview() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 84cbf3bea..549b9b6dc 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3521,3 +3521,61 @@ fn character_style_options_set_the_digits() { assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi)); } + +/// Collapsing advanced TOC controls changes visibility without discarding their values. +#[test] +fn toc_more_options_preserves_hidden_settings() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.newSample", json!({})).unwrap(); + open_toc(&mut app); + app.ui.dialog.as_mut().unwrap().fields.insert( + "included".into(), + json!([{ + "style": "Headline", "level": 3, "separator": " ^t", "pageNumber": "before", + "pageNumberStyle": "Accent", "separatorStyle": "Emphasis", "sort": true + }]), + ); + let before = toc_params(&app, app.ui.dialog.as_ref().unwrap()); + let revision = app.session.doc().unwrap().revision; + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + visible_label(&labels, screen, "Between Entry and Number:"); + click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "Fewer Options").center()); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + assert!(!labels.iter().any(|(text, _, _)| text == "Between Entry and Number:")); + visible_label(&labels, screen, "Entry Style:"); + assert_eq!(toc_params(&app, app.ui.dialog.as_ref().unwrap()), before); + click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "More Options").center()); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + visible_label(&labels, screen, "Between Entry and Number:"); + assert_eq!(toc_params(&app, app.ui.dialog.as_ref().unwrap()), before); + assert_eq!(app.session.doc().unwrap().revision, revision); +} + +/// Enter on the focused Fewer Options / More Options button toggles the options; it doesn't +/// also make the table of contents. +#[test] +fn enter_on_the_toc_options_toggle_only_toggles() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.newSample", json!({})).unwrap(); + open_toc(&mut app); + let revision = app.session.doc().unwrap().revision; + let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(|ui, app: &mut DesignApp| show(app, ui.ctx()), app); + h.run_steps(3); + h.get_by_label("Fewer Options").focus(); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(3); + let d = h.state().ui.dialog.as_ref().expect("the dialog stays open"); + assert_eq!((d.id.as_str(), d.b("moreOptions")), (TOC, false), "the options are fewer"); + assert_eq!(h.state().session.doc().unwrap().revision, revision, "no table of contents made"); + assert!(h.query_by_label("More Options").is_some()); +} From a769513826a9ef2662994bbf8ce8e066445da7ae Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 15:26:18 +0100 Subject: [PATCH 0384/1349] Tests: the branch's dialog tests beside main's dialog test helpers (dialogs/tests.rs) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 34 ----------------------------- crates/ui-egui/src/dialogs/tests.rs | 34 +++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 34 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index ef4814347..dc13b83ed 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -186,40 +186,6 @@ fn color_theme(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { mod color_theme_tests { use super::*; - /// The title stays readable beside the style selector after the grid settles. - #[test] - fn toc_title_field_shows_the_whole_default_title() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.newSample", json!({})).unwrap(); - open_toc(&mut app); - let ctx = dialog_context("en"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); - for _ in 0..3 { - dialog_frame(&mut app, &ctx, screen, vec![]); - } - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - let title_row = |labels: &[(String, egui::Rect, egui::Rect)]| { - let y = visible_label(labels, screen, "Title:").center().y; - labels.iter().filter(|(_, rect, _)| (rect.center().y - y).abs() < 2.0).cloned().collect::>() - }; - visible_label(&title_row(&labels), screen, "Contents"); - app.ui.dialog.as_mut().unwrap().fields.insert("title".into(), json!("Table of Contents")); - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - visible_label(&title_row(&labels), screen, "Table of Contents"); - // A small window: the title narrows and the style selector beside it stays in view. - let small = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(450.0, 280.0)); - for _ in 0..3 { - dialog_frame(&mut app, &ctx, small, vec![]); - } - let labels = dialog_frame(&mut app, &ctx, small, vec![]); - let y = visible_label(&labels, small, "Title:").center().y; - let row: Vec<_> = labels.iter().filter(|(_, rect, _)| (rect.center().y - y).abs() < 2.0).cloned().collect(); - let style = visible_label(&row, small, "TOC Title"); - // The selector is 200 pt wide from just before its text: all of it is in the dialog body. - let (_, _, body) = row.iter().find(|(text, _, _)| text == "Style:").unwrap(); - assert!(style.min.x - 4.0 + 200.0 <= body.max.x, "the style selector fits the dialog: {style:?} in {body:?}"); - } - #[test] fn color_theme_cancel_is_read_only_and_confirm_adds_the_preview() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 3d1ef0acc..7415066fb 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3521,3 +3521,37 @@ fn character_style_options_set_the_digits() { assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi)); } + +/// The title stays readable beside the style selector after the grid settles. +#[test] +fn toc_title_field_shows_the_whole_default_title() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.newSample", json!({})).unwrap(); + open_toc(&mut app); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + let title_row = |labels: &[(String, egui::Rect, egui::Rect)]| { + let y = visible_label(labels, screen, "Title:").center().y; + labels.iter().filter(|(_, rect, _)| (rect.center().y - y).abs() < 2.0).cloned().collect::>() + }; + visible_label(&title_row(&labels), screen, "Contents"); + app.ui.dialog.as_mut().unwrap().fields.insert("title".into(), json!("Table of Contents")); + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + visible_label(&title_row(&labels), screen, "Table of Contents"); + // A small window: the title narrows and the style selector beside it stays in view. + let small = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(450.0, 280.0)); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, small, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, small, vec![]); + let y = visible_label(&labels, small, "Title:").center().y; + let row: Vec<_> = labels.iter().filter(|(_, rect, _)| (rect.center().y - y).abs() < 2.0).cloned().collect(); + let style = visible_label(&row, small, "TOC Title"); + // The selector is 200 pt wide from just before its text: all of it is in the dialog body. + let (_, _, body) = row.iter().find(|(text, _, _)| text == "Style:").unwrap(); + assert!(style.min.x - 4.0 + 200.0 <= body.max.x, "the style selector fits the dialog: {style:?} in {body:?}"); +} From 0d486c91cac11f0d0fefb499eb3dd6bf42675084 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 15:26:19 +0100 Subject: [PATCH 0385/1349] Tests: the branch's dialog tests beside main's dialog test helpers (dialogs/tests.rs) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 77 ----------------------------- crates/ui-egui/src/dialogs/tests.rs | 77 +++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 77 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 9a607c59e..868d990d9 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -186,83 +186,6 @@ fn color_theme(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { mod color_theme_tests { use super::*; - /// Replace the text of the field beside the `nth` label `label` (on its row, to its right) with - /// `new`, and leave the field. - fn retype_beside(h: &mut egui_kittest::Harness<'static, crate::test_window::Window>, label: &str, nth: usize, new: &str) { - use egui_kittest::kittest::Queryable; - let l = h.get_all_by_label(label).nth(nth).unwrap_or_else(|| panic!("no label {label} #{nth}")).rect(); - let field = h - .get_all_by(|n| n.role() == egui::accesskit::Role::TextInput) - .map(|n| n.rect()) - .filter(|r| r.center().x > l.max.x && (r.center().y - l.center().y).abs() < l.height().max(8.0)) - .min_by(|a, b| a.min.x.total_cmp(&b.min.x)) - .unwrap_or_else(|| panic!("no field beside {label} #{nth}")) - .center(); - crate::test_window::click_at(h, field); - h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); - h.event(egui::Event::Text(new.into())); - h.run_steps(1); - // Tab leaves the field (Enter would be the dialog's OK). - h.key_press(egui::Key::Tab); - h.run_steps(3); - } - - /// The course's chapter 40: Paragraph Border's four weights are linked as InDesign's, so a - /// side typed in sets all four; with the link off ("Make all settings the same") a side is set - /// alone, as the lesson gives the border only a thick left side. The corners link the same way. - #[test] - fn paragraph_border_sides_and_corners_link_as_indesigns() { - use egui_kittest::kittest::Queryable; - let (app, _) = ruled_paragraph(); - let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); - h.state_mut().app.ui.dialog = - Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "border", "p.borderOn": true}))); - h.run_steps(4); - let field = |h: &egui_kittest::Harness<'static, crate::test_window::Window>, key: &str| { - h.state().app.ui.dialog.as_ref().and_then(|d| d.fields.get(&format!("p.{key}")).cloned()).unwrap_or_default() - }; - // The four weights start the same, so linked: Top sets them all. - retype_beside(&mut h, "Top:", 0, "3"); - assert_eq!(field(&h, "borderWeights"), json!([3.0, 3.0, 3.0, 3.0])); - // Unlinked, Left alone takes 10 pt. - // The link of the weights (0), corners (1) or offsets (2), where it is now: the dialog - // scrolls as fields take focus. - let link = |h: &egui_kittest::Harness<'static, crate::test_window::Window>, n: usize| { - let links: Vec = h.get_all_by_label("Make all settings the same").map(|n| n.rect()).collect(); - assert_eq!(links.len(), 3, "weights, corners and offsets each have a link"); - links[n].center() - }; - let at = link(&h, 0); - crate::test_window::click_at(&mut h, at); - retype_beside(&mut h, "Left:", 0, "10"); - assert_eq!(field(&h, "borderWeights"), json!([3.0, 10.0, 3.0, 3.0])); - // Linked again, the four take Top's weight; unlinked once more for the thick left side. - let at = link(&h, 0); - crate::test_window::click_at(&mut h, at); - assert_eq!(field(&h, "borderWeights"), json!([3.0, 3.0, 3.0, 3.0])); - let at = link(&h, 0); - crate::test_window::click_at(&mut h, at); - retype_beside(&mut h, "Left:", 0, "10"); - assert_eq!(field(&h, "borderWeights"), json!([3.0, 10.0, 3.0, 3.0])); - // The corners start the same too: Top Left's size goes to all four. - retype_beside(&mut h, "Top Left:", 0, "0p4"); - let corners = field(&h, "borderCorners"); - assert!((0..4).all(|i| corners[i]["size"] == json!(4.0)), "{corners}"); - // Unlinked, Top Right alone takes 0p8; linked again, all four take Top Left's 4 pt. - let at = link(&h, 1); - crate::test_window::click_at(&mut h, at); - retype_beside(&mut h, "Top Right:", 0, "0p8"); - assert_eq!(field(&h, "borderCorners")[1]["size"], json!(8.0)); - assert_eq!(field(&h, "borderCorners")[0]["size"], json!(4.0)); - let at = link(&h, 1); - crate::test_window::click_at(&mut h, at); - let corners = field(&h, "borderCorners"); - assert!((0..4).all(|i| corners[i] == corners[0] && corners[i]["size"] == json!(4.0)), "{corners}"); - confirm(&mut h.state_mut().app).unwrap(); - let style = h.state().app.session.doc().unwrap().doc.styles.para("Ruled Child").cloned().unwrap(); - assert_eq!(style.para.border_weights, Some([3.0, 10.0, 3.0, 3.0])); - } - #[test] fn color_theme_cancel_is_read_only_and_confirm_adds_the_preview() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 84cbf3bea..f144327be 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3521,3 +3521,80 @@ fn character_style_options_set_the_digits() { assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi)); } + +/// Replace the text of the field beside the `nth` label `label` (on its row, to its right) with +/// `new`, and leave the field. +fn retype_beside(h: &mut egui_kittest::Harness<'static, crate::test_window::Window>, label: &str, nth: usize, new: &str) { + use egui_kittest::kittest::Queryable; + let l = h.get_all_by_label(label).nth(nth).unwrap_or_else(|| panic!("no label {label} #{nth}")).rect(); + let field = h + .get_all_by(|n| n.role() == egui::accesskit::Role::TextInput) + .map(|n| n.rect()) + .filter(|r| r.center().x > l.max.x && (r.center().y - l.center().y).abs() < l.height().max(8.0)) + .min_by(|a, b| a.min.x.total_cmp(&b.min.x)) + .unwrap_or_else(|| panic!("no field beside {label} #{nth}")) + .center(); + crate::test_window::click_at(h, field); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(new.into())); + h.run_steps(1); + // Tab leaves the field (Enter would be the dialog's OK). + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +/// The course's chapter 40: Paragraph Border's four weights are linked as InDesign's, so a +/// side typed in sets all four; with the link off ("Make all settings the same") a side is set +/// alone, as the lesson gives the border only a thick left side. The corners link the same way. +#[test] +fn paragraph_border_sides_and_corners_link_as_indesigns() { + use egui_kittest::kittest::Queryable; + let (app, _) = ruled_paragraph(); + let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); + h.state_mut().app.ui.dialog = + Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "border", "p.borderOn": true}))); + h.run_steps(4); + let field = |h: &egui_kittest::Harness<'static, crate::test_window::Window>, key: &str| { + h.state().app.ui.dialog.as_ref().and_then(|d| d.fields.get(&format!("p.{key}")).cloned()).unwrap_or_default() + }; + // The four weights start the same, so linked: Top sets them all. + retype_beside(&mut h, "Top:", 0, "3"); + assert_eq!(field(&h, "borderWeights"), json!([3.0, 3.0, 3.0, 3.0])); + // Unlinked, Left alone takes 10 pt. + // The link of the weights (0), corners (1) or offsets (2), where it is now: the dialog + // scrolls as fields take focus. + let link = |h: &egui_kittest::Harness<'static, crate::test_window::Window>, n: usize| { + let links: Vec = h.get_all_by_label("Make all settings the same").map(|n| n.rect()).collect(); + assert_eq!(links.len(), 3, "weights, corners and offsets each have a link"); + links[n].center() + }; + let at = link(&h, 0); + crate::test_window::click_at(&mut h, at); + retype_beside(&mut h, "Left:", 0, "10"); + assert_eq!(field(&h, "borderWeights"), json!([3.0, 10.0, 3.0, 3.0])); + // Linked again, the four take Top's weight; unlinked once more for the thick left side. + let at = link(&h, 0); + crate::test_window::click_at(&mut h, at); + assert_eq!(field(&h, "borderWeights"), json!([3.0, 3.0, 3.0, 3.0])); + let at = link(&h, 0); + crate::test_window::click_at(&mut h, at); + retype_beside(&mut h, "Left:", 0, "10"); + assert_eq!(field(&h, "borderWeights"), json!([3.0, 10.0, 3.0, 3.0])); + // The corners start the same too: Top Left's size goes to all four. + retype_beside(&mut h, "Top Left:", 0, "0p4"); + let corners = field(&h, "borderCorners"); + assert!((0..4).all(|i| corners[i]["size"] == json!(4.0)), "{corners}"); + // Unlinked, Top Right alone takes 0p8; linked again, all four take Top Left's 4 pt. + let at = link(&h, 1); + crate::test_window::click_at(&mut h, at); + retype_beside(&mut h, "Top Right:", 0, "0p8"); + assert_eq!(field(&h, "borderCorners")[1]["size"], json!(8.0)); + assert_eq!(field(&h, "borderCorners")[0]["size"], json!(4.0)); + let at = link(&h, 1); + crate::test_window::click_at(&mut h, at); + let corners = field(&h, "borderCorners"); + assert!((0..4).all(|i| corners[i] == corners[0] && corners[i]["size"] == json!(4.0)), "{corners}"); + confirm(&mut h.state_mut().app).unwrap(); + let style = h.state().app.session.doc().unwrap().doc.styles.para("Ruled Child").cloned().unwrap(); + assert_eq!(style.para.border_weights, Some([3.0, 10.0, 3.0, 3.0])); +} From 1d62a5875c81b8f3cf6d3bdd1e0ef3ba5eede051 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 15:26:19 +0100 Subject: [PATCH 0386/1349] Tests: the branch's dialog tests beside main's dialog test helpers (dialogs/tests.rs) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 30 ----------------------------- crates/ui-egui/src/dialogs/tests.rs | 30 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 30 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index cba803f4d..9150f8d23 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -186,36 +186,6 @@ fn color_theme(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { mod color_theme_tests { use super::*; - /// The bookmarks checkbox persists through generation and reopening the dialog. - #[test] - fn toc_bookmarks_checkbox_sets_and_reopens_the_persisted_option() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.newSample", json!({})).unwrap(); - open_toc(&mut app); - assert!(app.ui.dialog.as_ref().unwrap().b("createBookmarks")); - app.ui.dialog.as_mut().unwrap().fields.insert("included".into(), json!([{"style": "Headline", "level": 1}])); - let ctx = dialog_context("en"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0)); - for _ in 0..3 { - dialog_frame(&mut app, &ctx, screen, vec![]); - } - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - visible_label(&labels, screen, "Create PDF Bookmarks"); - confirm(&mut app).unwrap(); - assert!(app.session.doc().unwrap().doc.toc.as_ref().unwrap().create_bookmarks); - assert!(!app.session.doc().unwrap().doc.bookmarks.is_empty()); - open_toc(&mut app); - for _ in 0..3 { - dialog_frame(&mut app, &ctx, screen, vec![]); - } - let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "Create PDF Bookmarks").center()); - confirm(&mut app).unwrap(); - assert!(app.session.doc().unwrap().doc.bookmarks.is_empty()); - open_toc(&mut app); - assert!(!app.ui.dialog.as_ref().unwrap().b("createBookmarks")); - } - #[test] fn color_theme_cancel_is_read_only_and_confirm_adds_the_preview() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 84cbf3bea..560af66bd 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3521,3 +3521,33 @@ fn character_style_options_set_the_digits() { assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi)); } + +/// The bookmarks checkbox persists through generation and reopening the dialog. +#[test] +fn toc_bookmarks_checkbox_sets_and_reopens_the_persisted_option() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.newSample", json!({})).unwrap(); + open_toc(&mut app); + assert!(app.ui.dialog.as_ref().unwrap().b("createBookmarks")); + app.ui.dialog.as_mut().unwrap().fields.insert("included".into(), json!([{"style": "Headline", "level": 1}])); + let ctx = dialog_context("en"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0)); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + visible_label(&labels, screen, "Create PDF Bookmarks"); + confirm(&mut app).unwrap(); + assert!(app.session.doc().unwrap().doc.toc.as_ref().unwrap().create_bookmarks); + assert!(!app.session.doc().unwrap().doc.bookmarks.is_empty()); + open_toc(&mut app); + for _ in 0..3 { + dialog_frame(&mut app, &ctx, screen, vec![]); + } + let labels = dialog_frame(&mut app, &ctx, screen, vec![]); + click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "Create PDF Bookmarks").center()); + confirm(&mut app).unwrap(); + assert!(app.session.doc().unwrap().doc.bookmarks.is_empty()); + open_toc(&mut app); + assert!(!app.ui.dialog.as_ref().unwrap().b("createBookmarks")); +} From b0068ee57b7b18f7c65f46040706413ddb5d8a5a Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 15:26:52 +0100 Subject: [PATCH 0387/1349] Parent page box: json! where main's split canvas view has no import Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/view.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas/view.rs b/crates/ui-egui/src/canvas/view.rs index 7f0e7768d..b679923d2 100644 --- a/crates/ui-egui/src/canvas/view.rs +++ b/crates/ui-egui/src/canvas/view.rs @@ -187,7 +187,7 @@ pub fn page_box(app: &DesignApp) -> Option { pub fn page_box_go(app: &mut DesignApp, b: &PageBox, i: usize) { if i < b.pages { if app.session.active().is_some_and(|st| st.editing_parents) { - let _ = app.run("layout.parents.edit", json!({"on": false})); + let _ = app.run("layout.parents.edit", serde_json::json!({"on": false})); // The canvas refits to the page's spread once it is centred. if let Some(v) = app.view_mut() { v.fitted = false; @@ -195,7 +195,7 @@ pub fn page_box_go(app: &mut DesignApp, b: &PageBox, i: usize) { } go_to_page(app, i); } else if let Some(id) = b.parents.get(i - b.pages) { - let _ = app.run("layout.parents.edit", json!({"parent": id.0})); + let _ = app.run("layout.parents.edit", serde_json::json!({"parent": id.0})); } } From a9814cae3995ac610f0ddfb32994ffa436740db9 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 15:27:13 +0100 Subject: [PATCH 0388/1349] Fill colour picker: the picker opener shared with the text panel, the swatches module's path, one Fill popup per chip Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/properties/object.rs | 4 ++-- crates/ui-egui/src/panels/properties/text.rs | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/object.rs b/crates/ui-egui/src/panels/properties/object.rs index 50f8e498e..e9daa0f32 100644 --- a/crates/ui-egui/src/panels/properties/object.rs +++ b/crates/ui-egui/src/panels/properties/object.rs @@ -378,8 +378,8 @@ pub(super) fn appearance_section(app: &mut DesignApp, ui: &mut Ui, i: &SelInfo) /// The Color Picker for a Fill or Stroke chip (a double-click on it, as in InDesign), with the /// chip's colour: the objects', or with `text` the selected text's. -fn open_color_picker(app: &mut DesignApp, doc: &designcraft_doc::Document, swatch: &str, stroke: bool, text: bool) { - let mut fields = super::swatches::picker_fields(doc.resolve_color(swatch, 1.0), stroke); +pub(super) fn open_color_picker(app: &mut DesignApp, doc: &designcraft_doc::Document, swatch: &str, stroke: bool, text: bool) { + let mut fields = crate::panels::swatches::picker_fields(doc.resolve_color(swatch, 1.0), stroke); fields["text"] = json!(text); app.ui.dialog = Some(crate::dialogs::Dialog::new("colorPicker", fields)); } diff --git a/crates/ui-egui/src/panels/properties/text.rs b/crates/ui-egui/src/panels/properties/text.rs index 05a2175a4..64c6d6890 100644 --- a/crates/ui-egui/src/panels/properties/text.rs +++ b/crates/ui-egui/src/panels/properties/text.rs @@ -1,4 +1,4 @@ -use super::object::swatch_menu; +use super::object::{open_color_picker, swatch_menu}; use super::typography::{para_field_min, show_typography_panel}; use super::{ Align, DesignApp, FIELD_H, NumField, Rect, Sense, Stroke, StrokeKind, Tokens, Ui, Value, block, full_width, icon_toggle, icons, json, link_label, @@ -128,7 +128,6 @@ pub(super) fn text_appearance_section(app: &mut DesignApp, ui: &mut Ui) { ui.painter().text(chip.center(), egui::Align2::CENTER_CENTER, "T", crate::theme::semibold(12.0), tc); } let resp = ui.interact(chip, ui.scope_id().with(("tchip", k)), Sense::click()).on_hover_text(format!("{label}: {sw}")); - swatch_menu(app, &resp, &doc, &sw, k != 0, false, true); resp.widget_info(|| { egui::WidgetInfo::labeled(egui::WidgetType::Button, true, if k == 0 { "Text fill swatch" } else { "Text stroke swatch" }) }); From d3db571e9df937bc4e373369ced7e65d1ca23719 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 15:27:38 +0100 Subject: [PATCH 0389/1349] Anchor points: the panels module's helpers from main's split Properties module Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/properties/object.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/object.rs b/crates/ui-egui/src/panels/properties/object.rs index 4557b7c03..50969f415 100644 --- a/crates/ui-egui/src/panels/properties/object.rs +++ b/crates/ui-egui/src/panels/properties/object.rs @@ -106,7 +106,7 @@ fn anchor_transform_section(app: &mut DesignApp, ui: &mut Ui, i: &SelInfo) { } let mut set = serde_json::Map::new(); // A single point has no size: as InDesign, W and H show its object's, greyed out. - let single = super::selected_anchor_points(app).len() == 1; + let single = crate::panels::selected_anchor_points(app).len() == 1; let (w, h) = if single { i.object_size } else { (r.width(), r.height()) }; for (row, (lx, vx, kx, lw, vw, kw)) in [("X:", x, "x", "W:", w, "width"), ("Y:", y, "y", "H:", h, "height")].into_iter().enumerate() { let yy = row as f32 * 25.0; @@ -133,8 +133,8 @@ fn anchor_transform_section(app: &mut DesignApp, ui: &mut Ui, i: &SelInfo) { /// in the page coordinates the fields show, from the reference point): one `path.moveAnchors` /// step, each point by its own movement. A width or height of a single point (0) can't scale. pub(crate) fn transform_anchors(app: &mut DesignApp, set: &Value) -> Result { - let points = super::selected_anchor_points(app); - let Some(i) = super::sel_info(app) else { return Ok(Value::Null) }; + let points = crate::panels::selected_anchor_points(app); + let Some(i) = crate::panels::sel_info(app) else { return Ok(Value::Null) }; if points.is_empty() { return Ok(Value::Null); } From cb036e06e28ecd7634182a815db4bf3fcaed4a4c Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 15:28:38 +0100 Subject: [PATCH 0390/1349] Frame X test: the corner-to-corner lines from main's split canvas frames module Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/canvas/frames.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index de4331c7d..84b3cd0d6 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -30,7 +30,7 @@ mod view; use column_guides::{COLUMN_DRAG, ColumnDrag, column_guide_at, spread_x_across}; use frames::{draw_frames, draw_selection}; #[cfg(test)] -use frames::{item_canvas_xf, overset_frames, overset_marks, ported_frames, text_frames_in}; +use frames::{frame_x, item_canvas_xf, overset_frames, overset_marks, ported_frames, text_frames_in}; use guides::{GUIDE_DRAG, GUIDE_PRESS, GuideDrag, GuidePress, guide_readout, guide_spot, moving_guides, readout_at}; #[cfg(test)] use guides::{guide_at, guide_drag_delta, guide_measure}; diff --git a/crates/ui-egui/src/canvas/frames.rs b/crates/ui-egui/src/canvas/frames.rs index 1378ba255..4578b933b 100644 --- a/crates/ui-egui/src/canvas/frames.rs +++ b/crates/ui-egui/src/canvas/frames.rs @@ -135,7 +135,7 @@ fn draw_item_edges(painter: &egui::Painter, xf: &Xf, doc: &Document, it: &Item, /// The X of an empty graphic frame, in its own space: a four-cornered frame joins its opposite /// corners, so a frame slanted with Direct Selection keeps its X corner to corner, as InDesign /// draws it; other shapes span their bounds. -fn frame_x(it: &Item) -> [(Point, Point); 2] { +pub(super) fn frame_x(it: &Item) -> [(Point, Point); 2] { // A rectangle (slanted or not: four corner points, no handles). Ellipses, polygons (a // four-sided one is a diamond) and curved paths keep the X across their bounds. Edited points // make any of them a path: a four-cornered one whose corners would cross as a plus (a diamond, From d8b2179b5698be2c7c5e64e53374bb1f37a0387b Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 15:29:22 +0100 Subject: [PATCH 0391/1349] Loaded cursor thumbnail: its drawing after main's canvas pass, one loaded field per snap context Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 11 +++++------ crates/ui-egui/src/canvas/column_guides.rs | 1 - 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ec1f1716b..c993193de 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -363,6 +363,11 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { draw_loaded_thumbnail(app, &painter, p, &t); } } + // A second viewport has no panels, dialogs or Quick Apply after its canvas: observe here, + // once, as the end of its pass. The root viewport observes at the end of `DesignApp::ui`. + if ui.ctx().viewport_id() != egui::ViewportId::ROOT { + ime_observe(app, ui.ctx()); + } } /// Longest side of the loaded place cursor's thumbnail, in points. @@ -414,12 +419,6 @@ fn loaded_thumb_texture(ctx: &egui::Context, doc: &Document, asset: designcraft_ let t = ctx.load_texture("loaded_thumb", crate::widgets::fit_texture(ci, max), egui::TextureOptions::LINEAR); ctx.data_mut(|d| d.insert_temp(key, t.clone())); Some(t) - } - // A second viewport has no panels, dialogs or Quick Apply after its canvas: observe here, - // once, as the end of its pass. The root viewport observes at the end of `DesignApp::ui`. - if ui.ctx().viewport_id() != egui::ViewportId::ROOT { - ime_observe(app, ui.ctx()); - } } /// Presses in a row on the canvas: the last press's count, and where and when it was released diff --git a/crates/ui-egui/src/canvas/column_guides.rs b/crates/ui-egui/src/canvas/column_guides.rs index 2cc1d4d0e..c15595442 100644 --- a/crates/ui-egui/src/canvas/column_guides.rs +++ b/crates/ui-egui/src/canvas/column_guides.rs @@ -107,7 +107,6 @@ fn snap_gutter(app: &DesignApp, g: &ColumnDrag, want: f64, shift: bool, zoom: f6 unit: app.ui.units, stroke_in_front: false, loaded: None, - loaded: None, }; let rect = DRect::new(want, m.y0, want + width, m.y1); let s = designcraft_tools::snap::snap( From 83aa235cbc85a927e0f0c14ad79ace9a3f0a9053 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 15:30:31 +0100 Subject: [PATCH 0392/1349] TOC import: the listed style reference shared from main's split import styles module Co-Authored-By: Claude Opus 5.5 --- crates/idml/src/import/styles.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/idml/src/import/styles.rs b/crates/idml/src/import/styles.rs index a05e7d50b..13b140733 100644 --- a/crates/idml/src/import/styles.rs +++ b/crates/idml/src/import/styles.rs @@ -225,7 +225,7 @@ impl<'r> Importer<'r> { /// A paragraph style reference written as an element's text: as written when it names a /// style, otherwise without surrounding whitespace (see [`Self::listed_char_style_ref`]). - fn listed_para_style_ref(&self, r: &str) -> String { + pub(super) fn listed_para_style_ref(&self, r: &str) -> String { if self.para_names.contains_key(r) { self.para_style_ref(r) } else { self.para_style_ref(r.trim()) } } /// A character style reference written as an element's text (nested, line and GREP styles). From 1698f69d683e58419565a4e241f38bf502223739 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 15:30:59 +0100 Subject: [PATCH 0393/1349] Hidden characters test: in canvas/tests.rs, out of the canvas paint function Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 32 ------------------------------ crates/ui-egui/src/canvas/tests.rs | 32 ++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 5c0926b44..1b1e10d13 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -194,38 +194,6 @@ fn paint_render(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc: &Documen painter.add(egui::Shape::mesh(mesh)); } } - - /// As InDesign: an end-of-story # in every cell (after its text), a ¶ where a cell paragraph - /// ends, and the table paragraph's ¶ just after the table's bottom right corner. - #[test] - fn table_cells_show_their_hidden_characters() { - let mut d = Document::new(&designcraft_doc::build::NewDocument::default()); - let lid = d.default_layer(); - let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), DRect::new(0.0, 0.0, 300.0, 300.0), lid, "", Default::default()).unwrap(); - let data = vec![vec!["Name:".to_string(), "".into()], vec!["a\nb".into(), "".into()]]; - let t = designcraft_doc::Table::from_strings(d.alloc(), &data, 200.0, &Default::default(), &Default::default()); - d.story_mut(sid).unwrap().insert_table(0, t); - let cs = compose::compose_story(&d, sid, &compose::ComposeOptions::default()); - let frag = &cs.frames[0].tables[0]; - // The whole frame: the table's own line adds no second ¶; the story's last paragraph - // (after the table) has its #. - let story = d.story(sid).unwrap().text.clone(); - let all = frame_hidden_marks(&story, &cs.frames[0]); - let marks: Vec<_> = all.iter().filter(|m| frag.rect.inflate(2.0, 2.0).contains(m.0)).cloned().collect(); - let ends = |m: &str| marks.iter().filter(|x| x.1 == m).count(); - assert_eq!(ends("#"), 4, "one per cell: {marks:?}"); - assert_eq!(ends("¶"), 2, "the cell's first paragraph and the table's, once: {marks:?}"); - assert_eq!(all.iter().filter(|m| m.1 == "¶" && m.3 > 20.0).count(), 0, "no ¶ the size of the table: {all:?}"); - // Each # is inside its cell, after the cell's text. - for c in &frag.cells { - let inside = marks.iter().filter(|m| m.1 == "#" && c.rect.contains(m.0)).count(); - assert_eq!(inside, 1, "cell {},{}: {marks:?}", c.row, c.col); - } - let name = frag.cell(0, 0).unwrap(); - assert!(marks.iter().any(|m| m.1 == "#" && name.rect.contains(m.0) && m.0.x > name.origin.x + 20.0), "after Name:"); - let last = marks.last().unwrap(); - assert_eq!((last.0, last.1), (designcraft_geom::Point::new(frag.rect.x1 + 1.0, frag.rect.y1), "¶")); - } } /// Presentation: a click shows the next spread, Shift-click the previous one. diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 01300bdd0..f36269479 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -2837,3 +2837,35 @@ fn trailing_spaces_show_dots_before_the_paragraph_mark() { assert!(para_x >= space.x + space.adv, "{mark} at {para_x} overlaps the last space"); } } + +/// As InDesign: an end-of-story # in every cell (after its text), a ¶ where a cell paragraph +/// ends, and the table paragraph's ¶ just after the table's bottom right corner. +#[test] +fn table_cells_show_their_hidden_characters() { + let mut d = Document::new(&designcraft_doc::build::NewDocument::default()); + let lid = d.default_layer(); + let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), DRect::new(0.0, 0.0, 300.0, 300.0), lid, "", Default::default()).unwrap(); + let data = vec![vec!["Name:".to_string(), "".into()], vec!["a\nb".into(), "".into()]]; + let t = designcraft_doc::Table::from_strings(d.alloc(), &data, 200.0, &Default::default(), &Default::default()); + d.story_mut(sid).unwrap().insert_table(0, t); + let cs = compose::compose_story(&d, sid, &compose::ComposeOptions::default()); + let frag = &cs.frames[0].tables[0]; + // The whole frame: the table's own line adds no second ¶; the story's last paragraph + // (after the table) has its #. + let story = d.story(sid).unwrap().text.clone(); + let all = frame_hidden_marks(&story, &cs.frames[0]); + let marks: Vec<_> = all.iter().filter(|m| frag.rect.inflate(2.0, 2.0).contains(m.0)).cloned().collect(); + let ends = |m: &str| marks.iter().filter(|x| x.1 == m).count(); + assert_eq!(ends("#"), 4, "one per cell: {marks:?}"); + assert_eq!(ends("¶"), 2, "the cell's first paragraph and the table's, once: {marks:?}"); + assert_eq!(all.iter().filter(|m| m.1 == "¶" && m.3 > 20.0).count(), 0, "no ¶ the size of the table: {all:?}"); + // Each # is inside its cell, after the cell's text. + for c in &frag.cells { + let inside = marks.iter().filter(|m| m.1 == "#" && c.rect.contains(m.0)).count(); + assert_eq!(inside, 1, "cell {},{}: {marks:?}", c.row, c.col); + } + let name = frag.cell(0, 0).unwrap(); + assert!(marks.iter().any(|m| m.1 == "#" && name.rect.contains(m.0) && m.0.x > name.origin.x + 20.0), "after Name:"); + let last = marks.last().unwrap(); + assert_eq!((last.0, last.1), (designcraft_geom::Point::new(frag.rect.x1 + 1.0, frag.rect.y1), "¶")); +} From a04852c8cd4fa756cb9895766f4bef679306f417 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 15:31:57 +0100 Subject: [PATCH 0394/1349] Georgian: main's rows for the Object menu's point words, once each Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/ka.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index b973aaba1..812b8d9a6 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -32,10 +32,6 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "ამოჭრა"), ("Copy", "კოპირება"), ("Paste", "ჩასმა"), - ("Join", "შეერთება"), - ("Convert Point", "წერტილის გარდაქმნა"), - ("Plain", "მარტივი"), - ("Symmetrical", "სიმეტრიული"), ("Restart Numbering", "ნუმერაციის თავიდან დაწყება"), ("Continue Numbering", "ნუმერაციის გაგრძელება"), ("Keep Options…", "შენარჩუნების პარამეტრები…"), From 948482d60fe1878eaf77afac11a5ae204c23d8d2 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 15:34:27 +0100 Subject: [PATCH 0395/1349] Tab in footnote text is typed, not taken for the next table cell Footnote text is addressed as a cell too (as 2e44b190 handled for Shift+Tab, Esc and the cell commands); text.insert now types the Tab there instead of failing in table.nextCell. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/text/edit.rs | 5 +++-- crates/engine/src/tests/table.rs | 4 ++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/text/edit.rs b/crates/engine/src/cmd/text/edit.rs index 21888cb22..fd104cbcd 100644 --- a/crates/engine/src/cmd/text/edit.rs +++ b/crates/engine/src/cmd/text/edit.rs @@ -13,8 +13,9 @@ fn reserve_command_text(st: &mut designcraft_doc::Story, additional: usize) -> R pub(super) fn insert(s: &mut Session, p: &Value) -> Result { let text = crate::cmd::text_param(p, "text"); - // Tab in a table cell moves to the next cell (Shift-Tab: `table.prevCell`). - if text == "\t" && s.doc()?.selection.text.is_some_and(|t| t.cell.is_some()) { + // Tab in a table cell moves to the next cell (Shift-Tab: `table.prevCell`). Footnote text is + // addressed as a cell too: a Tab there is typed. + if text == "\t" && s.doc()?.selection.text.is_some_and(|t| t.cell.is_some_and(|c| c.footnote_id().is_none())) { return crate::cmd::table::step_cell(s, true); } // Typing with one cell selected replaces its text, as InDesign. diff --git a/crates/engine/src/tests/table.rs b/crates/engine/src/tests/table.rs index c6b2b8824..45e4b8db8 100644 --- a/crates/engine/src/tests/table.rs +++ b/crates/engine/src/tests/table.rs @@ -140,6 +140,10 @@ fn the_cell_commands_refuse_footnote_text() { assert!(s.execute(cmd, &json!({})).is_err(), "{cmd}"); } assert_eq!(s.doc().unwrap().selection, before); + // A Tab there is typed into the footnote, not taken for the next cell. + s.execute("text.insert", &json!({"text": "\t"})).unwrap(); + let notes = s.execute("footnote.list", &json!({})).unwrap(); + assert!(notes[0]["text"].as_str().is_some_and(|t| t.contains('\t')), "{notes}"); } /// Esc in a table toggles between the text and the cell (InDesign's Esc): the caret in a cell From 963ac447faaf63334d09965e053e30dccaa42220 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 16:26:34 +0100 Subject: [PATCH 0396/1349] Text Frame Options: the paragraph spacing limit set without another branch in text_frame_options Keeps the function within clippy's cognitive complexity limit. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/object.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index c5c3ce307..474d22ca8 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -2592,9 +2592,7 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { if let Some(v) = reference { o.auto_size_ref = v; } - if let Some(v) = spacing_limit { - o.vj_paragraph_spacing_limit = v; - } + o.vj_paragraph_spacing_limit = spacing_limit.unwrap_or(o.vj_paragraph_spacing_limit); if let Some(v) = p.get("useMinimumHeight").and_then(Value::as_bool) { o.auto_size_use_min_height = v; } From 6c6efe2f7aff534c8eb5d20fdfb8ec2586a545b1 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Thu, 29 Oct 2026 15:43:45 +0000 Subject: [PATCH 0397/1349] Fix "-0" in Name with Color Value for slightly negative RGB Found while testing crates/color/src/swatch.rs:94-101 (value_name) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/color/src/swatch.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/color/src/swatch.rs b/crates/color/src/swatch.rs index e47bf4eef..d27a76428 100644 --- a/crates/color/src/swatch.rs +++ b/crates/color/src/swatch.rs @@ -96,7 +96,9 @@ pub fn value_name(c: Color) -> String { Color::Cmyk { c, m, y, k } => cmyk_name(c, m, y, k), other => { let [r, g, b] = other.to_rgb(); - format!("R={} G={} B={}", (r * 255.0).round(), (g * 255.0).round(), (b * 255.0).round()) + // `+ 0.0` turns -0.0 into 0.0 so it prints as "0", not "-0". + let p = |v: f32| (v * 255.0).round() + 0.0; + format!("R={} G={} B={}", p(r), p(g), p(b)) } } } @@ -172,6 +174,11 @@ pub fn default_swatches() -> Vec { mod tests { use super::*; + #[test] + fn value_name_has_no_negative_zero() { + assert_eq!(value_name(Color::rgb(-0.001, 0.5, 1.0)), "R=0 G=128 B=255"); + } + #[test] fn defaults_start_with_specials() { let s = default_swatches(); From 9fe094575a0a9a64e75e5885bb08ad3968361a7b Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 17:04:00 +0100 Subject: [PATCH 0398/1349] egui 0.37: Id::unique for the wrap offsets link state Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/properties/object.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/properties/object.rs b/crates/ui-egui/src/panels/properties/object.rs index 3795bcd8a..672c0cb31 100644 --- a/crates/ui-egui/src/panels/properties/object.rs +++ b/crates/ui-egui/src/panels/properties/object.rs @@ -541,7 +541,7 @@ fn wrap_offsets(app: &mut DesignApp, ui: &mut Ui, i: &SelInfo) { // The link's state belongs to the selection: another selection starts linked again when its // four offsets are the same. let selected: Vec = app.session.active().map(|st| st.selection.items.iter().map(|i| i.0).collect()).unwrap_or_default(); - let link_id = egui::Id::new(("prop_wrap_linked", selected)); + let link_id = egui::Id::unique(("prop_wrap_linked", selected)); ui.add_enabled_ui(enabled, |ui| { // Linked while the four are the same, until the link is clicked. let same = offsets.iter().all(|v| (v - offsets[0]).abs() < 1e-9); From 38d84c00814c782ad1c8bdd943c1b5d49daf537a Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 17:31:39 +0100 Subject: [PATCH 0399/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/color_panel_tests.rs | 2 +- crates/ui-egui/src/panels/swatches.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/color_panel_tests.rs b/crates/ui-egui/src/panels/color_panel_tests.rs index 05d5899b6..153216100 100644 --- a/crates/ui-egui/src/panels/color_panel_tests.rs +++ b/crates/ui-egui/src/panels/color_panel_tests.rs @@ -95,7 +95,7 @@ fn the_color_panel_edits_the_gradient_stop_selected_in_the_gradient_panel() { app.run("object.gradient", json!({})).unwrap(); let mut h = harness(app); h.run_steps(2); - h.ctx.data_mut(|d| d.insert_temp(egui::Id::new(GRAD_SEL), RampSel::Stop(1))); + h.ctx.data_mut(|d| d.insert_temp(egui::Id::unique(GRAD_SEL), RampSel::Stop(1))); h.run_steps(3); assert!(h.query_by_label("R=0 G=0 B=0").is_some(), "the black stop's values"); // C: the topmost field. diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index 92d7ff2ef..854e16a89 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -581,7 +581,7 @@ fn cmyk_ramp(k: usize, x: f32) -> egui::Color32 { fn gradient_stop(app: &mut DesignApp, ui: &mut egui::Ui, g: &designcraft_color::Gradient, target: &str, mode: ColorMode) { use designcraft_color::Color; let t = Tokens::get(ui.ctx()); - let sel: RampSel = ui.data(|d| d.get_temp(egui::Id::new(GRAD_SEL))).unwrap_or(RampSel::Stop(0)); + let sel: RampSel = ui.data(|d| d.get_temp(egui::Id::unique(GRAD_SEL))).unwrap_or(RampSel::Stop(0)); let i = match sel { RampSel::Stop(i) | RampSel::Mid(i) => i, } From 0dab4137eecd8e821c65d36de6a4f8cd0c57e1f4 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 17:49:56 +0100 Subject: [PATCH 0400/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/properties/object.rs | 2 +- crates/ui-egui/src/panels/properties/tests.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/object.rs b/crates/ui-egui/src/panels/properties/object.rs index 3d5ce2ab8..36a9fecaa 100644 --- a/crates/ui-egui/src/panels/properties/object.rs +++ b/crates/ui-egui/src/panels/properties/object.rs @@ -355,7 +355,7 @@ pub(super) fn appearance_section(app: &mut DesignApp, ui: &mut Ui, i: &SelInfo) let mresp = ui.interact(more, ui.scope_id().with("opmore"), Sense::click()); ui.painter().rect(more, 0.0, if mresp.hovered() { t.hover } else { t.input }, Stroke::new(1.0, t.field_border), StrokeKind::Inside); icons::paint(ui.painter(), more.shrink(4.0), "chevron-right", t.icon); - mresp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, crate::i18n::tr(&app.ui.language, "Opacity"))); + mresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, crate::i18n::tr(&app.ui.language, "Opacity"))); opacity_slider(app, &mresp, i.opacity); ui.add_space(6.0); ui.horizontal(|ui| { diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 2858392f0..06d462abe 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -722,7 +722,7 @@ fn the_opacity_arrow_opens_a_slider_and_a_drag_is_one_undo_step() { let steps = undo_steps(&app); let mut h = Harness::builder().with_size(vec2(320.0, 1400.0)).build_ui_state( |ui, app: &mut DesignApp| { - let id = egui::Id::new("test_fonts"); + let id = egui::Id::unique("test_fonts"); if ui.data(|d| d.get_temp::(id)).is_none() { crate::theme::install_fonts(ui.ctx(), ""); ui.data_mut(|d| d.insert_temp(id, true)); From d40bb87def4615e0be94002939182a28ca54489a Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 17:53:41 +0100 Subject: [PATCH 0401/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/pages.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/pages.rs b/crates/ui-egui/src/panels/pages.rs index 6834e56a2..4fe7fea8a 100644 --- a/crates/ui-egui/src/panels/pages.rs +++ b/crates/ui-egui/src/panels/pages.rs @@ -427,7 +427,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { // ---- Document spreads. let cur = crate::canvas::current_page(app).unwrap_or(0); let cur_spread = doc.page_loc(cur).map(|l| l.0); - let followed_id = egui::Id::new("pages_panel_followed"); + let followed_id = egui::Id::unique("pages_panel_followed"); let dragging = egui::DragAndDrop::has_any_payload(ui.ctx()); let tallest = doc.spreads.iter().flat_map(|sp| sp.pages.iter().map(|p| p.height)).fold(doc.settings.page_height, f64::max).max(1.0); let th = opts.page_size.page_h(); @@ -490,7 +490,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { crate::i18n::tr(&app.ui.language, "Numbering & Section Options…").trim_end_matches('…'), app.session.page_label(abs) ); - marker.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &label)); + marker.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &label)); // A double click, or the keyboard or a screen reader activating it (a // single pointer click only selects, as on a page). let activated = marker.double_clicked() || marker.clicked() && !marker.clicked_by(egui::PointerButton::Primary); @@ -552,7 +552,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { } ui.painter().galley(c - g.size() / 2.0, g, Color32::WHITE); let lr = ui.interact(br, ui.scope_id().with(("spread_label", si)), Sense::click()); - lr.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, &label)); + lr.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, &label)); if lr.clicked() { if editing_parents { let _ = app.run("layout.parents.edit", json!({"on": false})); @@ -831,7 +831,7 @@ mod spread_label_tests { app.run("layout.parents.edit", json!({"on": true})).unwrap(); let mut h = Harness::builder().with_size(vec2(280.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state( |ui, app: &mut DesignApp| { - let key = egui::Id::new("section_marker_test_fonts"); + let key = egui::Id::unique("section_marker_test_fonts"); if ui.data(|d| d.get_temp::(key)).is_none() { crate::theme::install_fonts(ui.ctx(), ""); ui.data_mut(|d| d.insert_temp(key, true)); @@ -865,7 +865,7 @@ mod spread_label_tests { app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1000.0, 800.0))); let mut h = Harness::builder().with_size(vec2(280.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state( |ui, app: &mut DesignApp| { - let key = egui::Id::new("section_marker_key_test_fonts"); + let key = egui::Id::unique("section_marker_key_test_fonts"); if ui.data(|d| d.get_temp::(key)).is_none() { crate::theme::install_fonts(ui.ctx(), ""); ui.data_mut(|d| d.insert_temp(key, true)); @@ -922,7 +922,7 @@ mod spread_label_tests { app.canvas_rect = Some(egui::Rect::from_min_size(egui::pos2(0.0, 0.0), vec2(1000.0, 800.0))); let mut h = Harness::builder().with_size(vec2(260.0, 900.0)).build_ui_state( |ui, app: &mut DesignApp| { - let key = egui::Id::new("test_fonts"); + let key = egui::Id::unique("test_fonts"); if ui.data(|d| d.get_temp::(key)).is_none() { crate::theme::install_fonts(ui.ctx(), ""); ui.data_mut(|d| d.insert_temp(key, true)); From 85991bf13f7aebc286c3f693611491017ef9fbf8 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 17:57:34 +0100 Subject: [PATCH 0402/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/new_document.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/new_document.rs b/crates/ui-egui/src/new_document.rs index 54fa76a33..1cd90d0a7 100644 --- a/crates/ui-egui/src/new_document.rs +++ b/crates/ui-egui/src/new_document.rs @@ -510,7 +510,7 @@ fn presets(app: &mut DesignApp, ui: &mut Ui, d: &mut Dialog) -> bool { let rect = Rect::from_min_size(pos2(x, resp.rect.top() + 4.0), vec2(22.0, 22.0)); let button = ui.interact(rect, ui.scope_id().with(("delete-preset", &c.key)), Sense::click()); let label = format!("{}: {}", crate::i18n::tr(&lang, "Delete Preset"), c.label); - button.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label.as_str())); + button.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label.as_str())); if button.hovered() { ui.painter().rect_filled(rect, 2.0, t.hover); } From 7a5101d0a85344763c39c7837285867df489e47b Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 18:01:19 +0100 Subject: [PATCH 0403/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/swatches.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index 51643b2fc..8864e75ce 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -575,7 +575,7 @@ fn cmyk_ramp(k: usize, x: f32) -> egui::Color32 { /// The spectrum ramp: hue across, light to dark down; click to apply. fn spectrum(app: &mut DesignApp, ui: &mut egui::Ui, target: &str) { let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 36.0), Sense::click()); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, crate::i18n::tr(&app.ui.language, "Color spectrum"))); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, crate::i18n::tr(&app.ui.language, "Color spectrum"))); let at = |u: f32, v: f32| -> [f32; 3] { let c = egui::ecolor::Hsva::new(u, (v * 2.0).min(1.0), (2.0 - v * 2.0).min(1.0), 1.0).to_rgb(); [c[0], c[1], c[2]] @@ -683,7 +683,7 @@ mod color_panel_defaults_tests { let mut h = egui_kittest::Harness::builder().with_size(vec2(320.0, 480.0)).build_ui_state( |ui, app: &mut DesignApp| { // The panel's fonts are installed on the first frame and used from the next. - let id = egui::Id::new("test_fonts"); + let id = egui::Id::unique("test_fonts"); if ui.data(|d| d.get_temp::(id)).is_none() { crate::theme::install_fonts(ui.ctx(), ""); ui.data_mut(|d| d.insert_temp(id, true)); From b348eb4efb9545e8ead9026c6e1ca0a41ef77d72 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 18:06:18 +0100 Subject: [PATCH 0404/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/pages.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/pages.rs b/crates/ui-egui/src/panels/pages.rs index 10a53e175..176daaa00 100644 --- a/crates/ui-egui/src/panels/pages.rs +++ b/crates/ui-egui/src/panels/pages.rs @@ -427,7 +427,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { // ---- Document spreads. let cur = crate::canvas::current_page(app).unwrap_or(0); let cur_spread = doc.page_loc(cur).map(|l| l.0); - let followed_id = egui::Id::new("pages_panel_followed"); + let followed_id = egui::Id::unique("pages_panel_followed"); let dragging = egui::DragAndDrop::has_any_payload(ui.ctx()); let tallest = doc.spreads.iter().flat_map(|sp| sp.pages.iter().map(|p| p.height)).fold(doc.settings.page_height, f64::max).max(1.0); let th = opts.page_size.page_h(); @@ -535,7 +535,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { ui.painter().galley(c - g.size() / 2.0, g, ink); let lr = ui.interact(br, ui.scope_id().with(("spread_label", si)), Sense::click()); // A click goes to the spread, so assistive technology hears a button. - lr.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &label)); + lr.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &label)); if lr.clicked() { if editing_parents { let _ = app.run("layout.parents.edit", json!({"on": false})); @@ -841,7 +841,7 @@ mod spread_label_tests { app.canvas_rect = Some(egui::Rect::from_min_size(egui::pos2(0.0, 0.0), vec2(1000.0, 800.0))); let mut h = Harness::builder().with_size(vec2(260.0, 900.0)).build_ui_state( |ui, app: &mut DesignApp| { - let key = egui::Id::new("test_fonts"); + let key = egui::Id::unique("test_fonts"); if ui.data(|d| d.get_temp::(key)).is_none() { crate::theme::install_fonts(ui.ctx(), ""); ui.data_mut(|d| d.insert_temp(key, true)); From f1a0b1eb29927239abe729f086617c1867ecca03 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 18:27:22 +0100 Subject: [PATCH 0405/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 4704cc870..7adb3f622 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -7244,7 +7244,7 @@ fn corner_options_dialog(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) let key = format!("shape{k}"); let shape: CornerShape = d.fields.get(&key).and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); let resp = crate::panels::properties::corner_shape_button(ui, shape, 46.0); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ComboBox, true, format!("{} {}", tr(tip), tr(shape.label())))); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, format!("{} {}", tr(tip), tr(shape.label())))); egui::Popup::menu(&resp).show(|ui| { ui.set_min_width(150.0); for s in CornerShape::ALL { @@ -7271,7 +7271,7 @@ fn corner_options_dialog(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) crate::icons::button(ui, if linked { "link" } else { "link-broken" }, 20.0, linked, &tip) }) .inner; - resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &tip)); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &tip)); if resp.clicked() { d.fields.insert("link".into(), json!(!linked)); } From d99434b18a68d15260c12fa29e40867a58aa3f96 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 18:27:45 +0100 Subject: [PATCH 0406/1349] Corner Options: the corner shape button re-exported from main's split Properties module Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/properties.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index a05eaccc5..888302763 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -31,7 +31,7 @@ use flex::flex_section; pub(crate) use links::run_update_links; pub use links::{info_panel, links_panel, preflight_panel, update_links}; use object::{align_row, appearance_section, guide_section, quick_actions_object, transform_section, wrap_section}; -pub(crate) use object::{corner_type_dropdown, ref_point_proxy, stroke_type_dropdown}; +pub(crate) use object::{corner_shape_button, corner_type_dropdown, ref_point_proxy, stroke_type_dropdown}; use object_panels::pathfinder_row; pub use object_panels::{align_panel, attributes_panel, effects_panel, pathfinder_panel, stroke_panel, wrap_panel}; pub(crate) use text::{LANGUAGES, kerning_control, language_menu}; From d5b4e11f2d015269efb8670f3bfd650d23248883 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 18:28:05 +0100 Subject: [PATCH 0407/1349] Paragraph border corners: the corner shape painter re-exported from main's split Properties module Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/properties.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index ee3b2c80c..554014c0d 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -31,7 +31,7 @@ use flex::flex_section; pub(crate) use links::run_update_links; pub use links::{info_panel, links_panel, preflight_panel, update_links}; use object::{align_row, appearance_section, guide_section, quick_actions_object, transform_section, wrap_section}; -pub(crate) use object::{corner_type_dropdown, preview_dropdown, preview_row, ref_point_proxy, stroke_type_dropdown}; +pub(crate) use object::{corner_type_dropdown, paint_corner_shape, preview_dropdown, preview_row, ref_point_proxy, stroke_type_dropdown}; use object_panels::pathfinder_row; pub use object_panels::{align_panel, attributes_panel, effects_panel, pathfinder_panel, stroke_panel, wrap_panel}; pub(crate) use text::{LANGUAGES, kerning_control, language_menu}; From 3079cd1400e5a5eea31470eb69feafeeff94973b Mon Sep 17 00:00:00 2001 From: ashokram-si <347905169+ashokram-si@users.noreply.github.com> Date: Thu, 29 Oct 2026 23:11:37 +0530 Subject: [PATCH 0408/1349] ROADMAP: progress-log line for the spread spine line (#1838) --- ROADMAP.md | 1 + 1 file changed, 1 insertion(+) diff --git a/ROADMAP.md b/ROADMAP.md index c02176bab..0ff635795 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -380,6 +380,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-10-29** · Spreads show a spine line where their pages meet, on the canvas only (it isn't printed or exported), so the binding edge of a facing-pages spread is visible while laying out across it; right-to-left spreads and pages of different sizes put it on the edge the two pages share (#1838). No readiness percentage change. - **2026-10-27** · An iconic panel's flyout stays open while you work in the canvas or a text field: Auto-Collapse Iconic Panels is off by default, and preferences saved with it on start with it off. Preferences › Interface › Panels holds the setting next to the column bar's menu item. No readiness percentage change. - **2026-10-24** · Column rules run from the top line's ascent to the bottom line's descent, as InDesign draws them, instead of from the top to the bottom of the columns, on screen, in PDF and in PowerPoint export. The top and bottom insets shorten the rule from those lines. Existing documents draw their column rules at the new length. No readiness percentage change. - **2026-10-20** · Edit › Keyboard Shortcuts is craft-keymap's shared dialog: commands grouped by menu with Show and Filter, recording that asks before taking a key from another command, undo and redo, named shortcut sets (edits of Default become Custom; an imported set becomes a set of its own), an on-screen US keyboard, InDesign Show Set files reviewed before they apply, JSON export and an HTML summary. ui.json keeps the `shortcuts` map earlier versions read, for the active set. No readiness percentage change. From 176b35aa332502979be0809edae676172a650a0d Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 18:42:51 +0100 Subject: [PATCH 0409/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/tests.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index f144327be..299fc6a66 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3551,8 +3551,7 @@ fn paragraph_border_sides_and_corners_link_as_indesigns() { use egui_kittest::kittest::Queryable; let (app, _) = ruled_paragraph(); let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); - h.state_mut().app.ui.dialog = - Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "border", "p.borderOn": true}))); + h.state_mut().app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "border", "p.borderOn": true}))); h.run_steps(4); let field = |h: &egui_kittest::Harness<'static, crate::test_window::Window>, key: &str| { h.state().app.ui.dialog.as_ref().and_then(|d| d.fields.get(&format!("p.{key}")).cloned()).unwrap_or_default() From 25e60b515b908e5e196a85bdf46f72d4804ba43e Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 18:46:31 +0100 Subject: [PATCH 0410/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/chrome/status_bar.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 519830620..5fde929be 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -131,7 +131,7 @@ pub fn status_bar(app: &mut DesignApp, ui: &mut egui::Ui) { ui.painter().text(fr.right_center() - vec2(5.0, 0.0), egui::Align2::RIGHT_CENTER, "▾", small.clone(), t.text); let label = crate::i18n::tr(&app.ui.language, "Page"); fresp.widget_info(|| { - let mut info = egui::WidgetInfo::labeled(egui::WidgetType::ComboBox, true, label); + let mut info = egui::WidgetInfo::labeled(egui::Role::ComboBox, true, label); info.current_text_value = Some(name.clone()); info }); From 5ef8f3e5b04ad8bbcb8555e6fb0bfc3aed33b6d7 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 18:46:46 +0100 Subject: [PATCH 0411/1349] Parent page box: re-exported from main's split canvas view module Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index de4331c7d..18aabfae5 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -62,7 +62,7 @@ pub(crate) use view::page_in_view; use view::present_fit; pub use view::{ apply_view_request, can_go_through_history, current_page, current_parent_page, current_slot, current_spread, current_spread_page, drop_point, - fit, go_through_history, go_to_page, set_zoom, show_spread, step_spread, view_centre, zoom_at, + PageBox, fit, go_through_history, go_to_page, page_box, page_box_go, set_zoom, show_spread, step_spread, view_centre, zoom_at, }; pub const RULER: f32 = 15.0; From 329bff534fed36bf4cf1f3e4df0ea302818c6f46 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 18:47:05 +0100 Subject: [PATCH 0412/1349] Eyedropper: the canvas colour sampler re-exported from main's split canvas render module Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index de4331c7d..c29cbdfd9 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -44,7 +44,7 @@ use input::{press_count, release_clicks}; #[cfg(test)] use page_decor::{MAX_BASELINES, baseline_grid_lines}; use page_decor::{dashed, draw_flattener_preview, draw_guides, shown_area}; -pub use render::DisplayKey; +pub use render::{DisplayKey, color_at}; use render::render_texture; #[cfg(test)] use render::{c32, invalidate_on_display_change, screen_options}; From 15b2f49342cf648d5216751d027815ab654f67a4 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 18:49:03 +0100 Subject: [PATCH 0413/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/properties/tests.rs | 2 +- crates/ui-egui/src/panels/properties/text.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 96a1b14b6..2f6a6f4fb 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -657,7 +657,7 @@ fn double_clicking_a_fill_chip_opens_the_color_picker() { let panel = |app: DesignApp| { let mut h = Harness::builder().with_size(vec2(320.0, 1400.0)).with_step_dt(0.001).build_ui_state( |ui, app: &mut DesignApp| { - let id = egui::Id::new("test_fonts"); + let id = egui::Id::unique("test_fonts"); if ui.data(|d| d.get_temp::(id)).is_none() { crate::theme::install_fonts(ui.ctx(), ""); ui.data_mut(|d| d.insert_temp(id, true)); diff --git a/crates/ui-egui/src/panels/properties/text.rs b/crates/ui-egui/src/panels/properties/text.rs index 64c6d6890..ad25a5a5a 100644 --- a/crates/ui-egui/src/panels/properties/text.rs +++ b/crates/ui-egui/src/panels/properties/text.rs @@ -129,7 +129,7 @@ pub(super) fn text_appearance_section(app: &mut DesignApp, ui: &mut Ui) { } let resp = ui.interact(chip, ui.scope_id().with(("tchip", k)), Sense::click()).on_hover_text(format!("{label}: {sw}")); resp.widget_info(|| { - egui::WidgetInfo::labeled(egui::WidgetType::Button, true, if k == 0 { "Text fill swatch" } else { "Text stroke swatch" }) + egui::WidgetInfo::labeled(egui::Role::Button, true, if k == 0 { "Text fill swatch" } else { "Text stroke swatch" }) }); swatch_menu(app, &resp, &doc, &sw, k != 0, false, true); if resp.double_clicked() { From 9577b7f09cb0d67846905a05fecd966115b4f087 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 18:51:14 +0100 Subject: [PATCH 0414/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/properties/text.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/text.rs b/crates/ui-egui/src/panels/properties/text.rs index ad25a5a5a..a9d6e9baa 100644 --- a/crates/ui-egui/src/panels/properties/text.rs +++ b/crates/ui-egui/src/panels/properties/text.rs @@ -128,9 +128,7 @@ pub(super) fn text_appearance_section(app: &mut DesignApp, ui: &mut Ui) { ui.painter().text(chip.center(), egui::Align2::CENTER_CENTER, "T", crate::theme::semibold(12.0), tc); } let resp = ui.interact(chip, ui.scope_id().with(("tchip", k)), Sense::click()).on_hover_text(format!("{label}: {sw}")); - resp.widget_info(|| { - egui::WidgetInfo::labeled(egui::Role::Button, true, if k == 0 { "Text fill swatch" } else { "Text stroke swatch" }) - }); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, if k == 0 { "Text fill swatch" } else { "Text stroke swatch" })); swatch_menu(app, &resp, &doc, &sw, k != 0, false, true); if resp.double_clicked() { open_color_picker(app, &doc, &sw, k != 0, true); From 1905b3ef9d04b7c1c1ce279e4663268a495c720a Mon Sep 17 00:00:00 2001 From: ashokram-si <347905169+ashokram-si@users.noreply.github.com> Date: Thu, 29 Oct 2026 23:26:49 +0530 Subject: [PATCH 0415/1349] Canvas: the spine takes the spread edge's colour The spine used the UI theme's dim text colour, which follows the app theme while the paper follows the document, so on white paper it was barely visible (about 1.25:1). The spine is the inner edge of the spread, so it now uses the same dark grey hairline as the spread's outline, through one shared PAGE_EDGE constant for both; it reads on white paper and doesn't change with the theme. Not the smart-guide green, which marks snapping and would make the spine look like one. --- crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/canvas/page_decor.rs | 16 +++++++++++----- crates/ui-egui/src/canvas/tests.rs | 2 +- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index de4331c7d..7a424fa85 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -272,7 +272,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { crate::separations::paint(app, ui.ctx(), &painter, &xf, &layout, screen); let hair = 1.0 / ui.ctx().pixels_per_point(); for slot in &layout.slots { - painter.rect_stroke(xf.rect(slot.bounds), 0.0, Stroke::new(hair, Color32::from_rgb(0x4a, 0x4a, 0x4a)), StrokeKind::Outside); + painter.rect_stroke(xf.rect(slot.bounds), 0.0, Stroke::new(hair, page_decor::PAGE_EDGE), StrokeKind::Outside); } if !preview { let drag = ui.data(|d| d.get_temp::(egui::Id::unique(GUIDE_DRAG))); diff --git a/crates/ui-egui/src/canvas/page_decor.rs b/crates/ui-egui/src/canvas/page_decor.rs index c7d76412e..cddb5fd56 100644 --- a/crates/ui-egui/src/canvas/page_decor.rs +++ b/crates/ui-egui/src/canvas/page_decor.rs @@ -10,6 +10,10 @@ pub(super) fn dashed(painter: &egui::Painter, a: Pos2, b: Pos2, stroke: Stroke, painter.extend(egui::Shape::dashed_line(&[a, b], stroke, dash, gap)); } +/// The hairline around each spread and at its spine, where its pages meet: one dark grey on any +/// paper colour and in either theme, so the binding edge reads like the spread's own edge. +pub(super) const PAGE_EDGE: Color32 = Color32::from_rgb(0x4a, 0x4a, 0x4a); + /// The most baseline grid lines drawn on a page: one per point of the tallest page (216 in). pub(super) const MAX_BASELINES: usize = 216 * 72; @@ -52,7 +56,7 @@ pub(super) fn draw_guides( let Some(sp) = doc.spread(slot.spread) else { continue }; if app.ui.guides { draw_bleed_and_slug(painter, xf, doc, slot, sp); - draw_spine(painter, xf, slot, sp, t); + draw_spine(painter, xf, slot, sp); } let pasteboard = slot.xf.inverse().transform_rect_bbox(layout.pasteboard); for (pi, p) in sp.pages.iter().enumerate() { @@ -66,6 +70,7 @@ pub(super) fn draw_guides( draw_page_guides(&cx, (pi, p, pr), moving, &selection); } } + let _ = t; } /// The bleed and slug outlines of a spread, in their own colours. @@ -81,9 +86,10 @@ fn draw_bleed_and_slug(painter: &egui::Painter, xf: &Xf, doc: &Document, slot: & } } -/// The spine: a hairline where the pages of a spread meet, the full height of the taller page. -/// Screen only, like the other guides; the paper is one rectangle and exports never show a seam. -fn draw_spine(painter: &egui::Painter, xf: &Xf, slot: &SpreadSlot, sp: &designcraft_doc::Spread, t: &Tokens) { +/// The spine: a hairline where the pages of a spread meet, the full height of the taller page, in +/// the spread edge's colour ([`PAGE_EDGE`]). Screen only, like the other guides; the paper is one +/// rectangle and exports never show a seam. +fn draw_spine(painter: &egui::Painter, xf: &Xf, slot: &SpreadSlot, sp: &designcraft_doc::Spread) { let pt = |p: Point| xf.to_screen(slot.xf * p); for pair in sp.pages.windows(2) { // Bound right to left, a spread lists its right page first: take the two edges that @@ -92,7 +98,7 @@ fn draw_spine(painter: &egui::Painter, xf: &Xf, slot: &SpreadSlot, sp: &designcr let (left, right) = if a.x0 <= b.x0 { (a, b) } else { (b, a) }; let x = (left.x1 + right.x0) / 2.0; let (y0, y1) = (a.y0.min(b.y0), a.y1.max(b.y1)); - painter.line_segment([pt(Point::new(x, y0)), pt(Point::new(x, y1))], Stroke::new(hair(painter), t.text_dim)); + painter.line_segment([pt(Point::new(x, y0)), pt(Point::new(x, y1))], Stroke::new(hair(painter), PAGE_EDGE)); } } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 8ca5d6e1c..ad4720cf9 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -36,7 +36,7 @@ fn canvas_shapes(app: &mut DesignApp) -> Vec { /// The spine-coloured vertical hairlines at screen x `x` that run the full height of `page` /// (the spine of one spread shares its x with the pages of the spreads above and below it). fn vertical_lines_at(shapes: &[egui::epaint::ClippedShape], x: f32, page: Rect) -> usize { - let spine = Tokens::get(&egui::Context::default()).text_dim; + let spine = page_decor::PAGE_EDGE; shapes .iter() .filter(|c| match &c.shape { From 1ca398b0b7ec209b90f4eae6e0842b223a01c93a Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 19:00:00 +0100 Subject: [PATCH 0416/1349] Anchor point sections: the Properties helpers they use from main's split modules Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/properties.rs | 2 +- crates/ui-egui/src/panels/properties/object.rs | 2 +- crates/ui-egui/src/panels/properties/object_panels.rs | 7 ++++--- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 8978edbe2..67c28f601 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -32,7 +32,7 @@ pub(crate) use links::run_update_links; pub use links::{info_panel, links_panel, preflight_panel, update_links}; use object::{align_row, appearance_section, guide_section, quick_actions_object, transform_section, wrap_section}; pub(crate) use object::{corner_type_dropdown, ref_point_proxy, stroke_type_dropdown}; -use object_panels::pathfinder_row; +use object_panels::{anchor_point_sections, pathfinder_row}; pub use object_panels::{align_panel, attributes_panel, effects_panel, pathfinder_panel, stroke_panel, wrap_panel}; pub(crate) use text::{LANGUAGES, kerning_control, language_menu}; use text::{ diff --git a/crates/ui-egui/src/panels/properties/object.rs b/crates/ui-egui/src/panels/properties/object.rs index 50969f415..c025aad89 100644 --- a/crates/ui-egui/src/panels/properties/object.rs +++ b/crates/ui-egui/src/panels/properties/object.rs @@ -94,7 +94,7 @@ pub(super) fn transform_section(app: &mut DesignApp, ui: &mut Ui, i: &SelInfo) { /// Properties › Transform for points selected with Direct Selection: X/Y/W/H of the points' /// bounds (from the reference point); X and Y move the points, W and H spread or gather them /// about the reference point. No angles: those turn objects. -fn anchor_transform_section(app: &mut DesignApp, ui: &mut Ui, i: &SelInfo) { +pub(super) fn anchor_transform_section(app: &mut DesignApp, ui: &mut Ui, i: &SelInfo) { let u = units(app); let rp = app.ui.ref_point; let b = block(ui, 2.0 * FIELD_H + 4.0); diff --git a/crates/ui-egui/src/panels/properties/object_panels.rs b/crates/ui-egui/src/panels/properties/object_panels.rs index 08228023d..8e6c210de 100644 --- a/crates/ui-egui/src/panels/properties/object_panels.rs +++ b/crates/ui-egui/src/panels/properties/object_panels.rs @@ -1,6 +1,7 @@ +use super::object::{anchor_transform_section, appearance_section}; use super::{ - Arrowhead, Cap, DesignApp, Join, Sense, Stroke, StrokeAlign, StrokeType, Tokens, Ui, Value, caption, divider, icon_toggle, icons, json, measure, - number, pos2, sel_info, text_attrs, units, vec2, widgets, + Arrowhead, Cap, DesignApp, Join, SelInfo, Sense, Stroke, StrokeAlign, StrokeType, Tokens, Ui, Value, caption, divider, full_width, icon_toggle, + icons, json, measure, number, outline_button, pos2, rule, section, section_row, sel_info, text_attrs, units, vec2, widgets, }; /// Stroke panel: weight, cap, miter limit, join, alignment, type, arrowheads, gap colour. @@ -366,7 +367,7 @@ const CONVERT_SHAPE: [(&str, &str, &str); 9] = [ /// Points selected with Direct Selection, as InDesign's Properties shows them: Transform, /// Appearance, Convert Points (the point type of the selected points) and Delete Point(s). -fn anchor_point_sections(app: &mut DesignApp, ui: &mut Ui, i: &SelInfo) { +pub(super) fn anchor_point_sections(app: &mut DesignApp, ui: &mut Ui, i: &SelInfo) { section(ui, crate::i18n::tr(&app.ui.language, "Transform"), true); anchor_transform_section(app, ui, i); divider(ui); From 793e0fc33770b1f5b48a107e2628fef7a8f7eefe Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 19:07:36 +0100 Subject: [PATCH 0417/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/guides.rs | 2 +- crates/ui-egui/src/canvas/tests.rs | 98 ++++++++++++++--------------- 2 files changed, 50 insertions(+), 50 deletions(-) diff --git a/crates/ui-egui/src/canvas/guides.rs b/crates/ui-egui/src/canvas/guides.rs index 540a295ee..4689b5fb6 100644 --- a/crates/ui-egui/src/canvas/guides.rs +++ b/crates/ui-egui/src/canvas/guides.rs @@ -143,7 +143,7 @@ pub(super) fn guide_spot(app: &DesignApp, xf: &Xf, g: &GuideDrag) -> Option Some(r), - _ => None, - }) - .expect("the frame is previewed"); - h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); - h.run_steps(3); - let placed = h.state().session.doc().unwrap().doc.spreads[0].items.last().expect("placed").bounds(); - let shown = slot.inverse().transform_rect_bbox(preview); - for (a, b) in [(placed.x0, shown.x0), (placed.y0, shown.y0), (placed.x1, shown.x1), (placed.y1, shown.y1)] { - assert!((a - b).abs() < 0.01, "placed {placed:?}, previewed {shown:?}"); - } +/// A place-cursor drag past its 3-point threshold but short of egui's drag distance previews +/// a frame, and the release places that frame: what's shown is what lands. +#[test] +fn a_short_place_cursor_drag_places_the_frame_it_previews() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let png = designcraft_render::Rendered { width: 40, height: 20, pixels: vec![200; 40 * 20 * 4] }.to_png(); + app.run("place.load", json!({"base64": designcraft_engine::cmd::base64_encode(&png), "name": "a.png"})).unwrap(); + let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut DesignApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(6); + let (from, slot) = { + let app = h.state(); + let layout = CanvasLayout::new(&app.session.doc().unwrap().doc, false); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + (xf.to_screen(layout.slots[0].xf * Point::new(200.0, 200.0)), layout.slots[0].xf) + }; + // About 5.4 points: past the place cursor's 3, short of egui's 6. + let to = from + vec2(4.5, 3.0); + assert!((to - from).length() < h.ctx.options(|o| o.input_options.max_click_dist)); + h.hover_at(from); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + h.event(egui::Event::PointerMoved(to)); + h.run_steps(2); + let vi = h.state().view_info(); + let preview = h + .state_mut() + .session + .overlays(vi) + .into_iter() + .find_map(|o| match o { + designcraft_tools::Overlay::Marquee(r) => Some(r), + _ => None, + }) + .expect("the frame is previewed"); + h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(3); + let placed = h.state().session.doc().unwrap().doc.spreads[0].items.last().expect("placed").bounds(); + let shown = slot.inverse().transform_rect_bbox(preview); + for (a, b) in [(placed.x0, shown.x0), (placed.y0, shown.y0), (placed.x1, shown.x1), (placed.y1, shown.y1)] { + assert!((a - b).abs() < 0.01, "placed {placed:?}, previewed {shown:?}"); } +} #[test] fn a_press_after_a_drag_is_not_a_double_click() { From cdf110d6fc5bbd4f02442b8e640fd065409b9ae2 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 19:10:39 +0100 Subject: [PATCH 0418/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index c993193de..714c75c5d 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -403,7 +403,7 @@ fn draw_loaded_thumbnail(app: &DesignApp, painter: &egui::Painter, p: Pos2, t: & /// The loaded graphic's thumbnail texture, cached per image data. fn loaded_thumb_texture(ctx: &egui::Context, doc: &Document, asset: designcraft_doc::AssetId, size: (f64, f64)) -> Option { let a = doc.assets.get(&asset)?; - let key = egui::Id::new(("loaded_thumb", std::sync::Arc::as_ptr(&a.data) as usize, a.data.len(), a.page)); + let key = egui::Id::unique(("loaded_thumb", std::sync::Arc::as_ptr(&a.data) as usize, a.data.len(), a.page)); if let Some(t) = ctx.data(|d| d.get_temp::(key)) { return Some(t); } From f5647c5e081c01f70283afc927dd15d66fd07622 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 19:11:29 +0100 Subject: [PATCH 0419/1349] Grid snap test: the tool context's loaded field in main's moved canvas test Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 51d5d32d3..ed57126bb 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1823,6 +1823,7 @@ fn document_grid_is_drawn_where_points_snap_to_it() { snap: SnapView { snap_to_document_grid: true, zone_px: 20.0, ..SnapView::OFF }, unit: Unit::Points, stroke_in_front: false, + loaded: None, }; let (snapped, _) = designcraft_tools::snap::snap_point(&cx, sr, Point::new(page.x0 + 31.3, page.y0 + 47.9)); assert_eq!((snapped.x - page.x0, snapped.y - page.y0), (27.0, 45.0)); From 4321999720af5f226acbff08cf80edf78ee7634a Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 19:39:04 +0100 Subject: [PATCH 0420/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/table.rs | 2 +- crates/ui-egui/src/dialogs/tests.rs | 6 +-- crates/ui-egui/src/menus/tests.rs | 80 ++++++++++++++--------------- 3 files changed, 44 insertions(+), 44 deletions(-) diff --git a/crates/engine/src/cmd/table.rs b/crates/engine/src/cmd/table.rs index e7e9cc3e7..ffa8687c1 100644 --- a/crates/engine/src/cmd/table.rs +++ b/crates/engine/src/cmd/table.rs @@ -28,5 +28,5 @@ mod styles; mod target; pub use registry::specs; -pub use structure::{MAX_BODY_ROWS, MAX_COLUMNS, MAX_HEADER_FOOTER_ROWS}; pub(crate) use selection::step_cell; +pub use structure::{MAX_BODY_ROWS, MAX_COLUMNS, MAX_HEADER_FOOTER_ROWS}; diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index f6b689e67..577b9a3ae 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3369,7 +3369,7 @@ fn dragging_the_title_moves_the_dialog_and_dragging_the_body_does_not() { assert!((centred.center() - egui::pos2(600.0, 400.0)).length() < 1.0, "{centred:?}"); assert!(centred.width() < 1000.0 && centred.height() < 700.0, "the area is the dialog, not the backdrop: {centred:?}"); - let title = h.get_by_label("Insert Table").rect().center(); + let title = h.get_by_label("Insert Table").rect().center(); drag(&mut h, title, title + vec2(100.0, 60.0)); let moved = rect(&h); assert!((moved.min - centred.min - vec2(100.0, 60.0)).length() < 2.0, "{centred:?} -> {moved:?}"); @@ -3379,7 +3379,7 @@ fn dragging_the_title_moves_the_dialog_and_dragging_the_body_does_not() { assert_eq!(rect(&h), moved, "a drag in the body leaves the dialog in place"); // The title row stays inside the top edge. - let title = h.get_by_label("Insert Table").rect().center(); + let title = h.get_by_label("Insert Table").rect().center(); drag(&mut h, title, title - vec2(0.0, 1000.0)); assert!(rect(&h).top().abs() < 1.0, "{:?}", rect(&h)); @@ -3391,7 +3391,7 @@ fn dragging_the_title_moves_the_dialog_and_dragging_the_body_does_not() { assert!((rect(&h).center() - centred.center()).length() < 1.0, "{:?}", rect(&h)); // Past the left edge, about 100 px of the title row stays inside. - let title = h.get_by_label("Insert Table").rect().center(); + let title = h.get_by_label("Insert Table").rect().center(); drag(&mut h, title, title - vec2(900.0, 0.0)); assert!((rect(&h).right() - 100.0).abs() < 2.0, "{:?}", rect(&h)); } diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 57ce99cd6..88e826607 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -2107,46 +2107,46 @@ fn context_menus_hold_commands_and_menu_bar_submenus() { } } - #[test] - fn the_table_menu_follows_indesigns_order() { - // InDesign's Table menu with a text insertion point (Adobe's "How to make a table"). - let table = menu_tree().into_iter().find(|(m, _)| *m == "Table").unwrap().1; - let labels: Vec = table - .iter() - .map(|i| match i { - Item::Sep => "-".to_string(), - Item::Sub(n, _) => format!("{n} >"), - Item::Cmd { label, .. } => label.clone(), - }) - .collect(); - let expected = [ - "Insert Table…", - "Convert Text to Table", - "Convert Table to Text", - "-", - "Cell Options >", - "-", - "Insert >", - "Delete >", - "Select >", - "-", - "Merge Cells", - "Unmerge Cells", - "Split Cell Horizontally", - "Split Cell Vertically", - "Convert Cell Type >", - "Convert Rows >", - "-", - "Distribute Rows Evenly", - "Distribute Columns Evenly", - ]; - assert_eq!(labels, expected); - // Cmd+Alt+Shift+T opens the dialog, as InDesign's; the engine command has no shortcut of - // its own. The Table panel is in Window › Type & Tables. - assert_eq!(ui_label("app.insertTableDialog").and_then(|c| c.1), Some("Cmd+Alt+Shift+T")); - assert_eq!(designcraft_engine::find_command("table.insert").unwrap().shortcut, None); - assert_eq!(ui_label("app.tablePanel").and_then(|c| c.1), Some("Shift+F9")); - } +#[test] +fn the_table_menu_follows_indesigns_order() { + // InDesign's Table menu with a text insertion point (Adobe's "How to make a table"). + let table = menu_tree().into_iter().find(|(m, _)| *m == "Table").unwrap().1; + let labels: Vec = table + .iter() + .map(|i| match i { + Item::Sep => "-".to_string(), + Item::Sub(n, _) => format!("{n} >"), + Item::Cmd { label, .. } => label.clone(), + }) + .collect(); + let expected = [ + "Insert Table…", + "Convert Text to Table", + "Convert Table to Text", + "-", + "Cell Options >", + "-", + "Insert >", + "Delete >", + "Select >", + "-", + "Merge Cells", + "Unmerge Cells", + "Split Cell Horizontally", + "Split Cell Vertically", + "Convert Cell Type >", + "Convert Rows >", + "-", + "Distribute Rows Evenly", + "Distribute Columns Evenly", + ]; + assert_eq!(labels, expected); + // Cmd+Alt+Shift+T opens the dialog, as InDesign's; the engine command has no shortcut of + // its own. The Table panel is in Window › Type & Tables. + assert_eq!(ui_label("app.insertTableDialog").and_then(|c| c.1), Some("Cmd+Alt+Shift+T")); + assert_eq!(designcraft_engine::find_command("table.insert").unwrap().shortcut, None); + assert_eq!(ui_label("app.tablePanel").and_then(|c| c.1), Some("Shift+F9")); +} #[test] fn the_type_menu_follows_indesigns_order() { From ae28681b2cc65ccdb1a63995a50f9f339e9b00fd Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 19:43:55 +0100 Subject: [PATCH 0421/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/table.rs | 2 +- crates/ui-egui/src/dialogs/tests.rs | 6 +-- crates/ui-egui/src/menus/tests.rs | 80 ++++++++++++++--------------- 3 files changed, 44 insertions(+), 44 deletions(-) diff --git a/crates/engine/src/cmd/table.rs b/crates/engine/src/cmd/table.rs index 7ad499635..b304edada 100644 --- a/crates/engine/src/cmd/table.rs +++ b/crates/engine/src/cmd/table.rs @@ -28,5 +28,5 @@ mod styles; mod target; pub use registry::specs; -pub use structure::{MAX_BODY_ROWS, MAX_COLUMNS, MAX_CONVERTED_CELLS, MAX_HEADER_FOOTER_ROWS}; pub(crate) use selection::step_cell; +pub use structure::{MAX_BODY_ROWS, MAX_COLUMNS, MAX_CONVERTED_CELLS, MAX_HEADER_FOOTER_ROWS}; diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index f6b689e67..577b9a3ae 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3369,7 +3369,7 @@ fn dragging_the_title_moves_the_dialog_and_dragging_the_body_does_not() { assert!((centred.center() - egui::pos2(600.0, 400.0)).length() < 1.0, "{centred:?}"); assert!(centred.width() < 1000.0 && centred.height() < 700.0, "the area is the dialog, not the backdrop: {centred:?}"); - let title = h.get_by_label("Insert Table").rect().center(); + let title = h.get_by_label("Insert Table").rect().center(); drag(&mut h, title, title + vec2(100.0, 60.0)); let moved = rect(&h); assert!((moved.min - centred.min - vec2(100.0, 60.0)).length() < 2.0, "{centred:?} -> {moved:?}"); @@ -3379,7 +3379,7 @@ fn dragging_the_title_moves_the_dialog_and_dragging_the_body_does_not() { assert_eq!(rect(&h), moved, "a drag in the body leaves the dialog in place"); // The title row stays inside the top edge. - let title = h.get_by_label("Insert Table").rect().center(); + let title = h.get_by_label("Insert Table").rect().center(); drag(&mut h, title, title - vec2(0.0, 1000.0)); assert!(rect(&h).top().abs() < 1.0, "{:?}", rect(&h)); @@ -3391,7 +3391,7 @@ fn dragging_the_title_moves_the_dialog_and_dragging_the_body_does_not() { assert!((rect(&h).center() - centred.center()).length() < 1.0, "{:?}", rect(&h)); // Past the left edge, about 100 px of the title row stays inside. - let title = h.get_by_label("Insert Table").rect().center(); + let title = h.get_by_label("Insert Table").rect().center(); drag(&mut h, title, title - vec2(900.0, 0.0)); assert!((rect(&h).right() - 100.0).abs() < 2.0, "{:?}", rect(&h)); } diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 0fc54a059..69e72e47e 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -2107,46 +2107,46 @@ fn context_menus_hold_commands_and_menu_bar_submenus() { } } - #[test] - fn the_table_menu_follows_indesigns_order() { - // InDesign's Table menu with a text insertion point (Adobe's "How to make a table"). - let table = menu_tree().into_iter().find(|(m, _)| *m == "Table").unwrap().1; - let labels: Vec = table - .iter() - .map(|i| match i { - Item::Sep => "-".to_string(), - Item::Sub(n, _) => format!("{n} >"), - Item::Cmd { label, .. } => label.clone(), - }) - .collect(); - let expected = [ - "Insert Table…", - "Convert Text to Table…", - "Convert Table to Text…", - "-", - "Cell Options >", - "-", - "Insert >", - "Delete >", - "Select >", - "-", - "Merge Cells", - "Unmerge Cells", - "Split Cell Horizontally", - "Split Cell Vertically", - "Convert Cell Type >", - "Convert Rows >", - "-", - "Distribute Rows Evenly", - "Distribute Columns Evenly", - ]; - assert_eq!(labels, expected); - // Cmd+Alt+Shift+T opens the dialog, as InDesign's; the engine command has no shortcut of - // its own. The Table panel is in Window › Type & Tables. - assert_eq!(ui_label("app.insertTableDialog").and_then(|c| c.1), Some("Cmd+Alt+Shift+T")); - assert_eq!(designcraft_engine::find_command("table.insert").unwrap().shortcut, None); - assert_eq!(ui_label("app.tablePanel").and_then(|c| c.1), Some("Shift+F9")); - } +#[test] +fn the_table_menu_follows_indesigns_order() { + // InDesign's Table menu with a text insertion point (Adobe's "How to make a table"). + let table = menu_tree().into_iter().find(|(m, _)| *m == "Table").unwrap().1; + let labels: Vec = table + .iter() + .map(|i| match i { + Item::Sep => "-".to_string(), + Item::Sub(n, _) => format!("{n} >"), + Item::Cmd { label, .. } => label.clone(), + }) + .collect(); + let expected = [ + "Insert Table…", + "Convert Text to Table…", + "Convert Table to Text…", + "-", + "Cell Options >", + "-", + "Insert >", + "Delete >", + "Select >", + "-", + "Merge Cells", + "Unmerge Cells", + "Split Cell Horizontally", + "Split Cell Vertically", + "Convert Cell Type >", + "Convert Rows >", + "-", + "Distribute Rows Evenly", + "Distribute Columns Evenly", + ]; + assert_eq!(labels, expected); + // Cmd+Alt+Shift+T opens the dialog, as InDesign's; the engine command has no shortcut of + // its own. The Table panel is in Window › Type & Tables. + assert_eq!(ui_label("app.insertTableDialog").and_then(|c| c.1), Some("Cmd+Alt+Shift+T")); + assert_eq!(designcraft_engine::find_command("table.insert").unwrap().shortcut, None); + assert_eq!(ui_label("app.tablePanel").and_then(|c| c.1), Some("Shift+F9")); +} #[test] fn the_type_menu_follows_indesigns_order() { From 21f21045af3520d43a5b36ba4a7bf0ab61a6c570 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 19:44:05 +0100 Subject: [PATCH 0422/1349] Tests: the branch's dialog tests beside main's dialog test helpers (dialogs/tests.rs) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 46 ----------------------------- crates/ui-egui/src/dialogs/tests.rs | 46 +++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 46 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6de67e638..6db142dcd 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -245,52 +245,6 @@ fn color_theme(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { mod color_theme_tests { use super::*; - /// Insert Table: the dimensions as typed, and the Table Style chosen is applied to the new - /// table; [Basic Table] (the default) leaves it unstyled. - #[test] - fn insert_table_applies_its_dimensions_and_table_style() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("style.table.create", json!({"name": "Grid"})).unwrap(); - for (style, expected) in [("Grid", "Grid"), (designcraft_doc::BASIC_TABLE, "")] { - app.run("frame.create", json!({"rect": [72, 72, 372, 372], "content": "text"})).unwrap(); - assert_eq!(app.run("app.insertTableDialog", json!({})).unwrap(), Value::Null); - for (field, value) in [("bodyRows", json!(5)), ("columns", json!(3)), ("headerRows", json!(1)), ("tableStyle", json!(style))] { - ctl(&mut app, "ui.dialog.set", json!({"field": field, "value": value})); - } - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); - let t = app.run("table.get", json!({})).unwrap(); - let len = |k: &str| t[k].as_array().map_or(0, Vec::len); - assert_eq!((len("rows"), len("columns"), t["headerRows"].as_u64()), (6, 3, Some(1)), "{t}"); - assert_eq!(t["style"].as_str().unwrap_or(""), expected, "{t}"); - // One Insert Table, one undo. - app.run("edit.undo", json!({})).unwrap(); - assert!(app.run("table.get", json!({})).is_err(), "the table is gone"); - } - // A null style is no style: the table is made, unstyled. - app.run("frame.create", json!({"rect": [72, 72, 372, 372], "content": "text"})).unwrap(); - app.run("app.insertTableDialog", json!({})).unwrap(); - ctl(&mut app, "ui.dialog.set", json!({"field": "tableStyle", "value": null})); - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); - assert_eq!(app.run("table.get", json!({})).unwrap()["style"].as_str().unwrap_or(""), ""); - app.run("edit.undo", json!({})).unwrap(); - // A style that no longer exists changes nothing. - let tables = |app: &DesignApp| app.session.active().unwrap().doc.stories.values().map(|s| s.tables.len()).sum::(); - app.run("frame.create", json!({"rect": [72, 72, 372, 372], "content": "text"})).unwrap(); - app.run("app.insertTableDialog", json!({})).unwrap(); - ctl(&mut app, "ui.dialog.set", json!({"field": "tableStyle", "value": "Gone"})); - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false); - assert_eq!(tables(&app), 0); - let d = app.ui.dialog.as_ref().expect("the dialog stays open to be corrected"); - assert_eq!((d.id.as_str(), d.s("tableStyle")), ("insertTable", "Gone".to_string())); - // So does a style that isn't a name: the command refuses it, rather than making the table - // unstyled. - ctl(&mut app, "ui.dialog.set", json!({"field": "tableStyle", "value": 42})); - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false); - assert_eq!(tables(&app), 0); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("insertTable"), "the dialog stays open"); - } - #[test] fn color_theme_cancel_is_read_only_and_confirm_adds_the_preview() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 577b9a3ae..4f5c825ba 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3521,3 +3521,49 @@ fn character_style_options_set_the_digits() { assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi)); } + +/// Insert Table: the dimensions as typed, and the Table Style chosen is applied to the new +/// table; [Basic Table] (the default) leaves it unstyled. +#[test] +fn insert_table_applies_its_dimensions_and_table_style() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("style.table.create", json!({"name": "Grid"})).unwrap(); + for (style, expected) in [("Grid", "Grid"), (designcraft_doc::BASIC_TABLE, "")] { + app.run("frame.create", json!({"rect": [72, 72, 372, 372], "content": "text"})).unwrap(); + assert_eq!(app.run("app.insertTableDialog", json!({})).unwrap(), Value::Null); + for (field, value) in [("bodyRows", json!(5)), ("columns", json!(3)), ("headerRows", json!(1)), ("tableStyle", json!(style))] { + ctl(&mut app, "ui.dialog.set", json!({"field": field, "value": value})); + } + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); + let t = app.run("table.get", json!({})).unwrap(); + let len = |k: &str| t[k].as_array().map_or(0, Vec::len); + assert_eq!((len("rows"), len("columns"), t["headerRows"].as_u64()), (6, 3, Some(1)), "{t}"); + assert_eq!(t["style"].as_str().unwrap_or(""), expected, "{t}"); + // One Insert Table, one undo. + app.run("edit.undo", json!({})).unwrap(); + assert!(app.run("table.get", json!({})).is_err(), "the table is gone"); + } + // A null style is no style: the table is made, unstyled. + app.run("frame.create", json!({"rect": [72, 72, 372, 372], "content": "text"})).unwrap(); + app.run("app.insertTableDialog", json!({})).unwrap(); + ctl(&mut app, "ui.dialog.set", json!({"field": "tableStyle", "value": null})); + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); + assert_eq!(app.run("table.get", json!({})).unwrap()["style"].as_str().unwrap_or(""), ""); + app.run("edit.undo", json!({})).unwrap(); + // A style that no longer exists changes nothing. + let tables = |app: &DesignApp| app.session.active().unwrap().doc.stories.values().map(|s| s.tables.len()).sum::(); + app.run("frame.create", json!({"rect": [72, 72, 372, 372], "content": "text"})).unwrap(); + app.run("app.insertTableDialog", json!({})).unwrap(); + ctl(&mut app, "ui.dialog.set", json!({"field": "tableStyle", "value": "Gone"})); + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false); + assert_eq!(tables(&app), 0); + let d = app.ui.dialog.as_ref().expect("the dialog stays open to be corrected"); + assert_eq!((d.id.as_str(), d.s("tableStyle")), ("insertTable", "Gone".to_string())); + // So does a style that isn't a name: the command refuses it, rather than making the table + // unstyled. + ctl(&mut app, "ui.dialog.set", json!({"field": "tableStyle", "value": 42})); + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false); + assert_eq!(tables(&app), 0); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("insertTable"), "the dialog stays open"); +} From 62387aeefd46965b79adf6c6d03856f96e508b3d Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 19:44:07 +0100 Subject: [PATCH 0423/1349] Tests: the branch's dialog tests beside main's dialog test helpers (dialogs/tests.rs) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 128 ---------------------------- crates/ui-egui/src/dialogs/tests.rs | 128 ++++++++++++++++++++++++++++ 2 files changed, 128 insertions(+), 128 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 4145ba7d2..f4b5730e6 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -186,134 +186,6 @@ fn color_theme(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { mod color_theme_tests { use super::*; - /// Replace the text of the field beside the `nth` label `label` (on its row, to its right) with - /// `new`, and leave the field. - fn retype_beside(h: &mut egui_kittest::Harness<'static, crate::test_window::Window>, label: &str, nth: usize, new: &str) { - use egui_kittest::kittest::Queryable; - let l = h.get_all_by_label(label).nth(nth).unwrap_or_else(|| panic!("no label {label} #{nth}")).rect(); - let field = h - .get_all_by(|n| n.role() == egui::accesskit::Role::TextInput) - .map(|n| n.rect()) - .filter(|r| r.center().x > l.max.x && (r.center().y - l.center().y).abs() < l.height().max(8.0)) - .min_by(|a, b| a.min.x.total_cmp(&b.min.x)) - .unwrap_or_else(|| panic!("no field beside {label} #{nth}")) - .center(); - crate::test_window::click_at(h, field); - h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); - h.event(egui::Event::Text(new.into())); - h.run_steps(1); - // Tab leaves the field (Enter would be the dialog's OK). - h.key_press(egui::Key::Tab); - h.run_steps(3); - } - - /// The course's chapter 40: Paragraph Border's four weights are linked as InDesign's, so a - /// side typed in sets all four; with the link off ("Make all settings the same") a side is set - /// alone, as the lesson gives the border only a thick left side. The corners link the same way. - #[test] - fn paragraph_border_sides_and_corners_link_as_indesigns() { - use egui_kittest::kittest::Queryable; - let (app, _) = ruled_paragraph(); - let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); - h.state_mut().app.ui.dialog = - Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "border", "p.borderOn": true}))); - h.run_steps(4); - let field = |h: &egui_kittest::Harness<'static, crate::test_window::Window>, key: &str| { - h.state().app.ui.dialog.as_ref().and_then(|d| d.fields.get(&format!("p.{key}")).cloned()).unwrap_or_default() - }; - // The four weights start the same, so linked: Top sets them all. - retype_beside(&mut h, "Top:", 0, "3"); - assert_eq!(field(&h, "borderWeights"), json!([3.0, 3.0, 3.0, 3.0])); - // Unlinked, Left alone takes 10 pt. - // The link of the weights (0), corners (1) or offsets (2), where it is now: the dialog - // scrolls as fields take focus. - let link = |h: &egui_kittest::Harness<'static, crate::test_window::Window>, n: usize| { - let links: Vec = h.get_all_by_label("Make all settings the same").map(|n| n.rect()).collect(); - assert_eq!(links.len(), 3, "weights, corners and offsets each have a link"); - links[n].center() - }; - let at = link(&h, 0); - crate::test_window::click_at(&mut h, at); - retype_beside(&mut h, "Left:", 0, "10"); - assert_eq!(field(&h, "borderWeights"), json!([3.0, 10.0, 3.0, 3.0])); - // Linked again, the four take Top's weight; unlinked once more for the thick left side. - let at = link(&h, 0); - crate::test_window::click_at(&mut h, at); - assert_eq!(field(&h, "borderWeights"), json!([3.0, 3.0, 3.0, 3.0])); - let at = link(&h, 0); - crate::test_window::click_at(&mut h, at); - retype_beside(&mut h, "Left:", 0, "10"); - assert_eq!(field(&h, "borderWeights"), json!([3.0, 10.0, 3.0, 3.0])); - // The corners start the same too: Top Left's size goes to all four. - retype_beside(&mut h, "Top Left Corner", 0, "0p4"); - let corners = field(&h, "borderCorners"); - assert!((0..4).all(|i| corners[i]["size"] == json!(4.0)), "{corners}"); - // Unlinked, Top Right alone takes 0p8; linked again, all four take Top Left's 4 pt. - let at = link(&h, 1); - crate::test_window::click_at(&mut h, at); - retype_beside(&mut h, "Top Right Corner", 0, "0p8"); - assert_eq!(field(&h, "borderCorners")[1]["size"], json!(8.0)); - assert_eq!(field(&h, "borderCorners")[0]["size"], json!(4.0)); - let at = link(&h, 1); - crate::test_window::click_at(&mut h, at); - let corners = field(&h, "borderCorners"); - assert!((0..4).all(|i| corners[i] == corners[0] && corners[i]["size"] == json!(4.0)), "{corners}"); - confirm(&mut h.state_mut().app).unwrap(); - let style = h.state().app.session.doc().unwrap().doc.styles.para("Ruled Child").cloned().unwrap(); - assert_eq!(style.para.border_weights, Some([3.0, 10.0, 3.0, 3.0])); - } - - /// The course's chapter 41: Paragraph Shading as InDesign's. The page is headed with its name; - /// the tint has Overprint beside it; the corners are a two-by-two grid whose shape menus show - /// the shapes. The lesson rounds the top two corners at 10 pt, unlinked, and moves the - /// offsets. - #[test] - fn paragraph_shading_page_is_laid_out_as_indesigns() { - use designcraft_geom::corners::CornerShape; - use egui_kittest::kittest::Queryable; - let (app, _) = ruled_paragraph(); - let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); - h.state_mut().app.ui.dialog = - Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "shading", "p.shadingOn": true}))); - h.run_steps(4); - let field = |h: &egui_kittest::Harness<'static, crate::test_window::Window>, key: &str| { - h.state().app.ui.dialog.as_ref().and_then(|d| d.fields.get(&format!("p.{key}")).cloned()).unwrap_or_default() - }; - assert!(h.get_all_by_label("Paragraph Shading").count() >= 2, "the section list and the page's heading"); - h.get_by_label("Overprint").click(); - h.run_steps(2); - assert_eq!(field(&h, "shadingOverprint"), json!(true)); - // The corners' link (0) and the offsets' (1). - let link = |h: &egui_kittest::Harness<'static, crate::test_window::Window>, n: usize| { - let links: Vec = h.get_all_by_label("Make all settings the same").map(|n| n.rect()).collect(); - assert_eq!(links.len(), 2, "corners and offsets each have a link"); - links[n].center() - }; - let at = link(&h, 0); - crate::test_window::click_at(&mut h, at); - for (corner, nth) in [("Top Left Corner", 0), ("Top Right Corner", 1)] { - retype_beside(&mut h, corner, 0, "10 pt"); - h.get_all_by_label("Corner Shape").nth(nth).unwrap().click(); - h.run_steps(2); - h.get_by_label("Rounded").click(); - h.run_steps(2); - } - let corners: [designcraft_geom::corners::Corner; 4] = serde_json::from_value(field(&h, "shadingCorners")).unwrap(); - assert_eq!( - corners.map(|c| (c.shape, c.size)), - [(CornerShape::Rounded, 10.0), (CornerShape::Rounded, 10.0), (CornerShape::None, 0.0), (CornerShape::None, 0.0)] - ); - // The offsets, unlinked: Top alone. - let at = link(&h, 1); - crate::test_window::click_at(&mut h, at); - retype_beside(&mut h, "Top:", 0, "3 pt"); - assert_eq!(field(&h, "shadingOffsets"), json!([3.0, 0.0, 0.0, 0.0])); - confirm(&mut h.state_mut().app).unwrap(); - let style = h.state().app.session.doc().unwrap().doc.styles.para("Ruled Child").cloned().unwrap(); - assert_eq!((style.para.shading_on, style.para.shading_overprint), (Some(true), Some(true))); - assert_eq!(style.para.shading_corners.map(|c| c[1].shape), Some(CornerShape::Rounded)); - } - #[test] fn color_theme_cancel_is_read_only_and_confirm_adds_the_preview() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 84cbf3bea..1cfd51abb 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3521,3 +3521,131 @@ fn character_style_options_set_the_digits() { assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi)); } + +/// Replace the text of the field beside the `nth` label `label` (on its row, to its right) with +/// `new`, and leave the field. +fn retype_beside(h: &mut egui_kittest::Harness<'static, crate::test_window::Window>, label: &str, nth: usize, new: &str) { + use egui_kittest::kittest::Queryable; + let l = h.get_all_by_label(label).nth(nth).unwrap_or_else(|| panic!("no label {label} #{nth}")).rect(); + let field = h + .get_all_by(|n| n.role() == egui::accesskit::Role::TextInput) + .map(|n| n.rect()) + .filter(|r| r.center().x > l.max.x && (r.center().y - l.center().y).abs() < l.height().max(8.0)) + .min_by(|a, b| a.min.x.total_cmp(&b.min.x)) + .unwrap_or_else(|| panic!("no field beside {label} #{nth}")) + .center(); + crate::test_window::click_at(h, field); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(new.into())); + h.run_steps(1); + // Tab leaves the field (Enter would be the dialog's OK). + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +/// The course's chapter 40: Paragraph Border's four weights are linked as InDesign's, so a +/// side typed in sets all four; with the link off ("Make all settings the same") a side is set +/// alone, as the lesson gives the border only a thick left side. The corners link the same way. +#[test] +fn paragraph_border_sides_and_corners_link_as_indesigns() { + use egui_kittest::kittest::Queryable; + let (app, _) = ruled_paragraph(); + let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); + h.state_mut().app.ui.dialog = + Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "border", "p.borderOn": true}))); + h.run_steps(4); + let field = |h: &egui_kittest::Harness<'static, crate::test_window::Window>, key: &str| { + h.state().app.ui.dialog.as_ref().and_then(|d| d.fields.get(&format!("p.{key}")).cloned()).unwrap_or_default() + }; + // The four weights start the same, so linked: Top sets them all. + retype_beside(&mut h, "Top:", 0, "3"); + assert_eq!(field(&h, "borderWeights"), json!([3.0, 3.0, 3.0, 3.0])); + // Unlinked, Left alone takes 10 pt. + // The link of the weights (0), corners (1) or offsets (2), where it is now: the dialog + // scrolls as fields take focus. + let link = |h: &egui_kittest::Harness<'static, crate::test_window::Window>, n: usize| { + let links: Vec = h.get_all_by_label("Make all settings the same").map(|n| n.rect()).collect(); + assert_eq!(links.len(), 3, "weights, corners and offsets each have a link"); + links[n].center() + }; + let at = link(&h, 0); + crate::test_window::click_at(&mut h, at); + retype_beside(&mut h, "Left:", 0, "10"); + assert_eq!(field(&h, "borderWeights"), json!([3.0, 10.0, 3.0, 3.0])); + // Linked again, the four take Top's weight; unlinked once more for the thick left side. + let at = link(&h, 0); + crate::test_window::click_at(&mut h, at); + assert_eq!(field(&h, "borderWeights"), json!([3.0, 3.0, 3.0, 3.0])); + let at = link(&h, 0); + crate::test_window::click_at(&mut h, at); + retype_beside(&mut h, "Left:", 0, "10"); + assert_eq!(field(&h, "borderWeights"), json!([3.0, 10.0, 3.0, 3.0])); + // The corners start the same too: Top Left's size goes to all four. + retype_beside(&mut h, "Top Left Corner", 0, "0p4"); + let corners = field(&h, "borderCorners"); + assert!((0..4).all(|i| corners[i]["size"] == json!(4.0)), "{corners}"); + // Unlinked, Top Right alone takes 0p8; linked again, all four take Top Left's 4 pt. + let at = link(&h, 1); + crate::test_window::click_at(&mut h, at); + retype_beside(&mut h, "Top Right Corner", 0, "0p8"); + assert_eq!(field(&h, "borderCorners")[1]["size"], json!(8.0)); + assert_eq!(field(&h, "borderCorners")[0]["size"], json!(4.0)); + let at = link(&h, 1); + crate::test_window::click_at(&mut h, at); + let corners = field(&h, "borderCorners"); + assert!((0..4).all(|i| corners[i] == corners[0] && corners[i]["size"] == json!(4.0)), "{corners}"); + confirm(&mut h.state_mut().app).unwrap(); + let style = h.state().app.session.doc().unwrap().doc.styles.para("Ruled Child").cloned().unwrap(); + assert_eq!(style.para.border_weights, Some([3.0, 10.0, 3.0, 3.0])); +} + +/// The course's chapter 41: Paragraph Shading as InDesign's. The page is headed with its name; +/// the tint has Overprint beside it; the corners are a two-by-two grid whose shape menus show +/// the shapes. The lesson rounds the top two corners at 10 pt, unlinked, and moves the +/// offsets. +#[test] +fn paragraph_shading_page_is_laid_out_as_indesigns() { + use designcraft_geom::corners::CornerShape; + use egui_kittest::kittest::Queryable; + let (app, _) = ruled_paragraph(); + let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); + h.state_mut().app.ui.dialog = + Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "shading", "p.shadingOn": true}))); + h.run_steps(4); + let field = |h: &egui_kittest::Harness<'static, crate::test_window::Window>, key: &str| { + h.state().app.ui.dialog.as_ref().and_then(|d| d.fields.get(&format!("p.{key}")).cloned()).unwrap_or_default() + }; + assert!(h.get_all_by_label("Paragraph Shading").count() >= 2, "the section list and the page's heading"); + h.get_by_label("Overprint").click(); + h.run_steps(2); + assert_eq!(field(&h, "shadingOverprint"), json!(true)); + // The corners' link (0) and the offsets' (1). + let link = |h: &egui_kittest::Harness<'static, crate::test_window::Window>, n: usize| { + let links: Vec = h.get_all_by_label("Make all settings the same").map(|n| n.rect()).collect(); + assert_eq!(links.len(), 2, "corners and offsets each have a link"); + links[n].center() + }; + let at = link(&h, 0); + crate::test_window::click_at(&mut h, at); + for (corner, nth) in [("Top Left Corner", 0), ("Top Right Corner", 1)] { + retype_beside(&mut h, corner, 0, "10 pt"); + h.get_all_by_label("Corner Shape").nth(nth).unwrap().click(); + h.run_steps(2); + h.get_by_label("Rounded").click(); + h.run_steps(2); + } + let corners: [designcraft_geom::corners::Corner; 4] = serde_json::from_value(field(&h, "shadingCorners")).unwrap(); + assert_eq!( + corners.map(|c| (c.shape, c.size)), + [(CornerShape::Rounded, 10.0), (CornerShape::Rounded, 10.0), (CornerShape::None, 0.0), (CornerShape::None, 0.0)] + ); + // The offsets, unlinked: Top alone. + let at = link(&h, 1); + crate::test_window::click_at(&mut h, at); + retype_beside(&mut h, "Top:", 0, "3 pt"); + assert_eq!(field(&h, "shadingOffsets"), json!([3.0, 0.0, 0.0, 0.0])); + confirm(&mut h.state_mut().app).unwrap(); + let style = h.state().app.session.doc().unwrap().doc.styles.para("Ruled Child").cloned().unwrap(); + assert_eq!((style.para.shading_on, style.para.shading_overprint), (Some(true), Some(true))); + assert_eq!(style.para.shading_corners.map(|c| c[1].shape), Some(CornerShape::Rounded)); +} From 47204fa0bb090411c7a526fe0e5e687e04ca00d4 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 19:44:08 +0100 Subject: [PATCH 0424/1349] Tests: the branch's dialog tests beside main's dialog test helpers (dialogs/tests.rs) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 67 ----------------------------- crates/ui-egui/src/dialogs/tests.rs | 67 +++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 67 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 5aad7fecd..d9d48e416 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -186,73 +186,6 @@ fn color_theme(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { mod color_theme_tests { use super::*; - /// The course's chapter 26: Preferences › Interface as InDesign's. A Color Theme swatch shows - /// its theme at once and Cancel goes back; OK keeps the theme and the Tools panel's columns. - /// UI Size is in a UI Scaling section of its own. - #[test] - fn preferences_interface_sets_the_color_theme_and_tools_panel() { - use crate::theme::Brightness; - use egui::accesskit::Role; - use egui_kittest::{Harness, kittest::Queryable}; - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let opened = app.ui.brightness; - let open = |app: &mut DesignApp| { - app.run("app.preferences", json!({})).unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("section".into(), json!("interface")); - }; - open(&mut app); - let mut h = Harness::builder().with_size(egui::vec2(1100.0, 760.0)).build_ui_state( - |ui, app: &mut DesignApp| { - let key = egui::Id::new("prefs_interface_test_fonts"); - if ui.data(|d| d.get_temp::(key)).is_none() { - crate::theme::install_fonts(ui.ctx(), ""); - ui.data_mut(|d| d.insert_temp(key, true)); - return; - } - show(app, ui.ctx()); - }, - app, - ); - h.run_steps(3); - let swatch = - |h: &Harness<'_, DesignApp>, name: &str| h.get_by(|n| n.role() == Role::RadioButton && n.label().as_deref() == Some(name)).click(); - for l in ["Appearance", "Color Theme:", "Panels", "Tools Panel:"] { - assert!(h.query_by_label(l).is_some(), "{l}"); - } - // A click shows the theme at once; Cancel goes back. - swatch(&h, "Light"); - h.run_steps(3); - assert_eq!(h.state().ui.brightness, Brightness::Light); - h.get_by_label("Cancel").click(); - h.run_steps(3); - assert!(h.state().ui.dialog.is_none()); - assert_eq!(h.state().ui.brightness, opened, "Cancel goes back to the theme Preferences opened with"); - // OK keeps the theme and the Tools panel's columns. - open(h.state_mut()); - h.run_steps(3); - swatch(&h, "Dark"); - h.run_steps(2); - h.get_by(|n| n.role() == Role::ComboBox && n.value().as_deref() == Some("Single Column")).click(); - h.run_steps(2); - h.get_by_label("Double Column").click(); - h.run_steps(2); - h.get_by_label(" OK ").click(); - h.run_steps(3); - assert!(h.state().ui.dialog.is_none()); - assert_eq!(h.state().ui.brightness, Brightness::Dark); - assert!(h.state().ui.tools_double_column); - // The same command the Window menu toggles, with an explicit state for Preferences. - assert_eq!(h.state_mut().run("window.toolsDoubleColumn", json!({"on": false})).unwrap(), json!(false)); - assert_eq!(h.state_mut().run("window.toolsDoubleColumn", json!({"on": false})).unwrap(), json!(false), "set, not toggled"); - assert_eq!(h.state_mut().run("window.toolsDoubleColumn", json!({})).unwrap(), json!(true), "toggled without `on`"); - // UI Size has a section of its own. - open(h.state_mut()); - h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("section".into(), json!("uiScaling")); - h.run_steps(3); - assert!(h.query_by_label("UI Size:").is_some()); - } - #[test] fn color_theme_cancel_is_read_only_and_confirm_adds_the_preview() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 84cbf3bea..9c99c92b4 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3521,3 +3521,70 @@ fn character_style_options_set_the_digits() { assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi)); } + +/// The course's chapter 26: Preferences › Interface as InDesign's. A Color Theme swatch shows +/// its theme at once and Cancel goes back; OK keeps the theme and the Tools panel's columns. +/// UI Size is in a UI Scaling section of its own. +#[test] +fn preferences_interface_sets_the_color_theme_and_tools_panel() { + use crate::theme::Brightness; + use egui::accesskit::Role; + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let opened = app.ui.brightness; + let open = |app: &mut DesignApp| { + app.run("app.preferences", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("section".into(), json!("interface")); + }; + open(&mut app); + let mut h = Harness::builder().with_size(egui::vec2(1100.0, 760.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let key = egui::Id::new("prefs_interface_test_fonts"); + if ui.data(|d| d.get_temp::(key)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(key, true)); + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(3); + let swatch = + |h: &Harness<'_, DesignApp>, name: &str| h.get_by(|n| n.role() == Role::RadioButton && n.label().as_deref() == Some(name)).click(); + for l in ["Appearance", "Color Theme:", "Panels", "Tools Panel:"] { + assert!(h.query_by_label(l).is_some(), "{l}"); + } + // A click shows the theme at once; Cancel goes back. + swatch(&h, "Light"); + h.run_steps(3); + assert_eq!(h.state().ui.brightness, Brightness::Light); + h.get_by_label("Cancel").click(); + h.run_steps(3); + assert!(h.state().ui.dialog.is_none()); + assert_eq!(h.state().ui.brightness, opened, "Cancel goes back to the theme Preferences opened with"); + // OK keeps the theme and the Tools panel's columns. + open(h.state_mut()); + h.run_steps(3); + swatch(&h, "Dark"); + h.run_steps(2); + h.get_by(|n| n.role() == Role::ComboBox && n.value().as_deref() == Some("Single Column")).click(); + h.run_steps(2); + h.get_by_label("Double Column").click(); + h.run_steps(2); + h.get_by_label(" OK ").click(); + h.run_steps(3); + assert!(h.state().ui.dialog.is_none()); + assert_eq!(h.state().ui.brightness, Brightness::Dark); + assert!(h.state().ui.tools_double_column); + // The same command the Window menu toggles, with an explicit state for Preferences. + assert_eq!(h.state_mut().run("window.toolsDoubleColumn", json!({"on": false})).unwrap(), json!(false)); + assert_eq!(h.state_mut().run("window.toolsDoubleColumn", json!({"on": false})).unwrap(), json!(false), "set, not toggled"); + assert_eq!(h.state_mut().run("window.toolsDoubleColumn", json!({})).unwrap(), json!(true), "toggled without `on`"); + // UI Size has a section of its own. + open(h.state_mut()); + h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("section".into(), json!("uiScaling")); + h.run_steps(3); + assert!(h.query_by_label("UI Size:").is_some()); +} From 408c7e14b58ded1f672abab2cda1ad08054c2296 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 19:44:18 +0100 Subject: [PATCH 0425/1349] Tests: the branch's dialog tests beside main's dialog test helpers (dialogs/tests.rs) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 90 ----------------------------- crates/ui-egui/src/dialogs/tests.rs | 90 +++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+), 90 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 438636154..e0e47e22c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -186,96 +186,6 @@ fn color_theme(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { mod color_theme_tests { use super::*; - /// The course's chapter 22: Find/Change › Change Format. "eggs", case sensitive, nothing in - /// Change to; Change Format Settings › Style Options sets Character Style "eggs", and the box - /// shows it (with Change to's ⓘ). Escape leaves the settings, not Find/Change. Change All - /// gives every lowercase "eggs" the style and keeps the words; the trash clears the format. - #[test] - fn find_change_gives_the_found_text_a_change_format() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let text = "Poached Eggs\nBreak eggs; cook until eggs are set."; - let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": text})).unwrap(); - let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap()); - app.run("style.character.create", json!({"name": "eggs", "chars": {"fontStyle": "Bold"}})).unwrap(); - app.run("app.findChange", json!({})).unwrap(); - if let Some(d) = app.ui.dialog.as_mut() { - d.fields.insert("find".into(), json!("eggs")); - d.fields.insert("caseSensitive".into(), json!(true)); - } - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state( - |ui, app: &mut DesignApp| { - let key = egui::Id::new("change_format_test_fonts"); - if ui.data(|d| d.get_temp::(key)).is_none() { - crate::theme::install_fonts(ui.ctx(), ""); - ui.data_mut(|d| d.insert_temp(key, true)); - return; - } - show(app, ui.ctx()); - }, - app, - ); - h.run_steps(4); - const TIP: &str = "With a Change Format and nothing in Change to, the found text stays and is only formatted"; - assert!(h.query_by_label("Change Format:").is_some()); - assert!(h.query_by_label(TIP).is_none(), "no ⓘ without a Change Format"); - h.get_by_label("Specify attributes to change").click(); - h.run_steps(3); - // Style Options is the section's name in the list and its heading. - for l in ["Change Format Settings", "Style Options", "Basic Character Formats", "Character Color"] { - assert!(h.query_all_by_label(l).next().is_some(), "{l}"); - } - // Style Options › Character Style: eggs. - h.get_all_by_value("[Any Style]").next().unwrap().click(); - h.run_steps(3); - h.get_by_label("eggs").click(); - h.run_steps(3); - h.get_all_by_label(" OK ").last().unwrap().click(); - h.run_steps(3); - let field = |h: &Harness<'_, DesignApp>, k: &str| h.state().ui.dialog.as_ref().unwrap().fields.get(k).cloned(); - assert_eq!((field(&h, CHANGE_FORMAT), field(&h, FORMAT_EDIT)), (Some(json!({"charStyle": "eggs"})), None)); - assert!(h.query_by_label("Character Style: eggs").is_some(), "the box shows it"); - assert!(h.query_by_label(TIP).is_some(), "Change to's ⓘ"); - // Escape closes Change Format Settings only, and keeps the Change Format. - h.get_by_label("Specify attributes to change").click(); - h.run_steps(3); - h.key_press(egui::Key::Escape); - h.run_steps(3); - assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.id.as_str()), Some("findChange")); - assert_eq!((field(&h, CHANGE_FORMAT), field(&h, FORMAT_EDIT)), (Some(json!({"charStyle": "eggs"})), None)); - // Change All: the words stay, every lowercase "eggs" has the style. - h.get_by_label("Change All").click(); - h.run_steps(3); - assert_eq!(field(&h, "status"), Some(json!("2 replacement(s) made"))); - let story = h.state().session.doc().unwrap().doc.story(sid).cloned().unwrap(); - assert_eq!(story.text, text); - assert_eq!( - [8, 19, 36].map(|at| story.format_after(at).style.clone()), - [designcraft_doc::NO_CHAR_STYLE.to_string(), "eggs".into(), "eggs".into()] - ); - // The trash clears it. - h.get_by_label("Clear specified attributes").click(); - h.run_steps(3); - assert_eq!(field(&h, CHANGE_FORMAT), None); - assert!(h.query_by_label(TIP).is_none()); - } - - /// What Change Format Settings sets goes to find.change: a paragraph style and character - /// attributes as well as a character style; the box sums them up. - #[test] - fn a_change_format_goes_with_change_all() { - let mut d = Dialog::new("findChange", json!({"find": "cook"})); - d.fields.insert(CHANGE_FORMAT.into(), json!({"charStyle": "eggs", "paraStyle": "Method", "chars": {"underline": true}})); - let p = find_change_params(&d); - assert_eq!( - (p["charStyle"].clone(), p["paraStyle"].clone(), p["attrs"].clone()), - (json!("eggs"), json!("Method"), json!({"underline": true})) - ); - assert_eq!(change_format_summary("en", d.fields.get(CHANGE_FORMAT)), "Character Style: eggs + Paragraph Style: Method + Underline: on"); - assert!(find_change_params(&Dialog::new("findChange", json!({"find": "cook"}))).get("attrs").is_none()); - } - #[test] fn color_theme_cancel_is_read_only_and_confirm_adds_the_preview() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 84cbf3bea..4d9a1ddb6 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3521,3 +3521,93 @@ fn character_style_options_set_the_digits() { assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi)); } + +/// The course's chapter 22: Find/Change › Change Format. "eggs", case sensitive, nothing in +/// Change to; Change Format Settings › Style Options sets Character Style "eggs", and the box +/// shows it (with Change to's ⓘ). Escape leaves the settings, not Find/Change. Change All +/// gives every lowercase "eggs" the style and keeps the words; the trash clears the format. +#[test] +fn find_change_gives_the_found_text_a_change_format() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let text = "Poached Eggs\nBreak eggs; cook until eggs are set."; + let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": text})).unwrap(); + let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap()); + app.run("style.character.create", json!({"name": "eggs", "chars": {"fontStyle": "Bold"}})).unwrap(); + app.run("app.findChange", json!({})).unwrap(); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("find".into(), json!("eggs")); + d.fields.insert("caseSensitive".into(), json!(true)); + } + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let key = egui::Id::new("change_format_test_fonts"); + if ui.data(|d| d.get_temp::(key)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(key, true)); + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + const TIP: &str = "With a Change Format and nothing in Change to, the found text stays and is only formatted"; + assert!(h.query_by_label("Change Format:").is_some()); + assert!(h.query_by_label(TIP).is_none(), "no ⓘ without a Change Format"); + h.get_by_label("Specify attributes to change").click(); + h.run_steps(3); + // Style Options is the section's name in the list and its heading. + for l in ["Change Format Settings", "Style Options", "Basic Character Formats", "Character Color"] { + assert!(h.query_all_by_label(l).next().is_some(), "{l}"); + } + // Style Options › Character Style: eggs. + h.get_all_by_value("[Any Style]").next().unwrap().click(); + h.run_steps(3); + h.get_by_label("eggs").click(); + h.run_steps(3); + h.get_all_by_label(" OK ").last().unwrap().click(); + h.run_steps(3); + let field = |h: &Harness<'_, DesignApp>, k: &str| h.state().ui.dialog.as_ref().unwrap().fields.get(k).cloned(); + assert_eq!((field(&h, CHANGE_FORMAT), field(&h, FORMAT_EDIT)), (Some(json!({"charStyle": "eggs"})), None)); + assert!(h.query_by_label("Character Style: eggs").is_some(), "the box shows it"); + assert!(h.query_by_label(TIP).is_some(), "Change to's ⓘ"); + // Escape closes Change Format Settings only, and keeps the Change Format. + h.get_by_label("Specify attributes to change").click(); + h.run_steps(3); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.id.as_str()), Some("findChange")); + assert_eq!((field(&h, CHANGE_FORMAT), field(&h, FORMAT_EDIT)), (Some(json!({"charStyle": "eggs"})), None)); + // Change All: the words stay, every lowercase "eggs" has the style. + h.get_by_label("Change All").click(); + h.run_steps(3); + assert_eq!(field(&h, "status"), Some(json!("2 replacement(s) made"))); + let story = h.state().session.doc().unwrap().doc.story(sid).cloned().unwrap(); + assert_eq!(story.text, text); + assert_eq!( + [8, 19, 36].map(|at| story.format_after(at).style.clone()), + [designcraft_doc::NO_CHAR_STYLE.to_string(), "eggs".into(), "eggs".into()] + ); + // The trash clears it. + h.get_by_label("Clear specified attributes").click(); + h.run_steps(3); + assert_eq!(field(&h, CHANGE_FORMAT), None); + assert!(h.query_by_label(TIP).is_none()); +} + +/// What Change Format Settings sets goes to find.change: a paragraph style and character +/// attributes as well as a character style; the box sums them up. +#[test] +fn a_change_format_goes_with_change_all() { + let mut d = Dialog::new("findChange", json!({"find": "cook"})); + d.fields.insert(CHANGE_FORMAT.into(), json!({"charStyle": "eggs", "paraStyle": "Method", "chars": {"underline": true}})); + let p = find_change_params(&d); + assert_eq!( + (p["charStyle"].clone(), p["paraStyle"].clone(), p["attrs"].clone()), + (json!("eggs"), json!("Method"), json!({"underline": true})) + ); + assert_eq!(change_format_summary("en", d.fields.get(CHANGE_FORMAT)), "Character Style: eggs + Paragraph Style: Method + Underline: on"); + assert!(find_change_params(&Dialog::new("findChange", json!({"find": "cook"}))).get("attrs").is_none()); +} From d19f41e54508f29c888178c492e5211456cd2e05 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 19:44:18 +0100 Subject: [PATCH 0426/1349] Tests: the branch's dialog tests beside main's dialog test helpers (dialogs/tests.rs) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 154 ---------------------------- crates/ui-egui/src/dialogs/tests.rs | 154 ++++++++++++++++++++++++++++ 2 files changed, 154 insertions(+), 154 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 4d362966f..6de0afa0a 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -186,160 +186,6 @@ fn color_theme(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { mod color_theme_tests { use super::*; - /// The course's chapter 22: Find/Change › Change Format. "eggs", case sensitive, nothing in - /// Change to; Change Format Settings › Style Options sets Character Style "eggs", and the box - /// shows it (with Change to's ⓘ). Escape leaves the settings, not Find/Change. Change All - /// gives every lowercase "eggs" the style and keeps the words; the trash clears the format. - #[test] - fn find_change_gives_the_found_text_a_change_format() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let text = "Poached Eggs\nBreak eggs; cook until eggs are set."; - let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": text})).unwrap(); - let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap()); - app.run("style.character.create", json!({"name": "eggs", "chars": {"fontStyle": "Bold"}})).unwrap(); - app.run("app.findChange", json!({})).unwrap(); - if let Some(d) = app.ui.dialog.as_mut() { - d.fields.insert("find".into(), json!("eggs")); - d.fields.insert("caseSensitive".into(), json!(true)); - } - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state( - |ui, app: &mut DesignApp| { - let key = egui::Id::new("change_format_test_fonts"); - if ui.data(|d| d.get_temp::(key)).is_none() { - crate::theme::install_fonts(ui.ctx(), ""); - ui.data_mut(|d| d.insert_temp(key, true)); - return; - } - show(app, ui.ctx()); - }, - app, - ); - h.run_steps(4); - const TIP: &str = "With a Change Format and nothing in Change to, the found text stays and is only formatted"; - assert!(h.query_by_label("Change Format:").is_some()); - assert!(h.query_by_label(TIP).is_none(), "no ⓘ without a Change Format"); - h.get_by_label("Specify attributes to change").click(); - h.run_steps(3); - // Style Options is the section's name in the list and its heading. - for l in ["Change Format Settings", "Style Options", "Basic Character Formats", "Character Color"] { - assert!(h.query_all_by_label(l).next().is_some(), "{l}"); - } - // Style Options › Character Style: eggs. - h.get_all_by_value("[Any Style]").next().unwrap().click(); - h.run_steps(3); - h.get_by_label("eggs").click(); - h.run_steps(3); - h.get_all_by_label(" OK ").last().unwrap().click(); - h.run_steps(3); - let field = |h: &Harness<'_, DesignApp>, k: &str| h.state().ui.dialog.as_ref().unwrap().fields.get(k).cloned(); - assert_eq!((field(&h, CHANGE_FORMAT), field(&h, FORMAT_EDIT)), (Some(json!({"charStyle": "eggs"})), None)); - assert!(h.query_by_label("Character Style: eggs").is_some(), "the box shows it"); - assert!(h.query_by_label(TIP).is_some(), "Change to's ⓘ"); - // Escape closes Change Format Settings only, and keeps the Change Format. - h.get_by_label("Specify attributes to change").click(); - h.run_steps(3); - h.key_press(egui::Key::Escape); - h.run_steps(3); - assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.id.as_str()), Some("findChange")); - assert_eq!((field(&h, CHANGE_FORMAT), field(&h, FORMAT_EDIT)), (Some(json!({"charStyle": "eggs"})), None)); - // Change All: the words stay, every lowercase "eggs" has the style. - h.get_by_label("Change All").click(); - h.run_steps(3); - assert_eq!(field(&h, "status"), Some(json!("2 replacement(s) made"))); - let story = h.state().session.doc().unwrap().doc.story(sid).cloned().unwrap(); - assert_eq!(story.text, text); - assert_eq!( - [8, 19, 36].map(|at| story.format_after(at).style.clone()), - [designcraft_doc::NO_CHAR_STYLE.to_string(), "eggs".into(), "eggs".into()] - ); - // The trash clears it (the second: the first is the Find Format's). - h.get_all_by_label("Clear specified attributes").nth(1).unwrap().click(); - h.run_steps(3); - assert_eq!(field(&h, CHANGE_FORMAT), None); - assert!(h.query_by_label(TIP).is_none()); - } - - /// What Change Format Settings sets goes to find.change: a paragraph style and character - /// attributes as well as a character style; the box sums them up. - #[test] - fn a_change_format_goes_with_change_all() { - let mut d = Dialog::new("findChange", json!({"find": "cook"})); - d.fields.insert(CHANGE_FORMAT.into(), json!({"charStyle": "eggs", "paraStyle": "Method", "chars": {"underline": true}})); - let p = find_change_params(&d); - assert_eq!( - (p["charStyle"].clone(), p["paraStyle"].clone(), p["attrs"].clone()), - (json!("eggs"), json!("Method"), json!({"underline": true})) - ); - assert_eq!(format_summary("en", d.fields.get(CHANGE_FORMAT)), "Character Style: eggs + Paragraph Style: Method + Underline: on"); - assert!(find_change_params(&Dialog::new("findChange", json!({"find": "cook"}))).get("attrs").is_none()); - // A Find Format goes with every search. - d.fields.insert(FIND_FORMAT.into(), json!({"paraStyle": "Method"})); - assert_eq!(find_change_params(&d)["findFormat"], json!({"paraStyle": "Method"})); - } - - /// Find/Change › Find Format, as InDesign's: Find Format Settings sets the character style the - /// found text must have, the box shows it with Find what's ⓘ, and Count counts only "eggs" in - /// it; with nothing in Find what, Find Next finds the text in the style; the first trash clears - /// it. - #[test] - fn find_format_finds_only_text_with_it() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": "Break eggs; cook eggs."})).unwrap(); - app.run("style.character.create", json!({"name": "eggs", "chars": {"fontStyle": "Bold"}})).unwrap(); - app.run("text.select", json!({"story": f["story"], "anchor": 6, "focus": 10})).unwrap(); - app.run("style.character.apply", json!({"name": "eggs"})).unwrap(); - app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 0})).unwrap(); - app.run("app.findChange", json!({})).unwrap(); - if let Some(d) = app.ui.dialog.as_mut() { - d.fields.insert("find".into(), json!("eggs")); - } - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state( - |ui, app: &mut DesignApp| { - let key = egui::Id::new("find_format_test_fonts"); - if ui.data(|d| d.get_temp::(key)).is_none() { - crate::theme::install_fonts(ui.ctx(), ""); - ui.data_mut(|d| d.insert_temp(key, true)); - return; - } - show(app, ui.ctx()); - }, - app, - ); - h.run_steps(4); - const TIP: &str = "With a Find Format, only text that has it is found; with nothing in Find what, all text that has it"; - assert!(h.query_by_label("Find Format:").is_some() && h.query_by_label(TIP).is_none()); - h.get_by_label("Specify attributes to find").click(); - h.run_steps(3); - assert!(h.query_by_label("Find Format Settings").is_some()); - h.get_all_by_value("[Any Style]").next().unwrap().click(); - h.run_steps(3); - h.get_by_label("eggs").click(); - h.run_steps(3); - h.get_all_by_label(" OK ").last().unwrap().click(); - h.run_steps(3); - let field = |h: &Harness<'_, DesignApp>, k: &str| h.state().ui.dialog.as_ref().unwrap().fields.get(k).cloned(); - assert_eq!((field(&h, FIND_FORMAT), field(&h, CHANGE_FORMAT)), (Some(json!({"charStyle": "eggs"})), None)); - assert!(h.query_by_label("Character Style: eggs").is_some() && h.query_by_label(TIP).is_some()); - h.get_by_label("Count").click(); - h.run_steps(3); - assert_eq!(field(&h, "status"), Some(json!("1 match(es)")), "only the \"eggs\" in the style"); - // Nothing in Find what: the text in the style. - h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("find".into(), json!("")); - h.run_steps(2); - h.get_by_label("Find Next").click(); - h.run_steps(3); - let sel = h.state().session.doc().unwrap().selection.text.unwrap(); - assert_eq!(sel.range(), 6..10); - // The first trash is the Find Format's. - h.get_all_by_label("Clear specified attributes").next().unwrap().click(); - h.run_steps(3); - assert_eq!(field(&h, FIND_FORMAT), None); - } - #[test] fn color_theme_cancel_is_read_only_and_confirm_adds_the_preview() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 84cbf3bea..8dfe5c8c2 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3521,3 +3521,157 @@ fn character_style_options_set_the_digits() { assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi)); } + +/// The course's chapter 22: Find/Change › Change Format. "eggs", case sensitive, nothing in +/// Change to; Change Format Settings › Style Options sets Character Style "eggs", and the box +/// shows it (with Change to's ⓘ). Escape leaves the settings, not Find/Change. Change All +/// gives every lowercase "eggs" the style and keeps the words; the trash clears the format. +#[test] +fn find_change_gives_the_found_text_a_change_format() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let text = "Poached Eggs\nBreak eggs; cook until eggs are set."; + let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": text})).unwrap(); + let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap()); + app.run("style.character.create", json!({"name": "eggs", "chars": {"fontStyle": "Bold"}})).unwrap(); + app.run("app.findChange", json!({})).unwrap(); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("find".into(), json!("eggs")); + d.fields.insert("caseSensitive".into(), json!(true)); + } + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let key = egui::Id::new("change_format_test_fonts"); + if ui.data(|d| d.get_temp::(key)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(key, true)); + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + const TIP: &str = "With a Change Format and nothing in Change to, the found text stays and is only formatted"; + assert!(h.query_by_label("Change Format:").is_some()); + assert!(h.query_by_label(TIP).is_none(), "no ⓘ without a Change Format"); + h.get_by_label("Specify attributes to change").click(); + h.run_steps(3); + // Style Options is the section's name in the list and its heading. + for l in ["Change Format Settings", "Style Options", "Basic Character Formats", "Character Color"] { + assert!(h.query_all_by_label(l).next().is_some(), "{l}"); + } + // Style Options › Character Style: eggs. + h.get_all_by_value("[Any Style]").next().unwrap().click(); + h.run_steps(3); + h.get_by_label("eggs").click(); + h.run_steps(3); + h.get_all_by_label(" OK ").last().unwrap().click(); + h.run_steps(3); + let field = |h: &Harness<'_, DesignApp>, k: &str| h.state().ui.dialog.as_ref().unwrap().fields.get(k).cloned(); + assert_eq!((field(&h, CHANGE_FORMAT), field(&h, FORMAT_EDIT)), (Some(json!({"charStyle": "eggs"})), None)); + assert!(h.query_by_label("Character Style: eggs").is_some(), "the box shows it"); + assert!(h.query_by_label(TIP).is_some(), "Change to's ⓘ"); + // Escape closes Change Format Settings only, and keeps the Change Format. + h.get_by_label("Specify attributes to change").click(); + h.run_steps(3); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.id.as_str()), Some("findChange")); + assert_eq!((field(&h, CHANGE_FORMAT), field(&h, FORMAT_EDIT)), (Some(json!({"charStyle": "eggs"})), None)); + // Change All: the words stay, every lowercase "eggs" has the style. + h.get_by_label("Change All").click(); + h.run_steps(3); + assert_eq!(field(&h, "status"), Some(json!("2 replacement(s) made"))); + let story = h.state().session.doc().unwrap().doc.story(sid).cloned().unwrap(); + assert_eq!(story.text, text); + assert_eq!( + [8, 19, 36].map(|at| story.format_after(at).style.clone()), + [designcraft_doc::NO_CHAR_STYLE.to_string(), "eggs".into(), "eggs".into()] + ); + // The trash clears it (the second: the first is the Find Format's). + h.get_all_by_label("Clear specified attributes").nth(1).unwrap().click(); + h.run_steps(3); + assert_eq!(field(&h, CHANGE_FORMAT), None); + assert!(h.query_by_label(TIP).is_none()); +} + +/// What Change Format Settings sets goes to find.change: a paragraph style and character +/// attributes as well as a character style; the box sums them up. +#[test] +fn a_change_format_goes_with_change_all() { + let mut d = Dialog::new("findChange", json!({"find": "cook"})); + d.fields.insert(CHANGE_FORMAT.into(), json!({"charStyle": "eggs", "paraStyle": "Method", "chars": {"underline": true}})); + let p = find_change_params(&d); + assert_eq!( + (p["charStyle"].clone(), p["paraStyle"].clone(), p["attrs"].clone()), + (json!("eggs"), json!("Method"), json!({"underline": true})) + ); + assert_eq!(format_summary("en", d.fields.get(CHANGE_FORMAT)), "Character Style: eggs + Paragraph Style: Method + Underline: on"); + assert!(find_change_params(&Dialog::new("findChange", json!({"find": "cook"}))).get("attrs").is_none()); + // A Find Format goes with every search. + d.fields.insert(FIND_FORMAT.into(), json!({"paraStyle": "Method"})); + assert_eq!(find_change_params(&d)["findFormat"], json!({"paraStyle": "Method"})); +} + +/// Find/Change › Find Format, as InDesign's: Find Format Settings sets the character style the +/// found text must have, the box shows it with Find what's ⓘ, and Count counts only "eggs" in +/// it; with nothing in Find what, Find Next finds the text in the style; the first trash clears +/// it. +#[test] +fn find_format_finds_only_text_with_it() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": "Break eggs; cook eggs."})).unwrap(); + app.run("style.character.create", json!({"name": "eggs", "chars": {"fontStyle": "Bold"}})).unwrap(); + app.run("text.select", json!({"story": f["story"], "anchor": 6, "focus": 10})).unwrap(); + app.run("style.character.apply", json!({"name": "eggs"})).unwrap(); + app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 0})).unwrap(); + app.run("app.findChange", json!({})).unwrap(); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("find".into(), json!("eggs")); + } + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let key = egui::Id::new("find_format_test_fonts"); + if ui.data(|d| d.get_temp::(key)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(key, true)); + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + const TIP: &str = "With a Find Format, only text that has it is found; with nothing in Find what, all text that has it"; + assert!(h.query_by_label("Find Format:").is_some() && h.query_by_label(TIP).is_none()); + h.get_by_label("Specify attributes to find").click(); + h.run_steps(3); + assert!(h.query_by_label("Find Format Settings").is_some()); + h.get_all_by_value("[Any Style]").next().unwrap().click(); + h.run_steps(3); + h.get_by_label("eggs").click(); + h.run_steps(3); + h.get_all_by_label(" OK ").last().unwrap().click(); + h.run_steps(3); + let field = |h: &Harness<'_, DesignApp>, k: &str| h.state().ui.dialog.as_ref().unwrap().fields.get(k).cloned(); + assert_eq!((field(&h, FIND_FORMAT), field(&h, CHANGE_FORMAT)), (Some(json!({"charStyle": "eggs"})), None)); + assert!(h.query_by_label("Character Style: eggs").is_some() && h.query_by_label(TIP).is_some()); + h.get_by_label("Count").click(); + h.run_steps(3); + assert_eq!(field(&h, "status"), Some(json!("1 match(es)")), "only the \"eggs\" in the style"); + // Nothing in Find what: the text in the style. + h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("find".into(), json!("")); + h.run_steps(2); + h.get_by_label("Find Next").click(); + h.run_steps(3); + let sel = h.state().session.doc().unwrap().selection.text.unwrap(); + assert_eq!(sel.range(), 6..10); + // The first trash is the Find Format's. + h.get_all_by_label("Clear specified attributes").next().unwrap().click(); + h.run_steps(3); + assert_eq!(field(&h, FIND_FORMAT), None); +} From c20579eb99d50bcd193646cb2616df78b43bed5f Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 19:44:19 +0100 Subject: [PATCH 0427/1349] Tests: the branch's dialog tests beside main's dialog test helpers (dialogs/tests.rs) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 200 ---------------------------- crates/ui-egui/src/dialogs/tests.rs | 200 ++++++++++++++++++++++++++++ 2 files changed, 200 insertions(+), 200 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 59d3db6c0..84dc359dc 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -186,206 +186,6 @@ fn color_theme(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { mod color_theme_tests { use super::*; - /// The course's chapter 22: Find/Change › Change Format. "eggs", case sensitive, nothing in - /// Change to; Change Format Settings › Style Options sets Character Style "eggs", and the box - /// shows it (with Change to's ⓘ). Escape leaves the settings, not Find/Change. Change All - /// gives every lowercase "eggs" the style and keeps the words; the trash clears the format. - #[test] - fn find_change_gives_the_found_text_a_change_format() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let text = "Poached Eggs\nBreak eggs; cook until eggs are set."; - let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": text})).unwrap(); - let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap()); - app.run("style.character.create", json!({"name": "eggs", "chars": {"fontStyle": "Bold"}})).unwrap(); - app.run("app.findChange", json!({})).unwrap(); - if let Some(d) = app.ui.dialog.as_mut() { - d.fields.insert("find".into(), json!("eggs")); - d.fields.insert("caseSensitive".into(), json!(true)); - } - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state( - |ui, app: &mut DesignApp| { - let key = egui::Id::new("change_format_test_fonts"); - if ui.data(|d| d.get_temp::(key)).is_none() { - crate::theme::install_fonts(ui.ctx(), ""); - ui.data_mut(|d| d.insert_temp(key, true)); - return; - } - show(app, ui.ctx()); - }, - app, - ); - h.run_steps(4); - const TIP: &str = "With a Change Format and nothing in Change to, the found text stays and is only formatted"; - assert!(h.query_by_label("Change Format:").is_some()); - assert!(h.query_by_label(TIP).is_none(), "no ⓘ without a Change Format"); - h.get_by_label("Specify attributes to change").click(); - h.run_steps(3); - // Style Options is the section's name in the list and its heading. - for l in ["Change Format Settings", "Style Options", "Basic Character Formats", "Character Color"] { - assert!(h.query_all_by_label(l).next().is_some(), "{l}"); - } - // Style Options › Character Style: eggs. - h.get_all_by_value("[Any Style]").next().unwrap().click(); - h.run_steps(3); - h.get_by_label("eggs").click(); - h.run_steps(3); - h.get_all_by_label(" OK ").last().unwrap().click(); - h.run_steps(3); - let field = |h: &Harness<'_, DesignApp>, k: &str| h.state().ui.dialog.as_ref().unwrap().fields.get(k).cloned(); - assert_eq!((field(&h, CHANGE_FORMAT), field(&h, FORMAT_EDIT)), (Some(json!({"charStyle": "eggs"})), None)); - assert!(h.query_by_label("Character Style: eggs").is_some(), "the box shows it"); - assert!(h.query_by_label(TIP).is_some(), "Change to's ⓘ"); - // Escape closes Change Format Settings only, and keeps the Change Format. - h.get_by_label("Specify attributes to change").click(); - h.run_steps(3); - h.key_press(egui::Key::Escape); - h.run_steps(3); - assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.id.as_str()), Some("findChange")); - assert_eq!((field(&h, CHANGE_FORMAT), field(&h, FORMAT_EDIT)), (Some(json!({"charStyle": "eggs"})), None)); - // Change All: the words stay, every lowercase "eggs" has the style. - h.get_by_label("Change All").click(); - h.run_steps(3); - assert_eq!(field(&h, "status"), Some(json!("2 replacement(s) made"))); - let story = h.state().session.doc().unwrap().doc.story(sid).cloned().unwrap(); - assert_eq!(story.text, text); - assert_eq!( - [8, 19, 36].map(|at| story.format_after(at).style.clone()), - [designcraft_doc::NO_CHAR_STYLE.to_string(), "eggs".into(), "eggs".into()] - ); - // The trash clears it (the second: the first is the Find Format's). - h.get_all_by_label("Clear specified attributes").nth(1).unwrap().click(); - h.run_steps(3); - assert_eq!(field(&h, CHANGE_FORMAT), None); - assert!(h.query_by_label(TIP).is_none()); - } - - /// What Change Format Settings sets goes to find.change: a paragraph style and character - /// attributes as well as a character style; the box sums them up. - #[test] - fn a_change_format_goes_with_change_all() { - let mut d = Dialog::new("findChange", json!({"find": "cook"})); - d.fields.insert(CHANGE_FORMAT.into(), json!({"charStyle": "eggs", "paraStyle": "Method", "chars": {"underline": true}})); - let p = find_change_params(&d); - assert_eq!( - (p["charStyle"].clone(), p["paraStyle"].clone(), p["attrs"].clone()), - (json!("eggs"), json!("Method"), json!({"underline": true})) - ); - assert_eq!(format_summary("en", d.fields.get(CHANGE_FORMAT)), "Character Style: eggs + Paragraph Style: Method + Underline: on"); - assert!(find_change_params(&Dialog::new("findChange", json!({"find": "cook"}))).get("attrs").is_none()); - // A Find Format goes with every search. - d.fields.insert(FIND_FORMAT.into(), json!({"paraStyle": "Method"})); - assert_eq!(find_change_params(&d)["findFormat"], json!({"paraStyle": "Method"})); - } - - /// Find/Change › Find Format, as InDesign's: Find Format Settings sets the character style the - /// found text must have, the box shows it with Find what's ⓘ, and Count counts only "eggs" in - /// it; with nothing in Find what, Find Next finds the text in the style; the first trash clears - /// it. - #[test] - fn find_format_finds_only_text_with_it() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": "Break eggs; cook eggs."})).unwrap(); - app.run("style.character.create", json!({"name": "eggs", "chars": {"fontStyle": "Bold"}})).unwrap(); - app.run("text.select", json!({"story": f["story"], "anchor": 6, "focus": 10})).unwrap(); - app.run("style.character.apply", json!({"name": "eggs"})).unwrap(); - app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 0})).unwrap(); - app.run("app.findChange", json!({})).unwrap(); - if let Some(d) = app.ui.dialog.as_mut() { - d.fields.insert("find".into(), json!("eggs")); - } - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state( - |ui, app: &mut DesignApp| { - let key = egui::Id::new("find_format_test_fonts"); - if ui.data(|d| d.get_temp::(key)).is_none() { - crate::theme::install_fonts(ui.ctx(), ""); - ui.data_mut(|d| d.insert_temp(key, true)); - return; - } - show(app, ui.ctx()); - }, - app, - ); - h.run_steps(4); - const TIP: &str = "With a Find Format, only text that has it is found; with nothing in Find what, all text that has it"; - assert!(h.query_by_label("Find Format:").is_some() && h.query_by_label(TIP).is_none()); - h.get_by_label("Specify attributes to find").click(); - h.run_steps(3); - assert!(h.query_by_label("Find Format Settings").is_some()); - h.get_all_by_value("[Any Style]").next().unwrap().click(); - h.run_steps(3); - h.get_by_label("eggs").click(); - h.run_steps(3); - h.get_all_by_label(" OK ").last().unwrap().click(); - h.run_steps(3); - let field = |h: &Harness<'_, DesignApp>, k: &str| h.state().ui.dialog.as_ref().unwrap().fields.get(k).cloned(); - assert_eq!((field(&h, FIND_FORMAT), field(&h, CHANGE_FORMAT)), (Some(json!({"charStyle": "eggs"})), None)); - assert!(h.query_by_label("Character Style: eggs").is_some() && h.query_by_label(TIP).is_some()); - h.get_by_label("Count").click(); - h.run_steps(3); - assert_eq!(field(&h, "status"), Some(json!("1 match(es)")), "only the \"eggs\" in the style"); - // Nothing in Find what: the text in the style. - h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("find".into(), json!("")); - h.run_steps(2); - h.get_by_label("Find Next").click(); - h.run_steps(3); - let sel = h.state().session.doc().unwrap().selection.text.unwrap(); - assert_eq!(sel.range(), 6..10); - // The first trash is the Find Format's. - h.get_all_by_label("Clear specified attributes").next().unwrap().click(); - h.run_steps(3); - assert_eq!(field(&h, FIND_FORMAT), None); - } - - /// Find/Change's Change and Change/Find, as InDesign's: Find Next selects a match, Change/Find - /// changes it and selects the next, Change changes that one and keeps it selected. With no - /// text selected they're off. - #[test] - fn change_and_change_find_change_the_found_text() { - use egui_kittest::Harness; - use egui_kittest::kittest::{NodeT, Queryable}; - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": "red red | red"})).unwrap(); - let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap()); - app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap(); - app.run("app.findChange", json!({})).unwrap(); - if let Some(d) = app.ui.dialog.as_mut() { - d.fields.insert("find".into(), json!("red")); - d.fields.insert("change".into(), json!("blue")); - } - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state( - |ui, app: &mut DesignApp| { - let key = egui::Id::new("change_find_test_fonts"); - if ui.data(|d| d.get_temp::(key)).is_none() { - crate::theme::install_fonts(ui.ctx(), ""); - ui.data_mut(|d| d.insert_temp(key, true)); - return; - } - show(app, ui.ctx()); - }, - app, - ); - h.run_steps(4); - assert!(h.query_by_value("Document").is_some(), "the Search choices are InDesign's"); - assert!(h.get_by_label("Change").accesskit_node().is_disabled(), "nothing found yet"); - let text = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().doc.story(sid).unwrap().text.clone(); - let selected = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().selection.text.unwrap().range(); - h.get_by_label("Find Next").click(); - h.run_steps(3); - assert_eq!(selected(&h), 0..3); - h.get_by_label("Change/Find").click(); - h.run_steps(3); - assert_eq!((text(&h), selected(&h)), ("blue red | red".to_string(), 5..8)); - h.get_by_label("Change").click(); - h.run_steps(3); - assert_eq!((text(&h), selected(&h)), ("blue blue | red".to_string(), 5..9)); - assert_eq!(h.state().ui.dialog.as_ref().unwrap().fields["status"], json!("1 replacement(s) made")); - } - #[test] fn color_theme_cancel_is_read_only_and_confirm_adds_the_preview() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 79e33322b..9d392ed90 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3530,3 +3530,203 @@ fn character_style_options_set_the_digits() { assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi)); } + +/// The course's chapter 22: Find/Change › Change Format. "eggs", case sensitive, nothing in +/// Change to; Change Format Settings › Style Options sets Character Style "eggs", and the box +/// shows it (with Change to's ⓘ). Escape leaves the settings, not Find/Change. Change All +/// gives every lowercase "eggs" the style and keeps the words; the trash clears the format. +#[test] +fn find_change_gives_the_found_text_a_change_format() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let text = "Poached Eggs\nBreak eggs; cook until eggs are set."; + let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": text})).unwrap(); + let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap()); + app.run("style.character.create", json!({"name": "eggs", "chars": {"fontStyle": "Bold"}})).unwrap(); + app.run("app.findChange", json!({})).unwrap(); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("find".into(), json!("eggs")); + d.fields.insert("caseSensitive".into(), json!(true)); + } + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let key = egui::Id::new("change_format_test_fonts"); + if ui.data(|d| d.get_temp::(key)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(key, true)); + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + const TIP: &str = "With a Change Format and nothing in Change to, the found text stays and is only formatted"; + assert!(h.query_by_label("Change Format:").is_some()); + assert!(h.query_by_label(TIP).is_none(), "no ⓘ without a Change Format"); + h.get_by_label("Specify attributes to change").click(); + h.run_steps(3); + // Style Options is the section's name in the list and its heading. + for l in ["Change Format Settings", "Style Options", "Basic Character Formats", "Character Color"] { + assert!(h.query_all_by_label(l).next().is_some(), "{l}"); + } + // Style Options › Character Style: eggs. + h.get_all_by_value("[Any Style]").next().unwrap().click(); + h.run_steps(3); + h.get_by_label("eggs").click(); + h.run_steps(3); + h.get_all_by_label(" OK ").last().unwrap().click(); + h.run_steps(3); + let field = |h: &Harness<'_, DesignApp>, k: &str| h.state().ui.dialog.as_ref().unwrap().fields.get(k).cloned(); + assert_eq!((field(&h, CHANGE_FORMAT), field(&h, FORMAT_EDIT)), (Some(json!({"charStyle": "eggs"})), None)); + assert!(h.query_by_label("Character Style: eggs").is_some(), "the box shows it"); + assert!(h.query_by_label(TIP).is_some(), "Change to's ⓘ"); + // Escape closes Change Format Settings only, and keeps the Change Format. + h.get_by_label("Specify attributes to change").click(); + h.run_steps(3); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.id.as_str()), Some("findChange")); + assert_eq!((field(&h, CHANGE_FORMAT), field(&h, FORMAT_EDIT)), (Some(json!({"charStyle": "eggs"})), None)); + // Change All: the words stay, every lowercase "eggs" has the style. + h.get_by_label("Change All").click(); + h.run_steps(3); + assert_eq!(field(&h, "status"), Some(json!("2 replacement(s) made"))); + let story = h.state().session.doc().unwrap().doc.story(sid).cloned().unwrap(); + assert_eq!(story.text, text); + assert_eq!( + [8, 19, 36].map(|at| story.format_after(at).style.clone()), + [designcraft_doc::NO_CHAR_STYLE.to_string(), "eggs".into(), "eggs".into()] + ); + // The trash clears it (the second: the first is the Find Format's). + h.get_all_by_label("Clear specified attributes").nth(1).unwrap().click(); + h.run_steps(3); + assert_eq!(field(&h, CHANGE_FORMAT), None); + assert!(h.query_by_label(TIP).is_none()); +} + +/// What Change Format Settings sets goes to find.change: a paragraph style and character +/// attributes as well as a character style; the box sums them up. +#[test] +fn a_change_format_goes_with_change_all() { + let mut d = Dialog::new("findChange", json!({"find": "cook"})); + d.fields.insert(CHANGE_FORMAT.into(), json!({"charStyle": "eggs", "paraStyle": "Method", "chars": {"underline": true}})); + let p = find_change_params(&d); + assert_eq!( + (p["charStyle"].clone(), p["paraStyle"].clone(), p["attrs"].clone()), + (json!("eggs"), json!("Method"), json!({"underline": true})) + ); + assert_eq!(format_summary("en", d.fields.get(CHANGE_FORMAT)), "Character Style: eggs + Paragraph Style: Method + Underline: on"); + assert!(find_change_params(&Dialog::new("findChange", json!({"find": "cook"}))).get("attrs").is_none()); + // A Find Format goes with every search. + d.fields.insert(FIND_FORMAT.into(), json!({"paraStyle": "Method"})); + assert_eq!(find_change_params(&d)["findFormat"], json!({"paraStyle": "Method"})); +} + +/// Find/Change › Find Format, as InDesign's: Find Format Settings sets the character style the +/// found text must have, the box shows it with Find what's ⓘ, and Count counts only "eggs" in +/// it; with nothing in Find what, Find Next finds the text in the style; the first trash clears +/// it. +#[test] +fn find_format_finds_only_text_with_it() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": "Break eggs; cook eggs."})).unwrap(); + app.run("style.character.create", json!({"name": "eggs", "chars": {"fontStyle": "Bold"}})).unwrap(); + app.run("text.select", json!({"story": f["story"], "anchor": 6, "focus": 10})).unwrap(); + app.run("style.character.apply", json!({"name": "eggs"})).unwrap(); + app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 0})).unwrap(); + app.run("app.findChange", json!({})).unwrap(); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("find".into(), json!("eggs")); + } + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let key = egui::Id::new("find_format_test_fonts"); + if ui.data(|d| d.get_temp::(key)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(key, true)); + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + const TIP: &str = "With a Find Format, only text that has it is found; with nothing in Find what, all text that has it"; + assert!(h.query_by_label("Find Format:").is_some() && h.query_by_label(TIP).is_none()); + h.get_by_label("Specify attributes to find").click(); + h.run_steps(3); + assert!(h.query_by_label("Find Format Settings").is_some()); + h.get_all_by_value("[Any Style]").next().unwrap().click(); + h.run_steps(3); + h.get_by_label("eggs").click(); + h.run_steps(3); + h.get_all_by_label(" OK ").last().unwrap().click(); + h.run_steps(3); + let field = |h: &Harness<'_, DesignApp>, k: &str| h.state().ui.dialog.as_ref().unwrap().fields.get(k).cloned(); + assert_eq!((field(&h, FIND_FORMAT), field(&h, CHANGE_FORMAT)), (Some(json!({"charStyle": "eggs"})), None)); + assert!(h.query_by_label("Character Style: eggs").is_some() && h.query_by_label(TIP).is_some()); + h.get_by_label("Count").click(); + h.run_steps(3); + assert_eq!(field(&h, "status"), Some(json!("1 match(es)")), "only the \"eggs\" in the style"); + // Nothing in Find what: the text in the style. + h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("find".into(), json!("")); + h.run_steps(2); + h.get_by_label("Find Next").click(); + h.run_steps(3); + let sel = h.state().session.doc().unwrap().selection.text.unwrap(); + assert_eq!(sel.range(), 6..10); + // The first trash is the Find Format's. + h.get_all_by_label("Clear specified attributes").next().unwrap().click(); + h.run_steps(3); + assert_eq!(field(&h, FIND_FORMAT), None); +} + +/// Find/Change's Change and Change/Find, as InDesign's: Find Next selects a match, Change/Find +/// changes it and selects the next, Change changes that one and keeps it selected. With no +/// text selected they're off. +#[test] +fn change_and_change_find_change_the_found_text() { + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT, Queryable}; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": "red red | red"})).unwrap(); + let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap()); + app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap(); + app.run("app.findChange", json!({})).unwrap(); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("find".into(), json!("red")); + d.fields.insert("change".into(), json!("blue")); + } + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let key = egui::Id::new("change_find_test_fonts"); + if ui.data(|d| d.get_temp::(key)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(key, true)); + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + assert!(h.query_by_value("Document").is_some(), "the Search choices are InDesign's"); + assert!(h.get_by_label("Change").accesskit_node().is_disabled(), "nothing found yet"); + let text = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().doc.story(sid).unwrap().text.clone(); + let selected = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().selection.text.unwrap().range(); + h.get_by_label("Find Next").click(); + h.run_steps(3); + assert_eq!(selected(&h), 0..3); + h.get_by_label("Change/Find").click(); + h.run_steps(3); + assert_eq!((text(&h), selected(&h)), ("blue red | red".to_string(), 5..8)); + h.get_by_label("Change").click(); + h.run_steps(3); + assert_eq!((text(&h), selected(&h)), ("blue blue | red".to_string(), 5..9)); + assert_eq!(h.state().ui.dialog.as_ref().unwrap().fields["status"], json!("1 replacement(s) made")); +} From 875c317e184cdad8888aa716f73b35bfa312a5d6 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 19:44:20 +0100 Subject: [PATCH 0428/1349] Tests: the branch's dialog tests beside main's dialog test helpers (dialogs/tests.rs) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 89 ----------------------------- crates/ui-egui/src/dialogs/tests.rs | 89 +++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+), 89 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index abb4892c9..cbf7ea6a6 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -186,95 +186,6 @@ fn color_theme(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { mod color_theme_tests { use super::*; - /// Paragraph Rules › Color offers Text Color above the swatches, so a rule set to a swatch can - /// go back to it; Gap Color lists only swatches. - #[test] - fn the_rule_colour_menu_offers_text_color() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let doc = app.session.doc().unwrap().doc.clone(); - let menu = |ctx: &egui::Context, text: Option<&str>, click: Option| { - let mut picked = None; - let mut labels = Vec::new(); - let mut events = Vec::new(); - if let Some(pos) = click { - events.push(egui::Event::PointerMoved(pos)); - events.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); - events.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); - } - let input = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 600.0))), - events, - ..Default::default() - }; - let mut out = ctx.run_ui(input, |ui| { - picked = swatch_menu_with(ui, &doc, "m", "[Black]", 130.0, text); - }); - out.textures_delta.clear(); - for s in out.shapes { - if let egui::Shape::Text(t) = s.shape { - labels.push((t.galley.job.text.clone(), t.visual_bounding_rect().center())); - } - } - (picked, labels) - }; - for text in [Some("Text Color"), None] { - let ctx = egui::Context::default(); - let (_, labels) = menu(&ctx, text, None); - let combo = labels.iter().find(|(t, _)| t == "[Black]").unwrap().1; - menu(&ctx, text, Some(combo)); - let (_, labels) = menu(&ctx, text, None); - let item = labels.iter().find(|(t, _)| t == "Text Color").map(|l| l.1); - assert_eq!(item.is_some(), text.is_some(), "{labels:?}"); - if let Some(pos) = item { - let (picked, _) = menu(&ctx, text, Some(pos)); - assert_eq!(picked.as_deref(), Some(designcraft_doc::TEXT_COLOR)); - } - } - } - - /// The course's chapter 20: a paragraph style's rule below becomes wavy, 3 pt, with a gap - /// colour, from Paragraph Rules › Type and Gap Color. - #[test] - fn paragraph_style_rules_take_a_type_and_a_gap_colour() { - let (mut app, _) = ruled_paragraph(); - let ctx = egui::Context::default(); - app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "rules", "rule": "ruleBelow"}))); - draw(&mut app, &ctx); - if let Some(d) = app.ui.dialog.as_mut() { - d.fields.insert("p.ruleBelow.type".into(), json!({"kind": "wavy"})); - d.fields.insert("p.ruleBelow.weight".into(), json!(3.0)); - d.fields.insert("p.ruleBelow.gapColor".into(), json!("[Paper]")); - } - draw(&mut app, &ctx); - confirm(&mut app).unwrap(); - let r = app.session.doc().unwrap().doc.styles.resolve_para_style("Ruled Child").0.rule_below; - assert_eq!((r.kind, r.weight, r.gap_color.as_str()), (designcraft_doc::StrokeType::Wavy, 3.0, "[Paper]")); - } - - /// A rule's Gap Tint shows 100% at its default (the rule's JSON leaves a full gap tint out). - #[test] - fn a_rules_default_gap_tint_shows_100() { - use egui_kittest::kittest::Queryable; - let (mut app, _) = ruled_paragraph(); - app.run( - "style.paragraph.edit", - json!({"name": "Ruled Child", "para": {"ruleBelow": {"type": {"kind": "dashed", "pattern": [4.0, 2.0]}, "gapColor": "[Paper]"}}}), - ) - .unwrap(); - let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); - h.state_mut().app.ui.dialog = - Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "rules", "rule": "ruleBelow"}))); - h.run_steps(4); - let label = h.get_by_label("Gap Tint:").rect(); - let field = h - .get_all_by(|n| n.role() == egui::accesskit::Role::TextInput) - .filter(|n| n.rect().center().x > label.max.x && (n.rect().center().y - label.center().y).abs() < 8.0) - .min_by(|a, b| a.rect().min.x.total_cmp(&b.rect().min.x)) - .and_then(|n| n.value()); - assert_eq!(field.as_deref(), Some("100%")); - } - #[test] fn color_theme_cancel_is_read_only_and_confirm_adds_the_preview() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 84cbf3bea..37452dd27 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3521,3 +3521,92 @@ fn character_style_options_set_the_digits() { assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi)); } + +/// Paragraph Rules › Color offers Text Color above the swatches, so a rule set to a swatch can +/// go back to it; Gap Color lists only swatches. +#[test] +fn the_rule_colour_menu_offers_text_color() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let doc = app.session.doc().unwrap().doc.clone(); + let menu = |ctx: &egui::Context, text: Option<&str>, click: Option| { + let mut picked = None; + let mut labels = Vec::new(); + let mut events = Vec::new(); + if let Some(pos) = click { + events.push(egui::Event::PointerMoved(pos)); + events.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + events.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + } + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 600.0))), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| { + picked = swatch_menu_with(ui, &doc, "m", "[Black]", 130.0, text); + }); + out.textures_delta.clear(); + for s in out.shapes { + if let egui::Shape::Text(t) = s.shape { + labels.push((t.galley.job.text.clone(), t.visual_bounding_rect().center())); + } + } + (picked, labels) + }; + for text in [Some("Text Color"), None] { + let ctx = egui::Context::default(); + let (_, labels) = menu(&ctx, text, None); + let combo = labels.iter().find(|(t, _)| t == "[Black]").unwrap().1; + menu(&ctx, text, Some(combo)); + let (_, labels) = menu(&ctx, text, None); + let item = labels.iter().find(|(t, _)| t == "Text Color").map(|l| l.1); + assert_eq!(item.is_some(), text.is_some(), "{labels:?}"); + if let Some(pos) = item { + let (picked, _) = menu(&ctx, text, Some(pos)); + assert_eq!(picked.as_deref(), Some(designcraft_doc::TEXT_COLOR)); + } + } +} + +/// The course's chapter 20: a paragraph style's rule below becomes wavy, 3 pt, with a gap +/// colour, from Paragraph Rules › Type and Gap Color. +#[test] +fn paragraph_style_rules_take_a_type_and_a_gap_colour() { + let (mut app, _) = ruled_paragraph(); + let ctx = egui::Context::default(); + app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "rules", "rule": "ruleBelow"}))); + draw(&mut app, &ctx); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("p.ruleBelow.type".into(), json!({"kind": "wavy"})); + d.fields.insert("p.ruleBelow.weight".into(), json!(3.0)); + d.fields.insert("p.ruleBelow.gapColor".into(), json!("[Paper]")); + } + draw(&mut app, &ctx); + confirm(&mut app).unwrap(); + let r = app.session.doc().unwrap().doc.styles.resolve_para_style("Ruled Child").0.rule_below; + assert_eq!((r.kind, r.weight, r.gap_color.as_str()), (designcraft_doc::StrokeType::Wavy, 3.0, "[Paper]")); +} + +/// A rule's Gap Tint shows 100% at its default (the rule's JSON leaves a full gap tint out). +#[test] +fn a_rules_default_gap_tint_shows_100() { + use egui_kittest::kittest::Queryable; + let (mut app, _) = ruled_paragraph(); + app.run( + "style.paragraph.edit", + json!({"name": "Ruled Child", "para": {"ruleBelow": {"type": {"kind": "dashed", "pattern": [4.0, 2.0]}, "gapColor": "[Paper]"}}}), + ) + .unwrap(); + let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); + h.state_mut().app.ui.dialog = + Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "rules", "rule": "ruleBelow"}))); + h.run_steps(4); + let label = h.get_by_label("Gap Tint:").rect(); + let field = h + .get_all_by(|n| n.role() == egui::accesskit::Role::TextInput) + .filter(|n| n.rect().center().x > label.max.x && (n.rect().center().y - label.center().y).abs() < 8.0) + .min_by(|a, b| a.rect().min.x.total_cmp(&b.rect().min.x)) + .and_then(|n| n.value()); + assert_eq!(field.as_deref(), Some("100%")); +} From 954e3158f1e4b8d0c2c7d30cb3fc4f0a0aedc615 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 19:44:29 +0100 Subject: [PATCH 0429/1349] Tests: the branch's dialog tests beside main's dialog test helpers (dialogs/tests.rs) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 128 ---------------------------- crates/ui-egui/src/dialogs/tests.rs | 128 ++++++++++++++++++++++++++++ 2 files changed, 128 insertions(+), 128 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 98324fb58..9183444cf 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -186,134 +186,6 @@ fn color_theme(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { mod color_theme_tests { use super::*; - /// The course's chapter 20: the "Recipe Categories" title formatted on the page (size, All - /// Caps, tracking, space after), then New Paragraph Style from it: the dialog starts from the - /// text, and with Apply Style to Selection the paragraph takes the new style. Next Style and - /// Reset To Base are set from General. - #[test] - fn a_new_paragraph_style_starts_from_the_selected_text() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": "Egg Recipes\rBoil them."})).unwrap(); - app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 11})).unwrap(); - app.run("type.char", json!({"attrs": {"size": 20, "capitalization": "allCaps", "tracking": 50}})).unwrap(); - app.run("type.para", json!({"attrs": {"spaceAfter": 6}})).unwrap(); - open_new_style(&mut app, true); - let d = app.ui.dialog.clone().unwrap(); - assert_eq!( - (d.fields["c.size"].clone(), d.fields["c.capitalization"].clone(), d.fields["p.spaceAfter"].clone()), - (json!(20.0), json!("allCaps"), json!(6.0)) - ); - assert!(d.b("apply") && !d.fields.contains_key("c.fontFamily"), "only what differs from [No Paragraph Style]"); - if let Some(d) = app.ui.dialog.as_mut() { - d.fields.insert("rename".into(), json!("Recipe Categories")); - d.fields.insert("nextStyle".into(), json!(designcraft_doc::BASIC_PARAGRAPH)); - } - confirm(&mut app).unwrap(); - let a = app.run("type.selectionAttrs", json!({})).unwrap(); - assert_eq!(a["paragraphStyle"], "Recipe Categories", "applied to the selection"); - assert_eq!(a["paraOverrides"].as_u64().unwrap_or(0) + a["charOverrides"].as_u64().unwrap_or(0), 0); - let style = |app: &DesignApp| app.session.doc().unwrap().doc.styles.para("Recipe Categories").cloned().unwrap(); - assert_eq!(style(&app).next_style.as_deref(), Some(designcraft_doc::BASIC_PARAGRAPH)); - assert_eq!(style(&app).chars.size, Some(20.0)); - // Reset To Base: the style keeps nothing of its own, apart from the edits made then. - app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Recipe Categories", "basedOn": designcraft_doc::BASIC_PARAGRAPH}))); - if let Some(d) = app.ui.dialog.as_mut() { - d.fields.insert("resetToBase".into(), json!(true)); - d.fields.insert("c.tracking".into(), json!(10.0)); - } - confirm(&mut app).unwrap(); - let s = style(&app); - assert_eq!((s.chars.size, s.chars.tracking, s.para.space_after), (None, Some(10.0), None), "{s:?}"); - assert_eq!(s.based_on.as_deref(), Some(designcraft_doc::BASIC_PARAGRAPH)); - } - - /// The course's chapter 22: "eggs" made bold and red on the page, then New Character Style - /// from it. The dialog is titled as InDesign's, starts from what the text has of its own - /// over its paragraph style ("[None] + Bold + color"), and Apply Style to Selection gives the - /// text the style, with no override left. - #[test] - fn a_new_character_style_starts_from_the_selected_text() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": "Drop eggs into boiling water."})).unwrap(); - app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 29})).unwrap(); - app.run("style.paragraph.create", json!({"name": "Recipe", "chars": {"size": 14}})).unwrap(); - app.run("style.paragraph.apply", json!({"name": "Recipe"})).unwrap(); - app.run("text.select", json!({"story": f["story"], "anchor": 5, "focus": 9})).unwrap(); - app.run("type.char", json!({"attrs": {"fontStyle": "Bold", "fill": "C=15 M=100 Y=100 K=0"}})).unwrap(); - open_new_style(&mut app, false); - let d = app.ui.dialog.clone().unwrap(); - assert_eq!((d.fields["c.fontStyle"].clone(), d.fields["c.fill"].clone()), (json!("Bold"), json!("C=15 M=100 Y=100 K=0"))); - assert!(d.b("apply")); - let mut h = Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_ui_state( - |ui, app: &mut DesignApp| { - let key = egui::Id::new("new_character_style_test_fonts"); - if ui.data(|d| d.get_temp::(key)).is_none() { - crate::theme::install_fonts(ui.ctx(), ""); - ui.data_mut(|d| d.insert_temp(key, true)); - return; - } - show(app, ui.ctx()); - }, - app, - ); - h.run_steps(4); - for l in ["New Character Style", "Apply Style to Selection"] { - assert!(h.query_by_label(l).is_some(), "{l}"); - } - let app = h.state_mut(); - if let Some(d) = app.ui.dialog.as_mut() { - d.fields.insert("rename".into(), json!("eggs")); - } - confirm(app).unwrap(); - let style = app.session.doc().unwrap().doc.styles.char_style("eggs").cloned().unwrap(); - assert_eq!((style.chars.font_style.as_deref(), style.chars.fill.as_deref()), (Some("Bold"), Some("C=15 M=100 Y=100 K=0"))); - assert_eq!(style.chars.size, None, "the size is the paragraph style's, not the text's own"); - let a = app.run("type.selectionAttrs", json!({})).unwrap(); - assert_eq!((a["characterStyle"].clone(), a["charOverrides"].clone()), (json!("eggs"), json!(0)), "applied to the selection"); - } - - /// A Based On changed in the dialog (without Reset To Base) is what the fields are checked - /// against: the style's own settings over the new parent. - #[test] - fn a_changed_based_on_is_what_the_fields_are_checked_against() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("style.paragraph.create", json!({"name": "Loose", "para": {"wordSpaceMin": 1.2, "wordSpaceDesired": 1.3}})).unwrap(); - app.run("style.paragraph.create", json!({"name": "Child", "basedOn": "Loose"})).unwrap(); - let mut d = Dialog::new("paragraphStyleOptions", json!({"name": "Child"})); - d.fields.insert("p.wordSpaceDesired".into(), json!(1.0)); - assert!(check_paragraph_style_justification(&app, &d).is_err(), "below Loose's minimum"); - d.fields.insert("basedOn".into(), json!(designcraft_doc::BASIC_PARAGRAPH)); - assert_eq!(check_paragraph_style_justification(&app, &d), Ok(()), "[Basic Paragraph]'s minimum is lower"); - } - - /// With Reset To Base, the justification fields are checked against the base style (the - /// style's own minimum no longer applies), and Preview shows the reset on the page. - #[test] - fn reset_to_base_checks_and_previews_against_the_base() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": "Loose words"})).unwrap(); - app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 5})).unwrap(); - app.run("style.paragraph.create", json!({"name": "Loose", "basedOn": designcraft_doc::BASIC_PARAGRAPH, "para": {"wordSpaceMin": 1.2, "wordSpaceDesired": 1.3}, "chars": {"size": 30}})) - .unwrap(); - app.run("style.paragraph.apply", json!({"name": "Loose"})).unwrap(); - let mut d = Dialog::new("paragraphStyleOptions", json!({"name": "Loose"})); - d.fields.insert("p.wordSpaceDesired".into(), json!(1.1)); - assert!(check_paragraph_style_justification(&app, &d).is_err(), "below the style's own minimum"); - d.fields.insert("resetToBase".into(), json!(true)); - assert_eq!(check_paragraph_style_justification(&app, &d), Ok(()), "the base's minimum is 100%"); - d.fields.insert("preview".into(), json!(true)); - style_options_preview(&mut app, &mut d); - assert_eq!(d.fields[PREVIEWED]["resetToBase"], true); - let size = app.run("type.selectionAttrs", json!({})).unwrap()["chars"]["size"].clone(); - assert_eq!(size, json!(12.0), "the page shows the style reset to its base"); - app.session.cancel_interaction(); - } - #[test] fn color_theme_cancel_is_read_only_and_confirm_adds_the_preview() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index ee94dd4c2..20f6e9aba 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3524,3 +3524,131 @@ fn character_style_options_set_the_digits() { assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi)); } + +/// The course's chapter 20: the "Recipe Categories" title formatted on the page (size, All +/// Caps, tracking, space after), then New Paragraph Style from it: the dialog starts from the +/// text, and with Apply Style to Selection the paragraph takes the new style. Next Style and +/// Reset To Base are set from General. +#[test] +fn a_new_paragraph_style_starts_from_the_selected_text() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": "Egg Recipes\rBoil them."})).unwrap(); + app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 11})).unwrap(); + app.run("type.char", json!({"attrs": {"size": 20, "capitalization": "allCaps", "tracking": 50}})).unwrap(); + app.run("type.para", json!({"attrs": {"spaceAfter": 6}})).unwrap(); + open_new_style(&mut app, true); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!( + (d.fields["c.size"].clone(), d.fields["c.capitalization"].clone(), d.fields["p.spaceAfter"].clone()), + (json!(20.0), json!("allCaps"), json!(6.0)) + ); + assert!(d.b("apply") && !d.fields.contains_key("c.fontFamily"), "only what differs from [No Paragraph Style]"); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("rename".into(), json!("Recipe Categories")); + d.fields.insert("nextStyle".into(), json!(designcraft_doc::BASIC_PARAGRAPH)); + } + confirm(&mut app).unwrap(); + let a = app.run("type.selectionAttrs", json!({})).unwrap(); + assert_eq!(a["paragraphStyle"], "Recipe Categories", "applied to the selection"); + assert_eq!(a["paraOverrides"].as_u64().unwrap_or(0) + a["charOverrides"].as_u64().unwrap_or(0), 0); + let style = |app: &DesignApp| app.session.doc().unwrap().doc.styles.para("Recipe Categories").cloned().unwrap(); + assert_eq!(style(&app).next_style.as_deref(), Some(designcraft_doc::BASIC_PARAGRAPH)); + assert_eq!(style(&app).chars.size, Some(20.0)); + // Reset To Base: the style keeps nothing of its own, apart from the edits made then. + app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Recipe Categories", "basedOn": designcraft_doc::BASIC_PARAGRAPH}))); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("resetToBase".into(), json!(true)); + d.fields.insert("c.tracking".into(), json!(10.0)); + } + confirm(&mut app).unwrap(); + let s = style(&app); + assert_eq!((s.chars.size, s.chars.tracking, s.para.space_after), (None, Some(10.0), None), "{s:?}"); + assert_eq!(s.based_on.as_deref(), Some(designcraft_doc::BASIC_PARAGRAPH)); +} + +/// The course's chapter 22: "eggs" made bold and red on the page, then New Character Style +/// from it. The dialog is titled as InDesign's, starts from what the text has of its own +/// over its paragraph style ("[None] + Bold + color"), and Apply Style to Selection gives the +/// text the style, with no override left. +#[test] +fn a_new_character_style_starts_from_the_selected_text() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": "Drop eggs into boiling water."})).unwrap(); + app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 29})).unwrap(); + app.run("style.paragraph.create", json!({"name": "Recipe", "chars": {"size": 14}})).unwrap(); + app.run("style.paragraph.apply", json!({"name": "Recipe"})).unwrap(); + app.run("text.select", json!({"story": f["story"], "anchor": 5, "focus": 9})).unwrap(); + app.run("type.char", json!({"attrs": {"fontStyle": "Bold", "fill": "C=15 M=100 Y=100 K=0"}})).unwrap(); + open_new_style(&mut app, false); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!((d.fields["c.fontStyle"].clone(), d.fields["c.fill"].clone()), (json!("Bold"), json!("C=15 M=100 Y=100 K=0"))); + assert!(d.b("apply")); + let mut h = Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let key = egui::Id::new("new_character_style_test_fonts"); + if ui.data(|d| d.get_temp::(key)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(key, true)); + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + for l in ["New Character Style", "Apply Style to Selection"] { + assert!(h.query_by_label(l).is_some(), "{l}"); + } + let app = h.state_mut(); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("rename".into(), json!("eggs")); + } + confirm(app).unwrap(); + let style = app.session.doc().unwrap().doc.styles.char_style("eggs").cloned().unwrap(); + assert_eq!((style.chars.font_style.as_deref(), style.chars.fill.as_deref()), (Some("Bold"), Some("C=15 M=100 Y=100 K=0"))); + assert_eq!(style.chars.size, None, "the size is the paragraph style's, not the text's own"); + let a = app.run("type.selectionAttrs", json!({})).unwrap(); + assert_eq!((a["characterStyle"].clone(), a["charOverrides"].clone()), (json!("eggs"), json!(0)), "applied to the selection"); +} + +/// A Based On changed in the dialog (without Reset To Base) is what the fields are checked +/// against: the style's own settings over the new parent. +#[test] +fn a_changed_based_on_is_what_the_fields_are_checked_against() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("style.paragraph.create", json!({"name": "Loose", "para": {"wordSpaceMin": 1.2, "wordSpaceDesired": 1.3}})).unwrap(); + app.run("style.paragraph.create", json!({"name": "Child", "basedOn": "Loose"})).unwrap(); + let mut d = Dialog::new("paragraphStyleOptions", json!({"name": "Child"})); + d.fields.insert("p.wordSpaceDesired".into(), json!(1.0)); + assert!(check_paragraph_style_justification(&app, &d).is_err(), "below Loose's minimum"); + d.fields.insert("basedOn".into(), json!(designcraft_doc::BASIC_PARAGRAPH)); + assert_eq!(check_paragraph_style_justification(&app, &d), Ok(()), "[Basic Paragraph]'s minimum is lower"); +} + +/// With Reset To Base, the justification fields are checked against the base style (the +/// style's own minimum no longer applies), and Preview shows the reset on the page. +#[test] +fn reset_to_base_checks_and_previews_against_the_base() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": "Loose words"})).unwrap(); + app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 5})).unwrap(); + app.run("style.paragraph.create", json!({"name": "Loose", "basedOn": designcraft_doc::BASIC_PARAGRAPH, "para": {"wordSpaceMin": 1.2, "wordSpaceDesired": 1.3}, "chars": {"size": 30}})) + .unwrap(); + app.run("style.paragraph.apply", json!({"name": "Loose"})).unwrap(); + let mut d = Dialog::new("paragraphStyleOptions", json!({"name": "Loose"})); + d.fields.insert("p.wordSpaceDesired".into(), json!(1.1)); + assert!(check_paragraph_style_justification(&app, &d).is_err(), "below the style's own minimum"); + d.fields.insert("resetToBase".into(), json!(true)); + assert_eq!(check_paragraph_style_justification(&app, &d), Ok(()), "the base's minimum is 100%"); + d.fields.insert("preview".into(), json!(true)); + style_options_preview(&mut app, &mut d); + assert_eq!(d.fields[PREVIEWED]["resetToBase"], true); + let size = app.run("type.selectionAttrs", json!({})).unwrap()["chars"]["size"].clone(); + assert_eq!(size, json!(12.0), "the page shows the style reset to its base"); + app.session.cancel_interaction(); +} From d4cebe862e30fc0ceb1147763b62d0665bb037a8 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 19:44:30 +0100 Subject: [PATCH 0430/1349] Tests: the branch's dialog tests beside main's dialog test helpers (dialogs/tests.rs) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 81 ----------------------------- crates/ui-egui/src/dialogs/tests.rs | 81 +++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 81 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 0cf58d61d..e286dc94f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -186,87 +186,6 @@ fn color_theme(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { mod color_theme_tests { use super::*; - /// The course's chapter 20: the "Recipe Categories" title formatted on the page (size, All - /// Caps, tracking, space after), then New Paragraph Style from it: the dialog starts from the - /// text, and with Apply Style to Selection the paragraph takes the new style. Next Style and - /// Reset To Base are set from General. - #[test] - fn a_new_paragraph_style_starts_from_the_selected_text() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": "Egg Recipes\rBoil them."})).unwrap(); - app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 11})).unwrap(); - app.run("type.char", json!({"attrs": {"size": 20, "capitalization": "allCaps", "tracking": 50}})).unwrap(); - app.run("type.para", json!({"attrs": {"spaceAfter": 6}})).unwrap(); - open_new_style(&mut app, true); - let d = app.ui.dialog.clone().unwrap(); - assert_eq!( - (d.fields["c.size"].clone(), d.fields["c.capitalization"].clone(), d.fields["p.spaceAfter"].clone()), - (json!(20.0), json!("allCaps"), json!(6.0)) - ); - assert!(d.b("apply") && !d.fields.contains_key("c.fontFamily"), "only what differs from [No Paragraph Style]"); - if let Some(d) = app.ui.dialog.as_mut() { - d.fields.insert("rename".into(), json!("Recipe Categories")); - d.fields.insert("nextStyle".into(), json!(designcraft_doc::BASIC_PARAGRAPH)); - } - confirm(&mut app).unwrap(); - let a = app.run("type.selectionAttrs", json!({})).unwrap(); - assert_eq!(a["paragraphStyle"], "Recipe Categories", "applied to the selection"); - assert_eq!(a["paraOverrides"].as_u64().unwrap_or(0) + a["charOverrides"].as_u64().unwrap_or(0), 0); - let style = |app: &DesignApp| app.session.doc().unwrap().doc.styles.para("Recipe Categories").cloned().unwrap(); - assert_eq!(style(&app).next_style.as_deref(), Some(designcraft_doc::BASIC_PARAGRAPH)); - assert_eq!(style(&app).chars.size, Some(20.0)); - // Reset To Base: the style keeps nothing of its own, apart from the edits made then. - app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Recipe Categories", "basedOn": designcraft_doc::BASIC_PARAGRAPH}))); - if let Some(d) = app.ui.dialog.as_mut() { - d.fields.insert("resetToBase".into(), json!(true)); - d.fields.insert("c.tracking".into(), json!(10.0)); - } - confirm(&mut app).unwrap(); - let s = style(&app); - assert_eq!((s.chars.size, s.chars.tracking, s.para.space_after), (None, Some(10.0), None), "{s:?}"); - assert_eq!(s.based_on.as_deref(), Some(designcraft_doc::BASIC_PARAGRAPH)); - } - - /// A Based On changed in the dialog (without Reset To Base) is what the fields are checked - /// against: the style's own settings over the new parent. - #[test] - fn a_changed_based_on_is_what_the_fields_are_checked_against() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("style.paragraph.create", json!({"name": "Loose", "para": {"wordSpaceMin": 1.2, "wordSpaceDesired": 1.3}})).unwrap(); - app.run("style.paragraph.create", json!({"name": "Child", "basedOn": "Loose"})).unwrap(); - let mut d = Dialog::new("paragraphStyleOptions", json!({"name": "Child"})); - d.fields.insert("p.wordSpaceDesired".into(), json!(1.0)); - assert!(check_paragraph_style_justification(&app, &d).is_err(), "below Loose's minimum"); - d.fields.insert("basedOn".into(), json!(designcraft_doc::BASIC_PARAGRAPH)); - assert_eq!(check_paragraph_style_justification(&app, &d), Ok(()), "[Basic Paragraph]'s minimum is lower"); - } - - /// With Reset To Base, the justification fields are checked against the base style (the - /// style's own minimum no longer applies), and Preview shows the reset on the page. - #[test] - fn reset_to_base_checks_and_previews_against_the_base() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": "Loose words"})).unwrap(); - app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 5})).unwrap(); - app.run("style.paragraph.create", json!({"name": "Loose", "basedOn": designcraft_doc::BASIC_PARAGRAPH, "para": {"wordSpaceMin": 1.2, "wordSpaceDesired": 1.3}, "chars": {"size": 30}})) - .unwrap(); - app.run("style.paragraph.apply", json!({"name": "Loose"})).unwrap(); - let mut d = Dialog::new("paragraphStyleOptions", json!({"name": "Loose"})); - d.fields.insert("p.wordSpaceDesired".into(), json!(1.1)); - assert!(check_paragraph_style_justification(&app, &d).is_err(), "below the style's own minimum"); - d.fields.insert("resetToBase".into(), json!(true)); - assert_eq!(check_paragraph_style_justification(&app, &d), Ok(()), "the base's minimum is 100%"); - d.fields.insert("preview".into(), json!(true)); - style_options_preview(&mut app, &mut d); - assert_eq!(d.fields[PREVIEWED]["resetToBase"], true); - let size = app.run("type.selectionAttrs", json!({})).unwrap()["chars"]["size"].clone(); - assert_eq!(size, json!(12.0), "the page shows the style reset to its base"); - app.session.cancel_interaction(); - } - #[test] fn color_theme_cancel_is_read_only_and_confirm_adds_the_preview() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 0d1430061..d221100cd 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3522,3 +3522,84 @@ fn character_style_options_set_the_digits() { assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi)); } + +/// The course's chapter 20: the "Recipe Categories" title formatted on the page (size, All +/// Caps, tracking, space after), then New Paragraph Style from it: the dialog starts from the +/// text, and with Apply Style to Selection the paragraph takes the new style. Next Style and +/// Reset To Base are set from General. +#[test] +fn a_new_paragraph_style_starts_from_the_selected_text() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": "Egg Recipes\rBoil them."})).unwrap(); + app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 11})).unwrap(); + app.run("type.char", json!({"attrs": {"size": 20, "capitalization": "allCaps", "tracking": 50}})).unwrap(); + app.run("type.para", json!({"attrs": {"spaceAfter": 6}})).unwrap(); + open_new_style(&mut app, true); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!( + (d.fields["c.size"].clone(), d.fields["c.capitalization"].clone(), d.fields["p.spaceAfter"].clone()), + (json!(20.0), json!("allCaps"), json!(6.0)) + ); + assert!(d.b("apply") && !d.fields.contains_key("c.fontFamily"), "only what differs from [No Paragraph Style]"); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("rename".into(), json!("Recipe Categories")); + d.fields.insert("nextStyle".into(), json!(designcraft_doc::BASIC_PARAGRAPH)); + } + confirm(&mut app).unwrap(); + let a = app.run("type.selectionAttrs", json!({})).unwrap(); + assert_eq!(a["paragraphStyle"], "Recipe Categories", "applied to the selection"); + assert_eq!(a["paraOverrides"].as_u64().unwrap_or(0) + a["charOverrides"].as_u64().unwrap_or(0), 0); + let style = |app: &DesignApp| app.session.doc().unwrap().doc.styles.para("Recipe Categories").cloned().unwrap(); + assert_eq!(style(&app).next_style.as_deref(), Some(designcraft_doc::BASIC_PARAGRAPH)); + assert_eq!(style(&app).chars.size, Some(20.0)); + // Reset To Base: the style keeps nothing of its own, apart from the edits made then. + app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Recipe Categories", "basedOn": designcraft_doc::BASIC_PARAGRAPH}))); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("resetToBase".into(), json!(true)); + d.fields.insert("c.tracking".into(), json!(10.0)); + } + confirm(&mut app).unwrap(); + let s = style(&app); + assert_eq!((s.chars.size, s.chars.tracking, s.para.space_after), (None, Some(10.0), None), "{s:?}"); + assert_eq!(s.based_on.as_deref(), Some(designcraft_doc::BASIC_PARAGRAPH)); +} + +/// A Based On changed in the dialog (without Reset To Base) is what the fields are checked +/// against: the style's own settings over the new parent. +#[test] +fn a_changed_based_on_is_what_the_fields_are_checked_against() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("style.paragraph.create", json!({"name": "Loose", "para": {"wordSpaceMin": 1.2, "wordSpaceDesired": 1.3}})).unwrap(); + app.run("style.paragraph.create", json!({"name": "Child", "basedOn": "Loose"})).unwrap(); + let mut d = Dialog::new("paragraphStyleOptions", json!({"name": "Child"})); + d.fields.insert("p.wordSpaceDesired".into(), json!(1.0)); + assert!(check_paragraph_style_justification(&app, &d).is_err(), "below Loose's minimum"); + d.fields.insert("basedOn".into(), json!(designcraft_doc::BASIC_PARAGRAPH)); + assert_eq!(check_paragraph_style_justification(&app, &d), Ok(()), "[Basic Paragraph]'s minimum is lower"); +} + +/// With Reset To Base, the justification fields are checked against the base style (the +/// style's own minimum no longer applies), and Preview shows the reset on the page. +#[test] +fn reset_to_base_checks_and_previews_against_the_base() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": "Loose words"})).unwrap(); + app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 5})).unwrap(); + app.run("style.paragraph.create", json!({"name": "Loose", "basedOn": designcraft_doc::BASIC_PARAGRAPH, "para": {"wordSpaceMin": 1.2, "wordSpaceDesired": 1.3}, "chars": {"size": 30}})) + .unwrap(); + app.run("style.paragraph.apply", json!({"name": "Loose"})).unwrap(); + let mut d = Dialog::new("paragraphStyleOptions", json!({"name": "Loose"})); + d.fields.insert("p.wordSpaceDesired".into(), json!(1.1)); + assert!(check_paragraph_style_justification(&app, &d).is_err(), "below the style's own minimum"); + d.fields.insert("resetToBase".into(), json!(true)); + assert_eq!(check_paragraph_style_justification(&app, &d), Ok(()), "the base's minimum is 100%"); + d.fields.insert("preview".into(), json!(true)); + style_options_preview(&mut app, &mut d); + assert_eq!(d.fields[PREVIEWED]["resetToBase"], true); + let size = app.run("type.selectionAttrs", json!({})).unwrap()["chars"]["size"].clone(); + assert_eq!(size, json!(12.0), "the page shows the style reset to its base"); + app.session.cancel_interaction(); +} From 5335e0a92fc8c976bdfa2fb7f03c3a53432b2f75 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 19:51:12 +0100 Subject: [PATCH 0431/1349] Tests: the branch's table tests beside main's moved test helpers and imports Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/tests/table.rs | 3 +- crates/ui-egui/src/dialogs.rs | 90 ----------------------------- crates/ui-egui/src/dialogs/tests.rs | 90 +++++++++++++++++++++++++++++ 3 files changed, 92 insertions(+), 91 deletions(-) diff --git a/crates/engine/src/tests/table.rs b/crates/engine/src/tests/table.rs index a837647e6..79ea51c7d 100644 --- a/crates/engine/src/tests/table.rs +++ b/crates/engine/src/tests/table.rs @@ -1,6 +1,7 @@ -use serde_json::json; +use serde_json::{Value, json}; use super::{Session, doc}; +use crate::Result; fn session_with_frame() -> (Session, u64, u64) { let mut s = Session::new(); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 1468470a3..17f9129f1 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -333,96 +333,6 @@ fn color_theme(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { mod color_theme_tests { use super::*; - /// Insert Table: the dimensions as typed, and the Table Style chosen is applied to the new - /// table; [Basic Table] (the default) leaves it unstyled. - #[test] - fn insert_table_applies_its_dimensions_and_table_style() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("style.table.create", json!({"name": "Grid"})).unwrap(); - for (style, expected) in [("Grid", "Grid"), (designcraft_doc::BASIC_TABLE, "")] { - app.run("frame.create", json!({"rect": [72, 72, 372, 372], "content": "text"})).unwrap(); - assert_eq!(app.run("app.insertTableDialog", json!({})).unwrap(), Value::Null); - for (field, value) in [("bodyRows", json!(5)), ("columns", json!(3)), ("headerRows", json!(1)), ("tableStyle", json!(style))] { - ctl(&mut app, "ui.dialog.set", json!({"field": field, "value": value})); - } - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); - let t = app.run("table.get", json!({})).unwrap(); - let len = |k: &str| t[k].as_array().map_or(0, Vec::len); - assert_eq!((len("rows"), len("columns"), t["headerRows"].as_u64()), (6, 3, Some(1)), "{t}"); - assert_eq!(t["style"].as_str().unwrap_or(""), expected, "{t}"); - // One Insert Table, one undo. - app.run("edit.undo", json!({})).unwrap(); - assert!(app.run("table.get", json!({})).is_err(), "the table is gone"); - } - // A null style is no style: the table is made, unstyled. - app.run("frame.create", json!({"rect": [72, 72, 372, 372], "content": "text"})).unwrap(); - app.run("app.insertTableDialog", json!({})).unwrap(); - ctl(&mut app, "ui.dialog.set", json!({"field": "tableStyle", "value": null})); - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); - assert_eq!(app.run("table.get", json!({})).unwrap()["style"].as_str().unwrap_or(""), ""); - app.run("edit.undo", json!({})).unwrap(); - // A style that no longer exists changes nothing. - let tables = |app: &DesignApp| app.session.active().unwrap().doc.stories.values().map(|s| s.tables.len()).sum::(); - app.run("frame.create", json!({"rect": [72, 72, 372, 372], "content": "text"})).unwrap(); - app.run("app.insertTableDialog", json!({})).unwrap(); - ctl(&mut app, "ui.dialog.set", json!({"field": "tableStyle", "value": "Gone"})); - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false); - assert_eq!(tables(&app), 0); - let d = app.ui.dialog.as_ref().expect("the dialog stays open to be corrected"); - assert_eq!((d.id.as_str(), d.s("tableStyle")), ("insertTable", "Gone".to_string())); - // So does a style that isn't a name: the command refuses it, rather than making the table - // unstyled. - ctl(&mut app, "ui.dialog.set", json!({"field": "tableStyle", "value": 42})); - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false); - assert_eq!(tables(&app), 0); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("insertTable"), "the dialog stays open"); - } - - /// Convert Text to Table: available with text selected (not with a caret alone); its - /// separators and Number of Columns shape the table. Convert Table to Text takes it back with - /// the separators chosen there. - #[test] - fn convert_dialogs_use_their_separators() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let text = "Name:\nAddress:\nCity:\nState:"; - let sid = app.run("frame.create", json!({"rect": [72, 72, 372, 372], "content": "text", "text": text})).unwrap()["story"].clone(); - app.run("text.select", json!({"story": sid, "anchor": 0, "focus": 0})).unwrap(); - assert!(!crate::menus::menu_enabled(&app, "app.convertTextToTableDialog"), "a caret alone"); - assert!(!crate::menus::menu_enabled(&app, "app.convertTableToTextDialog"), "no table"); - app.run("text.select", json!({"story": sid, "anchor": 0, "focus": text.len()})).unwrap(); - assert!(crate::menus::menu_enabled(&app, "app.convertTextToTableDialog")); - app.run("app.convertTextToTableDialog", json!({})).unwrap(); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("convertTextToTable")); - // "comma" and a typed "," are the same separator, so Number of Columns applies; a count of - // 0 is refused, not taken as 1, and the dialog stays open. - ctl(&mut app, "ui.dialog.set", json!({"field": "columnSeparator", "value": "comma"})); - ctl(&mut app, "ui.dialog.set", json!({"field": "rowSeparator", "value": ","})); - assert!(same_separators(app.ui.dialog.as_ref().unwrap())); - ctl(&mut app, "ui.dialog.set", json!({"field": "columns", "value": 0})); - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("convertTextToTable")); - // An emptied separator: the command refuses it and the dialog stays open, as typed. - ctl(&mut app, "ui.dialog.set", json!({"field": "rowSeparator", "value": ""})); - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false); - assert_eq!(app.ui.dialog.as_ref().map(|d| (d.id.as_str(), d.s("rowSeparator"))), Some(("convertTextToTable", String::new()))); - for (field, value) in [("columnSeparator", json!("paragraph")), ("rowSeparator", json!("paragraph")), ("columns", json!(2))] { - ctl(&mut app, "ui.dialog.set", json!({"field": field, "value": value})); - } - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); - let t = app.run("table.get", json!({})).unwrap(); - let len = |k: &str| t[k].as_array().map_or(0, Vec::len); - assert_eq!((len("rows"), len("columns")), (2, 2), "{t}"); - assert!(crate::menus::menu_enabled(&app, "app.convertTableToTextDialog")); - app.run("app.convertTableToTextDialog", json!({})).unwrap(); - ctl(&mut app, "ui.dialog.set", json!({"field": "columnSeparator", "value": ", "})); - assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); - let story = app.session.active().unwrap().doc.story(designcraft_doc::StoryId(sid.as_u64().unwrap())).unwrap().text.clone(); - // (The empty paragraph after a table that ends its story stays after the text.) - assert_eq!(story.trim_end(), "Name:, Address:\nCity:, State:"); - } - #[test] fn color_theme_cancel_is_read_only_and_confirm_adds_the_preview() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 577b9a3ae..c6d494f9e 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3521,3 +3521,93 @@ fn character_style_options_set_the_digits() { assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi)); } + +/// Insert Table: the dimensions as typed, and the Table Style chosen is applied to the new +/// table; [Basic Table] (the default) leaves it unstyled. +#[test] +fn insert_table_applies_its_dimensions_and_table_style() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("style.table.create", json!({"name": "Grid"})).unwrap(); + for (style, expected) in [("Grid", "Grid"), (designcraft_doc::BASIC_TABLE, "")] { + app.run("frame.create", json!({"rect": [72, 72, 372, 372], "content": "text"})).unwrap(); + assert_eq!(app.run("app.insertTableDialog", json!({})).unwrap(), Value::Null); + for (field, value) in [("bodyRows", json!(5)), ("columns", json!(3)), ("headerRows", json!(1)), ("tableStyle", json!(style))] { + ctl(&mut app, "ui.dialog.set", json!({"field": field, "value": value})); + } + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); + let t = app.run("table.get", json!({})).unwrap(); + let len = |k: &str| t[k].as_array().map_or(0, Vec::len); + assert_eq!((len("rows"), len("columns"), t["headerRows"].as_u64()), (6, 3, Some(1)), "{t}"); + assert_eq!(t["style"].as_str().unwrap_or(""), expected, "{t}"); + // One Insert Table, one undo. + app.run("edit.undo", json!({})).unwrap(); + assert!(app.run("table.get", json!({})).is_err(), "the table is gone"); + } + // A null style is no style: the table is made, unstyled. + app.run("frame.create", json!({"rect": [72, 72, 372, 372], "content": "text"})).unwrap(); + app.run("app.insertTableDialog", json!({})).unwrap(); + ctl(&mut app, "ui.dialog.set", json!({"field": "tableStyle", "value": null})); + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); + assert_eq!(app.run("table.get", json!({})).unwrap()["style"].as_str().unwrap_or(""), ""); + app.run("edit.undo", json!({})).unwrap(); + // A style that no longer exists changes nothing. + let tables = |app: &DesignApp| app.session.active().unwrap().doc.stories.values().map(|s| s.tables.len()).sum::(); + app.run("frame.create", json!({"rect": [72, 72, 372, 372], "content": "text"})).unwrap(); + app.run("app.insertTableDialog", json!({})).unwrap(); + ctl(&mut app, "ui.dialog.set", json!({"field": "tableStyle", "value": "Gone"})); + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false); + assert_eq!(tables(&app), 0); + let d = app.ui.dialog.as_ref().expect("the dialog stays open to be corrected"); + assert_eq!((d.id.as_str(), d.s("tableStyle")), ("insertTable", "Gone".to_string())); + // So does a style that isn't a name: the command refuses it, rather than making the table + // unstyled. + ctl(&mut app, "ui.dialog.set", json!({"field": "tableStyle", "value": 42})); + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false); + assert_eq!(tables(&app), 0); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("insertTable"), "the dialog stays open"); +} + +/// Convert Text to Table: available with text selected (not with a caret alone); its +/// separators and Number of Columns shape the table. Convert Table to Text takes it back with +/// the separators chosen there. +#[test] +fn convert_dialogs_use_their_separators() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let text = "Name:\nAddress:\nCity:\nState:"; + let sid = app.run("frame.create", json!({"rect": [72, 72, 372, 372], "content": "text", "text": text})).unwrap()["story"].clone(); + app.run("text.select", json!({"story": sid, "anchor": 0, "focus": 0})).unwrap(); + assert!(!crate::menus::menu_enabled(&app, "app.convertTextToTableDialog"), "a caret alone"); + assert!(!crate::menus::menu_enabled(&app, "app.convertTableToTextDialog"), "no table"); + app.run("text.select", json!({"story": sid, "anchor": 0, "focus": text.len()})).unwrap(); + assert!(crate::menus::menu_enabled(&app, "app.convertTextToTableDialog")); + app.run("app.convertTextToTableDialog", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("convertTextToTable")); + // "comma" and a typed "," are the same separator, so Number of Columns applies; a count of + // 0 is refused, not taken as 1, and the dialog stays open. + ctl(&mut app, "ui.dialog.set", json!({"field": "columnSeparator", "value": "comma"})); + ctl(&mut app, "ui.dialog.set", json!({"field": "rowSeparator", "value": ","})); + assert!(same_separators(app.ui.dialog.as_ref().unwrap())); + ctl(&mut app, "ui.dialog.set", json!({"field": "columns", "value": 0})); + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("convertTextToTable")); + // An emptied separator: the command refuses it and the dialog stays open, as typed. + ctl(&mut app, "ui.dialog.set", json!({"field": "rowSeparator", "value": ""})); + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false); + assert_eq!(app.ui.dialog.as_ref().map(|d| (d.id.as_str(), d.s("rowSeparator"))), Some(("convertTextToTable", String::new()))); + for (field, value) in [("columnSeparator", json!("paragraph")), ("rowSeparator", json!("paragraph")), ("columns", json!(2))] { + ctl(&mut app, "ui.dialog.set", json!({"field": field, "value": value})); + } + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); + let t = app.run("table.get", json!({})).unwrap(); + let len = |k: &str| t[k].as_array().map_or(0, Vec::len); + assert_eq!((len("rows"), len("columns")), (2, 2), "{t}"); + assert!(crate::menus::menu_enabled(&app, "app.convertTableToTextDialog")); + app.run("app.convertTableToTextDialog", json!({})).unwrap(); + ctl(&mut app, "ui.dialog.set", json!({"field": "columnSeparator", "value": ", "})); + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); + let story = app.session.active().unwrap().doc.story(designcraft_doc::StoryId(sid.as_u64().unwrap())).unwrap().text.clone(); + // (The empty paragraph after a table that ends its story stays after the text.) + assert_eq!(story.trim_end(), "Name:, Address:\nCity:, State:"); +} From aed32a85058dafd427706905d01b58de1945e465 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 19:52:38 +0100 Subject: [PATCH 0432/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/tests.rs | 3 +- crates/ui-egui/src/panels/properties/tests.rs | 92 +++++++++---------- 2 files changed, 47 insertions(+), 48 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 1cfd51abb..333cdab6a 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3551,8 +3551,7 @@ fn paragraph_border_sides_and_corners_link_as_indesigns() { use egui_kittest::kittest::Queryable; let (app, _) = ruled_paragraph(); let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); - h.state_mut().app.ui.dialog = - Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "border", "p.borderOn": true}))); + h.state_mut().app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "border", "p.borderOn": true}))); h.run_steps(4); let field = |h: &egui_kittest::Harness<'static, crate::test_window::Window>, key: &str| { h.state().app.ui.dialog.as_ref().and_then(|d| d.fields.get(&format!("p.{key}")).cloned()).unwrap_or_default() diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 7bb88cc2c..5c9feea47 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -710,55 +710,55 @@ fn several_shapes_show_pathfinder_and_intersect_combines_them() { assert!((r.x0 - 200.0).abs() < 0.5 && (r.y1 - 200.0).abs() < 0.5 && (r.x1 - 300.0).abs() < 0.5, "{r:?}"); } - /// A row is as wide as its translated name needs: a long one isn't cut at a fixed width. - #[test] - fn preview_rows_fit_long_translated_names() { - let ctx = egui::Context::default(); - let long = "Скругленный прямоугольник с обратным углом"; - let mut widths = (0.0, 0.0); - let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { - egui::Area::new(egui::Id::new("rows")).show(ui.ctx(), |ui| { - ui.set_max_width(10.0); - let r = preview_row(ui, false, long, 40.0, |_, _, _| {}); - let text = ui.fonts_mut(|f| f.layout_no_wrap(long.to_string(), egui::FontId::proportional(12.0), egui::Color32::WHITE).size().x); - widths = (r.rect.width(), 40.0 + 12.0 + text); - }); +/// A row is as wide as its translated name needs: a long one isn't cut at a fixed width. +#[test] +fn preview_rows_fit_long_translated_names() { + let ctx = egui::Context::default(); + let long = "Скругленный прямоугольник с обратным углом"; + let mut widths = (0.0, 0.0); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + egui::Area::new(egui::Id::new("rows")).show(ui.ctx(), |ui| { + ui.set_max_width(10.0); + let r = preview_row(ui, false, long, 40.0, |_, _, _| {}); + let text = ui.fonts_mut(|f| f.layout_no_wrap(long.to_string(), egui::FontId::proportional(12.0), egui::Color32::WHITE).size().x); + widths = (r.rect.width(), 40.0 + 12.0 + text); }); - out.textures_delta.clear(); - assert!(widths.0 >= widths.1, "{widths:?}"); - } + }); + out.textures_delta.clear(); + assert!(widths.0 >= widths.1, "{widths:?}"); +} - /// The corner shape list shows each shape's glyph beside its name, as InDesign's; a row picks - /// the shape and the current one is marked. - #[test] - fn the_corner_shape_list_has_glyph_rows_and_picks_a_shape() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let id = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "shape": "rectangle"})).unwrap()["id"].as_u64().unwrap(); - app.run("selection.set", json!({"ids": [id]})).unwrap(); - let mut h = panel(app); - h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Corner Shape").click(); - h.run_steps(3); - let rows = ["None", "Fancy", "Bevel", "Inset", "Inverse Rounded", "Rounded"]; - for r in rows { - let _ = h.get_by_role_and_label(egui::accesskit::Role::Button, r); - } - h.get_by_role_and_label(egui::accesskit::Role::Button, "Bevel").click(); - h.run_steps(3); - let it = h.state().session.active().unwrap().doc.item(designcraft_doc::ids::ItemId(id)).unwrap().clone(); - assert!(it.corners.corners.iter().all(|c| c.shape == designcraft_geom::corners::CornerShape::Bevel), "{:?}", it.corners); - h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Corner Shape").click(); - h.run_steps(3); - use egui_kittest::kittest::NodeT; - let n = h.get_by_role_and_label(egui::accesskit::Role::Button, "Bevel"); - assert_eq!(n.accesskit_node().toggled(), Some(egui::accesskit::Toggled::True), "the current shape is marked"); - // The stroke type list has the same rows, by name. - h.key_press(egui::Key::Escape); - h.run_steps(2); - h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Stroke Type").click(); - h.run_steps(3); - let _ = h.get_by_role_and_label(egui::accesskit::Role::Button, "Thick - Thin"); +/// The corner shape list shows each shape's glyph beside its name, as InDesign's; a row picks +/// the shape and the current one is marked. +#[test] +fn the_corner_shape_list_has_glyph_rows_and_picks_a_shape() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "shape": "rectangle"})).unwrap()["id"].as_u64().unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + let mut h = panel(app); + h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Corner Shape").click(); + h.run_steps(3); + let rows = ["None", "Fancy", "Bevel", "Inset", "Inverse Rounded", "Rounded"]; + for r in rows { + let _ = h.get_by_role_and_label(egui::accesskit::Role::Button, r); } + h.get_by_role_and_label(egui::accesskit::Role::Button, "Bevel").click(); + h.run_steps(3); + let it = h.state().session.active().unwrap().doc.item(designcraft_doc::ids::ItemId(id)).unwrap().clone(); + assert!(it.corners.corners.iter().all(|c| c.shape == designcraft_geom::corners::CornerShape::Bevel), "{:?}", it.corners); + h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Corner Shape").click(); + h.run_steps(3); + use egui_kittest::kittest::NodeT; + let n = h.get_by_role_and_label(egui::accesskit::Role::Button, "Bevel"); + assert_eq!(n.accesskit_node().toggled(), Some(egui::accesskit::Toggled::True), "the current shape is marked"); + // The stroke type list has the same rows, by name. + h.key_press(egui::Key::Escape); + h.run_steps(2); + h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Stroke Type").click(); + h.run_steps(3); + let _ = h.get_by_role_and_label(egui::accesskit::Role::Button, "Thick - Thin"); +} const CYAN: &str = "C=100 M=0 Y=0 K=0"; From 0268dd40e72a4031f81a1234dd4a3c683a7adc10 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 19:57:07 +0100 Subject: [PATCH 0433/1349] IDML export: paragraph overprint attributes through main's attribute macros Co-Authored-By: Claude Opus 5.5 --- crates/idml/src/export/text_attrs.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/idml/src/export/text_attrs.rs b/crates/idml/src/export/text_attrs.rs index 6fddcfeb2..7071f68ba 100644 --- a/crates/idml/src/export/text_attrs.rs +++ b/crates/idml/src/export/text_attrs.rs @@ -494,7 +494,7 @@ impl<'a> Ex<'a> { props.push(p("ParagraphShadingColor", "object", self.sw(c))); } n!(a, el, shading_tint, "ParagraphShadingTint", pct); - b!(shading_overprint, "ParagraphShadingOverprint"); + b!(a, el, shading_overprint, "ParagraphShadingOverprint"); const SIDES: [&str; 4] = ["Top", "Left", "Bottom", "Right"]; if let Some(o) = a.shading_offsets { for (i, side) in SIDES.iter().enumerate() { @@ -506,7 +506,7 @@ impl<'a> Ex<'a> { props.push(p("ParagraphBorderColor", "object", self.sw(c))); } n!(a, el, border_tint, "ParagraphBorderTint", pct); - b!(border_overprint, "ParagraphBorderOverprint"); + b!(a, el, border_overprint, "ParagraphBorderOverprint"); if let Some(w) = a.border_weights { for (i, side) in SIDES.iter().enumerate() { el.set(&format!("ParagraphBorder{side}LineWeight"), num(w[i])); From be7861364b87d0d5c6245e844b26b32233464e9d Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 19:57:14 +0100 Subject: [PATCH 0434/1349] IDML export: the border gap overprint through main's attribute macro too Co-Authored-By: Claude Opus 5.5 --- crates/idml/src/export/text_attrs.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/idml/src/export/text_attrs.rs b/crates/idml/src/export/text_attrs.rs index 7071f68ba..557602a18 100644 --- a/crates/idml/src/export/text_attrs.rs +++ b/crates/idml/src/export/text_attrs.rs @@ -542,7 +542,7 @@ impl<'a> Ex<'a> { props.push(p("ParagraphBorderGapColor", "object", self.sw(c))); } n!(a, el, border_gap_tint, "ParagraphBorderGapTint", pct); - b!(border_gap_overprint, "ParagraphBorderGapOverprint"); + b!(a, el, border_gap_overprint, "ParagraphBorderGapOverprint"); if let Some(w) = a.shading_width { el.set("ParagraphShadingWidth", names::box_width_out(w)); } From 42183766680f7716bdc73d0a59f0f7f25a5f821a Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 19:57:22 +0100 Subject: [PATCH 0435/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/tests.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 9c99c92b4..339354ac4 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3551,8 +3551,7 @@ fn preferences_interface_sets_the_color_theme_and_tools_panel() { app, ); h.run_steps(3); - let swatch = - |h: &Harness<'_, DesignApp>, name: &str| h.get_by(|n| n.role() == Role::RadioButton && n.label().as_deref() == Some(name)).click(); + let swatch = |h: &Harness<'_, DesignApp>, name: &str| h.get_by(|n| n.role() == Role::RadioButton && n.label().as_deref() == Some(name)).click(); for l in ["Appearance", "Color Theme:", "Panels", "Tools Panel:"] { assert!(h.query_by_label(l).is_some(), "{l}"); } From c20d4864e32e167d619a76269d72907611be669b Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 20:01:16 +0100 Subject: [PATCH 0436/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 2 +- crates/ui-egui/src/dialogs/tests.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index d9d48e416..7fb6037dc 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1988,7 +1988,7 @@ fn preferences(app: &crate::DesignApp, ui: &mut egui::Ui, d: &mut Dialog, max_he ui.painter().rect_stroke(r.shrink(1.0), 2.0, egui::Stroke::new(2.0, ring), egui::StrokeKind::Inside); } let name = crate::i18n::tr(&lang, b.label()).to_string(); - resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::RadioButton, true, on, &name)); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, on, &name)); if resp.on_hover_text(&name).clicked() && !on { d.fields.insert("brightness".into(), json!(b.id())); d.fields.insert("applyBrightness".into(), json!(b.id())); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 339354ac4..bdcac47a9 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3540,7 +3540,7 @@ fn preferences_interface_sets_the_color_theme_and_tools_panel() { open(&mut app); let mut h = Harness::builder().with_size(egui::vec2(1100.0, 760.0)).build_ui_state( |ui, app: &mut DesignApp| { - let key = egui::Id::new("prefs_interface_test_fonts"); + let key = egui::Id::unique("prefs_interface_test_fonts"); if ui.data(|d| d.get_temp::(key)).is_none() { crate::theme::install_fonts(ui.ctx(), ""); ui.data_mut(|d| d.insert_temp(key, true)); From fcb4b5c544893df314bf784b79d97b80bdf05af9 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 20:03:23 +0100 Subject: [PATCH 0437/1349] Georgian: main's row for Single Column, once Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/ka.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index b5779b321..e328562c2 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -33,7 +33,6 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Copy", "კოპირება"), ("Paste", "ჩასმა"), ("Double Column", "ორმაგი სვეტი"), - ("Single Column", "ერთმაგი სვეტი"), ("Tools Panel:", "ხელსაწყოების პანელი:"), ("Color Theme:", "ფერთა თემა:"), ("Restart Numbering", "ნუმერაციის თავიდან დაწყება"), From e72193c210c41554ac09def7beee1ef27fbad0b2 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 20:31:27 +0100 Subject: [PATCH 0438/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/properties/tests.rs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 73c600a55..59694954e 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -786,15 +786,15 @@ fn apply_to_text_colours_a_text_frames_text_not_the_frame() { assert_eq!(doc.item(designcraft_doc::ids::ItemId(id)).unwrap().fill.swatch, "[None]", "the frame isn't"); } - /// The Align To button shows the target picked in its menu. - #[test] - fn the_align_to_button_shows_its_target() { - assert_eq!(align_to_icon("selection"), "align-to"); - assert_eq!(align_to_icon("keyObject"), "align-to-key"); - assert_eq!(align_to_icon("margins"), "align-to-margins"); - assert_eq!(align_to_icon("page"), "align-to-page"); - assert_eq!(align_to_icon("spread"), "align-to-spread"); - } +/// The Align To button shows the target picked in its menu. +#[test] +fn the_align_to_button_shows_its_target() { + assert_eq!(align_to_icon("selection"), "align-to"); + assert_eq!(align_to_icon("keyObject"), "align-to-key"); + assert_eq!(align_to_icon("margins"), "align-to-margins"); + assert_eq!(align_to_icon("page"), "align-to-page"); + assert_eq!(align_to_icon("spread"), "align-to-spread"); +} #[test] fn transform_flips_and_rotates_from_properties() { From e3fd046ecc23595f62031319e28fbbd823177a9f Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 20:50:36 +0100 Subject: [PATCH 0439/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/properties/tests.rs | 92 +++++++++---------- 1 file changed, 46 insertions(+), 46 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 7bb88cc2c..5c9feea47 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -710,55 +710,55 @@ fn several_shapes_show_pathfinder_and_intersect_combines_them() { assert!((r.x0 - 200.0).abs() < 0.5 && (r.y1 - 200.0).abs() < 0.5 && (r.x1 - 300.0).abs() < 0.5, "{r:?}"); } - /// A row is as wide as its translated name needs: a long one isn't cut at a fixed width. - #[test] - fn preview_rows_fit_long_translated_names() { - let ctx = egui::Context::default(); - let long = "Скругленный прямоугольник с обратным углом"; - let mut widths = (0.0, 0.0); - let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { - egui::Area::new(egui::Id::new("rows")).show(ui.ctx(), |ui| { - ui.set_max_width(10.0); - let r = preview_row(ui, false, long, 40.0, |_, _, _| {}); - let text = ui.fonts_mut(|f| f.layout_no_wrap(long.to_string(), egui::FontId::proportional(12.0), egui::Color32::WHITE).size().x); - widths = (r.rect.width(), 40.0 + 12.0 + text); - }); +/// A row is as wide as its translated name needs: a long one isn't cut at a fixed width. +#[test] +fn preview_rows_fit_long_translated_names() { + let ctx = egui::Context::default(); + let long = "Скругленный прямоугольник с обратным углом"; + let mut widths = (0.0, 0.0); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + egui::Area::new(egui::Id::new("rows")).show(ui.ctx(), |ui| { + ui.set_max_width(10.0); + let r = preview_row(ui, false, long, 40.0, |_, _, _| {}); + let text = ui.fonts_mut(|f| f.layout_no_wrap(long.to_string(), egui::FontId::proportional(12.0), egui::Color32::WHITE).size().x); + widths = (r.rect.width(), 40.0 + 12.0 + text); }); - out.textures_delta.clear(); - assert!(widths.0 >= widths.1, "{widths:?}"); - } + }); + out.textures_delta.clear(); + assert!(widths.0 >= widths.1, "{widths:?}"); +} - /// The corner shape list shows each shape's glyph beside its name, as InDesign's; a row picks - /// the shape and the current one is marked. - #[test] - fn the_corner_shape_list_has_glyph_rows_and_picks_a_shape() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let id = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "shape": "rectangle"})).unwrap()["id"].as_u64().unwrap(); - app.run("selection.set", json!({"ids": [id]})).unwrap(); - let mut h = panel(app); - h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Corner Shape").click(); - h.run_steps(3); - let rows = ["None", "Fancy", "Bevel", "Inset", "Inverse Rounded", "Rounded"]; - for r in rows { - let _ = h.get_by_role_and_label(egui::accesskit::Role::Button, r); - } - h.get_by_role_and_label(egui::accesskit::Role::Button, "Bevel").click(); - h.run_steps(3); - let it = h.state().session.active().unwrap().doc.item(designcraft_doc::ids::ItemId(id)).unwrap().clone(); - assert!(it.corners.corners.iter().all(|c| c.shape == designcraft_geom::corners::CornerShape::Bevel), "{:?}", it.corners); - h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Corner Shape").click(); - h.run_steps(3); - use egui_kittest::kittest::NodeT; - let n = h.get_by_role_and_label(egui::accesskit::Role::Button, "Bevel"); - assert_eq!(n.accesskit_node().toggled(), Some(egui::accesskit::Toggled::True), "the current shape is marked"); - // The stroke type list has the same rows, by name. - h.key_press(egui::Key::Escape); - h.run_steps(2); - h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Stroke Type").click(); - h.run_steps(3); - let _ = h.get_by_role_and_label(egui::accesskit::Role::Button, "Thick - Thin"); +/// The corner shape list shows each shape's glyph beside its name, as InDesign's; a row picks +/// the shape and the current one is marked. +#[test] +fn the_corner_shape_list_has_glyph_rows_and_picks_a_shape() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "shape": "rectangle"})).unwrap()["id"].as_u64().unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + let mut h = panel(app); + h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Corner Shape").click(); + h.run_steps(3); + let rows = ["None", "Fancy", "Bevel", "Inset", "Inverse Rounded", "Rounded"]; + for r in rows { + let _ = h.get_by_role_and_label(egui::accesskit::Role::Button, r); } + h.get_by_role_and_label(egui::accesskit::Role::Button, "Bevel").click(); + h.run_steps(3); + let it = h.state().session.active().unwrap().doc.item(designcraft_doc::ids::ItemId(id)).unwrap().clone(); + assert!(it.corners.corners.iter().all(|c| c.shape == designcraft_geom::corners::CornerShape::Bevel), "{:?}", it.corners); + h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Corner Shape").click(); + h.run_steps(3); + use egui_kittest::kittest::NodeT; + let n = h.get_by_role_and_label(egui::accesskit::Role::Button, "Bevel"); + assert_eq!(n.accesskit_node().toggled(), Some(egui::accesskit::Toggled::True), "the current shape is marked"); + // The stroke type list has the same rows, by name. + h.key_press(egui::Key::Escape); + h.run_steps(2); + h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Stroke Type").click(); + h.run_steps(3); + let _ = h.get_by_role_and_label(egui::accesskit::Role::Button, "Thick - Thin"); +} const CYAN: &str = "C=100 M=0 Y=0 K=0"; From e5b17c21845f3a224e8b52da7f6f856aadc60322 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 20:56:41 +0100 Subject: [PATCH 0440/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/properties/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 5c9feea47..4458dae4f 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -717,7 +717,7 @@ fn preview_rows_fit_long_translated_names() { let long = "Скругленный прямоугольник с обратным углом"; let mut widths = (0.0, 0.0); let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { - egui::Area::new(egui::Id::new("rows")).show(ui.ctx(), |ui| { + egui::Area::new(egui::Id::unique("rows")).show(ui.ctx(), |ui| { ui.set_max_width(10.0); let r = preview_row(ui, false, long, 40.0, |_, _, _| {}); let text = ui.fonts_mut(|f| f.layout_no_wrap(long.to_string(), egui::FontId::proportional(12.0), egui::Color32::WHITE).size().x); From 5677b4021cbd23c3121ecd0a3c619c7bfae93824 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 21:00:41 +0100 Subject: [PATCH 0441/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/properties/tests.rs | 52 +++++++++---------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index e2ebf6feb..ea3c385bc 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -786,33 +786,33 @@ fn apply_to_text_colours_a_text_frames_text_not_the_frame() { assert_eq!(doc.item(designcraft_doc::ids::ItemId(id)).unwrap().fill.swatch, "[None]", "the frame isn't"); } - #[test] - fn apply_to_text_colours_the_text_of_several_text_frames() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let mut ids = vec![]; - let mut stories = vec![]; - for x in [72, 250, 430] { - let r = app.run("frame.create", json!({"rect": [x, 72, x + 150, 140], "content": "text", "text": "75%"})).unwrap(); - ids.push(r["id"].as_u64().unwrap()); - stories.push(designcraft_doc::StoryId(r["story"].as_u64().unwrap())); - } - app.run("selection.set", json!({"ids": ids})).unwrap(); - let mut h = panel(app); - h.get_by_label("Fill swatch").click(); - h.run_steps(3); - // Three text frames, as one: Apply To is offered. - assert!(h.query_by_label("Apply To:").is_some()); - h.get_by_label("Text").click(); - h.run_steps(3); - h.get_by_label(CYAN).click(); - h.run_steps(3); - let doc = &h.state().session.active().unwrap().doc; - for (id, story) in ids.iter().zip(&stories) { - assert_eq!(doc.story(*story).unwrap().char_format_at(0).over.fill.as_deref(), Some(CYAN), "every frame's text is cyan"); - assert_eq!(doc.item(designcraft_doc::ids::ItemId(*id)).unwrap().fill.swatch, "[None]", "the frames aren't"); - } +#[test] +fn apply_to_text_colours_the_text_of_several_text_frames() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let mut ids = vec![]; + let mut stories = vec![]; + for x in [72, 250, 430] { + let r = app.run("frame.create", json!({"rect": [x, 72, x + 150, 140], "content": "text", "text": "75%"})).unwrap(); + ids.push(r["id"].as_u64().unwrap()); + stories.push(designcraft_doc::StoryId(r["story"].as_u64().unwrap())); } + app.run("selection.set", json!({"ids": ids})).unwrap(); + let mut h = panel(app); + h.get_by_label("Fill swatch").click(); + h.run_steps(3); + // Three text frames, as one: Apply To is offered. + assert!(h.query_by_label("Apply To:").is_some()); + h.get_by_label("Text").click(); + h.run_steps(3); + h.get_by_label(CYAN).click(); + h.run_steps(3); + let doc = &h.state().session.active().unwrap().doc; + for (id, story) in ids.iter().zip(&stories) { + assert_eq!(doc.story(*story).unwrap().char_format_at(0).over.fill.as_deref(), Some(CYAN), "every frame's text is cyan"); + assert_eq!(doc.item(designcraft_doc::ids::ItemId(*id)).unwrap().fill.swatch, "[None]", "the frames aren't"); + } +} #[test] fn transform_flips_and_rotates_from_properties() { From 5b51b16b05c2c03b4e6c712279638ca0208322e4 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 21:10:35 +0100 Subject: [PATCH 0442/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 68e674b6e..591974004 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -301,7 +301,7 @@ fn interface_strings() -> HashSet<&'static str> { "Equal fixed heights for the selected rows; cell text may become overset.", "Found", "Grab bag", - "Include Inside Edges", + "Include Inside Edges", "Key Object", "Load Styles", "layer", From 49da13445a3e4d8118b639b2c45e8ded705a47fc Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 21:30:57 +0100 Subject: [PATCH 0443/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/tests.rs | 198 ++++++++++++++-------------- 1 file changed, 99 insertions(+), 99 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 706459679..83527c2ee 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -592,7 +592,7 @@ fn the_hex_field_keeps_typed_text_and_commits_a_valid_code() { dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]); type_slowly(&mut app, &ctx, screen, "zz"); let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "#:").center()); + click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "#:").center()); let labels = dialog_frame(&mut app, &ctx, screen, vec![]); visible_label(&labels, screen, "f59019"); assert_eq!(app.ui.dialog.as_ref().unwrap().s("hex"), "#f59019"); @@ -602,13 +602,13 @@ fn the_hex_field_keeps_typed_text_and_commits_a_valid_code() { fn typed_channel_values_are_kept_while_typing() { let (mut app, ctx, screen, id) = picker(json!({"target": "fill", "hex": "#010203", "model": "rgb", "rgb": [1, 2, 3]})); let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - let r = visible_label(&labels, screen, "R:"); - click_dialog(&mut app, &ctx, screen, egui::pos2(r.min.x + 46.0, r.center().y)); + let r = visible_label(&labels, screen, "R:"); + click_dialog(&mut app, &ctx, screen, egui::pos2(r.min.x + 46.0, r.center().y)); dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]); type_slowly(&mut app, &ctx, screen, "12.5"); let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - visible_label(&labels, screen, "12.5"); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["rgb"][1], json!(2.0)); + visible_label(&labels, screen, "12.5"); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["rgb"][1], json!(2.0)); assert_eq!(app.ui.dialog.as_ref().unwrap().s("hex"), "#0d0203"); confirm(&mut app).unwrap(); let designcraft_color::Color::Rgb { r, .. } = fill(&app, id) else { panic!("not RGB") }; @@ -630,8 +630,8 @@ fn a_cmyk_colour_stays_cmyk_unless_rgb_values_are_typed() { // A typed C/M/Y/K percent is a percent: M 1 is 1 %. let (mut app, ctx, screen, id) = picker(cmyk.clone()); let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - let r = visible_label(&labels, screen, "M:"); - click_dialog(&mut app, &ctx, screen, egui::pos2(r.max.x + 29.0, r.center().y)); + let r = visible_label(&labels, screen, "M:"); + click_dialog(&mut app, &ctx, screen, egui::pos2(r.max.x + 29.0, r.center().y)); dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]); type_slowly(&mut app, &ctx, screen, "1"); confirm(&mut app).unwrap(); @@ -641,9 +641,9 @@ fn a_cmyk_colour_stays_cmyk_unless_rgb_values_are_typed() { let (mut app, ctx, screen, id) = picker(cmyk); let r = app.ui.dialog.as_ref().unwrap().fields["rgb"][0].as_f64().unwrap(); let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - let _ = r; - let r = visible_label(&labels, screen, "R:"); - click_dialog(&mut app, &ctx, screen, egui::pos2(r.min.x + 46.0, r.center().y)); + let _ = r; + let r = visible_label(&labels, screen, "R:"); + click_dialog(&mut app, &ctx, screen, egui::pos2(r.min.x + 46.0, r.center().y)); dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]); type_slowly(&mut app, &ctx, screen, "10"); confirm(&mut app).unwrap(); @@ -1644,7 +1644,7 @@ fn dialog_frame(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, ev fn visible_label(labels: &[(String, egui::Rect, egui::Rect)], screen: egui::Rect, expected: &str) -> egui::Rect { let (_, rect, clip) = labels.iter().find(|(text, _, _)| text.trim() == expected).unwrap_or_else(|| panic!("{expected} is painted")); assert!(screen.contains_rect(*rect), "{expected} must stay on screen: {rect:?}"); - assert!(clip.expand(0.5).contains_rect(*rect), "{expected} must not be clipped: {rect:?}, {clip:?}"); + assert!(clip.expand(0.5).contains_rect(*rect), "{expected} must not be clipped: {rect:?}, {clip:?}"); *rect } @@ -3462,96 +3462,96 @@ fn guide_counts(app: &DesignApp) -> Vec { (0..doc.page_count()).map(|abs| doc.page(abs).unwrap().guides.len()).collect() } - /// The Color Picker laid out as InDesign's: a field and a slider for the component whose radio - /// is on, the new colour over the old one, and the values in every space. - #[test] +/// The Color Picker laid out as InDesign's: a field and a slider for the component whose radio +/// is on, the new colour over the old one, and the values in every space. +#[test] - fn the_color_picker_keeps_a_typed_cmyk_value_the_colour_shown_does_not_change_with() { - use egui_kittest::kittest::Queryable; - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.ui.dialog = Some(Dialog::new("colorPicker", json!({"target": "fill", "cmyk": [0.0, 0.0, 0.0, 100.0], "text": false}))); - let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); - h.run_steps(3); - // A C typed at 100% K is kept, whether or not the colour shown changes with it. - let rgb = h.state().app.ui.dialog.as_ref().unwrap().fields.get("rgb").cloned(); - h.get_by_label("C").focus(); - h.run_steps(1); - h.event(egui::Event::Text("50".into())); - h.run_steps(2); - let d = h.state().app.ui.dialog.as_ref().unwrap(); - assert_eq!(d.fields["cmyk"], json!([50.0, 0.0, 0.0, 100.0]), "rgb {:?} (was {rgb:?})", d.fields.get("rgb")); - assert!(d.b("edited")); - } +fn the_color_picker_keeps_a_typed_cmyk_value_the_colour_shown_does_not_change_with() { + use egui_kittest::kittest::Queryable; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.ui.dialog = Some(Dialog::new("colorPicker", json!({"target": "fill", "cmyk": [0.0, 0.0, 0.0, 100.0], "text": false}))); + let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); + h.run_steps(3); + // A C typed at 100% K is kept, whether or not the colour shown changes with it. + let rgb = h.state().app.ui.dialog.as_ref().unwrap().fields.get("rgb").cloned(); + h.get_by_label("C").focus(); + h.run_steps(1); + h.event(egui::Event::Text("50".into())); + h.run_steps(2); + let d = h.state().app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.fields["cmyk"], json!([50.0, 0.0, 0.0, 100.0]), "rgb {:?} (was {rgb:?})", d.fields.get("rgb")); + assert!(d.b("edited")); +} - #[test] - fn the_color_picker_picks_on_its_field_and_slider_and_adds_a_cmyk_swatch() { - use egui_kittest::kittest::Queryable; - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("frame.create", json!({"rect": [72, 72, 200, 200], "shape": "rectangle"})).unwrap(); - app.run("object.color", json!({"color":designcraft_color::Color::from_hex("#7c1315").unwrap(),"target":"fill"})).unwrap(); - app.ui.dialog = Some(Dialog::new("colorPicker", json!({"target": "fill", "hex": "#7c1315", "text": false}))); - let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); - h.run_steps(3); - // R at first: R up the slider, B across and G up the field. - let _ = h.get_by_label("RGB Color Space View"); - let field = h.get_by_label("Color field").rect(); - crate::test_window::click_at(&mut h, egui::pos2(field.right() - 1.0, field.top() + 1.0)); - h.run_steps(2); - let p = picked_of(h.state().app.ui.dialog.as_ref().unwrap()); - assert!((p.rgb[0] - 124.0 / 255.0).abs() < 0.01 && p.rgb[1] > 0.97 && p.rgb[2] > 0.97, "{p:?}: R kept, G and B full"); - // The slider sets R alone. - let slider = h.get_by_label("Color slider").rect(); - crate::test_window::click_at(&mut h, egui::pos2(slider.center().x, slider.bottom() - 1.0)); - h.run_steps(2); - let p = picked_of(h.state().app.ui.dialog.as_ref().unwrap()); - assert!(p.rgb[0] < 0.02 && p.rgb[1] > 0.97, "{p:?}"); - // Hue on the slider: the field is saturation across, brightness up. - store_picked(h.state_mut().app.ui.dialog.as_mut().unwrap(), &Picked::from_rgb([124.0 / 255.0, 19.0 / 255.0, 21.0 / 255.0], 0.0)); - h.state_mut().app.ui.dialog.as_mut().unwrap().fields.insert("component".into(), json!("h")); - h.run_steps(2); - crate::test_window::click_at(&mut h, egui::pos2(field.left() + 1.0, field.top() + 1.0)); - h.run_steps(2); - let p = picked_of(h.state().app.ui.dialog.as_ref().unwrap()); - assert!(p.hsb[1] < 0.02 && p.hsb[2] > 0.98 && (p.hsb[0] - 359.0).abs() < 2.0, "{p:?}: no saturation, full brightness, the hue kept"); - // Lab shows its own view. - h.state_mut().app.ui.dialog.as_mut().unwrap().fields.insert("component".into(), json!("l")); - h.run_steps(2); - let _ = h.get_by_label("Lab Color Space View"); - // Add CMYK Swatch adds the colour as a CMYK swatch; OK applies it. - store_picked(h.state_mut().app.ui.dialog.as_mut().unwrap(), &Picked::from_rgb([124.0 / 255.0, 19.0 / 255.0, 21.0 / 255.0], 0.0)); - h.run_steps(2); - let before = h.state().app.session.active().unwrap().doc.swatches.len(); - h.get_by_label("Add CMYK Swatch").click(); - h.run_steps(3); - let doc = &h.state().app.session.active().unwrap().doc; - assert_eq!(doc.swatches.len(), before + 1); - assert!(matches!( - doc.swatches.last().unwrap().value, - designcraft_color::swatch::SwatchValue::Color { color: designcraft_color::Color::Cmyk { .. }, .. } - )); - // The percentages the C/M/Y/K fields show, exactly (not the colour converted back). - h.state_mut().app.ui.dialog.as_mut().unwrap().fields.insert("cmyk".into(), json!([0.0, 50.0, 100.0, 0.0])); - h.run_steps(2); - h.get_by_label("Add CMYK Swatch").click(); - h.run_steps(3); - let doc = &h.state().app.session.active().unwrap().doc; - let designcraft_color::swatch::SwatchValue::Color { color: designcraft_color::Color::Cmyk { c, m, y, k }, .. } = - doc.swatches.last().unwrap().value - else { - panic!("a CMYK swatch") - }; - assert_eq!([c, m, y, k].map(|v| (v * 100.0).round()), [0.0, 50.0, 100.0, 0.0]); - // Its own OK, at the top right, applies it. - h.get_by_label("OK").click(); - h.run_steps(3); - assert!(h.state().app.ui.dialog.is_none(), "OK closes it"); - let st = h.state().app.session.active().unwrap(); - let id = st.selection.items[0]; - let fill = st.doc.item(id).unwrap().fill.swatch.clone(); - assert_eq!(st.doc.resolve_color(&fill, 1.0).unwrap().to_hex(), "#7c1315"); - } +#[test] +fn the_color_picker_picks_on_its_field_and_slider_and_adds_a_cmyk_swatch() { + use egui_kittest::kittest::Queryable; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("frame.create", json!({"rect": [72, 72, 200, 200], "shape": "rectangle"})).unwrap(); + app.run("object.color", json!({"color":designcraft_color::Color::from_hex("#7c1315").unwrap(),"target":"fill"})).unwrap(); + app.ui.dialog = Some(Dialog::new("colorPicker", json!({"target": "fill", "hex": "#7c1315", "text": false}))); + let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); + h.run_steps(3); + // R at first: R up the slider, B across and G up the field. + let _ = h.get_by_label("RGB Color Space View"); + let field = h.get_by_label("Color field").rect(); + crate::test_window::click_at(&mut h, egui::pos2(field.right() - 1.0, field.top() + 1.0)); + h.run_steps(2); + let p = picked_of(h.state().app.ui.dialog.as_ref().unwrap()); + assert!((p.rgb[0] - 124.0 / 255.0).abs() < 0.01 && p.rgb[1] > 0.97 && p.rgb[2] > 0.97, "{p:?}: R kept, G and B full"); + // The slider sets R alone. + let slider = h.get_by_label("Color slider").rect(); + crate::test_window::click_at(&mut h, egui::pos2(slider.center().x, slider.bottom() - 1.0)); + h.run_steps(2); + let p = picked_of(h.state().app.ui.dialog.as_ref().unwrap()); + assert!(p.rgb[0] < 0.02 && p.rgb[1] > 0.97, "{p:?}"); + // Hue on the slider: the field is saturation across, brightness up. + store_picked(h.state_mut().app.ui.dialog.as_mut().unwrap(), &Picked::from_rgb([124.0 / 255.0, 19.0 / 255.0, 21.0 / 255.0], 0.0)); + h.state_mut().app.ui.dialog.as_mut().unwrap().fields.insert("component".into(), json!("h")); + h.run_steps(2); + crate::test_window::click_at(&mut h, egui::pos2(field.left() + 1.0, field.top() + 1.0)); + h.run_steps(2); + let p = picked_of(h.state().app.ui.dialog.as_ref().unwrap()); + assert!(p.hsb[1] < 0.02 && p.hsb[2] > 0.98 && (p.hsb[0] - 359.0).abs() < 2.0, "{p:?}: no saturation, full brightness, the hue kept"); + // Lab shows its own view. + h.state_mut().app.ui.dialog.as_mut().unwrap().fields.insert("component".into(), json!("l")); + h.run_steps(2); + let _ = h.get_by_label("Lab Color Space View"); + // Add CMYK Swatch adds the colour as a CMYK swatch; OK applies it. + store_picked(h.state_mut().app.ui.dialog.as_mut().unwrap(), &Picked::from_rgb([124.0 / 255.0, 19.0 / 255.0, 21.0 / 255.0], 0.0)); + h.run_steps(2); + let before = h.state().app.session.active().unwrap().doc.swatches.len(); + h.get_by_label("Add CMYK Swatch").click(); + h.run_steps(3); + let doc = &h.state().app.session.active().unwrap().doc; + assert_eq!(doc.swatches.len(), before + 1); + assert!(matches!( + doc.swatches.last().unwrap().value, + designcraft_color::swatch::SwatchValue::Color { color: designcraft_color::Color::Cmyk { .. }, .. } + )); + // The percentages the C/M/Y/K fields show, exactly (not the colour converted back). + h.state_mut().app.ui.dialog.as_mut().unwrap().fields.insert("cmyk".into(), json!([0.0, 50.0, 100.0, 0.0])); + h.run_steps(2); + h.get_by_label("Add CMYK Swatch").click(); + h.run_steps(3); + let doc = &h.state().app.session.active().unwrap().doc; + let designcraft_color::swatch::SwatchValue::Color { color: designcraft_color::Color::Cmyk { c, m, y, k }, .. } = + doc.swatches.last().unwrap().value + else { + panic!("a CMYK swatch") + }; + assert_eq!([c, m, y, k].map(|v| (v * 100.0).round()), [0.0, 50.0, 100.0, 0.0]); + // Its own OK, at the top right, applies it. + h.get_by_label("OK").click(); + h.run_steps(3); + assert!(h.state().app.ui.dialog.is_none(), "OK closes it"); + let st = h.state().app.session.active().unwrap(); + let id = st.selection.items[0]; + let fill = st.doc.item(id).unwrap().fill.swatch.clone(); + assert_eq!(st.doc.resolve_color(&fill, 1.0).unwrap().to_hex(), "#7c1315"); +} #[test] From 9e9efb3ba3b9d047b3782a22282cd807a33c3872 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 21:31:11 +0100 Subject: [PATCH 0444/1349] Alpha text wrap: the default threshold re-exported from main's split item module Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/item.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rs index 1d2feb6a8..fc997825b 100644 --- a/crates/doc/src/item.rs +++ b/crates/doc/src/item.rs @@ -29,7 +29,7 @@ pub use paint::{ path_length_bound, }; pub use text_frame::{ - AutoSize, ColumnsKind, ContourType, FirstBaseline, FrameBaselineGrid, FrameGridRelative, PathAlign, PathType, TextFrame, TextFrameOptions, + AutoSize, ColumnsKind, DEFAULT_ALPHA_THRESHOLD, ContourType, FirstBaseline, FrameBaselineGrid, FrameGridRelative, PathAlign, PathType, TextFrame, TextFrameOptions, TextWrap, VerticalJustification, WrapMode, WrapSide, vertical_text_xf, }; From 10e9970cfedaaecfe0fa9e76e2e8c80f92065d89 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 21:44:05 +0100 Subject: [PATCH 0445/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/tests.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 4d9a1ddb6..ba5531870 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3604,10 +3604,7 @@ fn a_change_format_goes_with_change_all() { let mut d = Dialog::new("findChange", json!({"find": "cook"})); d.fields.insert(CHANGE_FORMAT.into(), json!({"charStyle": "eggs", "paraStyle": "Method", "chars": {"underline": true}})); let p = find_change_params(&d); - assert_eq!( - (p["charStyle"].clone(), p["paraStyle"].clone(), p["attrs"].clone()), - (json!("eggs"), json!("Method"), json!({"underline": true})) - ); + assert_eq!((p["charStyle"].clone(), p["paraStyle"].clone(), p["attrs"].clone()), (json!("eggs"), json!("Method"), json!({"underline": true}))); assert_eq!(change_format_summary("en", d.fields.get(CHANGE_FORMAT)), "Character Style: eggs + Paragraph Style: Method + Underline: on"); assert!(find_change_params(&Dialog::new("findChange", json!({"find": "cook"}))).get("attrs").is_none()); } From 8fec15f3dcf4152ffbec4ce7014df68c2f4c906e Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 21:44:21 +0100 Subject: [PATCH 0446/1349] Color Picker: the remembered colours seeded with map entries Keeps color_picker within clippy's cognitive complexity limit. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 608c4fcb6..2f0f0049d 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -7225,16 +7225,12 @@ fn color_picker(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { use picker_layout as at; let lang = app.ui.language.clone(); let tr = |s: &str| crate::i18n::tr(&lang, s).to_string(); - if !d.fields.contains_key("old") { - let old = d.s("hex"); - d.fields.insert("old".into(), json!(old)); - } + let old = d.s("hex"); + d.fields.entry("old").or_insert_with(|| json!(old)); let comp = PickComp::from_key(&d.s("component")); let mut p = picked_of(d); let before = p; - if !d.fields.contains_key("rgb") { - d.fields.insert("rgb".into(), json!(p.rgb.map(|x| x * 255.0))); - } + d.fields.entry("rgb").or_insert_with(|| json!(p.rgb.map(|x| x * 255.0))); if !d.fields.contains_key("cmyk") { d.fields.insert( "cmyk".into(), From 54190bb88612ce19e6a245c63504e5367aa6c8af Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 21:44:29 +0100 Subject: [PATCH 0447/1349] Color Picker: the remembered colours seeded with map entries Keeps color_picker within clippy's cognitive complexity limit. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index d345f1658..e13340a25 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -7225,16 +7225,12 @@ fn color_picker(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { use picker_layout as at; let lang = app.ui.language.clone(); let tr = |s: &str| crate::i18n::tr(&lang, s).to_string(); - if !d.fields.contains_key("old") { - let old = d.s("hex"); - d.fields.insert("old".into(), json!(old)); - } + let old = d.s("hex"); + d.fields.entry("old").or_insert_with(|| json!(old)); let comp = PickComp::from_key(&d.s("component")); let mut p = picked_of(d); let before = p; - if !d.fields.contains_key("rgb") { - d.fields.insert("rgb".into(), json!(p.rgb.map(|x| x * 255.0))); - } + d.fields.entry("rgb").or_insert_with(|| json!(p.rgb.map(|x| x * 255.0))); if !d.fields.contains_key("cmyk") { d.fields.insert( "cmyk".into(), From 27684daabefec09489f51f323bd709f39727e8c8 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:02:59 +0100 Subject: [PATCH 0448/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 4 ++-- crates/ui-egui/src/dialogs/tests.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index e0e47e22c..302a1b069 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -3279,7 +3279,7 @@ const FORMAT_SECTIONS: &[(&str, &str)] = &[ fn info_icon(ui: &mut egui::Ui, tip: &str) { let (r, resp) = ui.allocate_exact_size(egui::vec2(16.0, 16.0), egui::Sense::hover()); crate::icons::paint(ui.painter(), r, "info", crate::theme::Tokens::get(ui.ctx()).icon); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, tip)); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, tip)); resp.on_hover_text(tip); } @@ -3348,7 +3348,7 @@ fn change_format_settings(app: &mut DesignApp, ctx: &egui::Context, d: &mut Dial let cf = CharFields { base: &base, sparse: true }; let popup_open = egui::Popup::is_any_open(ctx); let mut result = None; - let host = egui::Id::new("change_format_settings"); + let host = egui::Id::unique("change_format_settings"); crate::modal_drag::modal(ctx, host, host).backdrop_color(egui::Color32::TRANSPARENT).show(ctx, |ui| { let title_top = ui.cursor().top(); crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&lang, "Change Format Settings")).font(semibold(16.0))); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index ba5531870..f6f6f0e77 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3542,7 +3542,7 @@ fn find_change_gives_the_found_text_a_change_format() { } let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state( |ui, app: &mut DesignApp| { - let key = egui::Id::new("change_format_test_fonts"); + let key = egui::Id::unique("change_format_test_fonts"); if ui.data(|d| d.get_temp::(key)).is_none() { crate::theme::install_fonts(ui.ctx(), ""); ui.data_mut(|d| d.insert_temp(key, true)); From c43319e0a2425c761e7f9057989d538eedee934d Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:07:17 +0100 Subject: [PATCH 0449/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/tests.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 8dfe5c8c2..c80127706 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3604,10 +3604,7 @@ fn a_change_format_goes_with_change_all() { let mut d = Dialog::new("findChange", json!({"find": "cook"})); d.fields.insert(CHANGE_FORMAT.into(), json!({"charStyle": "eggs", "paraStyle": "Method", "chars": {"underline": true}})); let p = find_change_params(&d); - assert_eq!( - (p["charStyle"].clone(), p["paraStyle"].clone(), p["attrs"].clone()), - (json!("eggs"), json!("Method"), json!({"underline": true})) - ); + assert_eq!((p["charStyle"].clone(), p["paraStyle"].clone(), p["attrs"].clone()), (json!("eggs"), json!("Method"), json!({"underline": true}))); assert_eq!(format_summary("en", d.fields.get(CHANGE_FORMAT)), "Character Style: eggs + Paragraph Style: Method + Underline: on"); assert!(find_change_params(&Dialog::new("findChange", json!({"find": "cook"}))).get("attrs").is_none()); // A Find Format goes with every search. From 08bab7a4776d85750e709da6fa7035b8015c52e9 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:10:30 +0100 Subject: [PATCH 0450/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/find/tests.rs | 40 ++++++++++++++--------------- crates/ui-egui/src/dialogs/tests.rs | 23 ++++++++--------- 2 files changed, 30 insertions(+), 33 deletions(-) diff --git a/crates/engine/src/cmd/find/tests.rs b/crates/engine/src/cmd/find/tests.rs index a60b40ebf..ae8742702 100644 --- a/crates/engine/src/cmd/find/tests.rs +++ b/crates/engine/src/cmd/find/tests.rs @@ -621,26 +621,26 @@ fn document_scope_searches_and_changes_table_cells() { assert_eq!(s.execute("find.find", &json!({"find": "13.00", "scope": "document"})).unwrap().as_array().unwrap().len(), 2); } - /// Change (`found`) on text Find Next found in a table cell changes it there, leaves the - /// same text in the story alone, and Find Next goes on after it. - #[test] - fn change_changes_the_text_find_next_found_in_a_cell() { - let (mut s, sid) = scope_session("red here"); - scope_select(&mut s, sid, 0, 0); - let table = s.execute("table.insert", &json!({"rows": 1, "cols": 2})).unwrap()["table"].as_u64().unwrap(); - s.execute("table.setCell", &json!({"row": 0, "col": 1, "text": "red"})).unwrap(); - let p = json!({"find": "red", "change": "blue", "scope": "document"}); - let hit = s.execute("find.next", &p).unwrap(); - assert_eq!(hit["cell"], json!({"table": table, "row": 0, "col": 1}), "{hit}"); - let mut change = p.clone(); - change["found"] = json!(true); - assert_eq!(s.execute("find.change", &change).unwrap()["count"], 1); - let t = s.execute("table.get", &json!({"table": table})).unwrap(); - assert_eq!(t["cells"][1]["text"], "blue"); - assert!(s.doc().unwrap().doc.story(sid).unwrap().text.contains("red here"), "the story's red stays"); - let next = s.execute("find.next", &p).unwrap(); - assert!(next.get("cell").is_none() && next.get("start").is_some(), "on to the story: {next}"); - } +/// Change (`found`) on text Find Next found in a table cell changes it there, leaves the +/// same text in the story alone, and Find Next goes on after it. +#[test] +fn change_changes_the_text_find_next_found_in_a_cell() { + let (mut s, sid) = scope_session("red here"); + scope_select(&mut s, sid, 0, 0); + let table = s.execute("table.insert", &json!({"rows": 1, "cols": 2})).unwrap()["table"].as_u64().unwrap(); + s.execute("table.setCell", &json!({"row": 0, "col": 1, "text": "red"})).unwrap(); + let p = json!({"find": "red", "change": "blue", "scope": "document"}); + let hit = s.execute("find.next", &p).unwrap(); + assert_eq!(hit["cell"], json!({"table": table, "row": 0, "col": 1}), "{hit}"); + let mut change = p.clone(); + change["found"] = json!(true); + assert_eq!(s.execute("find.change", &change).unwrap()["count"], 1); + let t = s.execute("table.get", &json!({"table": table})).unwrap(); + assert_eq!(t["cells"][1]["text"], "blue"); + assert!(s.doc().unwrap().doc.story(sid).unwrap().text.contains("red here"), "the story's red stays"); + let next = s.execute("find.next", &p).unwrap(); + assert!(next.get("cell").is_none() && next.get("start").is_some(), "on to the story: {next}"); +} fn child_scope_session(note: bool, child: &str) -> (Session, designcraft_doc::StoryId, designcraft_doc::TextSel) { let (mut s, sid) = scope_session("red"); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 9d392ed90..153a83486 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1647,14 +1647,14 @@ fn dialog_frame(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, ev labels } - /// What Find/Change's Search list shows for a scope. - fn scope_label(scope: &str) -> &'static str { - match scope { - "story" => "Story", - "selection" => "Selection", - _ => "Document", - } +/// What Find/Change's Search list shows for a scope. +fn scope_label(scope: &str) -> &'static str { + match scope { + "story" => "Story", + "selection" => "Selection", + _ => "Document", } +} fn visible_label(labels: &[(String, egui::Rect, egui::Rect)], screen: egui::Rect, expected: &str) -> egui::Rect { let (_, rect, clip) = labels.iter().find(|(text, _, _)| text.trim() == expected).unwrap_or_else(|| panic!("{expected} is painted")); @@ -1739,8 +1739,8 @@ fn scope_dialog_with_tool(text: &str, end: usize, tool: Option<&str>) -> (Design for _ in 0..3 { dialog_frame(&mut app, &ctx, screen, vec![]); } - scope_click(&mut app, &ctx, screen, "Document"); - scope_click(&mut app, &ctx, screen, "Selection"); + scope_click(&mut app, &ctx, screen, "Document"); + scope_click(&mut app, &ctx, screen, "Selection"); assert_eq!(app.ui.dialog.as_ref().unwrap().s("scope"), "selection"); (app, ctx, screen, sid) } @@ -3613,10 +3613,7 @@ fn a_change_format_goes_with_change_all() { let mut d = Dialog::new("findChange", json!({"find": "cook"})); d.fields.insert(CHANGE_FORMAT.into(), json!({"charStyle": "eggs", "paraStyle": "Method", "chars": {"underline": true}})); let p = find_change_params(&d); - assert_eq!( - (p["charStyle"].clone(), p["paraStyle"].clone(), p["attrs"].clone()), - (json!("eggs"), json!("Method"), json!({"underline": true})) - ); + assert_eq!((p["charStyle"].clone(), p["paraStyle"].clone(), p["attrs"].clone()), (json!("eggs"), json!("Method"), json!({"underline": true}))); assert_eq!(format_summary("en", d.fields.get(CHANGE_FORMAT)), "Character Style: eggs + Paragraph Style: Method + Underline: on"); assert!(find_change_params(&Dialog::new("findChange", json!({"find": "cook"}))).get("attrs").is_none()); // A Find Format goes with every search. From 776088c0d559b7fd4edc75aea078cd2e693a4d38 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:10:49 +0100 Subject: [PATCH 0451/1349] Paragraph style apply: the story's paragraph ranges, as main lists them Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/style/paragraph.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/style/paragraph.rs b/crates/engine/src/cmd/style/paragraph.rs index bccb8f6c2..bb70a8cfc 100644 --- a/crates/engine/src/cmd/style/paragraph.rs +++ b/crates/engine/src/cmd/style/paragraph.rs @@ -328,7 +328,7 @@ fn apply_para_in_story( f.chars.retain_differences(style_chars); } }); - for (pi, range) in st.paras_touching(r.clone()).into_iter().filter(|(pi, _)| (first..=last).contains(pi)) { + for (pi, range) in st.para_ranges().into_iter().enumerate().filter(|(pi, _)| (first..=last).contains(pi)) { let Some(pf) = st.paras.get(pi) else { continue }; let (_, base) = styles.resolve_para(pf); let end = range.end.saturating_add(1).min(st.len()); From d42333fb9d82c3757526cde9e3204484a1c0e7bd Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:10:58 +0100 Subject: [PATCH 0452/1349] Story: para_at's doc comment back on para_at Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/story.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/doc/src/story.rs b/crates/doc/src/story.rs index de753891c..fb04f9c9f 100644 --- a/crates/doc/src/story.rs +++ b/crates/doc/src/story.rs @@ -286,7 +286,6 @@ impl Story { v } - /// Index of the paragraph containing byte `pos`. /// The paragraphs `r` touches (at least the one at `r.start`), as (index, byte range without /// its return), found from `r` itself rather than by listing every paragraph of the story. pub fn paras_touching(&self, r: std::ops::Range) -> Vec<(usize, std::ops::Range)> { @@ -305,6 +304,7 @@ impl Story { } } + /// Index of the paragraph containing byte `pos`. pub fn para_at(&self, pos: usize) -> usize { self.text[..floor_char_boundary(&self.text, pos)].bytes().filter(|b| *b == b'\n').count() } From 573566fe658617a8e7bab0f45760272e49880ec3 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:12:48 +0100 Subject: [PATCH 0453/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/tests.rs | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 37452dd27..3f9bbfc10 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3538,11 +3538,8 @@ fn the_rule_colour_menu_offers_text_color() { events.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); events.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); } - let input = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 600.0))), - events, - ..Default::default() - }; + let input = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 600.0))), events, ..Default::default() }; let mut out = ctx.run_ui(input, |ui| { picked = swatch_menu_with(ui, &doc, "m", "[Black]", 130.0, text); }); @@ -3599,8 +3596,7 @@ fn a_rules_default_gap_tint_shows_100() { ) .unwrap(); let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); - h.state_mut().app.ui.dialog = - Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "rules", "rule": "ruleBelow"}))); + h.state_mut().app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "rules", "rule": "ruleBelow"}))); h.run_steps(4); let label = h.get_by_label("Gap Tint:").rect(); let field = h From bca78235a54fb19ea6e7ef4f9e6532f7cfa16f40 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:13:13 +0100 Subject: [PATCH 0454/1349] Find/Change: the paragraph ranges as main lists them; the branch's find tests beside main's scope helpers Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/find.rs | 186 ----------------------- crates/engine/src/cmd/find/tests.rs | 186 +++++++++++++++++++++++ crates/engine/src/cmd/style/paragraph.rs | 2 +- 3 files changed, 187 insertions(+), 187 deletions(-) diff --git a/crates/engine/src/cmd/find.rs b/crates/engine/src/cmd/find.rs index 0586fee05..ca55b30ad 100644 --- a/crates/engine/src/cmd/find.rs +++ b/crates/engine/src/cmd/find.rs @@ -814,192 +814,6 @@ mod object_find_tests { use crate::Session; - #[test] - fn change_format_styles_the_found_text_and_keeps_it() { - // The course's chapter 22: every lowercase "eggs" gets the character style "eggs", with - // Change to empty, so the words stay. - let mut s = Session::new(); - s.execute("file.new", &json!({})).unwrap(); - let text = "Poached Eggs\nBreak eggs; cook until eggs are set."; - let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": text})).unwrap(); - let sid = designcraft_doc::StoryId(r["story"].as_u64().unwrap()); - s.execute("style.character.create", &json!({"name": "eggs", "chars": {"fontStyle": "Bold", "fill": "C=15 M=100 Y=100 K=0"}})).unwrap(); - s.execute("style.paragraph.create", &json!({"name": "Method"})).unwrap(); - let undo = s.doc().unwrap().history.undo.len(); - let r = s.execute("find.change", &json!({"find": "eggs", "change": "", "caseSensitive": true, "charStyle": "eggs"})).unwrap(); - assert_eq!(r["count"], 2); - assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); - let style_at = |s: &Session, at: usize| s.doc().unwrap().doc.story(sid).unwrap().format_after(at).style.clone(); - let story = s.doc().unwrap().doc.story(sid).unwrap().clone(); - assert_eq!(story.text, text, "the words stay"); - for at in [19, 36] { - assert_eq!(&story.text[at..at + 4], "eggs"); - assert_eq!(style_at(&s, at), "eggs"); - } - assert_eq!(style_at(&s, 8), designcraft_doc::NO_CHAR_STYLE, "case sensitive: not \"Eggs\""); - assert_eq!(style_at(&s, 25), designcraft_doc::NO_CHAR_STYLE, "only the found text"); - // A paragraph style goes to the found text's paragraphs, with attributes over the text. - s.execute("find.change", &json!({"find": "cook", "change": "", "paraStyle": "Method", "attrs": {"underline": true}})).unwrap(); - let story = s.doc().unwrap().doc.story(sid).unwrap().clone(); - assert_eq!((story.paras[0].style.as_str(), story.paras[1].style.as_str()), (designcraft_doc::BASIC_PARAGRAPH, "Method")); - assert_eq!(story.format_after(25).over.underline, Some(true)); - assert_eq!(story.format_after(19).style, "eggs", "the other text keeps its character style"); - // Change to and a Change Format: the new text is formatted. - s.execute("find.change", &json!({"find": "set", "change": "firm", "charStyle": "eggs"})).unwrap(); - assert_eq!(style_at(&s, s.doc().unwrap().doc.story(sid).unwrap().text.find("firm").unwrap()), "eggs"); - // No such style: refused, nothing changed. - let before = s.doc().unwrap().doc.clone(); - assert!(s.execute("find.change", &json!({"find": "eggs", "change": "", "charStyle": "Nope"})).is_err()); - assert!(s.execute("find.change", &json!({"find": "eggs", "change": "", "paraStyle": "Nope"})).is_err()); - assert_eq!(s.doc().unwrap().doc, before); - // With no Change Format, an empty Change to still deletes the found text. - s.execute("find.change", &json!({"find": "Break ", "change": ""})).unwrap(); - assert!(!s.doc().unwrap().doc.story(sid).unwrap().text.contains("Break")); - } - - #[test] - fn a_find_format_finds_only_text_with_it() { - let mut s = Session::new(); - s.execute("file.new", &json!({})).unwrap(); - let r = s - .execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "Break eggs; cook eggs.\nEggs and eggs"})) - .unwrap(); - let sid = r["story"].as_u64().unwrap(); - s.execute("style.character.create", &json!({"name": "eggs", "chars": {"fontStyle": "Bold"}})).unwrap(); - s.execute("style.paragraph.create", &json!({"name": "Method"})).unwrap(); - for (a, b) in [(6, 10), (12, 16)] { - s.execute("text.select", &json!({"story": sid, "anchor": a, "focus": b})).unwrap(); - s.execute("style.character.apply", &json!({"name": "eggs"})).unwrap(); - } - s.execute("text.select", &json!({"story": sid, "anchor": 25, "focus": 25})).unwrap(); - s.execute("style.paragraph.apply", &json!({"name": "Method"})).unwrap(); - let found = |s: &mut Session, p: serde_json::Value| -> Vec<(u64, u64)> { - let m = s.execute("find.find", &p).unwrap(); - m.as_array().unwrap().iter().map(|m| (m["start"].as_u64().unwrap(), m["end"].as_u64().unwrap())).collect() - }; - // "eggs" where it has the character style: the first only. - assert_eq!(found(&mut s, json!({"find": "eggs", "findFormat": {"charStyle": "eggs"}})), [(6, 10)]); - // Nothing in Find what: each stretch of text in the style. - assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"charStyle": "eggs"}})), [(6, 10), (12, 16)]); - // A paragraph style, and resolved attributes. - assert_eq!(found(&mut s, json!({"find": "eggs", "findFormat": {"paraStyle": "Method"}})), [(23, 27), (32, 36)]); - assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"chars": {"fontStyle": "Bold"}}})), [(6, 10), (12, 16)]); - assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"chars": {"size": 12}}})), [(0, 22), (23, 36)], "each paragraph apart"); - // Find Next walks the stretches. - s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap(); - let next = json!({"find": "", "findFormat": {"charStyle": "eggs"}}); - assert_eq!(s.execute("find.next", &next).unwrap()["start"], 6); - assert_eq!(s.execute("find.next", &next).unwrap()["start"], 12); - // Equivalent spellings the attributes accept find the same text: a snake_case key, and a - // nested number written as an integer (14 pt leading on the second paragraph). - s.execute("text.select", &json!({"story": sid, "anchor": 23, "focus": 36})).unwrap(); - s.execute("type.char", &json!({"leading": {"kind": "points", "value": 14.0}})).unwrap(); - for (a, b) in [ - (json!({"fontStyle": "Bold"}), json!({"font_style": "Bold"})), - (json!({"leading": {"kind": "points", "value": 14.0}}), json!({"leading": {"kind": "points", "value": 14}})), - ] { - let (a, b) = (json!({"find": "", "findFormat": {"chars": a}}), json!({"find": "", "findFormat": {"chars": b}})); - let all = found(&mut s, a.clone()); - assert!(!all.is_empty(), "{a}"); - assert_eq!(found(&mut s, b.clone()), all, "{b}"); - for p in [&a, &b] { - s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap(); - assert_eq!(s.execute("find.next", p).unwrap()["start"].as_u64(), Some(all[0].0), "{p}"); - } - } - // A null attribute asks for nothing. - assert_eq!(found(&mut s, json!({"find": "eggs", "findFormat": {"charStyle": "eggs", "chars": {"size": null}}})), [(6, 10)]); - // With a Change Format: the text in the style goes back to [None], underlined. - let r = s - .execute( - "find.change", - &json!({"find": "", "change": "", "findFormat": {"charStyle": "eggs", "chars": {"font_style": "Bold"}}, "charStyle": "[None]", "attrs": {"underline": true}}), - ) - .unwrap(); - assert_eq!(r["count"], 2, "a snake_case attribute changes the same text"); - assert!(found(&mut s, json!({"find": "", "findFormat": {"charStyle": "eggs"}})).is_empty()); - assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"chars": {"underline": true}}})), [(6, 10), (12, 16)]); - // Unknown styles and attributes are refused; an empty search needs a Find Format. - assert!(s.execute("find.find", &json!({"find": "", "findFormat": {"charStyle": "Nope"}})).is_err()); - assert!(s.execute("find.next", &json!({"find": "eggs", "findFormat": {"paraStyle": "Nope"}})).is_err()); - assert!(s.execute("find.find", &json!({"find": "eggs", "findFormat": {"chars": {"bogus": 1}}})).is_err()); - // Malformed fields are refused, not searched without. - for f in [json!({"chars": [1]}), json!({"chars": 12}), json!({"charStyle": 3}), json!({"paraStyle": ["Body"]})] { - assert!(s.execute("find.find", &json!({"find": "eggs", "findFormat": f})).is_err(), "{f}"); - } - assert!(s.execute("find.find", &json!({"find": ""})).is_err()); - } - - /// Change and Change/Find: only the text Find Next found changes; it stays selected and the - /// search goes on after it in its domain (here the original selection). A selection that - /// isn't a match changes nothing and makes no undo step. - #[test] - fn change_changes_the_found_text_and_the_search_goes_on() { - let (mut s, sid) = scope_session("red red | red"); - scope_select(&mut s, sid, 0, 7); - let p = json!({"find": "red", "change": "blue", "scope": "selection"}); - let mut change = p.clone(); - change["found"] = json!(true); - scope_hit(&mut s, &p, sid, 0, 3); - assert_eq!(s.execute("find.change", &change).unwrap()["count"], 1); - let text = |s: &Session| s.doc().unwrap().doc.story(sid).unwrap().text.clone(); - assert_eq!(text(&s), "blue red | red"); - assert_eq!(s.doc().unwrap().selection.text.unwrap().range(), 0..4, "the changed text stays selected"); - scope_hit(&mut s, &p, sid, 5, 8); - s.execute("find.change", &change).unwrap(); - assert_eq!(text(&s), "blue blue | red"); - assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null, "the last red is outside the selection searched"); - // Not a match: nothing changes, no undo step. - scope_select(&mut s, sid, 0, 4); - let history = s.doc().unwrap().history.undo.len(); - assert_eq!(s.execute("find.change", &json!({"find": "red", "change": "blue", "found": true})).unwrap()["count"], 0); - assert_eq!(s.doc().unwrap().history.undo.len(), history); - // A Change Format with nothing in Change to formats the found text only. - scope_select(&mut s, sid, 0, 0); - let fmt = json!({"find": "red", "change": "", "attrs": {"underline": true}}); - let hit = s.execute("find.next", &fmt).unwrap(); - assert_eq!(hit["start"], 12); - let mut found = fmt.clone(); - found["found"] = json!(true); - s.execute("find.change", &found).unwrap(); - assert_eq!(text(&s), "blue blue | red"); - assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().format_after(12).over.underline, Some(true)); - assert_eq!(s.doc().unwrap().selection.text.unwrap().range(), 12..15); - } - - /// Change accepts what Find Next selected even when Change All wouldn't match there: the - /// rest of a Find Format stretch from a caret inside it, and an overlapping match. - #[test] - fn change_takes_any_selection_find_next_made() { - // A caret inside a bold stretch: Find Next with only a Find Format selects the rest of it. - let (mut s, sid) = scope_session("plain bold text"); - s.execute("style.character.create", &json!({"name": "Strong", "chars": {"fontStyle": "Bold"}})).unwrap(); - scope_select(&mut s, sid, 6, 10); - s.execute("style.character.apply", &json!({"name": "Strong"})).unwrap(); - scope_select(&mut s, sid, 8, 8); - let p = json!({"find": "", "change": "", "findFormat": {"charStyle": "Strong"}, "attrs": {"underline": true}, "scope": "story"}); - let hit = s.execute("find.next", &p).unwrap(); - assert_eq!((hit["start"].as_u64(), hit["end"].as_u64()), (Some(8), Some(10))); - let mut change = p.clone(); - change["found"] = json!(true); - assert_eq!(s.execute("find.change", &change).unwrap()["count"], 1); - let st = s.doc().unwrap().doc.story(sid).unwrap().clone(); - assert_eq!((st.format_after(7).over.underline, st.format_after(8).over.underline), (None, Some(true)), "only the selected rest"); - // "aa" in "aaa" from the second a: Find Next selects 1..3, which Change All never finds. - for grep in [false, true] { - let (mut s, sid) = scope_session("aaa"); - scope_select(&mut s, sid, 1, 1); - let (find, change) = if grep { ("(a)a", "<$1>") } else { ("aa", "b") }; - let p = json!({"find": find, "change": change, "grep": grep, "scope": "story"}); - let hit = s.execute("find.next", &p).unwrap(); - assert_eq!((hit["start"].as_u64(), hit["end"].as_u64()), (Some(1), Some(3))); - let mut found = p.clone(); - found["found"] = json!(true); - assert_eq!(s.execute("find.change", &found).unwrap()["count"], 1, "grep: {grep}"); - assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, if grep { "a" } else { "ab" }); - } - } - #[test] fn find_and_change_objects_by_attributes() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/find/tests.rs b/crates/engine/src/cmd/find/tests.rs index ae8742702..8a679269e 100644 --- a/crates/engine/src/cmd/find/tests.rs +++ b/crates/engine/src/cmd/find/tests.rs @@ -768,3 +768,189 @@ fn find_scope_revert_releases_context_with_same_document_uid() { assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "red red | red"); assert!(s.execute("find.find", &p).is_err(), "revert's empty selection cannot inherit a previous range"); } + +#[test] +fn change_format_styles_the_found_text_and_keeps_it() { + // The course's chapter 22: every lowercase "eggs" gets the character style "eggs", with + // Change to empty, so the words stay. + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let text = "Poached Eggs\nBreak eggs; cook until eggs are set."; + let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": text})).unwrap(); + let sid = designcraft_doc::StoryId(r["story"].as_u64().unwrap()); + s.execute("style.character.create", &json!({"name": "eggs", "chars": {"fontStyle": "Bold", "fill": "C=15 M=100 Y=100 K=0"}})).unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Method"})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute("find.change", &json!({"find": "eggs", "change": "", "caseSensitive": true, "charStyle": "eggs"})).unwrap(); + assert_eq!(r["count"], 2); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + let style_at = |s: &Session, at: usize| s.doc().unwrap().doc.story(sid).unwrap().format_after(at).style.clone(); + let story = s.doc().unwrap().doc.story(sid).unwrap().clone(); + assert_eq!(story.text, text, "the words stay"); + for at in [19, 36] { + assert_eq!(&story.text[at..at + 4], "eggs"); + assert_eq!(style_at(&s, at), "eggs"); + } + assert_eq!(style_at(&s, 8), designcraft_doc::NO_CHAR_STYLE, "case sensitive: not \"Eggs\""); + assert_eq!(style_at(&s, 25), designcraft_doc::NO_CHAR_STYLE, "only the found text"); + // A paragraph style goes to the found text's paragraphs, with attributes over the text. + s.execute("find.change", &json!({"find": "cook", "change": "", "paraStyle": "Method", "attrs": {"underline": true}})).unwrap(); + let story = s.doc().unwrap().doc.story(sid).unwrap().clone(); + assert_eq!((story.paras[0].style.as_str(), story.paras[1].style.as_str()), (designcraft_doc::BASIC_PARAGRAPH, "Method")); + assert_eq!(story.format_after(25).over.underline, Some(true)); + assert_eq!(story.format_after(19).style, "eggs", "the other text keeps its character style"); + // Change to and a Change Format: the new text is formatted. + s.execute("find.change", &json!({"find": "set", "change": "firm", "charStyle": "eggs"})).unwrap(); + assert_eq!(style_at(&s, s.doc().unwrap().doc.story(sid).unwrap().text.find("firm").unwrap()), "eggs"); + // No such style: refused, nothing changed. + let before = s.doc().unwrap().doc.clone(); + assert!(s.execute("find.change", &json!({"find": "eggs", "change": "", "charStyle": "Nope"})).is_err()); + assert!(s.execute("find.change", &json!({"find": "eggs", "change": "", "paraStyle": "Nope"})).is_err()); + assert_eq!(s.doc().unwrap().doc, before); + // With no Change Format, an empty Change to still deletes the found text. + s.execute("find.change", &json!({"find": "Break ", "change": ""})).unwrap(); + assert!(!s.doc().unwrap().doc.story(sid).unwrap().text.contains("Break")); +} + +#[test] +fn a_find_format_finds_only_text_with_it() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s + .execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "Break eggs; cook eggs.\nEggs and eggs"})) + .unwrap(); + let sid = r["story"].as_u64().unwrap(); + s.execute("style.character.create", &json!({"name": "eggs", "chars": {"fontStyle": "Bold"}})).unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Method"})).unwrap(); + for (a, b) in [(6, 10), (12, 16)] { + s.execute("text.select", &json!({"story": sid, "anchor": a, "focus": b})).unwrap(); + s.execute("style.character.apply", &json!({"name": "eggs"})).unwrap(); + } + s.execute("text.select", &json!({"story": sid, "anchor": 25, "focus": 25})).unwrap(); + s.execute("style.paragraph.apply", &json!({"name": "Method"})).unwrap(); + let found = |s: &mut Session, p: serde_json::Value| -> Vec<(u64, u64)> { + let m = s.execute("find.find", &p).unwrap(); + m.as_array().unwrap().iter().map(|m| (m["start"].as_u64().unwrap(), m["end"].as_u64().unwrap())).collect() + }; + // "eggs" where it has the character style: the first only. + assert_eq!(found(&mut s, json!({"find": "eggs", "findFormat": {"charStyle": "eggs"}})), [(6, 10)]); + // Nothing in Find what: each stretch of text in the style. + assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"charStyle": "eggs"}})), [(6, 10), (12, 16)]); + // A paragraph style, and resolved attributes. + assert_eq!(found(&mut s, json!({"find": "eggs", "findFormat": {"paraStyle": "Method"}})), [(23, 27), (32, 36)]); + assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"chars": {"fontStyle": "Bold"}}})), [(6, 10), (12, 16)]); + assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"chars": {"size": 12}}})), [(0, 22), (23, 36)], "each paragraph apart"); + // Find Next walks the stretches. + s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap(); + let next = json!({"find": "", "findFormat": {"charStyle": "eggs"}}); + assert_eq!(s.execute("find.next", &next).unwrap()["start"], 6); + assert_eq!(s.execute("find.next", &next).unwrap()["start"], 12); + // Equivalent spellings the attributes accept find the same text: a snake_case key, and a + // nested number written as an integer (14 pt leading on the second paragraph). + s.execute("text.select", &json!({"story": sid, "anchor": 23, "focus": 36})).unwrap(); + s.execute("type.char", &json!({"leading": {"kind": "points", "value": 14.0}})).unwrap(); + for (a, b) in [ + (json!({"fontStyle": "Bold"}), json!({"font_style": "Bold"})), + (json!({"leading": {"kind": "points", "value": 14.0}}), json!({"leading": {"kind": "points", "value": 14}})), + ] { + let (a, b) = (json!({"find": "", "findFormat": {"chars": a}}), json!({"find": "", "findFormat": {"chars": b}})); + let all = found(&mut s, a.clone()); + assert!(!all.is_empty(), "{a}"); + assert_eq!(found(&mut s, b.clone()), all, "{b}"); + for p in [&a, &b] { + s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap(); + assert_eq!(s.execute("find.next", p).unwrap()["start"].as_u64(), Some(all[0].0), "{p}"); + } + } + // A null attribute asks for nothing. + assert_eq!(found(&mut s, json!({"find": "eggs", "findFormat": {"charStyle": "eggs", "chars": {"size": null}}})), [(6, 10)]); + // With a Change Format: the text in the style goes back to [None], underlined. + let r = s + .execute( + "find.change", + &json!({"find": "", "change": "", "findFormat": {"charStyle": "eggs", "chars": {"font_style": "Bold"}}, "charStyle": "[None]", "attrs": {"underline": true}}), + ) + .unwrap(); + assert_eq!(r["count"], 2, "a snake_case attribute changes the same text"); + assert!(found(&mut s, json!({"find": "", "findFormat": {"charStyle": "eggs"}})).is_empty()); + assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"chars": {"underline": true}}})), [(6, 10), (12, 16)]); + // Unknown styles and attributes are refused; an empty search needs a Find Format. + assert!(s.execute("find.find", &json!({"find": "", "findFormat": {"charStyle": "Nope"}})).is_err()); + assert!(s.execute("find.next", &json!({"find": "eggs", "findFormat": {"paraStyle": "Nope"}})).is_err()); + assert!(s.execute("find.find", &json!({"find": "eggs", "findFormat": {"chars": {"bogus": 1}}})).is_err()); + // Malformed fields are refused, not searched without. + for f in [json!({"chars": [1]}), json!({"chars": 12}), json!({"charStyle": 3}), json!({"paraStyle": ["Body"]})] { + assert!(s.execute("find.find", &json!({"find": "eggs", "findFormat": f})).is_err(), "{f}"); + } + assert!(s.execute("find.find", &json!({"find": ""})).is_err()); +} + +/// Change and Change/Find: only the text Find Next found changes; it stays selected and the +/// search goes on after it in its domain (here the original selection). A selection that +/// isn't a match changes nothing and makes no undo step. +#[test] +fn change_changes_the_found_text_and_the_search_goes_on() { + let (mut s, sid) = scope_session("red red | red"); + scope_select(&mut s, sid, 0, 7); + let p = json!({"find": "red", "change": "blue", "scope": "selection"}); + let mut change = p.clone(); + change["found"] = json!(true); + scope_hit(&mut s, &p, sid, 0, 3); + assert_eq!(s.execute("find.change", &change).unwrap()["count"], 1); + let text = |s: &Session| s.doc().unwrap().doc.story(sid).unwrap().text.clone(); + assert_eq!(text(&s), "blue red | red"); + assert_eq!(s.doc().unwrap().selection.text.unwrap().range(), 0..4, "the changed text stays selected"); + scope_hit(&mut s, &p, sid, 5, 8); + s.execute("find.change", &change).unwrap(); + assert_eq!(text(&s), "blue blue | red"); + assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null, "the last red is outside the selection searched"); + // Not a match: nothing changes, no undo step. + scope_select(&mut s, sid, 0, 4); + let history = s.doc().unwrap().history.undo.len(); + assert_eq!(s.execute("find.change", &json!({"find": "red", "change": "blue", "found": true})).unwrap()["count"], 0); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + // A Change Format with nothing in Change to formats the found text only. + scope_select(&mut s, sid, 0, 0); + let fmt = json!({"find": "red", "change": "", "attrs": {"underline": true}}); + let hit = s.execute("find.next", &fmt).unwrap(); + assert_eq!(hit["start"], 12); + let mut found = fmt.clone(); + found["found"] = json!(true); + s.execute("find.change", &found).unwrap(); + assert_eq!(text(&s), "blue blue | red"); + assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().format_after(12).over.underline, Some(true)); + assert_eq!(s.doc().unwrap().selection.text.unwrap().range(), 12..15); +} + +/// Change accepts what Find Next selected even when Change All wouldn't match there: the +/// rest of a Find Format stretch from a caret inside it, and an overlapping match. +#[test] +fn change_takes_any_selection_find_next_made() { + // A caret inside a bold stretch: Find Next with only a Find Format selects the rest of it. + let (mut s, sid) = scope_session("plain bold text"); + s.execute("style.character.create", &json!({"name": "Strong", "chars": {"fontStyle": "Bold"}})).unwrap(); + scope_select(&mut s, sid, 6, 10); + s.execute("style.character.apply", &json!({"name": "Strong"})).unwrap(); + scope_select(&mut s, sid, 8, 8); + let p = json!({"find": "", "change": "", "findFormat": {"charStyle": "Strong"}, "attrs": {"underline": true}, "scope": "story"}); + let hit = s.execute("find.next", &p).unwrap(); + assert_eq!((hit["start"].as_u64(), hit["end"].as_u64()), (Some(8), Some(10))); + let mut change = p.clone(); + change["found"] = json!(true); + assert_eq!(s.execute("find.change", &change).unwrap()["count"], 1); + let st = s.doc().unwrap().doc.story(sid).unwrap().clone(); + assert_eq!((st.format_after(7).over.underline, st.format_after(8).over.underline), (None, Some(true)), "only the selected rest"); + // "aa" in "aaa" from the second a: Find Next selects 1..3, which Change All never finds. + for grep in [false, true] { + let (mut s, sid) = scope_session("aaa"); + scope_select(&mut s, sid, 1, 1); + let (find, change) = if grep { ("(a)a", "<$1>") } else { ("aa", "b") }; + let p = json!({"find": find, "change": change, "grep": grep, "scope": "story"}); + let hit = s.execute("find.next", &p).unwrap(); + assert_eq!((hit["start"].as_u64(), hit["end"].as_u64()), (Some(1), Some(3))); + let mut found = p.clone(); + found["found"] = json!(true); + assert_eq!(s.execute("find.change", &found).unwrap()["count"], 1, "grep: {grep}"); + assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, if grep { "a" } else { "ab" }); + } +} diff --git a/crates/engine/src/cmd/style/paragraph.rs b/crates/engine/src/cmd/style/paragraph.rs index bccb8f6c2..bb70a8cfc 100644 --- a/crates/engine/src/cmd/style/paragraph.rs +++ b/crates/engine/src/cmd/style/paragraph.rs @@ -328,7 +328,7 @@ fn apply_para_in_story( f.chars.retain_differences(style_chars); } }); - for (pi, range) in st.paras_touching(r.clone()).into_iter().filter(|(pi, _)| (first..=last).contains(pi)) { + for (pi, range) in st.para_ranges().into_iter().enumerate().filter(|(pi, _)| (first..=last).contains(pi)) { let Some(pf) = st.paras.get(pi) else { continue }; let (_, base) = styles.resolve_para(pf); let end = range.end.saturating_add(1).min(st.len()); From d6210b40ee8916efd9b9d9babe5c3af7cc80285f Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:13:20 +0100 Subject: [PATCH 0455/1349] Find/Change: the branch's find tests beside main's scope helpers (find/tests.rs) Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/find.rs | 116 ---------------------------- crates/engine/src/cmd/find/tests.rs | 116 ++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+), 116 deletions(-) diff --git a/crates/engine/src/cmd/find.rs b/crates/engine/src/cmd/find.rs index af05e45af..849d54232 100644 --- a/crates/engine/src/cmd/find.rs +++ b/crates/engine/src/cmd/find.rs @@ -709,122 +709,6 @@ mod object_find_tests { use crate::Session; - #[test] - fn change_format_styles_the_found_text_and_keeps_it() { - // The course's chapter 22: every lowercase "eggs" gets the character style "eggs", with - // Change to empty, so the words stay. - let mut s = Session::new(); - s.execute("file.new", &json!({})).unwrap(); - let text = "Poached Eggs\nBreak eggs; cook until eggs are set."; - let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": text})).unwrap(); - let sid = designcraft_doc::StoryId(r["story"].as_u64().unwrap()); - s.execute("style.character.create", &json!({"name": "eggs", "chars": {"fontStyle": "Bold", "fill": "C=15 M=100 Y=100 K=0"}})).unwrap(); - s.execute("style.paragraph.create", &json!({"name": "Method"})).unwrap(); - let undo = s.doc().unwrap().history.undo.len(); - let r = s.execute("find.change", &json!({"find": "eggs", "change": "", "caseSensitive": true, "charStyle": "eggs"})).unwrap(); - assert_eq!(r["count"], 2); - assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); - let style_at = |s: &Session, at: usize| s.doc().unwrap().doc.story(sid).unwrap().format_after(at).style.clone(); - let story = s.doc().unwrap().doc.story(sid).unwrap().clone(); - assert_eq!(story.text, text, "the words stay"); - for at in [19, 36] { - assert_eq!(&story.text[at..at + 4], "eggs"); - assert_eq!(style_at(&s, at), "eggs"); - } - assert_eq!(style_at(&s, 8), designcraft_doc::NO_CHAR_STYLE, "case sensitive: not \"Eggs\""); - assert_eq!(style_at(&s, 25), designcraft_doc::NO_CHAR_STYLE, "only the found text"); - // A paragraph style goes to the found text's paragraphs, with attributes over the text. - s.execute("find.change", &json!({"find": "cook", "change": "", "paraStyle": "Method", "attrs": {"underline": true}})).unwrap(); - let story = s.doc().unwrap().doc.story(sid).unwrap().clone(); - assert_eq!((story.paras[0].style.as_str(), story.paras[1].style.as_str()), (designcraft_doc::BASIC_PARAGRAPH, "Method")); - assert_eq!(story.format_after(25).over.underline, Some(true)); - assert_eq!(story.format_after(19).style, "eggs", "the other text keeps its character style"); - // Change to and a Change Format: the new text is formatted. - s.execute("find.change", &json!({"find": "set", "change": "firm", "charStyle": "eggs"})).unwrap(); - assert_eq!(style_at(&s, s.doc().unwrap().doc.story(sid).unwrap().text.find("firm").unwrap()), "eggs"); - // No such style: refused, nothing changed. - let before = s.doc().unwrap().doc.clone(); - assert!(s.execute("find.change", &json!({"find": "eggs", "change": "", "charStyle": "Nope"})).is_err()); - assert!(s.execute("find.change", &json!({"find": "eggs", "change": "", "paraStyle": "Nope"})).is_err()); - assert_eq!(s.doc().unwrap().doc, before); - // With no Change Format, an empty Change to still deletes the found text. - s.execute("find.change", &json!({"find": "Break ", "change": ""})).unwrap(); - assert!(!s.doc().unwrap().doc.story(sid).unwrap().text.contains("Break")); - } - - #[test] - fn a_find_format_finds_only_text_with_it() { - let mut s = Session::new(); - s.execute("file.new", &json!({})).unwrap(); - let r = s - .execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "Break eggs; cook eggs.\nEggs and eggs"})) - .unwrap(); - let sid = r["story"].as_u64().unwrap(); - s.execute("style.character.create", &json!({"name": "eggs", "chars": {"fontStyle": "Bold"}})).unwrap(); - s.execute("style.paragraph.create", &json!({"name": "Method"})).unwrap(); - for (a, b) in [(6, 10), (12, 16)] { - s.execute("text.select", &json!({"story": sid, "anchor": a, "focus": b})).unwrap(); - s.execute("style.character.apply", &json!({"name": "eggs"})).unwrap(); - } - s.execute("text.select", &json!({"story": sid, "anchor": 25, "focus": 25})).unwrap(); - s.execute("style.paragraph.apply", &json!({"name": "Method"})).unwrap(); - let found = |s: &mut Session, p: serde_json::Value| -> Vec<(u64, u64)> { - let m = s.execute("find.find", &p).unwrap(); - m.as_array().unwrap().iter().map(|m| (m["start"].as_u64().unwrap(), m["end"].as_u64().unwrap())).collect() - }; - // "eggs" where it has the character style: the first only. - assert_eq!(found(&mut s, json!({"find": "eggs", "findFormat": {"charStyle": "eggs"}})), [(6, 10)]); - // Nothing in Find what: each stretch of text in the style. - assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"charStyle": "eggs"}})), [(6, 10), (12, 16)]); - // A paragraph style, and resolved attributes. - assert_eq!(found(&mut s, json!({"find": "eggs", "findFormat": {"paraStyle": "Method"}})), [(23, 27), (32, 36)]); - assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"chars": {"fontStyle": "Bold"}}})), [(6, 10), (12, 16)]); - assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"chars": {"size": 12}}})), [(0, 22), (23, 36)], "each paragraph apart"); - // Find Next walks the stretches. - s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap(); - let next = json!({"find": "", "findFormat": {"charStyle": "eggs"}}); - assert_eq!(s.execute("find.next", &next).unwrap()["start"], 6); - assert_eq!(s.execute("find.next", &next).unwrap()["start"], 12); - // Equivalent spellings the attributes accept find the same text: a snake_case key, and a - // nested number written as an integer (14 pt leading on the second paragraph). - s.execute("text.select", &json!({"story": sid, "anchor": 23, "focus": 36})).unwrap(); - s.execute("type.char", &json!({"leading": {"kind": "points", "value": 14.0}})).unwrap(); - for (a, b) in [ - (json!({"fontStyle": "Bold"}), json!({"font_style": "Bold"})), - (json!({"leading": {"kind": "points", "value": 14.0}}), json!({"leading": {"kind": "points", "value": 14}})), - ] { - let (a, b) = (json!({"find": "", "findFormat": {"chars": a}}), json!({"find": "", "findFormat": {"chars": b}})); - let all = found(&mut s, a.clone()); - assert!(!all.is_empty(), "{a}"); - assert_eq!(found(&mut s, b.clone()), all, "{b}"); - for p in [&a, &b] { - s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap(); - assert_eq!(s.execute("find.next", p).unwrap()["start"].as_u64(), Some(all[0].0), "{p}"); - } - } - // A null attribute asks for nothing. - assert_eq!(found(&mut s, json!({"find": "eggs", "findFormat": {"charStyle": "eggs", "chars": {"size": null}}})), [(6, 10)]); - // With a Change Format: the text in the style goes back to [None], underlined. - let r = s - .execute( - "find.change", - &json!({"find": "", "change": "", "findFormat": {"charStyle": "eggs", "chars": {"font_style": "Bold"}}, "charStyle": "[None]", "attrs": {"underline": true}}), - ) - .unwrap(); - assert_eq!(r["count"], 2, "a snake_case attribute changes the same text"); - assert!(found(&mut s, json!({"find": "", "findFormat": {"charStyle": "eggs"}})).is_empty()); - assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"chars": {"underline": true}}})), [(6, 10), (12, 16)]); - // Unknown styles and attributes are refused; an empty search needs a Find Format. - assert!(s.execute("find.find", &json!({"find": "", "findFormat": {"charStyle": "Nope"}})).is_err()); - assert!(s.execute("find.next", &json!({"find": "eggs", "findFormat": {"paraStyle": "Nope"}})).is_err()); - assert!(s.execute("find.find", &json!({"find": "eggs", "findFormat": {"chars": {"bogus": 1}}})).is_err()); - // Malformed fields are refused, not searched without. - for f in [json!({"chars": [1]}), json!({"chars": 12}), json!({"charStyle": 3}), json!({"paraStyle": ["Body"]})] { - assert!(s.execute("find.find", &json!({"find": "eggs", "findFormat": f})).is_err(), "{f}"); - } - assert!(s.execute("find.find", &json!({"find": ""})).is_err()); - } - #[test] fn find_and_change_objects_by_attributes() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/find/tests.rs b/crates/engine/src/cmd/find/tests.rs index 5914c2e51..e88c81a3a 100644 --- a/crates/engine/src/cmd/find/tests.rs +++ b/crates/engine/src/cmd/find/tests.rs @@ -747,3 +747,119 @@ fn find_scope_revert_releases_context_with_same_document_uid() { assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "red red | red"); assert!(s.execute("find.find", &p).is_err(), "revert's empty selection cannot inherit a previous range"); } + +#[test] +fn change_format_styles_the_found_text_and_keeps_it() { + // The course's chapter 22: every lowercase "eggs" gets the character style "eggs", with + // Change to empty, so the words stay. + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let text = "Poached Eggs\nBreak eggs; cook until eggs are set."; + let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": text})).unwrap(); + let sid = designcraft_doc::StoryId(r["story"].as_u64().unwrap()); + s.execute("style.character.create", &json!({"name": "eggs", "chars": {"fontStyle": "Bold", "fill": "C=15 M=100 Y=100 K=0"}})).unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Method"})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute("find.change", &json!({"find": "eggs", "change": "", "caseSensitive": true, "charStyle": "eggs"})).unwrap(); + assert_eq!(r["count"], 2); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + let style_at = |s: &Session, at: usize| s.doc().unwrap().doc.story(sid).unwrap().format_after(at).style.clone(); + let story = s.doc().unwrap().doc.story(sid).unwrap().clone(); + assert_eq!(story.text, text, "the words stay"); + for at in [19, 36] { + assert_eq!(&story.text[at..at + 4], "eggs"); + assert_eq!(style_at(&s, at), "eggs"); + } + assert_eq!(style_at(&s, 8), designcraft_doc::NO_CHAR_STYLE, "case sensitive: not \"Eggs\""); + assert_eq!(style_at(&s, 25), designcraft_doc::NO_CHAR_STYLE, "only the found text"); + // A paragraph style goes to the found text's paragraphs, with attributes over the text. + s.execute("find.change", &json!({"find": "cook", "change": "", "paraStyle": "Method", "attrs": {"underline": true}})).unwrap(); + let story = s.doc().unwrap().doc.story(sid).unwrap().clone(); + assert_eq!((story.paras[0].style.as_str(), story.paras[1].style.as_str()), (designcraft_doc::BASIC_PARAGRAPH, "Method")); + assert_eq!(story.format_after(25).over.underline, Some(true)); + assert_eq!(story.format_after(19).style, "eggs", "the other text keeps its character style"); + // Change to and a Change Format: the new text is formatted. + s.execute("find.change", &json!({"find": "set", "change": "firm", "charStyle": "eggs"})).unwrap(); + assert_eq!(style_at(&s, s.doc().unwrap().doc.story(sid).unwrap().text.find("firm").unwrap()), "eggs"); + // No such style: refused, nothing changed. + let before = s.doc().unwrap().doc.clone(); + assert!(s.execute("find.change", &json!({"find": "eggs", "change": "", "charStyle": "Nope"})).is_err()); + assert!(s.execute("find.change", &json!({"find": "eggs", "change": "", "paraStyle": "Nope"})).is_err()); + assert_eq!(s.doc().unwrap().doc, before); + // With no Change Format, an empty Change to still deletes the found text. + s.execute("find.change", &json!({"find": "Break ", "change": ""})).unwrap(); + assert!(!s.doc().unwrap().doc.story(sid).unwrap().text.contains("Break")); +} + +#[test] +fn a_find_format_finds_only_text_with_it() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s + .execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "Break eggs; cook eggs.\nEggs and eggs"})) + .unwrap(); + let sid = r["story"].as_u64().unwrap(); + s.execute("style.character.create", &json!({"name": "eggs", "chars": {"fontStyle": "Bold"}})).unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Method"})).unwrap(); + for (a, b) in [(6, 10), (12, 16)] { + s.execute("text.select", &json!({"story": sid, "anchor": a, "focus": b})).unwrap(); + s.execute("style.character.apply", &json!({"name": "eggs"})).unwrap(); + } + s.execute("text.select", &json!({"story": sid, "anchor": 25, "focus": 25})).unwrap(); + s.execute("style.paragraph.apply", &json!({"name": "Method"})).unwrap(); + let found = |s: &mut Session, p: serde_json::Value| -> Vec<(u64, u64)> { + let m = s.execute("find.find", &p).unwrap(); + m.as_array().unwrap().iter().map(|m| (m["start"].as_u64().unwrap(), m["end"].as_u64().unwrap())).collect() + }; + // "eggs" where it has the character style: the first only. + assert_eq!(found(&mut s, json!({"find": "eggs", "findFormat": {"charStyle": "eggs"}})), [(6, 10)]); + // Nothing in Find what: each stretch of text in the style. + assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"charStyle": "eggs"}})), [(6, 10), (12, 16)]); + // A paragraph style, and resolved attributes. + assert_eq!(found(&mut s, json!({"find": "eggs", "findFormat": {"paraStyle": "Method"}})), [(23, 27), (32, 36)]); + assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"chars": {"fontStyle": "Bold"}}})), [(6, 10), (12, 16)]); + assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"chars": {"size": 12}}})), [(0, 22), (23, 36)], "each paragraph apart"); + // Find Next walks the stretches. + s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap(); + let next = json!({"find": "", "findFormat": {"charStyle": "eggs"}}); + assert_eq!(s.execute("find.next", &next).unwrap()["start"], 6); + assert_eq!(s.execute("find.next", &next).unwrap()["start"], 12); + // Equivalent spellings the attributes accept find the same text: a snake_case key, and a + // nested number written as an integer (14 pt leading on the second paragraph). + s.execute("text.select", &json!({"story": sid, "anchor": 23, "focus": 36})).unwrap(); + s.execute("type.char", &json!({"leading": {"kind": "points", "value": 14.0}})).unwrap(); + for (a, b) in [ + (json!({"fontStyle": "Bold"}), json!({"font_style": "Bold"})), + (json!({"leading": {"kind": "points", "value": 14.0}}), json!({"leading": {"kind": "points", "value": 14}})), + ] { + let (a, b) = (json!({"find": "", "findFormat": {"chars": a}}), json!({"find": "", "findFormat": {"chars": b}})); + let all = found(&mut s, a.clone()); + assert!(!all.is_empty(), "{a}"); + assert_eq!(found(&mut s, b.clone()), all, "{b}"); + for p in [&a, &b] { + s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap(); + assert_eq!(s.execute("find.next", p).unwrap()["start"].as_u64(), Some(all[0].0), "{p}"); + } + } + // A null attribute asks for nothing. + assert_eq!(found(&mut s, json!({"find": "eggs", "findFormat": {"charStyle": "eggs", "chars": {"size": null}}})), [(6, 10)]); + // With a Change Format: the text in the style goes back to [None], underlined. + let r = s + .execute( + "find.change", + &json!({"find": "", "change": "", "findFormat": {"charStyle": "eggs", "chars": {"font_style": "Bold"}}, "charStyle": "[None]", "attrs": {"underline": true}}), + ) + .unwrap(); + assert_eq!(r["count"], 2, "a snake_case attribute changes the same text"); + assert!(found(&mut s, json!({"find": "", "findFormat": {"charStyle": "eggs"}})).is_empty()); + assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"chars": {"underline": true}}})), [(6, 10), (12, 16)]); + // Unknown styles and attributes are refused; an empty search needs a Find Format. + assert!(s.execute("find.find", &json!({"find": "", "findFormat": {"charStyle": "Nope"}})).is_err()); + assert!(s.execute("find.next", &json!({"find": "eggs", "findFormat": {"paraStyle": "Nope"}})).is_err()); + assert!(s.execute("find.find", &json!({"find": "eggs", "findFormat": {"chars": {"bogus": 1}}})).is_err()); + // Malformed fields are refused, not searched without. + for f in [json!({"chars": [1]}), json!({"chars": 12}), json!({"charStyle": 3}), json!({"paraStyle": ["Body"]})] { + assert!(s.execute("find.find", &json!({"find": "eggs", "findFormat": f})).is_err(), "{f}"); + } + assert!(s.execute("find.find", &json!({"find": ""})).is_err()); +} From cb29eddb363741ab6209647f0bc245b771266981 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:24:22 +0100 Subject: [PATCH 0456/1349] Georgian: main's row for Gap Tint:, once Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/ka.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index 2304eb940..92f4843c2 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -33,7 +33,6 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Copy", "კოპირება"), ("Paste", "ჩასმა"), ("Keep In Frame", "ჩარჩოში შენარჩუნება"), - ("Gap Tint:", "ღრეჩოს ტონი:"), ("Restart Numbering", "ნუმერაციის თავიდან დაწყება"), ("Continue Numbering", "ნუმერაციის გაგრძელება"), ("Keep Options…", "შენარჩუნების პარამეტრები…"), From faee83dad68be3506a62d918df7e42723a880bed Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:24:59 +0100 Subject: [PATCH 0457/1349] Georgian: main's rows where the branch added the same keys again Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/ka.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index cd3a889a8..d0b94f549 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -36,7 +36,6 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Text Frame General Options", "ტექსტის ჩარჩოს ზოგადი პარამეტრები"), ("New Object Style", "ახალი ობიექტის სტილი"), ("Object Style Options", "ობიექტის სტილის პარამეტრები"), - ("Object Style Options…", "ობიექტის სტილის პარამეტრები…"), ("Basic Attributes", "ძირითადი ატრიბუტები"), ("Stroke & Corner Options", "კონტურისა და კუთხეების პარამეტრები"), ("Effects for:", "ეფექტები:"), From c6703e81f5769ac5dd1e05a6f8fe5c39a70e6ab8 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:25:00 +0100 Subject: [PATCH 0458/1349] Georgian: main's rows where the branch added the same keys again Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/ka.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index 8c44a18d7..46dc638d9 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -32,7 +32,6 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "ამოჭრა"), ("Copy", "კოპირება"), ("Paste", "ჩასმა"), - ("Packaged {count} files into {dir}", "{count} ფაილი შეიფუთა {dir}-ში"), ("Continue", "გაგრძელება"), ("Printing Instructions", "ბეჭდვის ინსტრუქციები"), ("Show Problems Only", "მხოლოდ პრობლემების ჩვენება"), @@ -41,8 +40,6 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Create Printing Instructions", "ბეჭდვის ინსტრუქციების შექმნა"), ("Entire Publication", "მთელი პუბლიკაცია"), ("Scope:", "არეალი:"), - ("Spot", "ლაქა"), - ("Process", "პროცესი"), ("Source", "წყარო"), ("Installed", "დაყენებული"), ("Bundled", "ჩაშენებული"), @@ -57,9 +54,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ), ("Fonts: {used} Fonts Used, {missing} Missing", "შრიფტები: გამოყენებულია {used}, აკლია {missing}"), ("Instructions:", "ინსტრუქციები:"), - ("Email:", "ელფოსტა:"), ("Fax:", "ფაქსი:"), - ("Phone:", "ტელეფონი:"), ("Address:", "მისამართი:"), ("Company:", "კომპანია:"), ("Contact:", "საკონტაქტო პირი:"), From c8bc257dcd0b9baa4c931f595e645d3c10a4df5c Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:25:01 +0100 Subject: [PATCH 0459/1349] Georgian: main's rows where the branch added the same keys again Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/ka.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index 48faae5a2..6a3c28d9e 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -33,7 +33,6 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Copy", "კოპირება"), ("Paste", "ჩასმა"), ("PDF Preset:", "PDF-ის წინასწარი პარამეტრი:"), - ("Packaged {count} files into {dir}", "{count} ფაილი შეიფუთა {dir}-ში"), ("Continue", "გაგრძელება"), ("Printing Instructions", "ბეჭდვის ინსტრუქციები"), ("Show Problems Only", "მხოლოდ პრობლემების ჩვენება"), @@ -42,8 +41,6 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Create Printing Instructions", "ბეჭდვის ინსტრუქციების შექმნა"), ("Entire Publication", "მთელი პუბლიკაცია"), ("Scope:", "არეალი:"), - ("Spot", "სპოტ-საღებავი"), - ("Process", "პროცესი"), ("Source", "წყარო"), ("Installed", "დაყენებული"), ("Bundled", "ჩაშენებული"), @@ -58,9 +55,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ), ("Fonts: {used} Fonts Used, {missing} Missing", "შრიფტები: გამოყენებულია {used}, აკლია {missing}"), ("Instructions:", "ინსტრუქციები:"), - ("Email:", "ელფოსტა:"), ("Fax:", "ფაქსი:"), - ("Phone:", "ტელეფონი:"), ("Address:", "მისამართი:"), ("Company:", "კომპანია:"), ("Contact:", "საკონტაქტო პირი:"), From 72c06ea4ac676e4bf0f10fe7061a36b9542025a3 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:33:44 +0100 Subject: [PATCH 0460/1349] IDML object style import: the HashMap import in main's split styles module Co-Authored-By: Claude Opus 5.5 --- crates/idml/src/import/styles.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/idml/src/import/styles.rs b/crates/idml/src/import/styles.rs index 013036d6a..9f5b6f69c 100644 --- a/crates/idml/src/import/styles.rs +++ b/crates/idml/src/import/styles.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; + use designcraft_geom::corners::CornerOptions; use super::object_style::{corners, corners_in}; From 0591765d36e828a5e845adcab10f9366ae2b9d8f Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:39:54 +0100 Subject: [PATCH 0461/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/dialogs/tests.rs | 374 ++++++++++++++-------------- 2 files changed, 188 insertions(+), 188 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index c29cbdfd9..a88f2d180 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -44,8 +44,8 @@ use input::{press_count, release_clicks}; #[cfg(test)] use page_decor::{MAX_BASELINES, baseline_grid_lines}; use page_decor::{dashed, draw_flattener_preview, draw_guides, shown_area}; -pub use render::{DisplayKey, color_at}; use render::render_texture; +pub use render::{DisplayKey, color_at}; #[cfg(test)] use render::{c32, invalidate_on_display_change, screen_options}; pub(crate) use rulers::fmt_tick; diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 165727cf8..a35377864 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -592,7 +592,7 @@ fn the_hex_field_keeps_typed_text_and_commits_a_valid_code() { dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]); type_slowly(&mut app, &ctx, screen, "zz"); let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "#:").center()); + click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "#:").center()); let labels = dialog_frame(&mut app, &ctx, screen, vec![]); visible_label(&labels, screen, "f59019"); assert_eq!(app.ui.dialog.as_ref().unwrap().s("hex"), "#f59019"); @@ -602,13 +602,13 @@ fn the_hex_field_keeps_typed_text_and_commits_a_valid_code() { fn typed_channel_values_are_kept_while_typing() { let (mut app, ctx, screen, id) = picker(json!({"target": "fill", "hex": "#010203", "model": "rgb", "rgb": [1, 2, 3]})); let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - let r = visible_label(&labels, screen, "R:"); - click_dialog(&mut app, &ctx, screen, egui::pos2(r.min.x + 46.0, r.center().y)); + let r = visible_label(&labels, screen, "R:"); + click_dialog(&mut app, &ctx, screen, egui::pos2(r.min.x + 46.0, r.center().y)); dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]); type_slowly(&mut app, &ctx, screen, "12.5"); let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - visible_label(&labels, screen, "12.5"); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["rgb"][1], json!(2.0)); + visible_label(&labels, screen, "12.5"); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["rgb"][1], json!(2.0)); assert_eq!(app.ui.dialog.as_ref().unwrap().s("hex"), "#0d0203"); confirm(&mut app).unwrap(); let designcraft_color::Color::Rgb { r, .. } = fill(&app, id) else { panic!("not RGB") }; @@ -630,8 +630,8 @@ fn a_cmyk_colour_stays_cmyk_unless_rgb_values_are_typed() { // A typed C/M/Y/K percent is a percent: M 1 is 1 %. let (mut app, ctx, screen, id) = picker(cmyk.clone()); let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - let r = visible_label(&labels, screen, "M:"); - click_dialog(&mut app, &ctx, screen, egui::pos2(r.max.x + 29.0, r.center().y)); + let r = visible_label(&labels, screen, "M:"); + click_dialog(&mut app, &ctx, screen, egui::pos2(r.max.x + 29.0, r.center().y)); dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]); type_slowly(&mut app, &ctx, screen, "1"); confirm(&mut app).unwrap(); @@ -641,9 +641,9 @@ fn a_cmyk_colour_stays_cmyk_unless_rgb_values_are_typed() { let (mut app, ctx, screen, id) = picker(cmyk); let r = app.ui.dialog.as_ref().unwrap().fields["rgb"][0].as_f64().unwrap(); let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - let _ = r; - let r = visible_label(&labels, screen, "R:"); - click_dialog(&mut app, &ctx, screen, egui::pos2(r.min.x + 46.0, r.center().y)); + let _ = r; + let r = visible_label(&labels, screen, "R:"); + click_dialog(&mut app, &ctx, screen, egui::pos2(r.min.x + 46.0, r.center().y)); dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]); type_slowly(&mut app, &ctx, screen, "10"); confirm(&mut app).unwrap(); @@ -1644,7 +1644,7 @@ fn dialog_frame(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, ev fn visible_label(labels: &[(String, egui::Rect, egui::Rect)], screen: egui::Rect, expected: &str) -> egui::Rect { let (_, rect, clip) = labels.iter().find(|(text, _, _)| text.trim() == expected).unwrap_or_else(|| panic!("{expected} is painted")); assert!(screen.contains_rect(*rect), "{expected} must stay on screen: {rect:?}"); - assert!(clip.expand(0.5).contains_rect(*rect), "{expected} must not be clipped: {rect:?}, {clip:?}"); + assert!(clip.expand(0.5).contains_rect(*rect), "{expected} must not be clipped: {rect:?}, {clip:?}"); *rect } @@ -3462,188 +3462,188 @@ fn guide_counts(app: &DesignApp) -> Vec { (0..doc.page_count()).map(|abs| doc.page(abs).unwrap().guides.len()).collect() } - /// The Color Picker laid out as InDesign's: a field and a slider for the component whose radio - /// is on, the new colour over the old one, and the values in every space. - /// The course's chapter 23: the Color Picker's eyedropper, dragged from the picker onto the - /// page and let go there, takes the colour the page shows. - /// The eyedropper takes the colour the canvas shows: with Proof Colors the proofed colour, and - /// with the ink-limit preview the warning colour over the limit. - #[test] - fn the_eyedropper_samples_what_proof_colors_and_the_ink_limit_show() { - use egui_kittest::Harness; - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("swatch.create", json!({"name": "Vivid Green", "color": [0, 255, 0]})).unwrap(); - let id = app.run("frame.create", json!({"rect": [36, 36, 560, 700], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap(); - app.run("object.fill", json!({"ids": [id], "swatch": "Vivid Green"})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state( - |ui, app: &mut DesignApp| { - let ctx = ui.ctx().clone(); - app.logic(&ctx); - app.ui(ui); - }, - app, - ); - h.run_steps(6); - let target = { - let app = h.state(); - let doc = &app.session.doc().unwrap().doc; - let layout = designcraft_tools::CanvasLayout::new(doc, false); - let v = *app.view().unwrap(); - crate::canvas::Xf::new(app.canvas_rect.unwrap(), &v).to_screen(layout.slots[0].xf * designcraft_geom::Point::new(300.0, 600.0)) - }; - let ctx = h.ctx.clone(); - let sample = |h: &mut Harness<'_, DesignApp>| crate::canvas::color_at(h.state_mut(), &ctx, target).expect("on the page"); - // What a view makes of the plain colour, as the canvas texture gets it. - let shown = |c: [u8; 3], view: &dyn Fn(&mut designcraft_render::Rendered)| { - let mut img = designcraft_render::Rendered { width: 1, height: 1, pixels: vec![c[0], c[1], c[2], 255] }; - view(&mut img); - [img.pixels[0], img.pixels[1], img.pixels[2]] - }; - let plain = sample(&mut h); - h.state_mut().ui.proof_colors = true; - let setup = h.state().ui.proof_setup.clone(); - let proofed = sample(&mut h); - assert_eq!(proofed, shown(plain, &|img| designcraft_render::proof_view(img, &setup))); - assert_ne!(proofed, plain, "the proof changes this green"); - } +/// The Color Picker laid out as InDesign's: a field and a slider for the component whose radio +/// is on, the new colour over the old one, and the values in every space. +/// The course's chapter 23: the Color Picker's eyedropper, dragged from the picker onto the +/// page and let go there, takes the colour the page shows. +/// The eyedropper takes the colour the canvas shows: with Proof Colors the proofed colour, and +/// with the ink-limit preview the warning colour over the limit. +#[test] +fn the_eyedropper_samples_what_proof_colors_and_the_ink_limit_show() { + use egui_kittest::Harness; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("swatch.create", json!({"name": "Vivid Green", "color": [0, 255, 0]})).unwrap(); + let id = app.run("frame.create", json!({"rect": [36, 36, 560, 700], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap(); + app.run("object.fill", json!({"ids": [id], "swatch": "Vivid Green"})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(6); + let target = { + let app = h.state(); + let doc = &app.session.doc().unwrap().doc; + let layout = designcraft_tools::CanvasLayout::new(doc, false); + let v = *app.view().unwrap(); + crate::canvas::Xf::new(app.canvas_rect.unwrap(), &v).to_screen(layout.slots[0].xf * designcraft_geom::Point::new(300.0, 600.0)) + }; + let ctx = h.ctx.clone(); + let sample = |h: &mut Harness<'_, DesignApp>| crate::canvas::color_at(h.state_mut(), &ctx, target).expect("on the page"); + // What a view makes of the plain colour, as the canvas texture gets it. + let shown = |c: [u8; 3], view: &dyn Fn(&mut designcraft_render::Rendered)| { + let mut img = designcraft_render::Rendered { width: 1, height: 1, pixels: vec![c[0], c[1], c[2], 255] }; + view(&mut img); + [img.pixels[0], img.pixels[1], img.pixels[2]] + }; + let plain = sample(&mut h); + h.state_mut().ui.proof_colors = true; + let setup = h.state().ui.proof_setup.clone(); + let proofed = sample(&mut h); + assert_eq!(proofed, shown(plain, &|img| designcraft_render::proof_view(img, &setup))); + assert_ne!(proofed, plain, "the proof changes this green"); +} #[test] - fn the_color_pickers_eyedropper_takes_a_colour_off_the_page() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let id = app.run("frame.create", json!({"rect": [36, 36, 560, 700], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap(); - app.run("object.fill", json!({"ids": [id], "swatch": "C=0 M=100 Y=100 K=0"})).unwrap(); - app.ui.dialog = Some(Dialog::new("colorPicker", json!({"target": "fill", "hex": "#000000"}))); - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state( - |ui, app: &mut DesignApp| { - let ctx = ui.ctx().clone(); - app.logic(&ctx); - app.ui(ui); - }, - app, - ); - h.run_steps(6); - // Where the frame shows on screen. - let target = { - let app = h.state(); - let doc = &app.session.doc().unwrap().doc; - let layout = designcraft_tools::CanvasLayout::new(doc, false); - let v = *app.view().unwrap(); - crate::canvas::Xf::new(app.canvas_rect.unwrap(), &v).to_screen(layout.slots[0].xf * designcraft_geom::Point::new(300.0, 600.0)) - }; - let from = h.get_by_label("Eyedropper: drag it onto the page").rect().center(); - h.hover_at(from); - h.drag_at(from); +fn the_color_pickers_eyedropper_takes_a_colour_off_the_page() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [36, 36, 560, 700], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap(); + app.run("object.fill", json!({"ids": [id], "swatch": "C=0 M=100 Y=100 K=0"})).unwrap(); + app.ui.dialog = Some(Dialog::new("colorPicker", json!({"target": "fill", "hex": "#000000"}))); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(6); + // Where the frame shows on screen. + let target = { + let app = h.state(); + let doc = &app.session.doc().unwrap().doc; + let layout = designcraft_tools::CanvasLayout::new(doc, false); + let v = *app.view().unwrap(); + crate::canvas::Xf::new(app.canvas_rect.unwrap(), &v).to_screen(layout.slots[0].xf * designcraft_geom::Point::new(300.0, 600.0)) + }; + let from = h.get_by_label("Eyedropper: drag it onto the page").rect().center(); + h.hover_at(from); + h.drag_at(from); + h.run_steps(1); + for k in 1..=4 { + h.hover_at(from + (target - from) * (k as f32 / 4.0)); h.run_steps(1); - for k in 1..=4 { - h.hover_at(from + (target - from) * (k as f32 / 4.0)); - h.run_steps(1); - } - h.drop_at(target); - h.run_steps(3); - let d = h.state().ui.dialog.as_ref().expect("the picker stays open"); - let [r, g, b, _] = h.state().session.doc().unwrap().doc.resolve_color("C=0 M=100 Y=100 K=0", 1.0).unwrap().to_rgba8(1.0); - let got: Vec = d.fields["rgb"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); - for (a, e) in got.iter().zip([r, g, b]) { - assert!((a - f64::from(e)).abs() <= 3.0, "{got:?} vs {:?}", [r, g, b]); - } - assert!(d.b("edited")); - // Let go off the page (here, on the dialog's own field area): no colour, nothing changes. - let hex = d.s("hex"); - h.hover_at(from); - h.drag_at(from); - h.run_steps(1); - h.hover_at(from + egui::vec2(-40.0, 0.0)); - h.run_steps(1); - h.drop_at(egui::pos2(2.0, 2.0)); - h.run_steps(3); - assert_eq!(h.state().ui.dialog.as_ref().unwrap().s("hex"), hex); - // Let go over the picker's own colour field, with the page under it: nothing either. - let field = h.get_by_label("Color field").rect().center(); - let ctx = h.ctx.clone(); - assert!(crate::canvas::color_at(h.state_mut(), &ctx, field).is_some(), "the page lies under the field"); - h.hover_at(from); - h.drag_at(from); - h.run_steps(1); - h.hover_at(field); - h.run_steps(1); - h.drop_at(field); - h.run_steps(3); - assert_eq!(h.state().ui.dialog.as_ref().unwrap().s("hex"), hex, "the picker isn't sampled"); } - - #[test] - fn the_color_picker_picks_on_its_field_and_slider_and_adds_a_cmyk_swatch() { - use egui_kittest::kittest::Queryable; - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - app.run("frame.create", json!({"rect": [72, 72, 200, 200], "shape": "rectangle"})).unwrap(); - app.run("object.color", json!({"color":designcraft_color::Color::from_hex("#7c1315").unwrap(),"target":"fill"})).unwrap(); - app.ui.dialog = Some(Dialog::new("colorPicker", json!({"target": "fill", "hex": "#7c1315", "text": false}))); - let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); - h.run_steps(3); - // R at first: R up the slider, B across and G up the field. - let _ = h.get_by_label("RGB Color Space View"); - let field = h.get_by_label("Color field").rect(); - crate::test_window::click_at(&mut h, egui::pos2(field.right() - 1.0, field.top() + 1.0)); - h.run_steps(2); - let p = picked_of(h.state().app.ui.dialog.as_ref().unwrap()); - assert!((p.rgb[0] - 124.0 / 255.0).abs() < 0.01 && p.rgb[1] > 0.97 && p.rgb[2] > 0.97, "{p:?}: R kept, G and B full"); - // The slider sets R alone. - let slider = h.get_by_label("Color slider").rect(); - crate::test_window::click_at(&mut h, egui::pos2(slider.center().x, slider.bottom() - 1.0)); - h.run_steps(2); - let p = picked_of(h.state().app.ui.dialog.as_ref().unwrap()); - assert!(p.rgb[0] < 0.02 && p.rgb[1] > 0.97, "{p:?}"); - // Hue on the slider: the field is saturation across, brightness up. - store_picked(h.state_mut().app.ui.dialog.as_mut().unwrap(), &Picked::from_rgb([124.0 / 255.0, 19.0 / 255.0, 21.0 / 255.0], 0.0)); - h.state_mut().app.ui.dialog.as_mut().unwrap().fields.insert("component".into(), json!("h")); - h.run_steps(2); - crate::test_window::click_at(&mut h, egui::pos2(field.left() + 1.0, field.top() + 1.0)); - h.run_steps(2); - let p = picked_of(h.state().app.ui.dialog.as_ref().unwrap()); - assert!(p.hsb[1] < 0.02 && p.hsb[2] > 0.98 && (p.hsb[0] - 359.0).abs() < 2.0, "{p:?}: no saturation, full brightness, the hue kept"); - // Lab shows its own view. - h.state_mut().app.ui.dialog.as_mut().unwrap().fields.insert("component".into(), json!("l")); - h.run_steps(2); - let _ = h.get_by_label("Lab Color Space View"); - // Add CMYK Swatch adds the colour as a CMYK swatch; OK applies it. - store_picked(h.state_mut().app.ui.dialog.as_mut().unwrap(), &Picked::from_rgb([124.0 / 255.0, 19.0 / 255.0, 21.0 / 255.0], 0.0)); - h.run_steps(2); - let before = h.state().app.session.active().unwrap().doc.swatches.len(); - h.get_by_label("Add CMYK Swatch").click(); - h.run_steps(3); - let doc = &h.state().app.session.active().unwrap().doc; - assert_eq!(doc.swatches.len(), before + 1); - assert!(matches!( - doc.swatches.last().unwrap().value, - designcraft_color::swatch::SwatchValue::Color { color: designcraft_color::Color::Cmyk { .. }, .. } - )); - // The percentages the C/M/Y/K fields show, exactly (not the colour converted back). - h.state_mut().app.ui.dialog.as_mut().unwrap().fields.insert("cmyk".into(), json!([0.0, 50.0, 100.0, 0.0])); - h.run_steps(2); - h.get_by_label("Add CMYK Swatch").click(); - h.run_steps(3); - let doc = &h.state().app.session.active().unwrap().doc; - let designcraft_color::swatch::SwatchValue::Color { color: designcraft_color::Color::Cmyk { c, m, y, k }, .. } = - doc.swatches.last().unwrap().value - else { - panic!("a CMYK swatch") - }; - assert_eq!([c, m, y, k].map(|v| (v * 100.0).round()), [0.0, 50.0, 100.0, 0.0]); - // Its own OK, at the top right, applies it. - h.get_by_label("OK").click(); - h.run_steps(3); - assert!(h.state().app.ui.dialog.is_none(), "OK closes it"); - let st = h.state().app.session.active().unwrap(); - let id = st.selection.items[0]; - let fill = st.doc.item(id).unwrap().fill.swatch.clone(); - assert_eq!(st.doc.resolve_color(&fill, 1.0).unwrap().to_hex(), "#7c1315"); + h.drop_at(target); + h.run_steps(3); + let d = h.state().ui.dialog.as_ref().expect("the picker stays open"); + let [r, g, b, _] = h.state().session.doc().unwrap().doc.resolve_color("C=0 M=100 Y=100 K=0", 1.0).unwrap().to_rgba8(1.0); + let got: Vec = d.fields["rgb"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + for (a, e) in got.iter().zip([r, g, b]) { + assert!((a - f64::from(e)).abs() <= 3.0, "{got:?} vs {:?}", [r, g, b]); } + assert!(d.b("edited")); + // Let go off the page (here, on the dialog's own field area): no colour, nothing changes. + let hex = d.s("hex"); + h.hover_at(from); + h.drag_at(from); + h.run_steps(1); + h.hover_at(from + egui::vec2(-40.0, 0.0)); + h.run_steps(1); + h.drop_at(egui::pos2(2.0, 2.0)); + h.run_steps(3); + assert_eq!(h.state().ui.dialog.as_ref().unwrap().s("hex"), hex); + // Let go over the picker's own colour field, with the page under it: nothing either. + let field = h.get_by_label("Color field").rect().center(); + let ctx = h.ctx.clone(); + assert!(crate::canvas::color_at(h.state_mut(), &ctx, field).is_some(), "the page lies under the field"); + h.hover_at(from); + h.drag_at(from); + h.run_steps(1); + h.hover_at(field); + h.run_steps(1); + h.drop_at(field); + h.run_steps(3); + assert_eq!(h.state().ui.dialog.as_ref().unwrap().s("hex"), hex, "the picker isn't sampled"); +} - #[test] +#[test] +fn the_color_picker_picks_on_its_field_and_slider_and_adds_a_cmyk_swatch() { + use egui_kittest::kittest::Queryable; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("frame.create", json!({"rect": [72, 72, 200, 200], "shape": "rectangle"})).unwrap(); + app.run("object.color", json!({"color":designcraft_color::Color::from_hex("#7c1315").unwrap(),"target":"fill"})).unwrap(); + app.ui.dialog = Some(Dialog::new("colorPicker", json!({"target": "fill", "hex": "#7c1315", "text": false}))); + let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); + h.run_steps(3); + // R at first: R up the slider, B across and G up the field. + let _ = h.get_by_label("RGB Color Space View"); + let field = h.get_by_label("Color field").rect(); + crate::test_window::click_at(&mut h, egui::pos2(field.right() - 1.0, field.top() + 1.0)); + h.run_steps(2); + let p = picked_of(h.state().app.ui.dialog.as_ref().unwrap()); + assert!((p.rgb[0] - 124.0 / 255.0).abs() < 0.01 && p.rgb[1] > 0.97 && p.rgb[2] > 0.97, "{p:?}: R kept, G and B full"); + // The slider sets R alone. + let slider = h.get_by_label("Color slider").rect(); + crate::test_window::click_at(&mut h, egui::pos2(slider.center().x, slider.bottom() - 1.0)); + h.run_steps(2); + let p = picked_of(h.state().app.ui.dialog.as_ref().unwrap()); + assert!(p.rgb[0] < 0.02 && p.rgb[1] > 0.97, "{p:?}"); + // Hue on the slider: the field is saturation across, brightness up. + store_picked(h.state_mut().app.ui.dialog.as_mut().unwrap(), &Picked::from_rgb([124.0 / 255.0, 19.0 / 255.0, 21.0 / 255.0], 0.0)); + h.state_mut().app.ui.dialog.as_mut().unwrap().fields.insert("component".into(), json!("h")); + h.run_steps(2); + crate::test_window::click_at(&mut h, egui::pos2(field.left() + 1.0, field.top() + 1.0)); + h.run_steps(2); + let p = picked_of(h.state().app.ui.dialog.as_ref().unwrap()); + assert!(p.hsb[1] < 0.02 && p.hsb[2] > 0.98 && (p.hsb[0] - 359.0).abs() < 2.0, "{p:?}: no saturation, full brightness, the hue kept"); + // Lab shows its own view. + h.state_mut().app.ui.dialog.as_mut().unwrap().fields.insert("component".into(), json!("l")); + h.run_steps(2); + let _ = h.get_by_label("Lab Color Space View"); + // Add CMYK Swatch adds the colour as a CMYK swatch; OK applies it. + store_picked(h.state_mut().app.ui.dialog.as_mut().unwrap(), &Picked::from_rgb([124.0 / 255.0, 19.0 / 255.0, 21.0 / 255.0], 0.0)); + h.run_steps(2); + let before = h.state().app.session.active().unwrap().doc.swatches.len(); + h.get_by_label("Add CMYK Swatch").click(); + h.run_steps(3); + let doc = &h.state().app.session.active().unwrap().doc; + assert_eq!(doc.swatches.len(), before + 1); + assert!(matches!( + doc.swatches.last().unwrap().value, + designcraft_color::swatch::SwatchValue::Color { color: designcraft_color::Color::Cmyk { .. }, .. } + )); + // The percentages the C/M/Y/K fields show, exactly (not the colour converted back). + h.state_mut().app.ui.dialog.as_mut().unwrap().fields.insert("cmyk".into(), json!([0.0, 50.0, 100.0, 0.0])); + h.run_steps(2); + h.get_by_label("Add CMYK Swatch").click(); + h.run_steps(3); + let doc = &h.state().app.session.active().unwrap().doc; + let designcraft_color::swatch::SwatchValue::Color { color: designcraft_color::Color::Cmyk { c, m, y, k }, .. } = + doc.swatches.last().unwrap().value + else { + panic!("a CMYK swatch") + }; + assert_eq!([c, m, y, k].map(|v| (v * 100.0).round()), [0.0, 50.0, 100.0, 0.0]); + // Its own OK, at the top right, applies it. + h.get_by_label("OK").click(); + h.run_steps(3); + assert!(h.state().app.ui.dialog.is_none(), "OK closes it"); + let st = h.state().app.session.active().unwrap(); + let id = st.selection.items[0]; + let fill = st.doc.item(id).unwrap().fill.swatch.clone(); + assert_eq!(st.doc.resolve_color(&fill, 1.0).unwrap().to_hex(), "#7c1315"); +} + +#[test] fn create_guides_dialog_targets_the_page_in_view() { let mut app = facing_app(6); From 1141f3a22b58d45c56e3cc4a3fe968748a1ecbbd Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:40:12 +0100 Subject: [PATCH 0462/1349] Object styles: the branch's true/false parameter helper, beside the other object style parameters in main's split module Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/style/object.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/engine/src/cmd/style/object.rs b/crates/engine/src/cmd/style/object.rs index 732d9fba6..7fcc3d1f3 100644 --- a/crates/engine/src/cmd/style/object.rs +++ b/crates/engine/src/cmd/style/object.rs @@ -159,6 +159,15 @@ pub(super) fn create_object(s: &mut Session, p: &Value) -> Result { }) } +/// A true/false parameter, when given. +fn bool_param(cmd: &str, p: &Value, key: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Bool(b)) => Ok(Some(*b)), + Some(_) => Err(bad(cmd, format!("`{key}` must be true or false"))), + } +} + /// `p.stroke` merged over `base` (as [`group_param`]), refused when the weight isn't a number ≥ 0 /// or the tint isn't 0–1. fn stroke_param(cmd: &str, p: &Value, base: Option<&designcraft_doc::Stroke>) -> Result>> { From 7e51494eacd9460e9cc3c56942fe530c2c1a7916 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:42:42 +0100 Subject: [PATCH 0463/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index e13340a25..2a7567400 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -7262,11 +7262,11 @@ fn color_picker(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { }, ); let fr = put(at::field()); - let fresp = ui.interact(fr, ui.id().with("cp_field"), egui::Sense::click_and_drag()); + let fresp = ui.interact(fr, ui.scope_id().with("cp_field"), egui::Sense::click_and_drag()); let (tv, _, _) = p.coords(comp); let cells = if matches!(comp, PickComp::R | PickComp::G | PickComp::Bl | PickComp::H) { 2 } else { 24 }; gradient_mesh(ui.painter(), fr, cells, cells, |x, y| p.at(comp, tv, x, y).rgb); - fresp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Other, true, "Color field")); + fresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Unknown, true, "Color field")); if let Some(pos) = fresp.interact_pointer_pos().filter(|_| fresp.is_pointer_button_down_on() || fresp.clicked()) { let u = ((pos.x - fr.left()) / fr.width()).clamp(0.0, 1.0); let v = ((fr.bottom() - pos.y) / fr.height()).clamp(0.0, 1.0); @@ -7285,9 +7285,9 @@ fn color_picker(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { } // The slider, with a marker on each side. let sr = put(at::slider()); - let sresp = ui.interact(sr.expand2(egui::vec2(6.0, 0.0)), ui.id().with("cp_slider"), egui::Sense::click_and_drag()); + let sresp = ui.interact(sr.expand2(egui::vec2(6.0, 0.0)), ui.scope_id().with("cp_slider"), egui::Sense::click_and_drag()); gradient_mesh(ui.painter(), sr, 1, 48, |_, y| p.slider_at(comp, y)); - sresp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Slider, true, "Color slider")); + sresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Slider, true, "Color slider")); if let Some(pos) = sresp.interact_pointer_pos().filter(|_| sresp.is_pointer_button_down_on() || sresp.clicked()) { let tn = ((sr.bottom() - pos.y) / sr.height()).clamp(0.0, 1.0); let (_, u, v) = p.coords(comp); @@ -7314,7 +7314,7 @@ fn color_picker(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { // OK, Cancel, Add CMYK Swatch: rounded, OK filled. let pill = |ui: &mut egui::Ui, i: usize, label: &str, primary: bool| -> bool { let r = put(at::button(i)); - let resp = ui.interact(r, ui.id().with(("cp_button", i)), egui::Sense::click()); + let resp = ui.interact(r, ui.scope_id().with(("cp_button", i)), egui::Sense::click()); let (fill, fg, stroke) = if primary { (t.accent_strong, egui::Color32::WHITE, egui::Stroke::NONE) } else { @@ -7322,7 +7322,7 @@ fn color_picker(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { }; ui.painter().rect(r, r.height() / 2.0, fill, stroke, egui::StrokeKind::Inside); ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, label, egui::FontId::proportional(12.0), fg); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label)); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); resp.clicked() }; // The footer's padded OK key, which every catalog has. @@ -7370,12 +7370,12 @@ fn color_picker(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { match c { Some(c) => { let rr = egui::Rect::from_center_size(egui::pos2(x, cy), egui::vec2(14.0, 14.0)); - let resp = ui.interact(rr, ui.id().with(("cp_radio", key)), egui::Sense::click()); + let resp = ui.interact(rr, ui.scope_id().with(("cp_radio", key)), egui::Sense::click()); ui.painter().circle(rr.center(), 6.0, t.input, egui::Stroke::new(1.0, t.text_dim)); if comp_now == c { ui.painter().circle_filled(rr.center(), 2.6, t.text_strong); } - resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::RadioButton, true, comp_now == c, label)); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, comp_now == c, label)); if resp.clicked() { comp_now = c; } @@ -7425,11 +7425,11 @@ fn color_picker(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { let cy = area.min.y + at::ROWS[7]; text(ui, egui::pos2(area.min.x + 321.0, cy), egui::Align2::LEFT_CENTER, "#:"); let hr = egui::Rect::from_min_size(egui::pos2(area.min.x + 341.0, cy - 10.5), egui::vec2(64.0, 21.0)); - let id = egui::Id::new("color_picker_hex"); + let id = egui::Id::unique("color_picker_hex"); let editing = ui.memory(|m| m.has_focus(id)); let mut h = if editing { d.s("hexEdit") } else { p.hex().trim_start_matches('#').to_string() }; if ui - .put(hr, egui::TextEdit::singleline(&mut h).id(id).font(font).vertical_align(egui::Align::Center).margin(egui::Margin::symmetric(4, 2))) + .put(hr, egui::TextEdit::singleline(&mut h).id(id).font(font).align(egui::Align2::LEFT_CENTER).margin(egui::Margin::symmetric(4, 2))) .changed() && (h.len() == 6 || (h.len() == 7 && h.starts_with('#'))) && let Some(c) = designcraft_color::Color::from_hex(&h) @@ -7441,8 +7441,8 @@ fn color_picker(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { // pointer when it is let go. let tip = tr("Eyedropper: drag it onto the page"); let er = egui::Rect::from_center_size(egui::pos2(hr.right() + 16.0, cy), egui::vec2(21.0, 21.0)); - let resp = ui.interact(er, egui::Id::new("color_picker_eyedropper"), egui::Sense::click_and_drag()); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &tip)); + let resp = ui.interact(er, egui::Id::unique("color_picker_eyedropper"), egui::Sense::click_and_drag()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &tip)); if resp.hovered() || resp.dragged() { ui.painter().rect_filled(er, 3.0, t.hover); } @@ -7853,7 +7853,7 @@ mod picker_layout { /// A value field: the text typed stays while it has the focus; a number that parses applies. fn picker_field(ui: &mut egui::Ui, d: &mut Dialog, r: egui::Rect, key: &str, value: f32, range: (f32, f32)) -> Option { - let id = egui::Id::new(("color_picker_field", key)); + let id = egui::Id::unique(("color_picker_field", key)); let editing = ui.memory(|m| m.has_focus(id)); let shown = format!("{}", value.round() as i64); let edit_key = format!("_edit_{key}"); @@ -7863,7 +7863,7 @@ fn picker_field(ui: &mut egui::Ui, d: &mut Dialog, r: egui::Rect, key: &str, val egui::TextEdit::singleline(&mut text) .id(id) .font(egui::FontId::proportional(11.5)) - .vertical_align(egui::Align::Center) + .align(egui::Align2::LEFT_CENTER) .margin(egui::Margin::symmetric(4, 2)), ); let mut out = None; From 24b923dfc0de855009fa08ced9a4c85e2193a566 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:43:09 +0100 Subject: [PATCH 0464/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/package/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/package/tests.rs b/crates/engine/src/cmd/package/tests.rs index 3440c68f6..fe559bfb8 100644 --- a/crates/engine/src/cmd/package/tests.rs +++ b/crates/engine/src/cmd/package/tests.rs @@ -169,7 +169,7 @@ fn package_writes_document_links_and_report() { assert!(out.join("Links").join("logo.svg").exists()); let report = std::fs::read_to_string(out.join("Instructions.txt")).unwrap(); assert!(report.contains("Print on matte.") && report.contains("logo.svg"), "{report}"); - assert!(report.find("Print on matte.") < report.find("Package report:"), "the instructions come first: {report}"); + assert!(report.find("Print on matte.") < report.find("Package report:"), "the instructions come first: {report}"); assert!(report.contains("Preflight:"), "{report}"); // The packaged document links to its Links folder. let doc_file = files.iter().find(|f| f.ends_with(".designcraft")).unwrap(); From 12425aafd7d12868ebafc081ceecc49174aa69f5 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:43:22 +0100 Subject: [PATCH 0465/1349] Eyedropper: the canvas render module's imports for the colour sampler; screen_options keeps its doc comment Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/render.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas/render.rs b/crates/ui-egui/src/canvas/render.rs index 691d9c162..5b7358996 100644 --- a/crates/ui-egui/src/canvas/render.rs +++ b/crates/ui-egui/src/canvas/render.rs @@ -1,10 +1,9 @@ -use super::{Affine, CanvasLayout, Color32, DRect, DesignApp, Point, Rect, Xf}; +use super::{Affine, CanvasLayout, Color32, DRect, DesignApp, Point, Pos2, Rect, ScreenMode, Xf}; pub(super) fn c32(c: [u8; 3]) -> Color32 { Color32::from_rgb(c[0], c[1], c[2]) } -/// Render options for the canvas texture. /// The colour the canvas shows at screen point `pos` (the Color Picker's eyedropper): one device /// pixel rendered as the page is, over its paper. None off the pages. pub fn color_at(app: &mut DesignApp, ctx: &egui::Context, pos: Pos2) -> Option<[u8; 3]> { @@ -36,6 +35,7 @@ pub fn color_at(app: &mut DesignApp, ctx: &egui::Context, pos: Pos2) -> Option<[ Some([over(r, paper[0]), over(g, paper[1]), over(b, paper[2])]) } +/// Render options for the canvas texture. pub(super) fn screen_options(app: &DesignApp, layout: &CanvasLayout, preview: bool, ppp: f64) -> designcraft_render::RenderOptions { designcraft_render::RenderOptions { printing_only: preview, From 94209bec7e77f6fdcab3e2511c1617aa0e99a7ed Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:51:14 +0100 Subject: [PATCH 0466/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 2 +- crates/ui-egui/src/package_dialog.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 72ea2913e..1e1972ed6 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -3040,7 +3040,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { style_options_preview(app, &mut d); } // A multi-line field with focus (set by the dialog this frame) takes Enter as a new line. - let multiline = ui.ctx().data_mut(|m| m.remove_temp::(egui::Id::new(MULTILINE_FOCUS))).unwrap_or(false); + let multiline = ui.ctx().data_mut(|m| m.remove_temp::(egui::Id::unique(MULTILINE_FOCUS))).unwrap_or(false); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if ui .add( diff --git a/crates/ui-egui/src/package_dialog.rs b/crates/ui-egui/src/package_dialog.rs index 423870451..35b041d1f 100644 --- a/crates/ui-egui/src/package_dialog.rs +++ b/crates/ui-egui/src/package_dialog.rs @@ -308,7 +308,7 @@ pub fn show_instructions(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { } // Enter there makes a new line: the footer mustn't take it for Continue. if lines > 1 && resp.has_focus() { - ui.ctx().data_mut(|m| m.insert_temp(egui::Id::new(crate::dialogs::MULTILINE_FOCUS), true)); + ui.ctx().data_mut(|m| m.insert_temp(egui::Id::unique(crate::dialogs::MULTILINE_FOCUS), true)); } ui.end_row(); } @@ -392,7 +392,7 @@ mod tests { fn harness(app: DesignApp) -> Harness<'static, DesignApp> { Harness::builder().with_size(egui::vec2(1100.0, 760.0)).build_ui_state( |ui, app: &mut DesignApp| { - let key = egui::Id::new("package_test_fonts"); + let key = egui::Id::unique("package_test_fonts"); if ui.data(|d| d.get_temp::(key)).is_none() { crate::theme::install_fonts(ui.ctx(), ""); ui.data_mut(|d| d.insert_temp(key, true)); From e8b27c91f116515ff21e1ba03d6e88b6ff357e14 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:55:15 +0100 Subject: [PATCH 0467/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/package/tests.rs | 100 ++++++++++++------------- 1 file changed, 50 insertions(+), 50 deletions(-) diff --git a/crates/engine/src/cmd/package/tests.rs b/crates/engine/src/cmd/package/tests.rs index 124ea19c4..4d6513425 100644 --- a/crates/engine/src/cmd/package/tests.rs +++ b/crates/engine/src/cmd/package/tests.rs @@ -25,57 +25,57 @@ fn relocated_packages_rebind_embedded_image_links_on_open() { std::fs::remove_dir_all(dir).unwrap(); } - /// `pdf` takes file.exportPdf's options (a PDF preset's): a PDF/X-4 package PDF; `true` is the - /// default PDF, and bad options are refused. - #[test] - fn package_pdf_takes_export_options() { - let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); - let dir = std::env::temp_dir().join(format!("dc-package-pdf-options-{}-{nonce}", std::process::id())); - let mut s = Session::new(); - s.execute("file.new", &json!({"title": "Options", "width": 72, "height": 72})).unwrap(); - let x4 = dir.join("x4"); - s.execute("file.package", &json!({"dir": x4.to_string_lossy(), "idml": false, "pdf": {"standard": "x4"}})).unwrap(); - let has = |path: &std::path::Path, what: &[u8]| std::fs::read(path).unwrap().windows(what.len()).any(|w| w == what); - assert!(has(&x4.join("Options.pdf"), b"GTS_PDFX")); - let plain = dir.join("plain"); - s.execute("file.package", &json!({"dir": plain.to_string_lossy(), "idml": false, "pdf": true})).unwrap(); - assert!(!has(&plain.join("Options.pdf"), b"GTS_PDFX")); - // Refused before anything is written: bad options, a bad flattener or view option, and a - // `pdf` that is neither a switch nor options. - for bad in [ - json!({"standard": "nope"}), - json!({"flatten": "extreme"}), - json!({"pageLayout": "spiral"}), - json!({"view": "zoomed"}), - json!("print"), - json!(3), - ] { - let out = dir.join("bad"); - assert!(s.execute("file.package", &json!({"dir": out.to_string_lossy(), "pdf": bad})).is_err(), "{bad}"); - assert!(!out.exists(), "{bad}: bad options write nothing"); - } - std::fs::remove_dir_all(dir).unwrap(); +/// `pdf` takes file.exportPdf's options (a PDF preset's): a PDF/X-4 package PDF; `true` is the +/// default PDF, and bad options are refused. +#[test] +fn package_pdf_takes_export_options() { + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let dir = std::env::temp_dir().join(format!("dc-package-pdf-options-{}-{nonce}", std::process::id())); + let mut s = Session::new(); + s.execute("file.new", &json!({"title": "Options", "width": 72, "height": 72})).unwrap(); + let x4 = dir.join("x4"); + s.execute("file.package", &json!({"dir": x4.to_string_lossy(), "idml": false, "pdf": {"standard": "x4"}})).unwrap(); + let has = |path: &std::path::Path, what: &[u8]| std::fs::read(path).unwrap().windows(what.len()).any(|w| w == what); + assert!(has(&x4.join("Options.pdf"), b"GTS_PDFX")); + let plain = dir.join("plain"); + s.execute("file.package", &json!({"dir": plain.to_string_lossy(), "idml": false, "pdf": true})).unwrap(); + assert!(!has(&plain.join("Options.pdf"), b"GTS_PDFX")); + // Refused before anything is written: bad options, a bad flattener or view option, and a + // `pdf` that is neither a switch nor options. + for bad in [ + json!({"standard": "nope"}), + json!({"flatten": "extreme"}), + json!({"pageLayout": "spiral"}), + json!({"view": "zoomed"}), + json!("print"), + json!(3), + ] { + let out = dir.join("bad"); + assert!(s.execute("file.package", &json!({"dir": out.to_string_lossy(), "pdf": bad})).is_err(), "{bad}"); + assert!(!out.exists(), "{bad}: bad options write nothing"); } + std::fs::remove_dir_all(dir).unwrap(); +} - /// A preset that flattens transparency (Screen and Email's `flatten: low`) gives the packaged - /// PDF the flattening `file.exportPdf` does. - #[test] - fn the_packaged_pdf_is_flattened_as_export_flattens_it() { - let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); - let dir = std::env::temp_dir().join(format!("dc-package-pdf-flatten-{}-{nonce}", std::process::id())); - let mut s = Session::new(); - s.execute("file.new", &json!({"title": "Flat", "width": 144, "height": 144})).unwrap(); - let id = s.execute("frame.create", &json!({"rect": [10, 10, 100, 100], "content": "unassigned"})).unwrap()["id"].clone(); - s.execute("object.fill", &json!({"ids": [id], "swatch": "[Black]"})).unwrap(); - s.execute("object.opacity", &json!({"ids": [id], "opacity": 0.5})).unwrap(); - let exported = super::super::base64_decode(s.execute("file.exportPdf", &json!({"flatten": "low"})).unwrap()["base64"].as_str().unwrap()); - s.execute("file.package", &json!({"dir": dir.to_string_lossy(), "idml": false, "pdf": {"flatten": "low"}})).unwrap(); - let packaged = std::fs::read(dir.join("Flat.pdf")).unwrap(); - let images = |pdf: &[u8]| pdf.windows(b"/Subtype/Image".len()).filter(|w| *w == b"/Subtype/Image").count(); - assert!(images(&exported) > 0, "the export rasterises the transparent object"); - assert_eq!(images(&packaged), images(&exported), "so does the package"); - std::fs::remove_dir_all(dir).unwrap(); - } +/// A preset that flattens transparency (Screen and Email's `flatten: low`) gives the packaged +/// PDF the flattening `file.exportPdf` does. +#[test] +fn the_packaged_pdf_is_flattened_as_export_flattens_it() { + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let dir = std::env::temp_dir().join(format!("dc-package-pdf-flatten-{}-{nonce}", std::process::id())); + let mut s = Session::new(); + s.execute("file.new", &json!({"title": "Flat", "width": 144, "height": 144})).unwrap(); + let id = s.execute("frame.create", &json!({"rect": [10, 10, 100, 100], "content": "unassigned"})).unwrap()["id"].clone(); + s.execute("object.fill", &json!({"ids": [id], "swatch": "[Black]"})).unwrap(); + s.execute("object.opacity", &json!({"ids": [id], "opacity": 0.5})).unwrap(); + let exported = super::super::base64_decode(s.execute("file.exportPdf", &json!({"flatten": "low"})).unwrap()["base64"].as_str().unwrap()); + s.execute("file.package", &json!({"dir": dir.to_string_lossy(), "idml": false, "pdf": {"flatten": "low"}})).unwrap(); + let packaged = std::fs::read(dir.join("Flat.pdf")).unwrap(); + let images = |pdf: &[u8]| pdf.windows(b"/Subtype/Image".len()).filter(|w| *w == b"/Subtype/Image").count(); + assert!(images(&exported) > 0, "the export rasterises the transparent object"); + assert_eq!(images(&packaged), images(&exported), "so does the package"); + std::fs::remove_dir_all(dir).unwrap(); +} /// A per-placement PDF layer choice cannot travel in an IDML copy that links its files, so the /// report says the copies differ instead of leaving it to be discovered. @@ -221,7 +221,7 @@ fn package_writes_document_links_and_report() { assert!(out.join("Links").join("logo.svg").exists()); let report = std::fs::read_to_string(out.join("Instructions.txt")).unwrap(); assert!(report.contains("Print on matte.") && report.contains("logo.svg"), "{report}"); - assert!(report.find("Print on matte.") < report.find("Package report:"), "the instructions come first: {report}"); + assert!(report.find("Print on matte.") < report.find("Package report:"), "the instructions come first: {report}"); assert!(report.contains("Preflight:"), "{report}"); // The packaged document links to its Links folder. let doc_file = files.iter().find(|f| f.ends_with(".designcraft")).unwrap(); From 2a01caf0de75908da9830c0da8bf475db7ba2b13 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:59:47 +0100 Subject: [PATCH 0468/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 2 +- crates/ui-egui/src/package_dialog.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index d8d3f7f5a..175dcd5f4 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -3075,7 +3075,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { style_options_preview(app, &mut d); } // A multi-line field with focus (set by the dialog this frame) takes Enter as a new line. - let multiline = ui.ctx().data_mut(|m| m.remove_temp::(egui::Id::new(MULTILINE_FOCUS))).unwrap_or(false); + let multiline = ui.ctx().data_mut(|m| m.remove_temp::(egui::Id::unique(MULTILINE_FOCUS))).unwrap_or(false); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if ui .add( diff --git a/crates/ui-egui/src/package_dialog.rs b/crates/ui-egui/src/package_dialog.rs index 9583d84fe..eada9a244 100644 --- a/crates/ui-egui/src/package_dialog.rs +++ b/crates/ui-egui/src/package_dialog.rs @@ -335,7 +335,7 @@ pub fn show_instructions(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { } // Enter there makes a new line: the footer mustn't take it for Continue. if lines > 1 && resp.has_focus() { - ui.ctx().data_mut(|m| m.insert_temp(egui::Id::new(crate::dialogs::MULTILINE_FOCUS), true)); + ui.ctx().data_mut(|m| m.insert_temp(egui::Id::unique(crate::dialogs::MULTILINE_FOCUS), true)); } ui.end_row(); } @@ -420,7 +420,7 @@ mod tests { fn harness(app: DesignApp) -> Harness<'static, DesignApp> { Harness::builder().with_size(egui::vec2(1100.0, 760.0)).build_ui_state( |ui, app: &mut DesignApp| { - let key = egui::Id::new("package_test_fonts"); + let key = egui::Id::unique("package_test_fonts"); if ui.data(|d| d.get_temp::(key)).is_none() { crate::theme::install_fonts(ui.ctx(), ""); ui.data_mut(|d| d.insert_temp(key, true)); From 05a2fb4d3697ecc436129d180de49c4988e42f1d Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 23:05:27 +0100 Subject: [PATCH 0469/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/tests.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 20f6e9aba..b0c46f5ad 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3253,9 +3253,9 @@ fn new_character_style_opens_its_options_and_creates_the_style() { ctl(&mut app, "ui.dialog.set", json!({"field": "c.size", "value": 9})); assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); let st = char_style(&app, "Character Style 1").unwrap(); - // The selected text's own Italic (its Emphasis style) comes along, as InDesign's New - // Character Style takes it. - assert_eq!((st.based_on, st.chars), (None, CharAttrs { size: Some(9.0), font_style: Some("Italic".into()), ..Default::default() })); + // The selected text's own Italic (its Emphasis style) comes along, as InDesign's New + // Character Style takes it. + assert_eq!((st.based_on, st.chars), (None, CharAttrs { size: Some(9.0), font_style: Some("Italic".into()), ..Default::default() })); crate::menus::activate(&mut app, "style.character.create", &Value::Null); assert_eq!(app.ui.dialog.as_ref().unwrap().s("rename"), "Character Style 2"); } @@ -3271,8 +3271,8 @@ fn new_paragraph_style_opens_its_options_and_creates_the_style() { assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); let st = app.session.active().unwrap().doc.styles.para("Paragraph Style 1").cloned().unwrap(); assert_eq!(st.based_on.as_deref(), Some(designcraft_doc::BASIC_PARAGRAPH)); - // The selected text's own Italic comes along, as InDesign's New Paragraph Style takes it. - assert_eq!(st.chars, CharAttrs { size: Some(20.0), font_style: Some("Italic".into()), ..Default::default() }); + // The selected text's own Italic comes along, as InDesign's New Paragraph Style takes it. + assert_eq!(st.chars, CharAttrs { size: Some(20.0), font_style: Some("Italic".into()), ..Default::default() }); } #[test] From a05bf962e8d2ce0ec249127c12c57840f0c2264d Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 23:05:46 +0100 Subject: [PATCH 0470/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index d221100cd..e2877fb41 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3269,8 +3269,8 @@ fn new_paragraph_style_opens_its_options_and_creates_the_style() { assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); let st = app.session.active().unwrap().doc.styles.para("Paragraph Style 1").cloned().unwrap(); assert_eq!(st.based_on.as_deref(), Some(designcraft_doc::BASIC_PARAGRAPH)); - // The selected text's own Italic comes along, as InDesign's New Paragraph Style takes it. - assert_eq!(st.chars, CharAttrs { size: Some(20.0), font_style: Some("Italic".into()), ..Default::default() }); + // The selected text's own Italic comes along, as InDesign's New Paragraph Style takes it. + assert_eq!(st.chars, CharAttrs { size: Some(20.0), font_style: Some("Italic".into()), ..Default::default() }); } #[test] From 741fbe9fac2f4689e60b611015ab721437a36ada Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 23:06:21 +0100 Subject: [PATCH 0471/1349] Paragraph styles: create_para whole again, with the style name parameter helper before it Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/style/paragraph.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/style/paragraph.rs b/crates/engine/src/cmd/style/paragraph.rs index b7842daef..1f501cf7a 100644 --- a/crates/engine/src/cmd/style/paragraph.rs +++ b/crates/engine/src/cmd/style/paragraph.rs @@ -403,8 +403,6 @@ fn continue_numbering(p: Option<&Value>, para: &mut ParaAttrs) { } } -pub(super) fn create_para(s: &mut Session, p: &Value) -> Result { - let base = str_param(p, "name").unwrap_or("Paragraph Style 1").to_string(); /// The style `p[key]` names: none when absent or null; anything but a name is refused. fn style_name_param(cmd: &str, p: &Value, key: &str) -> Result> { match p.get(key) { @@ -414,7 +412,7 @@ fn style_name_param(cmd: &str, p: &Value, key: &str) -> Result> { } } -fn create_para(s: &mut Session, p: &Value) -> Result { +pub(super) fn create_para(s: &mut Session, p: &Value) -> Result { let base = str_param(p, "name").unwrap_or("Paragraph Style 1").to_string(); let based_on = style_name_param("style.paragraph.create", p, "basedOn")?; let next = style_name_param("style.paragraph.create", p, "nextStyle")?; From 991f51479fd008640d37551cb99cdebc23af14ec Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 23:19:46 +0100 Subject: [PATCH 0472/1349] TOC toggle test: the app's fonts installed first, as main's dialog tests do Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/tests.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 549b9b6dc..5dc50bd67 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3568,7 +3568,18 @@ fn enter_on_the_toc_options_toggle_only_toggles() { app.run("file.newSample", json!({})).unwrap(); open_toc(&mut app); let revision = app.session.doc().unwrap().revision; - let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(|ui, app: &mut DesignApp| show(app, ui.ctx()), app); + let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let key = egui::Id::unique("toc_toggle_test_fonts"); + if ui.data(|d| d.get_temp::(key)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(key, true)); + return; + } + show(app, ui.ctx()); + }, + app, + ); h.run_steps(3); h.get_by_label("Fewer Options").focus(); h.run_steps(2); From 50647c57204824200b0f71f24ee57de2c071ffa7 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 23:26:17 +0100 Subject: [PATCH 0473/1349] Printing instructions: each field named by its label, for screen readers Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/package_dialog.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/package_dialog.rs b/crates/ui-egui/src/package_dialog.rs index 35b041d1f..1919e6d9c 100644 --- a/crates/ui-egui/src/package_dialog.rs +++ b/crates/ui-egui/src/package_dialog.rs @@ -299,10 +299,11 @@ pub fn show_instructions(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { let lang = app.ui.language.clone(); egui::Grid::new("printing_instructions").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| { for (key, label, lines) in INSTRUCTION_FIELDS { - crate::rtl::label(ui, crate::i18n::tr(&lang, label)); + let name = crate::rtl::label(ui, crate::i18n::tr(&lang, label)); let mut text = d.s(key); let edit = if lines > 1 { egui::TextEdit::multiline(&mut text).desired_rows(lines) } else { egui::TextEdit::singleline(&mut text) }; - let resp = ui.add(edit.desired_width(320.0)); + // Named by its label, for screen readers. + let resp = ui.add(edit.desired_width(320.0)).labelled_by(name.id); if resp.changed() { d.fields.insert(key.into(), json!(text)); } From 261f698aa26141d6a03a765e025789ecceb1afe5 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 23:26:19 +0100 Subject: [PATCH 0474/1349] Printing instructions: each field named by its label, for screen readers Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/package_dialog.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/package_dialog.rs b/crates/ui-egui/src/package_dialog.rs index eada9a244..2225e3d08 100644 --- a/crates/ui-egui/src/package_dialog.rs +++ b/crates/ui-egui/src/package_dialog.rs @@ -326,10 +326,11 @@ pub fn show_instructions(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { let lang = app.ui.language.clone(); egui::Grid::new("printing_instructions").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| { for (key, label, lines) in INSTRUCTION_FIELDS { - crate::rtl::label(ui, crate::i18n::tr(&lang, label)); + let name = crate::rtl::label(ui, crate::i18n::tr(&lang, label)); let mut text = d.s(key); let edit = if lines > 1 { egui::TextEdit::multiline(&mut text).desired_rows(lines) } else { egui::TextEdit::singleline(&mut text) }; - let resp = ui.add(edit.desired_width(320.0)); + // Named by its label, for screen readers. + let resp = ui.add(edit.desired_width(320.0)).labelled_by(name.id); if resp.changed() { d.fields.insert(key.into(), json!(text)); } From 6557f20c80354f4a3d312d2d90dff73e975b5763 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 23:26:34 +0100 Subject: [PATCH 0475/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 18aabfae5..0bd0d39e6 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -61,8 +61,8 @@ use tool_overlays::draw_tool_overlays; pub(crate) use view::page_in_view; use view::present_fit; pub use view::{ - apply_view_request, can_go_through_history, current_page, current_parent_page, current_slot, current_spread, current_spread_page, drop_point, - PageBox, fit, go_through_history, go_to_page, page_box, page_box_go, set_zoom, show_spread, step_spread, view_centre, zoom_at, + PageBox, apply_view_request, can_go_through_history, current_page, current_parent_page, current_slot, current_spread, current_spread_page, + drop_point, fit, go_through_history, go_to_page, page_box, page_box_go, set_zoom, show_spread, step_spread, view_centre, zoom_at, }; pub const RULER: f32 = 15.0; From 840d75b46fc02128ca572ac62531925cf0206108 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 23:36:32 +0100 Subject: [PATCH 0476/1349] Find/Change: Find what, Change to and Search named by their captions, for screen readers Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 302a1b069..e245b2c5c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -2462,7 +2462,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { let formatted = d.fields.get(CHANGE_FORMAT).and_then(Value::as_object).is_some_and(|f| !f.is_empty()); egui::Grid::new("fc").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| { crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Find what:")); - text_field(ui, &mut d, "find", 260.0); + text_field_named(ui, &mut d, "find", 260.0, crate::i18n::tr(&app.ui.language, "Find what:")); ui.end_row(); ui.horizontal(|ui| { crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Change to:")); @@ -2477,9 +2477,9 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { ); } }); - text_field(ui, &mut d, "change", 260.0); + text_field_named(ui, &mut d, "change", 260.0, crate::i18n::tr(&app.ui.language, "Change to:")); ui.end_row(); - crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Search:")); + let scope_name = crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Search:")); let cur = d.s("scope"); craft_ui::ComboBox::from_id_salt("fcscope") .selected_text(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, &cur))) @@ -2491,7 +2491,9 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { app.session.reset_find_scope(); } } - }); + }) + .response + .labelled_by(scope_name.id); ui.end_row(); }); ui.horizontal(|ui| { From f61871deae5b570eba619465831c350f72eb1afd Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 23:36:33 +0100 Subject: [PATCH 0477/1349] Find/Change: Find what, Change to and Search named by their captions, for screen readers Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 84dc359dc..1a740a147 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -2474,7 +2474,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { ); } }); - text_field(ui, &mut d, "find", 260.0); + text_field_named(ui, &mut d, "find", 260.0, crate::i18n::tr(&app.ui.language, "Find what:")); ui.end_row(); ui.horizontal(|ui| { crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Change to:")); @@ -2489,9 +2489,9 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { ); } }); - text_field(ui, &mut d, "change", 260.0); + text_field_named(ui, &mut d, "change", 260.0, crate::i18n::tr(&app.ui.language, "Change to:")); ui.end_row(); - crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Search:")); + let scope_name = crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Search:")); let cur = d.s("scope"); // InDesign's names for the scopes. let scope_name = |v: &str| match v { @@ -2511,7 +2511,9 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { app.session.reset_find_scope(); } } - }); + }) + .response + .labelled_by(scope_name.id); ui.end_row(); }); ui.horizontal(|ui| { From c9621daa3635056c756a76a9ae4817873b3bf508 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 23:36:33 +0100 Subject: [PATCH 0478/1349] Find/Change: Find what, Change to and Search named by their captions, for screen readers Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6de0afa0a..fd96522cd 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -2474,7 +2474,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { ); } }); - text_field(ui, &mut d, "find", 260.0); + text_field_named(ui, &mut d, "find", 260.0, crate::i18n::tr(&app.ui.language, "Find what:")); ui.end_row(); ui.horizontal(|ui| { crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Change to:")); @@ -2489,9 +2489,9 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { ); } }); - text_field(ui, &mut d, "change", 260.0); + text_field_named(ui, &mut d, "change", 260.0, crate::i18n::tr(&app.ui.language, "Change to:")); ui.end_row(); - crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Search:")); + let scope_name = crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Search:")); let cur = d.s("scope"); craft_ui::ComboBox::from_id_salt("fcscope") .selected_text(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, &cur))) @@ -2503,7 +2503,9 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { app.session.reset_find_scope(); } } - }); + }) + .response + .labelled_by(scope_name.id); ui.end_row(); }); ui.horizontal(|ui| { From c35afdf719fce13b42cf2c81571b4a74d767acea Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 23:43:20 +0100 Subject: [PATCH 0479/1349] Insert Pages: Pages, Insert, its page and Parent named for screen readers; the page list is craft_ui's Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 40 ++++++++++++++++++++--------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 26f87dbdc..6c3690625 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -166,20 +166,20 @@ fn insert_pages_dialog(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { let mut parents = vec![(String::new(), crate::i18n::tr(&lang, "[None]").to_string())]; parents.extend(st.doc.parents.iter().map(|p| (p.id.0.to_string(), p.parent.as_ref().map(|i| i.label()).unwrap_or_default()))); egui::Grid::new("insert_pages").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| { - crate::rtl::label(ui, crate::i18n::tr(&lang, "Pages:")); + let name = crate::rtl::label(ui, crate::i18n::tr(&lang, "Pages:")); let mut n = d.n("count").unwrap_or(1.0).clamp(1.0, 9999.0) as u32; - if ui.add(egui::DragValue::new(&mut n).range(1..=9999)).changed() { + if ui.add(egui::DragValue::new(&mut n).range(1..=9999)).labelled_by(name.id).changed() { d.fields.insert("count".into(), json!(n)); } ui.end_row(); - crate::rtl::label(ui, crate::i18n::tr(&lang, "Insert:")); + let name = crate::rtl::label(ui, crate::i18n::tr(&lang, "Insert:")); ui.horizontal(|ui| { let wheres = [("after", "After Page"), ("before", "Before Page"), ("start", "At Start of Document"), ("end", "At End of Document")]; - translated_combo(&lang, ui, d, "insert", &wheres); + translated_combo(&lang, ui, d, "insert", &wheres).labelled_by(name.id); // The page, by name: At Start and At End need none. ui.add_enabled_ui(matches!(d.s("insert").as_str(), "after" | "before"), |ui| { let cur = (d.n("page").unwrap_or(0.0).max(0.0) as usize).min(pages.len().saturating_sub(1)); - egui::ComboBox::from_id_salt("insert_page").selected_text(pages.get(cur).cloned().unwrap_or_default()).width(64.0).show_ui( + craft_ui::ComboBox::from_id_salt("insert_page").selected_text(pages.get(cur).cloned().unwrap_or_default()).width(64.0).show_ui( ui, |ui| { for (i, name) in pages.iter().enumerate() { @@ -188,13 +188,15 @@ fn insert_pages_dialog(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { } } }, - ); + ) + .response + .accessible_name(crate::i18n::tr(&lang, "Page").to_owned()); }); }); ui.end_row(); - crate::rtl::label(ui, crate::i18n::tr(&lang, "Parent:")); + let name = crate::rtl::label(ui, crate::i18n::tr(&lang, "Parent:")); let opts: Vec<(&str, &str)> = parents.iter().map(|(v, l)| (v.as_str(), l.as_str())).collect(); - combo(ui, d, "parent", &opts); + combo(ui, d, "parent", &opts).labelled_by(name.id); ui.end_row(); }); } @@ -6226,22 +6228,26 @@ fn delete_character_style(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog }); } -fn combo(ui: &mut egui::Ui, d: &mut Dialog, key: &str, opts: &[(&str, &str)]) { +fn combo(ui: &mut egui::Ui, d: &mut Dialog, key: &str, opts: &[(&str, &str)]) -> egui::Response { let cur = d.s(key); let shown = opts.iter().find(|o| o.0 == cur).map_or(cur.as_str(), |o| o.1).to_string(); - craft_ui::ComboBox::from_id_salt(key).selected_text(crate::rtl::widget(ui, &shown)).width(170.0).show_ui(ui, |ui| { - for (v, label) in opts { - if ui.selectable_label(cur == *v, crate::rtl::widget(ui, *label)).clicked() { - d.fields.insert(key.into(), json!(v)); + craft_ui::ComboBox::from_id_salt(key) + .selected_text(crate::rtl::widget(ui, &shown)) + .width(170.0) + .show_ui(ui, |ui| { + for (v, label) in opts { + if ui.selectable_label(cur == *v, crate::rtl::widget(ui, *label)).clicked() { + d.fields.insert(key.into(), json!(v)); + } } - } - }); + }) + .response } /// Translate enum captions without changing serialized values or user-defined names. -fn translated_combo(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, key: &str, opts: &[(&str, &str)]) { +fn translated_combo(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, key: &str, opts: &[(&str, &str)]) -> egui::Response { let opts: Vec<_> = opts.iter().map(|(value, label)| (*value, crate::i18n::tr(lang, label))).collect(); - combo(ui, d, key, &opts); + combo(ui, d, key, &opts) } /// Style name picker (paragraph or character styles of the active document). From c6573d95577899826ccd000144df52d351c0b60c Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 23:46:49 +0100 Subject: [PATCH 0480/1349] Swatch rename test: the app's fonts installed first, as main's panel tests do; egui 0.37 Id::unique Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/swatches.rs | 55 ++++++++++++++++----------- 1 file changed, 33 insertions(+), 22 deletions(-) diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index 7652251c5..789474bbe 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -14,11 +14,11 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { // Another document (switched to, or moved to this one's place by a close) drops a rename in // place: a swatch of the same name there isn't the one being renamed. let uid = st.uid; - if ui.data(|d| d.get_temp::(egui::Id::new(RENAME_DOC))) != Some(uid) { + if ui.data(|d| d.get_temp::(egui::Id::unique(RENAME_DOC))) != Some(uid) { ui.data_mut(|d| { - d.remove_temp::<(String, String)>(egui::Id::new(RENAMING)); - d.remove_temp::<(String, f64)>(egui::Id::new(RENAME_CLICK)); - d.insert_temp(egui::Id::new(RENAME_DOC), uid); + d.remove_temp::<(String, String)>(egui::Id::unique(RENAMING)); + d.remove_temp::<(String, f64)>(egui::Id::unique(RENAME_CLICK)); + d.insert_temp(egui::Id::unique(RENAME_DOC), uid); }); } let target = super::color_target(app); @@ -262,9 +262,9 @@ fn folder_button(ui: &mut egui::Ui, tip: &str) -> egui::Response { /// The name field of a swatch being renamed in place, over `rect`; false when `sw` isn't. Enter or /// a click elsewhere renames it (`swatch.options`), Escape leaves it as it was. fn rename_field(app: &mut DesignApp, ui: &mut egui::Ui, sw: &designcraft_color::swatch::Swatch, rect: egui::Rect) -> bool { - let key = egui::Id::new(RENAMING); + let key = egui::Id::unique(RENAMING); let Some((name, mut text)) = ui.data(|d| d.get_temp::<(String, String)>(key)).filter(|(n, _)| *n == sw.name) else { return false }; - let id = egui::Id::new(("swatch_rename", &sw.name)); + let id = egui::Id::unique(("swatch_rename", &sw.name)); let edit = egui::TextEdit::singleline(&mut text).id(id).font(egui::FontId::proportional(12.5)).margin(vec2(2.0, 1.0)); let resp = ui.put(rect, edit); if !resp.has_focus() && !resp.lost_focus() { @@ -285,8 +285,8 @@ fn rename_field(app: &mut DesignApp, ui: &mut egui::Ui, sw: &designcraft_color:: // Still picked under its new name, unless the click that ended the rename picked // another swatch. Ok(_) => ui.data_mut(|d| { - if d.get_temp::(egui::Id::new(PICKED)).is_none_or(|p| p == name) { - d.insert_temp(egui::Id::new(PICKED), to.to_string()); + if d.get_temp::(egui::Id::unique(PICKED)).is_none_or(|p| p == name) { + d.insert_temp(egui::Id::unique(PICKED), to.to_string()); } }), Err(e) => { @@ -369,30 +369,30 @@ fn swatch_row( if resp.clicked() && !resp.double_clicked() { // A click on the name of the swatch picked already renames it in place, as InDesign's // (a slow double-click), unless it turns into a double-click. - let picked = ui.data(|d| d.get_temp::(egui::Id::new(PICKED))).is_some_and(|p| p == sw.name); + let picked = ui.data(|d| d.get_temp::(egui::Id::unique(PICKED))).is_some_and(|p| p == sw.name); // A click on another swatch cancels a rename still waiting. - ui.data_mut(|d| d.remove_temp::<(String, f64)>(egui::Id::new(RENAME_CLICK))); + ui.data_mut(|d| d.remove_temp::<(String, f64)>(egui::Id::unique(RENAME_CLICK))); if picked && !sw.locked && resp.interact_pointer_pos().is_some_and(|p| name_rect.contains(p)) { let now = ui.input(|i| i.time); - ui.data_mut(|d| d.insert_temp(egui::Id::new(RENAME_CLICK), (sw.name.clone(), now))); + ui.data_mut(|d| d.insert_temp(egui::Id::unique(RENAME_CLICK), (sw.name.clone(), now))); } ui.data_mut(|d| d.insert_temp(egui::Id::unique(PICKED), sw.name.clone())); let _ = super::apply_swatch(app, app.ui.stroke_front, &sw.name, None); } // Double-click: Swatch Options (the first click has applied the swatch). if resp.double_clicked() { - ui.data_mut(|d| d.remove_temp::<(String, f64)>(egui::Id::new(RENAME_CLICK))); + ui.data_mut(|d| d.remove_temp::<(String, f64)>(egui::Id::unique(RENAME_CLICK))); let _ = app.run("app.swatchOptionsDialog", json!({"name": sw.name})); } - if let Some((name, at)) = ui.data(|d| d.get_temp::<(String, f64)>(egui::Id::new(RENAME_CLICK))).filter(|(n, _)| *n == sw.name) { + if let Some((name, at)) = ui.data(|d| d.get_temp::<(String, f64)>(egui::Id::unique(RENAME_CLICK))).filter(|(n, _)| *n == sw.name) { let wait = ui.ctx().options(|o| o.input_options.max_double_click_delay); - if ui.data(|d| d.get_temp::(egui::Id::new(PICKED))).is_none_or(|p| p != name) { + if ui.data(|d| d.get_temp::(egui::Id::unique(PICKED))).is_none_or(|p| p != name) { // Another swatch picked since: no rename. - ui.data_mut(|d| d.remove_temp::<(String, f64)>(egui::Id::new(RENAME_CLICK))); + ui.data_mut(|d| d.remove_temp::<(String, f64)>(egui::Id::unique(RENAME_CLICK))); } else if ui.input(|i| i.time) - at > wait { ui.data_mut(|d| { - d.remove_temp::<(String, f64)>(egui::Id::new(RENAME_CLICK)); - d.insert_temp(egui::Id::new(RENAMING), (name.clone(), name)); + d.remove_temp::<(String, f64)>(egui::Id::unique(RENAME_CLICK)); + d.insert_temp(egui::Id::unique(RENAMING), (name.clone(), name)); }); } else { ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(wait)); @@ -1373,10 +1373,21 @@ mod swatches_header_tests { app.run("file.new", json!({})).unwrap(); let color = json!({"color": {"c": 14, "m": 8, "y": 95, "k": 0}}); let name = app.run("swatch.create", color.clone()).unwrap()["name"].as_str().unwrap().to_string(); - let mut h = Harness::builder().with_size(vec2(300.0, 520.0)).build_ui_state(|ui, app: &mut DesignApp| super::show(app, ui), app); - h.run_steps(2); + let mut h = Harness::builder().with_size(vec2(300.0, 520.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let id = egui::Id::unique("rename_test_fonts"); + if ui.data(|d| d.get_temp::(id)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(id, true)); + return; + } + super::show(app, ui); + }, + app, + ); + h.run_steps(3); let fields = h.query_all_by_role(egui::accesskit::Role::TextInput).count(); - let renaming = egui::Id::new(super::RENAMING); + let renaming = egui::Id::unique(super::RENAMING); h.ctx.data_mut(|d| d.insert_temp(renaming, (name.clone(), "Typed".to_string()))); h.run_steps(2); assert!(h.query_all_by_role(egui::accesskit::Role::TextInput).count() > fields, "the name is a field"); @@ -1400,7 +1411,7 @@ mod swatches_header_tests { // Frames 50 ms apart: the double-click time is six of them. let mut h = Harness::builder().with_size(vec2(300.0, 520.0)).with_step_dt(0.05).build_ui_state( |ui, app: &mut DesignApp| { - let id = egui::Id::new("test_fonts"); + let id = egui::Id::unique("test_fonts"); if ui.data(|d| d.get_temp::(id)).is_none() { crate::theme::install_fonts(ui.ctx(), ""); ui.data_mut(|d| d.insert_temp(id, true)); @@ -1467,7 +1478,7 @@ mod swatches_header_tests { assert!(!field(&h)); // A click on another swatch while the rename waits: that one is picked, and nothing // renames. - let picked = |h: &Harness<'_, DesignApp>| h.ctx.data(|d| d.get_temp::(egui::Id::new(super::PICKED))); + let picked = |h: &Harness<'_, DesignApp>| h.ctx.data(|d| d.get_temp::(egui::Id::unique(super::PICKED))); let (lemon, paper) = (name_at(&h, "Lemon Yellow Sun"), name_at(&h, "[Paper]")); h.run_steps(20); click(&mut h, lemon); From 9fdaa815849ed4800b1589f86ebc6f35042619d0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 29 Oct 2026 18:48:35 -0400 Subject: [PATCH 0481/1349] packaging: Flatpak finds and prints to CUPS printers (#2012) * packaging: Flatpak finds and prints to CUPS printers The Print dialog listed no printers in the Flatpak: the runtime has libcups but not lpstat/lp, the sandbox couldn't reach the CUPS socket, and driverless network printers (lpstat -e) need Avahi. Bundle lpstat/lp/lpoptions from CUPS 2.4.20 (Apache-2.0, statically linked, licence installed) and grant --socket=cups and --system-talk-name=org.freedesktop.Avahi in both manifests. * packaging: Flatpak reads the user's CUPS settings (~/.cups, read-only) Review (CodeRabbit): without it the sandbox's lp/lpstat ignore the user's default printer and saved options (lpoptions) and a print server named in their client.conf. * packaging: Flatpak CUPS tools reach the host socket when client.conf names a custom path Review: Flatpak mounts the host's CUPS socket at /var/run/cups/cups.sock whatever path ~/.cups/client.conf or CUPS_SERVER names, so lp/lpstat/lpoptions now run through a wrapper that points a socket path missing in the sandbox there. Server names (remote servers) and sockets that exist are left alone. Tested in the sandbox: CUPS_SERVER=/run/custom/cups.sock lists the host's printers through the wrapper and none without it; a host name is passed through unchanged. * packaging: redirect a custom CUPS socket only when it is the one Flatpak mounted Review (CodeRabbit): Flatpak picks the socket it mounts at /var/run/cups/cups.sock with stricter rules than CUPS (flatpak-run-cups.c: a socket CUPS_SERVER, else the first line spelled exactly "ServerName /path" in ~/.cups/client.conf, else the default), while CUPS reads the keyword in any case and takes the last ServerName. The wrapper now redirects only when CUPS' socket is the one Flatpak chose, so a job can't reach a different server; otherwise CUPS fails on the missing path. * packaging: never redirect a CUPS_SERVER the sandbox was given Review (CodeRabbit): Flatpak picks the socket it mounts from the host's CUPS_SERVER, so one set by flatpak run --env or an override may not be what it mounted. The wrapper now leaves any CUPS_SERVER alone and redirects only a client.conf socket that matches Flatpak's choice; otherwise CUPS fails on the missing path instead of reaching a different server. * packaging: point CUPS at the mounted socket only when it is the one Flatpak chose, else fail Review (CodeRabbit): with a custom socket listed first and the default last in ~/.cups/client.conf, Flatpak mounts the custom one at /var/run/cups/cups.sock while CUPS picks the last line, finds that path, and talks to the custom server. The wrapper now compares CUPS' socket with Flatpak's choice even when the path exists: equal, CUPS is pointed at the mount; different, the tool fails with an error instead of reaching another server. --- .../ai.storyteller.designcraft.bundle.yml | 52 +++++++++++++++++++ .../flatpak/ai.storyteller.designcraft.yml | 52 +++++++++++++++++++ 2 files changed, 104 insertions(+) diff --git a/packaging/linux/flatpak/ai.storyteller.designcraft.bundle.yml b/packaging/linux/flatpak/ai.storyteller.designcraft.bundle.yml index 755d2e2a3..09ac37d73 100644 --- a/packaging/linux/flatpak/ai.storyteller.designcraft.bundle.yml +++ b/packaging/linux/flatpak/ai.storyteller.designcraft.bundle.yml @@ -27,6 +27,14 @@ finish-args: - --share=network # GPU access for egui's renderer (Vulkan, or GL as a fallback). - --device=dri + # Printing: lpstat/lp (the cups-client module) reach the host's CUPS through its socket and + # find driverless network printers through Avahi (`lpstat -e`). Without these the Print + # dialog lists no printers. + - --socket=cups + - --system-talk-name=org.freedesktop.Avahi + # The user's CUPS settings, read-only: their default printer and saved options (lpoptions) + # and a print server named in their client.conf, which lp reaches over the network. + - --filesystem=~/.cups:ro # Open/Save, Place and Export go through the file-chooser portal (rfd's xdg-portal backend) # and drag-and-drop through the document portal, so picked files work anywhere without broad # filesystem access. Documents and Pictures are granted so files passed by path (the command @@ -35,6 +43,50 @@ finish-args: - --filesystem=xdg-pictures # Home/host filesystem access is deliberately not granted. modules: + # CUPS client tools for craft-print: the runtime has libcups but not lpstat/lp/lpoptions. + # Linked statically against this release's libcups, so a runtime update can't break them; + # the socket path matches the host's, which --socket=cups mounts. + - name: cups-client + buildsystem: simple + build-commands: + - ./configure --prefix=/app --sysconfdir=/etc --localstatedir=/var --with-rundir=/run/cups + --with-domainsocket=/run/cups/cups.sock --disable-shared --with-components=libcups + --with-dnssd=avahi --with-tls=gnutls --disable-pam --disable-dbus + - make -C cups libs + - make -C systemv lp lpoptions lpstat + - install -Dm755 -t /app/libexec/cups systemv/lp systemv/lpoptions systemv/lpstat + - for tool in lp lpoptions lpstat; do install -Dm755 cups-socket.sh "/app/bin/$tool"; done + - install -Dm644 -t /app/share/licenses/cups LICENSE NOTICE + sources: + - type: archive + url: https://github.com/OpenPrinting/cups/releases/download/v2.4.20/cups-2.4.20-source.tar.gz + sha256: ab4d9cd7f3e58060091d2b24972223d6401675f11c49b65abf4f6ef31dea22ff + # Runs each tool. Flatpak mounts the host's CUPS socket at /var/run/cups/cups.sock, choosing + # it as flatpak-run-cups.c does from the host's CUPS_SERVER, else the first line spelled + # exactly `ServerName /path` in ~/.cups/client.conf, else the default; it mounts nothing + # when that socket is missing. CUPS reads the keyword in any case and takes the last + # ServerName. When CUPS' socket from client.conf is the one Flatpak chose, it is pointed at + # the mount; when it isn't, the tool fails rather than reach a different server. A + # CUPS_SERVER is left alone: one set by `flatpak run --env` may not be what was mounted. + - type: script + dest-filename: cups-socket.sh + commands: + - 'conf="$HOME/.cups/client.conf"' + - 'if [ -z "${CUPS_SERVER:-}" ] && [ -r "$conf" ]; then' + - ' server=$(sed -n ''s/^[[:space:]]*[Ss][Ee][Rr][Vv][Ee][Rr][Nn][Aa][Mm][Ee][[:space:]]\{1,\}\([^[:space:]]*\).*/\1/p'' "$conf" | tail -n 1)' + - ' case "$server" in' + - ' /*)' + - ' mounted=$(sed -n ''s/^[[:space:]]*ServerName \(.*\)$/\1/p'' "$conf" | sed ''s/^[[:space:]]*//'' | grep -m 1 ''^/[^:]*$'')' + - ' if [ "$mounted" = "$server" ]; then' + - ' export CUPS_SERVER=/var/run/cups/cups.sock' + - ' else' + - ' echo "${0##*/}: ~/.cups/client.conf names the CUPS socket $server, but Flatpak gave this app ${mounted:-a different one}; give each socket one ServerName line, spelled ServerName" >&2' + - ' exit 1' + - ' fi' + - ' ;;' + - ' esac' + - 'fi' + - 'exec "/app/libexec/cups/${0##*/}" "$@"' - name: designcraft buildsystem: simple build-commands: diff --git a/packaging/linux/flatpak/ai.storyteller.designcraft.yml b/packaging/linux/flatpak/ai.storyteller.designcraft.yml index 1dc2ee4ed..bd456579f 100644 --- a/packaging/linux/flatpak/ai.storyteller.designcraft.yml +++ b/packaging/linux/flatpak/ai.storyteller.designcraft.yml @@ -28,6 +28,14 @@ finish-args: - --share=network # GPU access for egui's renderer (Vulkan, or GL as a fallback). - --device=dri + # Printing: lpstat/lp (the cups-client module) reach the host's CUPS through its socket and + # find driverless network printers through Avahi (`lpstat -e`). Without these the Print + # dialog lists no printers. + - --socket=cups + - --system-talk-name=org.freedesktop.Avahi + # The user's CUPS settings, read-only: their default printer and saved options (lpoptions) + # and a print server named in their client.conf, which lp reaches over the network. + - --filesystem=~/.cups:ro # Open/Save, Place and Export go through the file-chooser portal (rfd's xdg-portal backend) # and drag-and-drop through the document portal, so picked files work anywhere without broad # filesystem access. Documents and Pictures are granted so files passed by path (the command @@ -38,6 +46,50 @@ finish-args: build-options: append-path: /usr/lib/sdk/rust-stable/bin modules: + # CUPS client tools for craft-print: the runtime has libcups but not lpstat/lp/lpoptions. + # Linked statically against this release's libcups, so a runtime update can't break them; + # the socket path matches the host's, which --socket=cups mounts. + - name: cups-client + buildsystem: simple + build-commands: + - ./configure --prefix=/app --sysconfdir=/etc --localstatedir=/var --with-rundir=/run/cups + --with-domainsocket=/run/cups/cups.sock --disable-shared --with-components=libcups + --with-dnssd=avahi --with-tls=gnutls --disable-pam --disable-dbus + - make -C cups libs + - make -C systemv lp lpoptions lpstat + - install -Dm755 -t /app/libexec/cups systemv/lp systemv/lpoptions systemv/lpstat + - for tool in lp lpoptions lpstat; do install -Dm755 cups-socket.sh "/app/bin/$tool"; done + - install -Dm644 -t /app/share/licenses/cups LICENSE NOTICE + sources: + - type: archive + url: https://github.com/OpenPrinting/cups/releases/download/v2.4.20/cups-2.4.20-source.tar.gz + sha256: ab4d9cd7f3e58060091d2b24972223d6401675f11c49b65abf4f6ef31dea22ff + # Runs each tool. Flatpak mounts the host's CUPS socket at /var/run/cups/cups.sock, choosing + # it as flatpak-run-cups.c does from the host's CUPS_SERVER, else the first line spelled + # exactly `ServerName /path` in ~/.cups/client.conf, else the default; it mounts nothing + # when that socket is missing. CUPS reads the keyword in any case and takes the last + # ServerName. When CUPS' socket from client.conf is the one Flatpak chose, it is pointed at + # the mount; when it isn't, the tool fails rather than reach a different server. A + # CUPS_SERVER is left alone: one set by `flatpak run --env` may not be what was mounted. + - type: script + dest-filename: cups-socket.sh + commands: + - 'conf="$HOME/.cups/client.conf"' + - 'if [ -z "${CUPS_SERVER:-}" ] && [ -r "$conf" ]; then' + - ' server=$(sed -n ''s/^[[:space:]]*[Ss][Ee][Rr][Vv][Ee][Rr][Nn][Aa][Mm][Ee][[:space:]]\{1,\}\([^[:space:]]*\).*/\1/p'' "$conf" | tail -n 1)' + - ' case "$server" in' + - ' /*)' + - ' mounted=$(sed -n ''s/^[[:space:]]*ServerName \(.*\)$/\1/p'' "$conf" | sed ''s/^[[:space:]]*//'' | grep -m 1 ''^/[^:]*$'')' + - ' if [ "$mounted" = "$server" ]; then' + - ' export CUPS_SERVER=/var/run/cups/cups.sock' + - ' else' + - ' echo "${0##*/}: ~/.cups/client.conf names the CUPS socket $server, but Flatpak gave this app ${mounted:-a different one}; give each socket one ServerName line, spelled ServerName" >&2' + - ' exit 1' + - ' fi' + - ' ;;' + - ' esac' + - 'fi' + - 'exec "/app/libexec/cups/${0##*/}" "$@"' - name: designcraft buildsystem: simple build-options: From 515daea39311b71eee08a6c553da7dbd6992232a Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 23:54:42 +0100 Subject: [PATCH 0482/1349] Effects: one Mode row for both glows (main's Inner Glow picker and the branch's Outer Glow), craft_ui's dropdown Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/effects_dialog.rs | 20 ++------------------ 1 file changed, 2 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/effects_dialog.rs b/crates/ui-egui/src/effects_dialog.rs index fbf8c185a..cd536487b 100644 --- a/crates/ui-egui/src/effects_dialog.rs +++ b/crates/ui-egui/src/effects_dialog.rs @@ -360,23 +360,7 @@ fn page_ui(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, page: &str) { let key = page; heading(ui, &tr("Blending")); grid("b").show(ui, |ui| { - // Inner Glow: its blend mode (Screen, as InDesign starts it). - if key == "innerGlow" { - row(ui, "Mode:"); - let cur = d.fields.get("fx").and_then(|f| f["innerGlow"]["mode"].as_str()).unwrap_or("Screen").to_string(); - let label = |m: &designcraft_color::BlendMode| { - serde_json::to_value(m).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default() - }; - let shown = designcraft_color::BlendMode::ALL.iter().find(|m| label(m) == cur).map_or("Screen", |m| m.label()); - craft_ui::ComboBox::from_id_salt("fx_glow_mode").selected_text(tr(shown)).width(150.0).show_ui(ui, |ui| { - for m in designcraft_color::BlendMode::ALL { - if ui.selectable_label(label(&m) == cur, tr(m.label())).clicked() { - set(d, &["innerGlow", "mode"], json!(label(&m))); - } - } - }); - ui.end_row(); - } + mode_row(ui, d, key, &tr); row(ui, "Color:"); swatch(app, ui, d, &[key, "color"]); row(ui, "Opacity:"); @@ -576,7 +560,7 @@ fn mode_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, tr: &dyn Fn(&str) -> S let name = |m: &designcraft_color::BlendMode| serde_json::to_value(m).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(); let shown = designcraft_color::BlendMode::ALL.iter().find(|m| name(m) == cur).map_or(fallback, |m| m.label()); let mut picked = None; - egui::ComboBox::from_id_salt(("fx_mode", key.to_string())).selected_text(tr(shown)).width(150.0).show_ui(ui, |ui| { + craft_ui::ComboBox::from_id_salt(("fx_mode", key.to_string())).selected_text(tr(shown)).width(150.0).show_ui(ui, |ui| { for m in designcraft_color::BlendMode::ALL { if ui.selectable_label(name(&m) == cur, tr(m.label())).clicked() { picked = Some(name(&m)); From 3d03258989d29dade45c222d42f422dbb5893cc9 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 23:56:54 +0100 Subject: [PATCH 0483/1349] Preferences: the Tools Panel dropdown named by its label, for screen readers Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 7fb6037dc..1802a1fcf 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1998,8 +1998,8 @@ fn preferences(app: &crate::DesignApp, ui: &mut egui::Ui, d: &mut Dialog, max_he ui.add_space(8.0); crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&lang, "Panels")).font(semibold(12.0))); ui.horizontal(|ui| { - crate::rtl::label(ui, crate::i18n::tr(&lang, "Tools Panel:")); - translated_combo(&lang, ui, d, "toolsColumns", &[("single", "Single Column"), ("double", "Double Column")]); + let name = crate::rtl::label(ui, crate::i18n::tr(&lang, "Tools Panel:")); + translated_combo(&lang, ui, d, "toolsColumns", &[("single", "Single Column"), ("double", "Double Column")]).labelled_by(name.id); }); } "uiScaling" => { @@ -6131,22 +6131,26 @@ fn delete_character_style(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog }); } -fn combo(ui: &mut egui::Ui, d: &mut Dialog, key: &str, opts: &[(&str, &str)]) { +fn combo(ui: &mut egui::Ui, d: &mut Dialog, key: &str, opts: &[(&str, &str)]) -> egui::Response { let cur = d.s(key); let shown = opts.iter().find(|o| o.0 == cur).map_or(cur.as_str(), |o| o.1).to_string(); - craft_ui::ComboBox::from_id_salt(key).selected_text(crate::rtl::widget(ui, &shown)).width(170.0).show_ui(ui, |ui| { - for (v, label) in opts { - if ui.selectable_label(cur == *v, crate::rtl::widget(ui, *label)).clicked() { - d.fields.insert(key.into(), json!(v)); + craft_ui::ComboBox::from_id_salt(key) + .selected_text(crate::rtl::widget(ui, &shown)) + .width(170.0) + .show_ui(ui, |ui| { + for (v, label) in opts { + if ui.selectable_label(cur == *v, crate::rtl::widget(ui, *label)).clicked() { + d.fields.insert(key.into(), json!(v)); + } } - } - }); + }) + .response } /// Translate enum captions without changing serialized values or user-defined names. -fn translated_combo(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, key: &str, opts: &[(&str, &str)]) { +fn translated_combo(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, key: &str, opts: &[(&str, &str)]) -> egui::Response { let opts: Vec<_> = opts.iter().map(|(value, label)| (*value, crate::i18n::tr(lang, label))).collect(); - combo(ui, d, key, &opts); + combo(ui, d, key, &opts) } /// Style name picker (paragraph or character styles of the active document). From b622e045088fee1d05160a7255ef5b27b48556ea Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 00:00:22 +0100 Subject: [PATCH 0484/1349] Paragraph Style Options: Next Style named by its label, for screen readers; craft_ui dropdowns Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index e286dc94f..13d7e54b3 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -4396,7 +4396,7 @@ fn paragraph_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo let _ = crate::widgets::name_combo(combo, crate::i18n::tr(&app.ui.language, "Based On")); ui.end_row(); // Next Style: the style of the paragraph that follows when Enter ends this one. - crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Next Style:")); + let next_name = crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Next Style:")); let next = match d.fields.get("nextStyle") { Some(Value::String(n)) => Some(n.clone()), Some(_) => None, @@ -4404,7 +4404,7 @@ fn paragraph_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo }; let same = crate::i18n::tr(&app.ui.language, "[Same style]").to_string(); let shown = next.as_deref().map_or(same.clone(), |n| crate::i18n::style_name(&app.ui.language, n).to_string()); - egui::ComboBox::from_id_salt("psnext").selected_text(crate::rtl::widget(ui, shown)).width(220.0).show_ui(ui, |ui| { + craft_ui::ComboBox::from_id_salt("psnext").selected_text(crate::rtl::widget(ui, shown)).width(220.0).show_ui(ui, |ui| { if ui.selectable_label(next.is_none(), crate::rtl::widget(ui, &same)).clicked() { d.fields.insert("nextStyle".into(), Value::Null); } @@ -4416,7 +4416,9 @@ fn paragraph_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo d.fields.insert("nextStyle".into(), json!(n)); } } - }); + }) + .response + .labelled_by(next_name.id); ui.end_row(); }); // Reset To Base: the style keeps nothing of its own (the edits made here stay). @@ -5832,7 +5834,7 @@ fn char_number(ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, key: &str, su fn char_choice(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, key: &str, opts: &[(Value, &str)]) { let cur = cf.get(d, key); let shown = opts.iter().find(|o| o.0 == cur).map_or("", |o| crate::i18n::tr(lang, o.1)); - egui::ComboBox::from_id_salt(("cs", key)).selected_text(crate::rtl::widget(ui, shown)).width(140.0).show_ui(ui, |ui| { + craft_ui::ComboBox::from_id_salt(("cs", key)).selected_text(crate::rtl::widget(ui, shown)).width(140.0).show_ui(ui, |ui| { if cf.sparse && ui.selectable_label(cur.is_null(), " ").clicked() { cf.set(d, key, Value::Null); } From 1c3b9280024919ba742c9e663269f979543af4da Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 00:00:52 +0100 Subject: [PATCH 0485/1349] Dropdowns: craft_ui::ComboBox, as main's clippy configuration asks Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 9183444cf..256cfeaef 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -4412,7 +4412,7 @@ fn paragraph_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo }; let same = crate::i18n::tr(&app.ui.language, "[Same style]").to_string(); let shown = next.as_deref().map_or(same.clone(), |n| crate::i18n::style_name(&app.ui.language, n).to_string()); - egui::ComboBox::from_id_salt("psnext").selected_text(crate::rtl::widget(ui, shown)).width(220.0).show_ui(ui, |ui| { + craft_ui::ComboBox::from_id_salt("psnext").selected_text(crate::rtl::widget(ui, shown)).width(220.0).show_ui(ui, |ui| { if ui.selectable_label(next.is_none(), crate::rtl::widget(ui, &same)).clicked() { d.fields.insert("nextStyle".into(), Value::Null); } @@ -5857,7 +5857,7 @@ fn char_number(ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, key: &str, su fn char_choice(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, key: &str, opts: &[(Value, &str)]) { let cur = cf.get(d, key); let shown = opts.iter().find(|o| o.0 == cur).map_or("", |o| crate::i18n::tr(lang, o.1)); - egui::ComboBox::from_id_salt(("cs", key)).selected_text(crate::rtl::widget(ui, shown)).width(140.0).show_ui(ui, |ui| { + craft_ui::ComboBox::from_id_salt(("cs", key)).selected_text(crate::rtl::widget(ui, shown)).width(140.0).show_ui(ui, |ui| { if cf.sparse && ui.selectable_label(cur.is_null(), " ").clicked() { cf.set(d, key, Value::Null); } From 9c0ab48b9a4e8c9cb1d8e7bc0e8b8e0fb20372fa Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 00:00:55 +0100 Subject: [PATCH 0486/1349] Dropdowns: craft_ui::ComboBox, as main's clippy configuration asks Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 1a740a147..f3832a9d7 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -3511,7 +3511,7 @@ fn format_style_options(lang: &str, ui: &mut egui::Ui, fd: &mut Dialog, styles: crate::rtl::label(ui, crate::i18n::tr(lang, label)); let cur = fd.fields.get(key).and_then(Value::as_str).map(str::to_string); let shown = cur.as_deref().map_or_else(|| any.to_string(), |n| crate::i18n::style_name(lang, n).to_string()); - egui::ComboBox::from_id_salt(("format_style", key)).selected_text(crate::rtl::widget(ui, shown)).width(240.0).show_ui(ui, |ui| { + craft_ui::ComboBox::from_id_salt(("format_style", key)).selected_text(crate::rtl::widget(ui, shown)).width(240.0).show_ui(ui, |ui| { if ui.selectable_label(cur.is_none(), crate::rtl::widget(ui, any)).clicked() { fd.fields.remove(key); } From 5db160f9e8d6353ceac0767038d9cd2539b3ed80 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 00:00:56 +0100 Subject: [PATCH 0487/1349] Dropdowns: craft_ui::ComboBox, as main's clippy configuration asks Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index fd96522cd..35031149a 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -3476,7 +3476,7 @@ fn format_style_options(lang: &str, ui: &mut egui::Ui, fd: &mut Dialog, styles: crate::rtl::label(ui, crate::i18n::tr(lang, label)); let cur = fd.fields.get(key).and_then(Value::as_str).map(str::to_string); let shown = cur.as_deref().map_or_else(|| any.to_string(), |n| crate::i18n::style_name(lang, n).to_string()); - egui::ComboBox::from_id_salt(("format_style", key)).selected_text(crate::rtl::widget(ui, shown)).width(240.0).show_ui(ui, |ui| { + craft_ui::ComboBox::from_id_salt(("format_style", key)).selected_text(crate::rtl::widget(ui, shown)).width(240.0).show_ui(ui, |ui| { if ui.selectable_label(cur.is_none(), crate::rtl::widget(ui, any)).clicked() { fd.fields.remove(key); } From d865a7cca15fa7ed81d18e0bf6e2bad41e47a153 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 00:00:58 +0100 Subject: [PATCH 0488/1349] Dropdowns: craft_ui::ComboBox, as main's clippy configuration asks Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index e245b2c5c..805a5ffc6 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -3441,7 +3441,7 @@ fn format_style_options(lang: &str, ui: &mut egui::Ui, fd: &mut Dialog, styles: crate::rtl::label(ui, crate::i18n::tr(lang, label)); let cur = fd.fields.get(key).and_then(Value::as_str).map(str::to_string); let shown = cur.as_deref().map_or_else(|| any.to_string(), |n| crate::i18n::style_name(lang, n).to_string()); - egui::ComboBox::from_id_salt(("format_style", key)).selected_text(crate::rtl::widget(ui, shown)).width(240.0).show_ui(ui, |ui| { + craft_ui::ComboBox::from_id_salt(("format_style", key)).selected_text(crate::rtl::widget(ui, shown)).width(240.0).show_ui(ui, |ui| { if ui.selectable_label(cur.is_none(), crate::rtl::widget(ui, any)).clicked() { fd.fields.remove(key); } From 197f75941e179d5c9009fd52d75f58069c52b00c Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 00:01:01 +0100 Subject: [PATCH 0489/1349] Dropdowns: craft_ui::ComboBox, as main's clippy configuration asks Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/object_style_dialog.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/object_style_dialog.rs b/crates/ui-egui/src/object_style_dialog.rs index 61b7cbe7b..5ce0d56a5 100644 --- a/crates/ui-egui/src/object_style_dialog.rs +++ b/crates/ui-egui/src/object_style_dialog.rs @@ -333,7 +333,7 @@ fn page_ui(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, page: &str) { // Based On isn't editable yet: the style's parent, as it is. ui.add_enabled_ui(false, |ui| { let based = d.s("basedOn"); - egui::ComboBox::from_id_salt("os_based_on") + craft_ui::ComboBox::from_id_salt("os_based_on") .selected_text(crate::i18n::style_name(&app.ui.language, &based)) .width(220.0) .show_ui(ui, |_| {}); @@ -390,7 +390,7 @@ fn page_ui(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, page: &str) { let cur: designcraft_geom::corners::CornerShape = serde_json::from_value(get(d, &["corners", "corners"])[0]["shape"].clone()).unwrap_or_default(); let mut picked = None; - egui::ComboBox::from_id_salt("os_corner_shape").selected_text(tr(cur.label())).width(140.0).show_ui(ui, |ui| { + craft_ui::ComboBox::from_id_salt("os_corner_shape").selected_text(tr(cur.label())).width(140.0).show_ui(ui, |ui| { for s in designcraft_geom::corners::CornerShape::ALL { if ui.selectable_label(s == cur, tr(s.label())).clicked() { picked = Some(s); @@ -415,7 +415,7 @@ fn page_ui(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, page: &str) { let cur = d.s("paragraphStyle"); let shown = if cur.is_empty() { String::new() } else { crate::i18n::style_name(&app.ui.language, &cur).to_string() }; let mut picked = None; - egui::ComboBox::from_id_salt("os_paragraph_style").selected_text(shown).width(240.0).show_ui(ui, |ui| { + craft_ui::ComboBox::from_id_salt("os_paragraph_style").selected_text(shown).width(240.0).show_ui(ui, |ui| { for s in &doc.styles.paragraph { if ui.selectable_label(s.name == cur, crate::i18n::style_name(&app.ui.language, &s.name)).clicked() { picked = Some(s.name.clone()); @@ -472,7 +472,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { crate::rtl::label(ui, tr("Effects for:")); // Stroke, Fill and Text levels aren't in the document model yet: the object only. ui.add_enabled_ui(false, |ui| { - egui::ComboBox::from_id_salt("os_fx_level").selected_text(tr("Object")).width(100.0).show_ui(ui, |_| {}); + craft_ui::ComboBox::from_id_salt("os_fx_level").selected_text(tr("Object")).width(100.0).show_ui(ui, |_| {}); }); }); for (key, label) in crate::effects_dialog::PAGES.iter().skip(1) { From 63340f51a55d358773c72c52f03c4e1977e7647e Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 00:01:06 +0100 Subject: [PATCH 0490/1349] Dropdowns: craft_ui::ComboBox, as main's clippy configuration asks Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index cbf7ea6a6..82221a4d1 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -4616,7 +4616,7 @@ fn swatch_menu_with( Some(label) if current == designcraft_doc::TEXT_COLOR => label, _ => current, }; - egui::ComboBox::from_id_salt(id).selected_text(shown).width(width).show_ui(ui, |ui| { + craft_ui::ComboBox::from_id_salt(id).selected_text(shown).width(width).show_ui(ui, |ui| { if let Some(label) = text_color && ui.selectable_label(current == designcraft_doc::TEXT_COLOR, label).clicked() { @@ -6476,7 +6476,7 @@ fn paragraph_rules(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, prefix: & designcraft_doc::StrokeType::Style { name } => name.clone(), k => crate::i18n::tr(lang, k.label()).to_string(), }; - egui::ComboBox::from_id_salt(("rule_type", which)).selected_text(crate::rtl::widget(ui, shown)).width(130.0).show_ui(ui, |ui| { + craft_ui::ComboBox::from_id_salt(("rule_type", which)).selected_text(crate::rtl::widget(ui, shown)).width(130.0).show_ui(ui, |ui| { for k in rule_types().into_iter().chain(custom.into_iter().map(|name| designcraft_doc::StrokeType::Style { name })) { let label = match &k { designcraft_doc::StrokeType::Style { name } => name.clone(), From 454d5ca10cbb9111d5a41d6bcf33939577880052 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 00:01:08 +0100 Subject: [PATCH 0491/1349] Dropdowns: craft_ui::ComboBox, as main's clippy configuration asks Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index f4b5730e6..5896fdfee 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -4572,7 +4572,7 @@ fn para_choice(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: & fn para_choice_width(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, opts: &[(&str, &str)], width: f32) { let cur = para_value(d, pv, key); let shown = opts.iter().find(|o| cur == o.0).map_or("", |o| crate::i18n::tr(lang, o.1)); - egui::ComboBox::from_id_salt(("pschoice", key)).selected_text(crate::rtl::widget(ui, shown)).width(width).show_ui(ui, |ui| { + craft_ui::ComboBox::from_id_salt(("pschoice", key)).selected_text(crate::rtl::widget(ui, shown)).width(width).show_ui(ui, |ui| { for (v, label) in opts { if ui.selectable_label(cur == *v, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() { para_set(d, key, json!(v)); From 693e9b13a888f1664c3d6ba342eca7744d2abb86 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 00:01:11 +0100 Subject: [PATCH 0492/1349] Dropdowns: craft_ui::ComboBox, as main's clippy configuration asks Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 17f9129f1..3beaa0964 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -226,7 +226,7 @@ fn convert_table_dialog(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { label(ui, "Table Style", true); let names: Vec = app.session.active().map(|st| st.doc.styles.table.iter().map(|s| s.name.clone()).collect()).unwrap_or_default(); let cur = table_style_field(d).unwrap_or_else(|| designcraft_doc::BASIC_TABLE.to_string()); - egui::ComboBox::from_id_salt("convert_table_style").selected_text(&cur).width(170.0).show_ui(ui, |ui| { + craft_ui::ComboBox::from_id_salt("convert_table_style").selected_text(&cur).width(170.0).show_ui(ui, |ui| { for n in &names { if ui.selectable_label(*n == cur, n).clicked() { d.fields.insert("tableStyle".into(), json!(n)); @@ -286,7 +286,7 @@ fn insert_table_dialog(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { let cur = table_style_field(d).unwrap_or_else(|| designcraft_doc::BASIC_TABLE.to_string()); ui.horizontal(|ui| { crate::rtl::label(ui, format!("{}:", crate::i18n::tr(lang, "Table Style"))); - egui::ComboBox::from_id_salt("ins_table_style").selected_text(&cur).width(160.0).show_ui(ui, |ui| { + craft_ui::ComboBox::from_id_salt("ins_table_style").selected_text(&cur).width(160.0).show_ui(ui, |ui| { for n in &names { if ui.selectable_label(*n == cur, n).clicked() { d.fields.insert("tableStyle".into(), json!(n)); From 4814096392a75001630b50b98ca9a89dba07267d Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 00:01:12 +0100 Subject: [PATCH 0493/1349] Dropdowns: craft_ui::ComboBox, as main's clippy configuration asks Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6db142dcd..d7e67d2fc 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -198,7 +198,7 @@ fn insert_table_dialog(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { let cur = table_style_field(d).unwrap_or_else(|| designcraft_doc::BASIC_TABLE.to_string()); ui.horizontal(|ui| { crate::rtl::label(ui, format!("{}:", crate::i18n::tr(lang, "Table Style"))); - egui::ComboBox::from_id_salt("ins_table_style").selected_text(&cur).width(160.0).show_ui(ui, |ui| { + craft_ui::ComboBox::from_id_salt("ins_table_style").selected_text(&cur).width(160.0).show_ui(ui, |ui| { for n in &names { if ui.selectable_label(*n == cur, n).clicked() { d.fields.insert("tableStyle".into(), json!(n)); From cd612b1836a79153f5b6de432092ffbe924cee37 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 00:04:27 +0100 Subject: [PATCH 0494/1349] Package: the PDF Preset dropdown named by its label, for screen readers; craft_ui's dropdown Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/package_dialog.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/package_dialog.rs b/crates/ui-egui/src/package_dialog.rs index 2225e3d08..536c5e4ac 100644 --- a/crates/ui-egui/src/package_dialog.rs +++ b/crates/ui-egui/src/package_dialog.rs @@ -278,9 +278,9 @@ pub fn show(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { ui.add_enabled_ui(d.b("pdf"), |ui| { ui.horizontal(|ui| { ui.add_space(24.0); - crate::rtl::label(ui, tr("PDF Preset:")); + let name = crate::rtl::label(ui, tr("PDF Preset:")); let cur = d.s("pdfPreset"); - egui::ComboBox::from_id_salt("package_pdf_preset").selected_text(crate::rtl::widget(ui, tr(&cur))).width(180.0).show_ui( + craft_ui::ComboBox::from_id_salt("package_pdf_preset").selected_text(crate::rtl::widget(ui, tr(&cur))).width(180.0).show_ui( ui, |ui| { for p in crate::dialogs::pdf_presets() { @@ -289,7 +289,9 @@ pub fn show(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { } } }, - ); + ) + .response + .labelled_by(name.id); }); }); } From 9d30ad7e7bdfdcd6906628c3e219972adb342145 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 00:19:51 +0100 Subject: [PATCH 0495/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/properties.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 67c28f601..c27a3618b 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -32,8 +32,8 @@ pub(crate) use links::run_update_links; pub use links::{info_panel, links_panel, preflight_panel, update_links}; use object::{align_row, appearance_section, guide_section, quick_actions_object, transform_section, wrap_section}; pub(crate) use object::{corner_type_dropdown, ref_point_proxy, stroke_type_dropdown}; -use object_panels::{anchor_point_sections, pathfinder_row}; pub use object_panels::{align_panel, attributes_panel, effects_panel, pathfinder_panel, stroke_panel, wrap_panel}; +use object_panels::{anchor_point_sections, pathfinder_row}; pub(crate) use text::{LANGUAGES, kerning_control, language_menu}; use text::{ bullets_section, character_section, paragraph_section, quick_actions_text, text_appearance_section, text_frame_section, text_style_section, From 34d97eae377e27f7141ade69f4e999ed1b0bce2f Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 00:20:02 +0100 Subject: [PATCH 0496/1349] Page box test: the menu's entries found among the names the window shows elsewhere too Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/chrome/tests.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index eb84e74ca..742aba403 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -203,16 +203,18 @@ fn the_page_box_names_the_parent_in_view_and_lists_the_parents() { h.get_by(|n| n.role() == Role::ComboBox && n.label().as_deref() == Some("Page")).click(); h.run_steps(3); for name in ["1", "2", "3", "4", "A-Parent"] { - assert!(h.query_by_label(name).is_some(), "{name} is listed"); + // The canvas or a panel may show the name too: the menu lists it. + assert!(h.query_all_by_label(name).next().is_some(), "{name} is listed"); } - h.get_by_label("B-Cover").click(); + // The menu, drawn last, holds the last match. + h.get_all_by_label("B-Cover").last().unwrap().click(); h.run_steps(6); assert_eq!(shown(&h), "B-Cover"); assert_eq!(crate::canvas::current_parent_page(&h.state().app).map(|(i, _)| i), Some(1)); // A page: the parents are left. h.get_by(|n| n.role() == Role::ComboBox && n.label().as_deref() == Some("Page")).click(); h.run_steps(3); - h.get_by_label("3").click(); + h.get_all_by_label("3").last().unwrap().click(); h.run_steps(6); assert!(!h.state().app.session.active().unwrap().editing_parents); assert_eq!(crate::canvas::current_page(&h.state().app), Some(2)); From d0fce7e9a3cc93340a3be02cef9e3681848b7c51 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Thu, 29 Oct 2026 21:38:46 -0400 Subject: [PATCH 0497/1349] Declare Spanish and Simplified Chinese in CFBundleLocalizations Both are interface languages in LANGUAGES but were missing from the list. Co-Authored-By: Claude Opus 5.5 --- packaging/macos/Info.plist.in | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packaging/macos/Info.plist.in b/packaging/macos/Info.plist.in index 1fbabdee2..5fdf8a278 100644 --- a/packaging/macos/Info.plist.in +++ b/packaging/macos/Info.plist.in @@ -14,6 +14,7 @@ ar cs de + es fr it ja @@ -22,6 +23,7 @@ pt-BR ru uk + zh-Hans CFBundleDisplayName DesignCraft From 84801932f2897a4b355e634132f58c7d2ae01996 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Thu, 29 Oct 2026 21:39:23 -0400 Subject: [PATCH 0498/1349] Renumbering duplicate ids stops at the top of the id range instead of overflowing Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/lib.rs | 5 ++++- crates/format/src/tests.rs | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 08ba34ca0..fecb2c3b4 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -1007,7 +1007,10 @@ impl Document { return; } if !seen.insert(old) { - next += 1; + // An id at the top of the range has no successor: leave the duplicate for + // `check()` to refuse rather than overflow. + let Some(n) = next.checked_add(1) else { return }; + next = n; it.id = ItemId(next); } if let Some(t) = it.text_frame() { diff --git a/crates/format/src/tests.rs b/crates/format/src/tests.rs index 702428d14..882f5e6b8 100644 --- a/crates/format/src/tests.rs +++ b/crates/format/src/tests.rs @@ -822,3 +822,17 @@ fn duplicate_anchored_item_ids_are_renumbered() { assert_eq!(anchored[0].1.shape, Shape::Oval); assert_ne!(anchored[0].1.id, g); } + +#[test] +fn duplicate_ids_at_the_top_of_the_range_do_not_overflow() { + let mut d = Document::new(&NewDocument::default()); + let one = png_asset(&mut d, &[1]); + let two = png_asset(&mut d, &[2]); + place(&mut d, one, 0.0); + place(&mut d, two, 0.0); + set_item_id(&mut d, 0, designcraft_doc::ItemId(u64::MAX)); + set_item_id(&mut d, 1, designcraft_doc::ItemId(u64::MAX)); + d.renumber_duplicate_items(); + assert_eq!(all_item_ids(&d), vec![u64::MAX, u64::MAX]); + assert!(d.check().is_err()); +} From a9256308e32ee8cadd2051226986003ff80fbcb9 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Thu, 29 Oct 2026 21:39:35 -0400 Subject: [PATCH 0499/1349] Keep at least four wrap passes for a story with few anchored objects A single wrapping object moved by keep options or vertical justification had four passes to settle before; one-per-object would have given it two. Co-Authored-By: Claude Opus 5.5 --- crates/compose/src/wrap.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/compose/src/wrap.rs b/crates/compose/src/wrap.rs index 7d38f0ef8..724310b00 100644 --- a/crates/compose/src/wrap.rs +++ b/crates/compose/src/wrap.rs @@ -15,7 +15,8 @@ //! moving. An object's wrap can push the anchors of the objects after it, so a chain of n such //! objects needs n + 1 more compositions: the k-th pass places the (k + 1)-th object where the //! wraps before it leave its anchor, and the last pass wraps around the last object. The story -//! is composed at most that many more times, and never more than [`MAX_PASSES`]. +//! is composed at most that many more times (at least [`MIN_PASSES`]), and never more than +//! [`MAX_PASSES`]. use designcraft_doc::{AnchorPosition, AnchoredObject, Document, Item, OBJECT_MARK, PageSide, SpreadRef, Story, StoryId, WrapMode}; use designcraft_geom::Affine; @@ -24,9 +25,13 @@ use crate::{ComposeOptions, ComposedStory, Exclusion, FrameSpec}; /// Most extra compositions of a story with its own anchored objects' wrap, however many objects /// it has; a layout that keeps moving its objects (keep options, vertical justification) stops -/// sooner, after one per object and one more. +/// sooner, after one per object and one more (but never fewer than [`MIN_PASSES`]). pub(crate) const MAX_PASSES: usize = 64; +/// Fewest extra compositions allowed before giving up on a layout that keeps moving: a single +/// object that keep options or vertical justification move still gets the room it had before. +const MIN_PASSES: usize = 4; + /// How far an obstacle may move between passes and still count as settled (points). const SETTLED: f64 = 0.01; @@ -205,7 +210,7 @@ pub(crate) fn compose_among(doc: &Document, sid: StoryId, opts: &ComposeOptions, } let own = st.objects.iter().filter(|o| wraps(o) && !matches!(o.position, AnchorPosition::Inline { .. })).count(); let mut prev = vec![Vec::new(); specs.len()]; - for _ in 0..(own + 1).min(MAX_PASSES) { + for _ in 0..(own + 1).max(MIN_PASSES).min(MAX_PASSES) { let added = exclusions(doc, &specs, &obstacles(doc, st, &out, true)); if settled(&added, &prev) { break; From e6e478bccba5eb3fc46a77d16909afaaa4eaa77e Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Thu, 29 Oct 2026 21:39:41 -0400 Subject: [PATCH 0500/1349] Leave the Windows print test to #1840 The expectation change is unrelated to hyphenation and lands with #1840. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/print.rs | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index dfa0a410d..e71c230de 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -86,15 +86,7 @@ mod tests { } else { assert_eq!( command, - [ - "xps-print", - "printer=Office", - "copies=2", - "collate=true", - "duplex=(queue default)", - "scaling=shrink-to-fit", - "color=(driver default)" - ] + ["xps-print", "printer=Office", "copies=2", "collate=true", "duplex=(queue default)", "scaling=shrink-to-fit", "color=color"] ); } assert!(r["bytes"].as_u64().unwrap() > 500); From 794b7a29de1c754f73ec415f4187061e856cf1a7 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Thu, 29 Oct 2026 21:39:56 -0400 Subject: [PATCH 0501/1349] Hold the guide-drag cursor only while the primary button is down Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 19bcb87e3..bf8a88563 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -744,8 +744,10 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { None => c, }; // A ruler guide being dragged keeps the cursor across it until it is dropped, over the - // canvas too (the tool's cursor took over as soon as the pointer left the ruler). - let c = match ui.data(|d| d.get_temp::(egui::Id::unique(GUIDE_DRAG))).map(|g| g.orientation) { + // canvas too (the tool's cursor took over as soon as the pointer left the ruler). Only + // while the button is down: a drag state left behind by a skipped release doesn't stick. + let dragging = ui.input(|i| i.pointer.primary_down()); + let c = match ui.data(|d| d.get_temp::(egui::Id::unique(GUIDE_DRAG))).filter(|_| dragging).map(|g| g.orientation) { Some(designcraft_doc::Orientation::Horizontal) => Cursor::ResizeV, Some(designcraft_doc::Orientation::Vertical) => Cursor::ResizeH, None => c, From 44b07403b1502cd676108f75f81b895dda4a2348 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Thu, 29 Oct 2026 21:40:04 -0400 Subject: [PATCH 0502/1349] Draw a checkbox's border at the item's stroke weight Co-Authored-By: Claude Opus 5.5 --- crates/pdf/src/forms.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/pdf/src/forms.rs b/crates/pdf/src/forms.rs index bf0d955fc..73165dc7a 100644 --- a/crates/pdf/src/forms.rs +++ b/crates/pdf/src/forms.rs @@ -179,7 +179,7 @@ pub(crate) fn add_fields(pdf: &[u8], fields: &[Placed], media: &[PlacedMedia]) - FieldKind::CheckBox => { // Appearances: an empty box, and a box with a check mark. let border = - if *bw > 0.0 { format!("0.45 G 1 w 0.5 0.5 {:.2} {:.2} re S", (w - 1.0).max(0.0), (h - 1.0).max(0.0)) } else { String::new() }; + if *bw > 0.0 { format!("0.45 G {bw:.2} w {i:.2} {i:.2} {:.2} {:.2} re S", (w - bw).max(0.0), (h - bw).max(0.0), i = bw / 2.0) } else { String::new() }; let check = format!( "{border} 0 g {:.2} w 1 J 1 j {:.2} {:.2} m {:.2} {:.2} l {:.2} {:.2} l S", (w.min(h) * 0.12).max(0.8), From 56eebe9556b55eda9fc624968f764dafb3c062ab Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Thu, 29 Oct 2026 21:40:24 -0400 Subject: [PATCH 0503/1349] Keep the host frame's text area across anchored text frames in PDF export Co-Authored-By: Claude Opus 5.5 --- crates/pdf/src/export/walk.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/pdf/src/export/walk.rs b/crates/pdf/src/export/walk.rs index d8a4d2739..cf96dac25 100644 --- a/crates/pdf/src/export/walk.rs +++ b/crates/pdf/src/export/walk.rs @@ -396,9 +396,12 @@ impl Exporter<'_> { if local != Affine::IDENTITY { s.push_transform(&tf(local)); } - self.text_area = (local.determinant().abs() > 1e-12).then(|| local.inverse().transform_rect_bbox(it.inner_bounds())); + // Anchored text frames now draw inside `frame_text`: restore the host's area + // after, so an object drawn there doesn't clear it for the host's glyphs. + let area = (local.determinant().abs() > 1e-12).then(|| local.inverse().transform_rect_bbox(it.inner_bounds())); + let outer = std::mem::replace(&mut self.text_area, area); drawn = self.frame_text(s, &cs, ft, text, Some((xf * local, page))); - self.text_area = None; + self.text_area = outer; if local != Affine::IDENTITY { s.pop(); } From 680dfdc964b3dd86858326fc44c1f963f3f9fc4c Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Thu, 29 Oct 2026 21:41:41 -0400 Subject: [PATCH 0504/1349] Format the checkbox border Co-Authored-By: Claude Opus 5.5 --- crates/pdf/src/forms.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/pdf/src/forms.rs b/crates/pdf/src/forms.rs index 73165dc7a..90234859d 100644 --- a/crates/pdf/src/forms.rs +++ b/crates/pdf/src/forms.rs @@ -178,8 +178,11 @@ pub(crate) fn add_fields(pdf: &[u8], fields: &[Placed], media: &[PlacedMedia]) - } FieldKind::CheckBox => { // Appearances: an empty box, and a box with a check mark. - let border = - if *bw > 0.0 { format!("0.45 G {bw:.2} w {i:.2} {i:.2} {:.2} {:.2} re S", (w - bw).max(0.0), (h - bw).max(0.0), i = bw / 2.0) } else { String::new() }; + let border = if *bw > 0.0 { + format!("0.45 G {bw:.2} w {i:.2} {i:.2} {:.2} {:.2} re S", (w - bw).max(0.0), (h - bw).max(0.0), i = bw / 2.0) + } else { + String::new() + }; let check = format!( "{border} 0 g {:.2} w 1 J 1 j {:.2} {:.2} m {:.2} {:.2} l {:.2} {:.2} l S", (w.min(h) * 0.12).max(0.8), From cc47975960edb8ff3993b35f160dcbf9664a06c5 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Thu, 29 Oct 2026 21:43:16 -0400 Subject: [PATCH 0505/1349] Use clamp for the wrap pass bounds Co-Authored-By: Claude Opus 5.5 --- crates/compose/src/wrap.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/compose/src/wrap.rs b/crates/compose/src/wrap.rs index 724310b00..f28bba424 100644 --- a/crates/compose/src/wrap.rs +++ b/crates/compose/src/wrap.rs @@ -31,6 +31,8 @@ pub(crate) const MAX_PASSES: usize = 64; /// Fewest extra compositions allowed before giving up on a layout that keeps moving: a single /// object that keep options or vertical justification move still gets the room it had before. const MIN_PASSES: usize = 4; +// `clamp` needs min <= max. +const _: () = assert!(MIN_PASSES <= MAX_PASSES); /// How far an obstacle may move between passes and still count as settled (points). const SETTLED: f64 = 0.01; @@ -210,7 +212,7 @@ pub(crate) fn compose_among(doc: &Document, sid: StoryId, opts: &ComposeOptions, } let own = st.objects.iter().filter(|o| wraps(o) && !matches!(o.position, AnchorPosition::Inline { .. })).count(); let mut prev = vec![Vec::new(); specs.len()]; - for _ in 0..(own + 1).max(MIN_PASSES).min(MAX_PASSES) { + for _ in 0..(own + 1).clamp(MIN_PASSES, MAX_PASSES) { let added = exclusions(doc, &specs, &obstacles(doc, st, &out, true)); if settled(&added, &prev) { break; From eace4735dac32df6785e82718991f391bdc5ac97 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Thu, 29 Oct 2026 21:43:49 -0400 Subject: [PATCH 0506/1349] Draw the checkbox border in its own function Keeps add_fields under the cognitive complexity limit. Co-Authored-By: Claude Opus 5.5 --- crates/pdf/src/forms.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/pdf/src/forms.rs b/crates/pdf/src/forms.rs index 90234859d..e36478971 100644 --- a/crates/pdf/src/forms.rs +++ b/crates/pdf/src/forms.rs @@ -79,6 +79,16 @@ fn pdf_string(s: &str) -> String { o } +/// A checkbox appearance's border: the item's stroke weight, inset by half of it so it stays +/// inside the box; nothing for an unstroked item. +fn checkbox_border(bw: f64, w: f64, h: f64) -> String { + if bw > 0.0 { + format!("0.45 G {bw:.2} w {i:.2} {i:.2} {:.2} {:.2} re S", (w - bw).max(0.0), (h - bw).max(0.0), i = bw / 2.0) + } else { + String::new() + } +} + /// Add `fields` and `media` to `pdf` (page indices in output order). `None` when the file's /// structure isn't the simple kind this understands. pub(crate) fn add_fields(pdf: &[u8], fields: &[Placed], media: &[PlacedMedia]) -> Option> { @@ -178,11 +188,7 @@ pub(crate) fn add_fields(pdf: &[u8], fields: &[Placed], media: &[PlacedMedia]) - } FieldKind::CheckBox => { // Appearances: an empty box, and a box with a check mark. - let border = if *bw > 0.0 { - format!("0.45 G {bw:.2} w {i:.2} {i:.2} {:.2} {:.2} re S", (w - bw).max(0.0), (h - bw).max(0.0), i = bw / 2.0) - } else { - String::new() - }; + let border = checkbox_border(*bw, w, h); let check = format!( "{border} 0 g {:.2} w 1 J 1 j {:.2} {:.2} m {:.2} {:.2} l {:.2} {:.2} l S", (w.min(h) * 0.12).max(0.8), From e7e780ec74a953f1de1a53834fb7bc95dbb0b051 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Thu, 29 Oct 2026 21:56:27 -0400 Subject: [PATCH 0507/1349] docs: keep ROADMAP progress log newest first after batch landing Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index 8307b65ed..ad3f52a14 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -384,12 +384,12 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. -- **2026-10-26** · Inner Shadow, Inner Glow (from the edges) and Bevel and Emboss on a frame holding an image follow what the image paints: a transparent part is outside the object, so the effect lines the image's opaque edge, not the frame (#1622). Satin and a centred Inner Glow still follow the frame. No readiness percentage change. - **2026-10-29** · Inserting text with many returns no longer takes time that grows with their square (part of #1588): each return copied its paragraph's format with its own insert, moving every format after it. Splitting 20,000 returns into paragraphs took 15.8 s; placing a text file of them now takes 0.2 s, and one of a million returns 5.5 s. No readiness percentage change. - **2026-10-28** · Discretionary hyphens (U+00AD) break in the single-line composer with automatic hyphenation on or off, matching the paragraph composer. Unbroken soft hyphens remain invisible and zero-width, and words containing them keep only their discretionary break points (#1955). No readiness percentage change. - **2026-10-28** · Autoflow no longer sizes the rest of a story by a frame that a Start Paragraph option (next column, frame, page, or odd or even page) ends early (#1209). With a title before a chapter that starts on the next odd page, it estimated a page per few characters, added up to 2000 pages (the autoflow limit) and removed them again: placing 2000 words took 36 s in the app, now 0.4 s, with the same pages. It looks past tracked-deleted paragraphs for the option, as composing does, and asks for every frame that start options and breaks force in one round: 200 one-line chapters on their own pages take 9 ms (58 ms before). A break and the start option it meets count once, and breaks that tracked changes delete or a hidden condition hides don't count. No readiness percentage change. - **2026-10-28** · IDML export writes the document's default `StoryPreference` in `Resources/Preferences.xml`, as InDesign does. Only each story carried one, and IDML readers that take the spread reading order from the document's (Okapi's IDML filter) failed on DesignCraft's files. No readiness percentage change. - **2026-10-27** · An iconic panel's flyout stays open while you work in the canvas or a text field: Auto-Collapse Iconic Panels is off by default, and preferences saved with it on start with it off. Preferences › Interface › Panels holds the setting next to the column bar's menu item. No readiness percentage change. +- **2026-10-26** · Inner Shadow, Inner Glow (from the edges) and Bevel and Emboss on a frame holding an image follow what the image paints: a transparent part is outside the object, so the effect lines the image's opaque edge, not the frame (#1622). Satin and a centred Inner Glow still follow the frame. No readiness percentage change. - **2026-10-24** · Column rules run from the top line's ascent to the bottom line's descent, as InDesign draws them, instead of from the top to the bottom of the columns, on screen, in PDF and in PowerPoint export. The top and bottom insets shorten the rule from those lines. Existing documents draw their column rules at the new length. No readiness percentage change. - **2026-10-20** · Edit › Keyboard Shortcuts is craft-keymap's shared dialog: commands grouped by menu with Show and Filter, recording that asks before taking a key from another command, undo and redo, named shortcut sets (edits of Default become Custom; an imported set becomes a set of its own), an on-screen US keyboard, InDesign Show Set files reviewed before they apply, JSON export and an HTML summary. ui.json keeps the `shortcuts` map earlier versions read, for the active set. No readiness percentage change. - **2026-10-19** · Import InDesign Set… runs on craft-keymap's importer: a set's Window menu panel items (Layers F7, Pages F12, Swatches F5) and Tools items set the panel and tool shortcuts, all of an item's Default keys apply, and the report adds numeric keypad keys read as main keys and likely commands for unmatched items (`window.importShortcuts`). On InDesign's Windows defaults it matches 366 of 1,629 items (was 233) and changes 23 commands. No readiness percentage change. From ec059c042b34dcac6db4452a27169e441968e73e Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Sat, 24 Oct 2026 23:11:57 +0200 Subject: [PATCH 0508/1349] Linux: file managers show a .designcraft file's first page through a freedesktop thumbnailer (#1782) --- Cargo.lock | 1 + ROADMAP.md | 1 + apps/designcraft-cli/Cargo.toml | 1 + apps/designcraft-cli/src/main.rs | 40 ++++++++++++- apps/designcraft-cli/tests/it/cli.rs | 60 +++++++++++++++++++ .../ai.storyteller.designcraft.thumbnailer | 8 +++ packaging/linux/package.sh | 1 + 7 files changed, 111 insertions(+), 1 deletion(-) create mode 100644 packaging/linux/ai.storyteller.designcraft.thumbnailer diff --git a/Cargo.lock b/Cargo.lock index 1c361aef2..13a009d2f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1340,6 +1340,7 @@ dependencies = [ "designcraft-mcp", "designcraft-pdf", "designcraft-render", + "image", "serde_json", ] diff --git a/ROADMAP.md b/ROADMAP.md index ad3f52a14..807aa5dbf 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -405,6 +405,7 @@ Newest first. - **2026-10-24** · Renaming a paragraph or character style, or moving it into a style group, keeps its Export Tagging under the new name, and undo puts it back under the old one. Deleting a tagged style drops its tagging and leaves the replacement style's own tagging as it was. No readiness percentage change. - **2026-10-24** · Quick Apply and the application bar's search leave out the interface commands that failed or reset a setting when chosen there: those that need a workspace, a command and shortcut, a menu item, a panel, a window edge, an app page, a recent file or a swatch they can't give them, a Contextual Task Bar place, and Interface Color Theme, UI Scaling, Reset Shortcuts, the flattener preset, Screen Mode and Zoom To, which without a value switched to the dark theme, set 100%, cleared every custom shortcut or the preset, or went to Normal mode or 100% zoom. Each stays in the menu, panel or dialog that gives it the value. No readiness percentage change. - **2026-10-24** · EPUB Export Options › Split Document, a dialog before File › Export EPUB… saves (`document.epubSplit`, stored with the document): off, a single paragraph style, or based on paragraph style export tags, with Paragraph Style Options › Export Tagging's Split Document flag marking those styles. A reflowable EPUB is one content file unless Split Document is on; the split before each top-level h1 from #791 is gone. A split before a list item or preformatted line no longer leaves an unclosed list or block in a content file. IDML import and export keep the setting and the flag, and Load Styles the flag. No readiness percentage change. +- **2026-10-24** · Linux file managers show a `.designcraft` file's first page instead of a blank icon: the packages install a freedesktop thumbnailer (`share/thumbnailers/ai.storyteller.designcraft.thumbnailer`) that runs `designcraft-cli thumbnail FILE OUT.png SIZE`, which writes the `preview.png` saving already puts in the file, fitted to the size asked for and never enlarged. A file without a preview fails, so the file manager keeps the file type's icon (#1782). No readiness percentage change. - **2026-10-18** · Repeated placed-PDF layer variants are prepared once per asset and hidden-name set, with recovery warnings retained. All-visible named layers keep their original source bytes, including PDFs whose cross-reference tables the reader repairs, in plain, PDF/X-4, booklet and book-merge output. Layer changes that require writing still reject an unusable cross-reference table with a file-named damage error; the first placement error is retained (#906). No readiness percentage change. - **2026-10-18** · Placed PDF optional-content defaults and per-frame overrides survive plain and PDF/X-4 vector export, including repeated placements, booklet output and book merging (#906). Source usage-application arrays are accepted; groups without a catalog configuration stay visible. Missing or unreadable default configurations and unsupported base states use all-ON defaults with a file-named export warning, retaining explicit frame overrides. Readable groups omitted from the catalog list are added with a distinct file-named warning, preserving their default ON/OFF states. Concurrent recovery warnings are combined. Malformed ON data is recoverable when a known ON base and empty OFF list prove it cannot hide artwork; missing display names are generated without changing known visibility when no override needs name matching. Contradictory states, unresolved references and ambiguous name overrides still fail export. Print-usage adjustments and IDML layer overrides remain follow-ups. No readiness percentage change. diff --git a/apps/designcraft-cli/Cargo.toml b/apps/designcraft-cli/Cargo.toml index 7aaa454cb..ab2464147 100644 --- a/apps/designcraft-cli/Cargo.toml +++ b/apps/designcraft-cli/Cargo.toml @@ -22,4 +22,5 @@ designcraft-compose = { workspace = true } designcraft-format = { workspace = true } designcraft-pdf = { workspace = true } designcraft-mcp = { workspace = true } +image = { workspace = true } serde_json = { workspace = true } diff --git a/apps/designcraft-cli/src/main.rs b/apps/designcraft-cli/src/main.rs index 9ce15674c..bf7b6b351 100644 --- a/apps/designcraft-cli/src/main.rs +++ b/apps/designcraft-cli/src/main.rs @@ -16,6 +16,8 @@ //! designcraft-cli bench FILE [--runs N] # the same measurements on one document //! designcraft-cli validate-pdf FILE.pdf [--standard x4|x1a] # the built-in PDF/X-4 or PDF/X-1a checks (default: the //! # file's own GTS_PDFXVersion) +//! designcraft-cli thumbnail FILE.designcraft OUT.png [SIZE] # the file's first-page preview, fitted to SIZE +//! # (the freedesktop thumbnailer for Linux file managers) //! designcraft-cli links # Discord, website, app page and GitHub links //! designcraft-cli --version # print the version //! ``` @@ -40,7 +42,7 @@ use designcraft_engine::Session; use serde_json::{Value, json}; /// The usage block. Shared by `--help` (stdout, success) and an unknown command (stderr, failure). -const USAGE: &str = "usage: designcraft-cli run [--in FILE | --sample] [--cmd ID[=JSON]]... [--page N] [--scale S] [--pdf-options JSON] [--export OUT] [--all-pages DIR]\n (--page, --scale and --pdf-options apply to the exports that follow them)\n designcraft-cli commands [FILTER]\n designcraft-cli describe COMMAND\n designcraft-cli script [FILE|-] [--in FILE | --sample] [--connect PORT] [--save OUT] [--export OUT] [--keep-going]\n designcraft-cli app [--port PORT] COMMAND [JSON] | --method METHOD [JSON]\n designcraft-cli mcp [--connect PORT] [--sample] [--automation-read-root DIR]... [--automation-write-root DIR]...\n the roots confine every file the agent's commands read (open, placed images, data sources, libraries) and\n write (save, export, package) to those folders, links followed. Each may be given more than once; a kind\n left out grants none of its access.\n They run the in-process server, so they conflict with --connect (a running app is not confined by them).\n designcraft-cli perf [--pages N] [--runs N] [--strict]\n designcraft-cli bench FILE [--runs N]\n designcraft-cli validate-pdf FILE.pdf # built-in PDF/X-4 checks (including visible unembedded fonts)\n designcraft-cli links\n designcraft-cli --version"; +const USAGE: &str = "usage: designcraft-cli run [--in FILE | --sample] [--cmd ID[=JSON]]... [--page N] [--scale S] [--pdf-options JSON] [--export OUT] [--all-pages DIR]\n (--page, --scale and --pdf-options apply to the exports that follow them)\n designcraft-cli commands [FILTER]\n designcraft-cli describe COMMAND\n designcraft-cli script [FILE|-] [--in FILE | --sample] [--connect PORT] [--save OUT] [--export OUT] [--keep-going]\n designcraft-cli app [--port PORT] COMMAND [JSON] | --method METHOD [JSON]\n designcraft-cli mcp [--connect PORT] [--sample] [--automation-read-root DIR]... [--automation-write-root DIR]...\n the roots confine every file the agent's commands read (open, placed images, data sources, libraries) and\n write (save, export, package) to those folders, links followed. Each may be given more than once; a kind\n left out grants none of its access.\n They run the in-process server, so they conflict with --connect (a running app is not confined by them).\n designcraft-cli perf [--pages N] [--runs N] [--strict]\n designcraft-cli bench FILE [--runs N]\n designcraft-cli validate-pdf FILE.pdf # built-in PDF/X-4 checks (including visible unembedded fonts)\n designcraft-cli thumbnail FILE.designcraft OUT.png [SIZE] # the saved first-page preview, at most SIZE px\n designcraft-cli links\n designcraft-cli --version"; /// `script --help`: the script syntax, otherwise only in `describe script.run` and docs/agents.md. const SCRIPT_HELP: &str = r#"usage: designcraft-cli script [FILE|-] [--in FILE | --sample] [--connect PORT] [--save OUT] [--export OUT] [--keep-going] @@ -124,6 +126,7 @@ fn main() -> ExitCode { Some("perf") => report(perf::perf(&args[1..])), Some("bench") => report(perf::bench(&args[1..])), Some("validate-pdf") => report(validate_pdf(args.get(1..).unwrap_or_default())), + Some("thumbnail") => report(thumbnail(&args[1..])), Some("links") => { use designcraft_engine::links::{APP_PAGE, DISCORD, GITHUB, ISSUES, WEBSITE}; outln!("Discord {DISCORD}\nWebsite {WEBSITE}\nApp page {APP_PAGE}\nGitHub {GITHUB}\nIssues {ISSUES}"); @@ -188,6 +191,41 @@ fn validate_pdf(args: &[String]) -> Result<(), String> { if valid { Ok(()) } else { Err(format!("{path} failed {name} validation")) } } +/// `thumbnail FILE OUT [SIZE]`: the first-page preview saved in a `.designcraft` file, as a PNG +/// whose longer side is at most SIZE pixels (never enlarged). It is the freedesktop thumbnailer +/// (`packaging/linux/ai.storyteller.designcraft.thumbnailer`), so it only reads the preview: a file +/// without one fails, and the file manager keeps the file type's icon. +fn thumbnail(args: &[String]) -> Result<(), String> { + const USAGE: &str = "usage: designcraft-cli thumbnail FILE.designcraft OUT.png [SIZE]"; + let [input, out, rest @ ..] = args else { return Err(USAGE.into()) }; + let size = match rest { + [] => None, + [s] => Some(s.parse::().ok().filter(|s| *s > 0).ok_or_else(|| format!("bad SIZE `{s}`: expected a positive number of pixels"))?), + _ => return Err(USAGE.into()), + }; + let file = std::fs::File::open(input).map_err(|e| format!("{input}: {e}"))?; + let preview = designcraft_format::read_preview(std::io::BufReader::new(file)) + .ok_or_else(|| format!("{input} has no preview (a DesignCraft file saved before they had one, or not a DesignCraft file)"))?; + let png = fit_png(preview, size).map_err(|e| format!("{input}: the preview can't be read: {e}"))?; + designcraft_engine::atomic::write_atomic(std::path::Path::new(out), &png).map_err(|e| format!("{out}: {e}")) +} + +/// `png` with its longer side brought down to `size`. A picture already that small is returned +/// as it is; it is decoded anyway, so a broken one is an error rather than an unreadable thumbnail. +fn fit_png(png: Vec, size: Option) -> Result, String> { + // The preview comes from the file: it may claim any size. + let mut limits = image::Limits::default(); + limits.max_image_width = Some(4096); + limits.max_image_height = Some(4096); + let mut reader = image::ImageReader::with_format(std::io::Cursor::new(&png), image::ImageFormat::Png); + reader.limits(limits); + let img = reader.decode().map_err(|e| e.to_string())?; + let Some(size) = size.filter(|s| img.width().max(img.height()) > *s) else { return Ok(png) }; + let mut out = std::io::Cursor::new(Vec::new()); + img.resize(size, size, image::imageops::FilterType::Triangle).write_to(&mut out, image::ImageFormat::Png).map_err(|e| e.to_string())?; + Ok(out.into_inner()) +} + /// `mcp` (headless, in-process engine) or `mcp --connect PORT|HOST:PORT` (drive a running app /// started with `designcraft --control PORT`). JSON-RPC on stdin/stdout; logs on stderr. fn mcp(args: &[String]) -> Result<(), String> { diff --git a/apps/designcraft-cli/tests/it/cli.rs b/apps/designcraft-cli/tests/it/cli.rs index 861cb514f..98b4f5edf 100644 --- a/apps/designcraft-cli/tests/it/cli.rs +++ b/apps/designcraft-cli/tests/it/cli.rs @@ -556,3 +556,63 @@ fn usage_lists_the_automation_root_flags() { let usage = String::from_utf8_lossy(&out.stdout); assert!(usage.contains("--automation-read-root DIR") && usage.contains("--automation-write-root DIR"), "{usage}"); } + +/// Width and height from a PNG's IHDR chunk. +fn png_size(png: &[u8]) -> (u32, u32) { + assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"), "not a PNG"); + let be = |at: usize| u32::from_be_bytes(png[at..at + 4].try_into().unwrap()); + (be(16), be(20)) +} + +/// Linux file managers (Dolphin, Nautilus, Thunar) draw a `.designcraft` file's icon through the +/// freedesktop thumbnailer, which runs `designcraft-cli thumbnail %i %o %s` (#1782). The picture is +/// the first-page preview the file already holds, fitted to the size asked for and never enlarged. +#[test] +fn thumbnail_writes_the_saved_preview_fitted_to_the_size() { + let dir = std::env::temp_dir().join(format!("dc-cli-thumb-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let doc = dir.join("a.designcraft"); + make_document(&doc); + let preview = designcraft_format::read_preview(std::fs::File::open(&doc).unwrap()).unwrap(); + let (pw, ph) = png_size(&preview); + assert!(pw.max(ph) > 128, "the saved preview is {pw}×{ph}"); + + let small = dir.join("small.png"); + let out = cli().arg("thumbnail").arg(&doc).arg(&small).arg("128").output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let (w, h) = png_size(&std::fs::read(&small).unwrap()); + assert_eq!(w.max(h), 128, "{w}×{h} from a {pw}×{ph} preview"); + // The page's proportions stay. + let ratio = |a: u32, b: u32| f64::from(a) / f64::from(b); + assert!((ratio(w, h) - ratio(pw, ph)).abs() < 0.02, "{w}×{h} from a {pw}×{ph} preview"); + + let large = dir.join("large.png"); + let out = cli().arg("thumbnail").arg(&doc).arg(&large).arg("1024").output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert_eq!(std::fs::read(&large).unwrap(), preview, "a preview smaller than the size is written as saved"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A file saved without a preview (by an older version, or not by DesignCraft) has no picture: the +/// thumbnailer fails and writes nothing, so the file manager keeps the file type's icon. +#[test] +fn thumbnail_of_a_file_without_a_preview_fails_and_writes_nothing() { + let dir = std::env::temp_dir().join(format!("dc-cli-thumb-none-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let with = dir.join("with.designcraft"); + make_document(&with); + let doc = designcraft_format::load(&std::fs::read(&with).unwrap()).unwrap(); + let without = dir.join("without.designcraft"); + std::fs::write(&without, designcraft_format::save(&doc).unwrap()).unwrap(); + let text = dir.join("notes.designcraft"); + std::fs::write(&text, "not a document").unwrap(); + for input in [&without, &text] { + let png = dir.join("out.png"); + let out = cli().arg("thumbnail").arg(input).arg(&png).arg("256").output().unwrap(); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{}", input.display()); + assert!(err.contains("no preview"), "{}: {err}", input.display()); + assert!(!png.exists(), "{}", input.display()); + } + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/packaging/linux/ai.storyteller.designcraft.thumbnailer b/packaging/linux/ai.storyteller.designcraft.thumbnailer new file mode 100644 index 000000000..4642996b3 --- /dev/null +++ b/packaging/linux/ai.storyteller.designcraft.thumbnailer @@ -0,0 +1,8 @@ +# Installed as share/thumbnailers/ai.storyteller.designcraft.thumbnailer (package.sh). File managers +# that read freedesktop thumbnailers (Nautilus, Thunar, Dolphin through KIO) run it for .designcraft +# files: %i is the file, %o the PNG to write, %s the size in pixels. It writes the first-page preview +# saved in the file; a file without one keeps the file type's icon. +[Thumbnailer Entry] +TryExec=designcraft-cli +Exec=designcraft-cli thumbnail %i %o %s +MimeType=application/x-designcraft; diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index fa24385d5..7b120c525 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -61,6 +61,7 @@ install -Dm755 "$BIN/designcraft-cli" "$STAGE/usr/bin/designcraft-cli" "${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/designcraft" "$STAGE/usr/bin/designcraft-cli" 2>/dev/null || true install -Dm644 "$HERE/$APP_ID.desktop" "$STAGE/usr/share/applications/$APP_ID.desktop" install -Dm644 "$HERE/$APP_ID.mime.xml" "$STAGE/usr/share/mime/packages/$APP_ID.xml" +install -Dm644 "$HERE/$APP_ID.thumbnailer" "$STAGE/usr/share/thumbnailers/$APP_ID.thumbnailer" mkdir -p "$STAGE/usr/share/metainfo" sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$DESIGNCRAFT_BUILD_DATE/g" \ "$HERE/$APP_ID.metainfo.xml.in" >"$STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" From 8e8865bba18922e29dd57ed9c62fa910ab701c41 Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Fri, 30 Oct 2026 03:08:39 +0100 Subject: [PATCH 0509/1349] thumbnail: refuse an output that names the input document (#1782) designcraft-cli thumbnail a.designcraft a.designcraft replaced the document with PNG bytes. The output is now refused before anything is read or written when it is the input by the same path, through a symlink, or on Unix as a hard link (same device and inode). --- apps/designcraft-cli/src/main.rs | 20 ++++++++++++ apps/designcraft-cli/tests/it/cli.rs | 47 ++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) diff --git a/apps/designcraft-cli/src/main.rs b/apps/designcraft-cli/src/main.rs index bf7b6b351..a26c3d977 100644 --- a/apps/designcraft-cli/src/main.rs +++ b/apps/designcraft-cli/src/main.rs @@ -203,6 +203,9 @@ fn thumbnail(args: &[String]) -> Result<(), String> { [s] => Some(s.parse::().ok().filter(|s| *s > 0).ok_or_else(|| format!("bad SIZE `{s}`: expected a positive number of pixels"))?), _ => return Err(USAGE.into()), }; + if names_the_same_file(input.as_ref(), out.as_ref()) { + return Err(format!("{out} is the document {input}: the thumbnail would replace it")); + } let file = std::fs::File::open(input).map_err(|e| format!("{input}: {e}"))?; let preview = designcraft_format::read_preview(std::io::BufReader::new(file)) .ok_or_else(|| format!("{input} has no preview (a DesignCraft file saved before they had one, or not a DesignCraft file)"))?; @@ -210,6 +213,23 @@ fn thumbnail(args: &[String]) -> Result<(), String> { designcraft_engine::atomic::write_atomic(std::path::Path::new(out), &png).map_err(|e| format!("{out}: {e}")) } +/// Whether `out` is the file `input` names: the same path, a symlink to it or, on Unix, a hard +/// link (the same device and inode). An `out` that doesn't exist yet can't be the input. +fn names_the_same_file(input: &std::path::Path, out: &std::path::Path) -> bool { + let (Ok(a), Ok(b)) = (std::fs::canonicalize(input), std::fs::canonicalize(out)) else { return false }; + if a == b { + return true; + } + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if let (Ok(a), Ok(b)) = (std::fs::metadata(&a), std::fs::metadata(&b)) { + return (a.dev(), a.ino()) == (b.dev(), b.ino()); + } + } + false +} + /// `png` with its longer side brought down to `size`. A picture already that small is returned /// as it is; it is decoded anyway, so a broken one is an error rather than an unreadable thumbnail. fn fit_png(png: Vec, size: Option) -> Result, String> { diff --git a/apps/designcraft-cli/tests/it/cli.rs b/apps/designcraft-cli/tests/it/cli.rs index 98b4f5edf..f19551a71 100644 --- a/apps/designcraft-cli/tests/it/cli.rs +++ b/apps/designcraft-cli/tests/it/cli.rs @@ -616,3 +616,50 @@ fn thumbnail_of_a_file_without_a_preview_fails_and_writes_nothing() { } let _ = std::fs::remove_dir_all(&dir); } + +/// `thumbnail a.designcraft a.designcraft` would replace the document with a PNG. An output that +/// names the input, by the same path, through a symlink or (on Unix) as a hard link, is refused +/// before anything is read or written, and the document keeps its bytes. +#[test] +fn thumbnail_refuses_an_output_that_names_the_input() { + let dir = std::env::temp_dir().join(format!("dc-cli-thumb-self-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let doc = dir.join("a.designcraft"); + make_document(&doc); + let saved = std::fs::read(&doc).unwrap(); + let mut outs = vec![doc.clone(), dir.join(".").join("a.designcraft")]; + #[cfg(unix)] + { + let link = dir.join("link.png"); + std::os::unix::fs::symlink(&doc, &link).unwrap(); + outs.push(link); + let hard = dir.join("hard.png"); + std::fs::hard_link(&doc, &hard).unwrap(); + outs.push(hard); + } + for out_path in &outs { + let out = cli().arg("thumbnail").arg(&doc).arg(out_path).arg("128").output().unwrap(); + let err = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(1), "{}: {err}", out_path.display()); + assert!(err.contains("is the document"), "{}: {err}", out_path.display()); + assert!(std::fs::read(&doc).unwrap() == saved, "{} changed the document", out_path.display()); + assert!(std::fs::read(out_path).unwrap() == saved, "{} was written", out_path.display()); + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// Another existing file at the output path is still replaced by the thumbnail. +#[test] +fn thumbnail_replaces_another_existing_file() { + let dir = std::env::temp_dir().join(format!("dc-cli-thumb-other-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let doc = dir.join("a.designcraft"); + make_document(&doc); + let png = dir.join("old.png"); + std::fs::write(&png, b"an older thumbnail").unwrap(); + let out = cli().arg("thumbnail").arg(&doc).arg(&png).arg("128").output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let (w, h) = png_size(&std::fs::read(&png).unwrap()); + assert_eq!(w.max(h), 128, "{w}×{h}"); + let _ = std::fs::remove_dir_all(&dir); +} From faccd43153d41f674a3384e9c5b099a3c3cbb891 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 29 Oct 2026 22:20:23 -0400 Subject: [PATCH 0510/1349] CI: workflows only call craft-common-actions at @main (#2018) AGENTS.md (and CLAUDE.md where present) gets a CI workflows section: workflows only call craft-common-actions at @main, with no other jobs; feature and fix PRs don't touch CI and link or open a craft-common-actions issue (a PR only for a small fix that is safe for every app and does not increase CI time); legacy jobs aren't added to and move only as their own task, staying until a shared workflow runs them. windows-arm64.yml moves from its SHA pin to @main. The pinned revision is on craft-common-actions main and the workflow (and the actions it calls) is identical there, so nothing changes in behaviour. --- .github/workflows/windows-arm64.yml | 4 ++-- AGENTS.md | 5 +++++ CLAUDE.md | 5 +++++ 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/.github/workflows/windows-arm64.yml b/.github/workflows/windows-arm64.yml index 211ed988d..668e904d2 100644 --- a/.github/workflows/windows-arm64.yml +++ b/.github/workflows/windows-arm64.yml @@ -26,8 +26,8 @@ permissions: jobs: windows-arm64: - # Immutable supporting workflow revision until the new install contract lands upstream. - uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@8bb4e5ab95443171104ad88113fe1ef9b0e5ce3f + # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. + uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@main with: app-name: designcraft app-dir: DesignCraft diff --git a/AGENTS.md b/AGENTS.md index 0be7fa87b..152f6bb06 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,3 +58,8 @@ People trust DesignCraft with their layouts; a crash loses their work. **This ou GitHub profiles). Never hand-edit `contributors.json`. - Maintainers refresh the stats with `python3 ../../craftrules/scripts/contributors.py .` (it also re-verifies who wrote each `people.toml` entry; `--check` only verifies). + +## CI workflows +- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. +- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. +- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. diff --git a/CLAUDE.md b/CLAUDE.md index bed556afb..ff1d0c61c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -39,3 +39,8 @@ People trust DesignCraft with their layouts; a crash loses their work. **This ou ## Roadmap `ROADMAP.md` (committed) is the one-page summary: stage, headline numbers, dimensions, languages, progress log. It follows craftrules' [`standards/progress-docs.md`](https://github.com/storytold/craftrules/blob/main/standards/progress-docs.md). Details: `docs/target-app-parity.md` (assessment), `docs/gaps.md` (ranked work list: pick from the top), `docs/roadmap.md` (milestones, current focus), `docs/parity-checklist.md` (presence checklist, `cargo xtask parity`), and the typography, file-format, UI, hardware and localization parity docs in `docs/`. When work lands, update the affected docs and their status lines, delete or shrink the closed gap, and add a progress-log line to ROADMAP.md. + +## CI workflows +- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. +- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. +- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. From c31ad07f38e0403a5a0fc687cbbdf7331aa5353f Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Fri, 16 Oct 2026 14:19:00 +0200 Subject: [PATCH 0511/1349] =?UTF-8?q?InDesign's=20type=20shortcuts:=20Just?= =?UTF-8?q?ify=20All=20Lines=20=E2=87=A7=E2=8C=98F,=20Em=20Space=20?= =?UTF-8?q?=E2=87=A7=E2=8C=98M,=20En=20Space=20=E2=87=A7=E2=8C=98N,=20Para?= =?UTF-8?q?graph=20Rules=20=E2=8C=A5=E2=8C=98J?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - type.justifyAll ("Justify all lines", ⇧⌘F) next to Justify Left ⇧⌘J. - Insert White Space › Em Space and En Space become app.insertEmSpace / app.insertEnSpace, so the menu (and the Mac menu bar) shows ⇧⌘M / ⇧⌘N; they are enabled at an insertion point only. - Paragraph Rules… gets ⌥⌘J, shown in the Paragraph panel menu. - On the Mac a menu-bar insert (Em/En Space, Current Page Number) does nothing while a text field has focus, instead of typing at the canvas caret behind it. --- ROADMAP.md | 4 +- crates/engine/src/cmd/text.rs | 26 +++++ crates/ui-egui/src/menus/invoke.rs | 8 ++ crates/ui-egui/src/menus/run.rs | 2 + crates/ui-egui/src/menus/state.rs | 3 + crates/ui-egui/src/menus/tables.rs | 4 +- crates/ui-egui/src/menus/tests.rs | 94 +++++++++++++++++++ crates/ui-egui/src/menus/ui_commands.rs | 4 +- .../src/panels/properties/typography.rs | 7 +- docs/target-app-parity.md | 2 +- 10 files changed, 148 insertions(+), 6 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index ad3f52a14..004b957c2 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -63,7 +63,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope - EPUB 3 (reflowable) export: stories in reading order, CSS from paragraph/character styles, images, navigation (`file.exportEpub`, CLI `--export x.epub`). - Data Merge (one linked CSV, TSV, text, or Excel file; text, image, QR, and hyperlink placeholders; preview; a new document with one record per page or records tiled on a single page), spell checking (public-domain Moby list + document dictionary, suggestions), Step and Repeat (count or grid), snippets, object styles, Numbering & Section Options. - Footnotes: Type › Insert Footnote (caret moves into the note), Document Footnote Options (numbering style incl. symbols, start/restart per page/spread/section, prefix/suffix, reference position/character style, paragraph style, separator, spacing, first baseline, rule above); notes composed at the bottom of the referencing column with the body text making room; edited in place on the canvas; rendered, exported to PDF (real text) and IDML (InDesign's structure, verified opening in InDesign 2026) and imported from IDML; `footnote.*` commands. -- Paragraph Rules: Rule Above / Rule Below (on, weight, colour, tint, column or text width, offset, left/right indent) set in Type › Paragraph Rules…, the Paragraph panel menu and Paragraph Style Options › Paragraph Rules; inherited style values shown, and `type.para` / `style.paragraph.edit` change only the rule fields named. +- Paragraph Rules: Rule Above / Rule Below (on, weight, colour, tint, column or text width, offset, left/right indent) set in Type › Paragraph Rules…, the Paragraph panel menu (⌥⌘J) and Paragraph Style Options › Paragraph Rules; inherited style values shown, and `type.para` / `style.paragraph.edit` change only the rule fields named. - Cross-references and text anchors: Insert Cross-Reference (paragraph by style, or text anchor), 11 formats with InDesign's building blocks (full/partial paragraph, paragraph text/number, page number, anchor name, chapter, file name) plus user formats; resolved live at composition — never out of date, no Update step; unresolved destinations show `??`; PDF link annotations to the destination page; IDML export/import as InDesign cross-reference sources, hyperlinks, text destinations and formats (verified in InDesign 2026); `xref.*` / `anchor.*` commands. - Index: page references (topic from the selection or up to 4 levels, sort keys; current page, to end of story, next n paragraphs, suppressed, See / See also), Generate / Update Index (section headings, nested or run-in, page ranges merged, Index Title / Section Head / Level 1–4 styles); IDML export/import as InDesign topics, page references and topic cross-references (verified in InDesign 2026); `index.*` commands. - Text clipboard keeps formatting (character/paragraph formats, footnotes, cross-references, index markers, tables) and falls back to plain text when the system clipboard changed; Paste without Formatting (⇧⌘V); Change Case (UPPERCASE, lowercase, Title Case, Sentence case — formatting kept); Type › Insert Special Character / White Space / Break Character submenus. @@ -756,3 +756,5 @@ The shared craft-installer UI preserves this revision's install options and prov - **2026-10-15** · Windows recovery folders validate the identity of the live locked file without reading it through a second handle. Missing or replaced locks disable writes and cleanup; regression tests cover retained exclusive locking and replacement-file protection. No readiness percentage change. - PDF reader infrastructure: pinned shared parsing/rasterization, transformed page-box geometry and explicit failures for known incomplete layered-PDF exports. Application ownership and parity targets are unchanged. + +- **2026-10-16** · InDesign's type shortcuts: Justify All Lines ⇧⌘F, Insert White Space › Em Space ⇧⌘M and En Space ⇧⌘N (shown in the menu, enabled at an insertion point), Paragraph Rules… ⌥⌘J (shown in the Paragraph panel menu). On the Mac a menu-bar insert (Em/En Space, Current Page Number) no longer types into the document while a text field has focus. No readiness percentage change. diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index 8e6038741..9109e98fd 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -241,6 +241,10 @@ pub fn specs() -> Vec { s, &json!({"align": "leftJustified"}) )), + cmd!("type.justifyAll", "Justify all lines", [], Some("Cmd+Shift+F"), "{}", has_text_or_frames, |s, _| format_paras( + s, + &json!({"align": "fullyJustified"}) + )), cmd!( "type.bold", "Bold", @@ -432,3 +436,25 @@ pub fn specs() -> Vec { ), ] } + +#[cfg(test)] +mod alignment_shortcut_tests { + use serde_json::json; + + use crate::Session; + + /// InDesign's Justify All Lines is ⇧⌘F (Shift+Ctrl+F), next to Justify Left ⇧⌘J. + #[test] + fn justify_all_lines_has_indesigns_shortcut_and_justifies_the_last_line_too() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Spring issue"})).unwrap(); + s.execute("text.select", &json!({"story": r["story"], "anchor": 3, "focus": 3})).unwrap(); + // From Justify Left, so the result is not a default or a neighbouring justification. + s.execute("type.justify", &json!({})).unwrap(); + assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["para"]["align"], "leftJustified"); + s.execute("type.justifyAll", &json!({})).unwrap(); + assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["para"]["align"], "fullyJustified"); + assert_eq!(crate::find_command("type.justifyAll").and_then(|c| c.shortcut), Some("Cmd+Shift+F")); + } +} diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index d11b8deaa..628dff472 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -141,6 +141,11 @@ pub fn activate_native(app: &mut DesignApp, ctx: &egui::Context, id: &str, param if params.is_null() && ctx.text_edit_focused() && forward_to_text_edit(app, ctx, id) { return; } + // The menu bar takes ⇧⌘M before the window: with a field focused (Story Editor, Find/Change) + // the character would land at the canvas caret, not where the person is typing. + if params.is_null() && ctx.text_edit_focused() && TEXT_INSERTS.contains(&id) { + return; + } // The canvas text editor is not an egui TextEdit, so its clipboard events must pass through // egui for the desktop integration to read/write the macOS clipboard. if params.is_null() && app.session.wants_text() && matches!(id, "edit.copy" | "edit.cut" | "edit.paste") && forward_to_text_edit(app, ctx, id) { @@ -149,6 +154,9 @@ pub fn activate_native(app: &mut DesignApp, ctx: &egui::Context, id: &str, param activate(app, id, params); } +/// Menu items that type a character at the canvas insertion point. +const TEXT_INSERTS: [&str; 3] = ["app.insertCurrentPageNumber", "app.insertEmSpace", "app.insertEnSpace"]; + /// The editing commands a focused text field takes from the native menu bar. pub(super) const TEXT_FIELD_COMMANDS: [&str; 6] = ["edit.selectAll", "edit.copy", "edit.cut", "edit.paste", "edit.undo", "edit.redo"]; diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 6a8d797b5..41188e16e 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -778,6 +778,8 @@ fn run_ui_part4(app: &mut DesignApp, id: &str, p: &Value) -> Option app.run("text.insert", json!({"text": "\u{e000}", "raw": true})), + "app.insertEmSpace" => app.run("text.insert", json!({"text": "\u{2003}", "raw": true})), + "app.insertEnSpace" => app.run("text.insert", json!({"text": "\u{2002}", "raw": true})), // `panel_docking::command` takes the dock panels (and the Window › Styles group) first. "window.panel" => { let panel = p.get("panel").and_then(Value::as_str).unwrap_or("properties"); diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index f9e78c28f..8c7a84d88 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -172,6 +172,9 @@ pub fn menu_enabled(app: &DesignApp, id: &str) -> bool { if id.starts_with("fit.") { return enabled(app, "object.fit"); } + if matches!(id, "app.insertEmSpace" | "app.insertEnSpace") { + return enabled(app, "text.insert"); + } if id == "guide.selectAll" && (!app.ui.guides || app.ui.guides_locked) { return false; } diff --git a/crates/ui-egui/src/menus/tables.rs b/crates/ui-egui/src/menus/tables.rs index 4d63d485f..f3d02596b 100644 --- a/crates/ui-egui/src/menus/tables.rs +++ b/crates/ui-egui/src/menus/tables.rs @@ -244,8 +244,8 @@ pub const MENUS: &[(&str, &[&str])] = &[ "<", "<", ">Insert White Space", - "cmd:text.insert|Em Space|{\"text\": \"\u{2003}\", \"raw\": true}", - "cmd:text.insert|En Space|{\"text\": \"\u{2002}\", \"raw\": true}", + "ui:app.insertEmSpace", + "ui:app.insertEnSpace", "cmd:text.insert|Nonbreaking Space|{\"text\": \"\u{a0}\", \"raw\": true}", "cmd:text.insert|Hair Space|{\"text\": \"\u{200a}\", \"raw\": true}", "cmd:text.insert|Sixth Space|{\"text\": \"\u{2006}\", \"raw\": true}", diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 5e82f6d3f..b0f6af869 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -2202,6 +2202,100 @@ fn type_panel_items_open_their_panels_and_the_marker_shortcut_inserts_a_page_num assert_eq!(d.story(designcraft_doc::StoryId(story.as_u64().unwrap())).unwrap().text, "Page \u{e000}"); } +/// A key press with `modifiers` through the window's shortcut dispatch, one frame. +fn press(app: &mut crate::DesignApp, ctx: &egui::Context, key: egui::Key, modifiers: egui::Modifiers) { + let events = [true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }).to_vec(); + native_frame(app, ctx, events, None); +} + +fn story_text(app: &crate::DesignApp, story: &Value) -> String { + let d = &app.session.doc().unwrap().doc; + d.story(designcraft_doc::StoryId(story.as_u64().unwrap())).unwrap().text.clone() +} + +#[test] +fn indesigns_type_shortcuts_insert_spaces_justify_all_lines_and_open_paragraph_rules() { + use egui::{Key, Modifiers}; + let ctx = egui::Context::default(); + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let frame = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text", "text": "ab"})).unwrap(); + let story = frame["story"].clone(); + // A selected frame and no insertion point: the spaces have nowhere to go, as in InDesign. + app.run("selection.set", json!({"ids": [frame["id"]]})).unwrap(); + assert!(app.session.doc().unwrap().selection.text.is_none()); + assert!(!menu_enabled(&app, "app.insertEmSpace") && !menu_enabled(&app, "app.insertEnSpace")); + press(&mut app, &ctx, Key::M, Modifiers::COMMAND | Modifiers::SHIFT); + assert_eq!(story_text(&app, &story), "ab"); + app.run("text.select", json!({"story": story, "anchor": 1, "focus": 1})).unwrap(); + assert!(menu_enabled(&app, "app.insertEmSpace") && menu_enabled(&app, "app.insertEnSpace")); + press(&mut app, &ctx, Key::M, Modifiers::COMMAND | Modifiers::SHIFT); + assert_eq!(story_text(&app, &story), "a\u{2003}b", "⇧⌘M types an em space at the caret"); + press(&mut app, &ctx, Key::N, Modifiers::COMMAND | Modifiers::SHIFT); + assert_eq!(story_text(&app, &story), "a\u{2003}\u{2002}b", "⇧⌘N an en space after it"); + app.run("type.justify", json!({})).unwrap(); + press(&mut app, &ctx, Key::F, Modifiers::COMMAND | Modifiers::SHIFT); + assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["align"], "fullyJustified", "⇧⌘F justifies all lines"); + // Guard: ⌥⇧⌘J is another chord (InDesign's Justification…); the rules want Shift up. + press(&mut app, &ctx, Key::J, Modifiers::COMMAND | Modifiers::ALT | Modifiers::SHIFT); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("justification"), "⌥⇧⌘J opens Justification"); + app.ui.dialog = None; + press(&mut app, &ctx, Key::J, Modifiers::COMMAND | Modifiers::ALT); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("paragraphRules"), "⌥⌘J opens Paragraph Rules"); + // Each chord belongs to one command only, so the editor shows no conflict and nothing else fires. + let all = effective_shortcuts(&app); + for (sc, id) in [ + ("Cmd+Shift+F", "type.justifyAll"), + ("Cmd+Shift+M", "app.insertEmSpace"), + ("Cmd+Shift+N", "app.insertEnSpace"), + ("Cmd+Alt+J", "app.paragraphRulesDialog"), + ] { + let owners: Vec<&str> = all.iter().filter(|(_, s)| s == sc).map(|(i, _)| i.as_str()).collect(); + assert_eq!(owners, [id], "{sc}"); + } +} + +#[test] +fn insert_white_space_shows_the_em_and_en_space_shortcuts() { + let ty = menu_tree().into_iter().find(|(m, _)| *m == "Type").unwrap().1; + let white = ty + .iter() + .find_map(|i| match i { + Item::Sub(n, c) if n == "Insert White Space" => Some(c.clone()), + _ => None, + }) + .unwrap(); + // Null params, so the macOS menu bar carries the accelerator too. + for (label, sc) in [("Em Space", "Cmd+Shift+M"), ("En Space", "Cmd+Shift+N")] { + assert!( + white.iter().any(|i| matches!(i, Item::Cmd { label: l, shortcut: Some(s), params, .. } if l == label && *s == sc && params.is_null())), + "{label}" + ); + } +} + +#[test] +fn native_insert_shortcuts_leave_the_document_alone_while_a_field_has_focus() { + // On the Mac the menu bar takes ⇧⌘M before the window: with Quick Apply's field focused it + // must not type into the story behind it. + let ctx = egui::Context::default(); + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let story = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text", "text": "ab"})).unwrap()["story"].clone(); + app.run("text.select", json!({"story": story, "anchor": 1, "focus": 1})).unwrap(); + app.ui.palette = Some("x".into()); + for _ in 0..3 { + native_frame(&mut app, &ctx, vec![], None); + } + assert!(ctx.text_edit_focused()); + for id in ["app.insertEmSpace", "app.insertEnSpace", "app.insertCurrentPageNumber"] { + native_frame(&mut app, &ctx, vec![], Some(id)); + native_frame(&mut app, &ctx, vec![], None); + assert_eq!(story_text(&app, &story), "ab", "{id}"); + } + assert_eq!(app.ui.palette.as_deref(), Some("x")); +} + #[test] fn custom_workspaces_save_apply_and_delete() { let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 649469f30..1defda7f5 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -121,7 +121,7 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[ ( "app.paragraphRulesDialog", "Paragraph Rules…", - None, + Some("Cmd+Alt+J"), "{rule?: ruleAbove|ruleBelow} — Rule Above / Rule Below of the selected paragraphs (type.para)", ), ( @@ -165,6 +165,8 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[ ("app.characterStylesPanel", "Character Styles", Some("Cmd+Shift+F11"), "{} — the Character Styles panel"), ("app.paragraphStylesPanel", "Paragraph Styles", Some("Cmd+F11"), "{} — the Paragraph Styles panel"), ("app.insertCurrentPageNumber", "Current Page Number", Some("Cmd+Alt+Shift+N"), "{} — the Current Page Number marker at the insertion point"), + ("app.insertEmSpace", "Em Space", Some("Cmd+Shift+M"), "{} — an em space at the insertion point"), + ("app.insertEnSpace", "En Space", Some("Cmd+Shift+N"), "{} — an en space at the insertion point"), ("app.storyEditor", "Edit in Story Editor", Some("Cmd+Y"), "{story?}"), ("view.zoomIn", "Zoom In", Some("Cmd+="), "{}"), ("view.zoomOut", "Zoom Out", Some("Cmd+-"), "{}"), diff --git a/crates/ui-egui/src/panels/properties/typography.rs b/crates/ui-egui/src/panels/properties/typography.rs index d4959c406..178dfb529 100644 --- a/crates/ui-egui/src/panels/properties/typography.rs +++ b/crates/ui-egui/src/panels/properties/typography.rs @@ -381,7 +381,12 @@ fn paragraph_panel_menu(app: &mut DesignApp, ui: &mut Ui, p: &Value) { ("Paragraph Rules…", "app.paragraphRulesDialog"), ("Paragraph Borders and Shading…", "app.paragraphBordersDialog"), ] { - if item(ui, label, None, true) { + let mut b = egui::Button::new(crate::rtl::widget(ui, crate::i18n::tr(&lang, label))); + if let Some(sc) = crate::menus::shortcut_of(app, id) { + b = b.shortcut_text(crate::menus::shortcut_text(&sc)); + } + if ui.add(b).clicked() { + ui.close(); command = Some(id); } } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 239920184..26d13d3de 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -285,7 +285,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - EPUB 3 (reflowable) export: stories in reading order, CSS from paragraph/character styles, images, navigation (`file.exportEpub`, CLI `--export x.epub`). - Data Merge (one linked CSV, TSV, text, or Excel file; text, image, QR, and hyperlink placeholders; preview; a new document with one record per page or records tiled on a single page), spell checking (public-domain Moby list + document dictionary, suggestions), Step and Repeat (count or grid, with a previewing dialog), snippets, object styles, Numbering & Section Options. - Footnotes: Type › Insert Footnote (caret moves into the note), Document Footnote Options (numbering style incl. symbols, start/restart per page/spread/section, prefix/suffix, reference position/character style, paragraph style, separator, spacing, first baseline, rule above); notes composed at the bottom of the referencing column with the body text making room, or across all the columns of the frame with Span Footnotes Across Columns; edited in place on the canvas; rendered, exported to PDF (real text) and IDML (InDesign's structure, verified opening in InDesign 2026) and imported from IDML; `footnote.*` commands. -- Paragraph Rules: Rule Above / Rule Below (on, weight, colour, tint, column or text width, offset, left/right indent) set in the Paragraph panel menu and Paragraph Style Options › Paragraph Rules; inherited style values shown, and `type.para` / `style.paragraph.edit` change only the rule fields named. +- Paragraph Rules: Rule Above / Rule Below (on, weight, colour, tint, column or text width, offset, left/right indent) set in the Paragraph panel menu (⌥⌘J) and Paragraph Style Options › Paragraph Rules; inherited style values shown, and `type.para` / `style.paragraph.edit` change only the rule fields named. - Cross-references and text anchors: Insert Cross-Reference (paragraph by style, or text anchor), 11 formats with InDesign's building blocks (full/partial paragraph, paragraph text/number, page number, anchor name, chapter, file name) plus user formats; resolved live at composition — never out of date, no Update step; unresolved destinations show `??`; PDF link annotations to the destination page; IDML export/import as InDesign cross-reference sources, hyperlinks, text destinations and formats (verified in InDesign 2026); `xref.*` / `anchor.*` commands. - Index: page references (topic from the selection or up to 4 levels, sort keys; current page, to end of story, next n paragraphs, suppressed, See / See also), Generate / Update Index (section headings, nested or run-in, page ranges merged, Index Title / Section Head / Level 1–4 styles); IDML export/import as InDesign topics, page references and topic cross-references (verified in InDesign 2026); `index.*` commands. - Text clipboard keeps formatting (character/paragraph formats, footnotes, cross-references, index markers, tables) and falls back to plain text when the system clipboard changed; Paste without Formatting (⇧⌘V); Change Case (UPPERCASE, lowercase, Title Case, Sentence case — formatting kept); Type › Insert Special Character / White Space / Break Character submenus. From be81d5db0e458998e18eeb64a635b41a4471f0a2 Mon Sep 17 00:00:00 2001 From: VoiceLessQ Date: Fri, 30 Oct 2026 00:40:00 -0200 Subject: [PATCH 0512/1349] Images: check the RGBA budget before GIF tone and CMYK TIFF decodes (#1586) tone() decoded a GIF to RGBA and decode_cmyk_tiff() called read_image() without the header check decode_rgba() runs. Both now call too_large_to_decode() first. The decoders' own limits (image 512 MiB, tiff 256 MiB) already refused these files; the guard refuses them from the header instead. --- crates/images/src/lib.rs | 3 +++ crates/images/src/tests.rs | 54 ++++++++++++++++++++++++++++++++++++++ crates/images/src/tone.rs | 3 +++ 3 files changed, 60 insertions(+) diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index dfe4166b7..97067ac41 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -532,6 +532,9 @@ pub fn is_cmyk_tiff(bytes: &[u8]) -> bool { /// over the decoder's 256 MiB limit; [`is_cmyk_tiff`] tells those apart from RGB files. pub fn decode_cmyk_tiff(bytes: &[u8]) -> Option { use tiff::tags::Tag; + if too_large_to_decode(bytes) { + return None; + } let mut d = tiff_decoder(bytes)?; let has_alpha = match d.colortype().ok()? { tiff::ColorType::CMYK(8 | 16) => false, diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index 9ca9fe14f..dd09f2577 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -441,3 +441,57 @@ fn rasters_past_the_rgba_budget_are_refused_before_decoding() { let small = decode_rgba(&blank_png(9)).expect("decodes"); assert_eq!(small.get_pixel(8, 8).0, [0, 0, 0, 255]); } + +/// A GIF whose logical screen is `side` x `side`, holding one black 1x1 frame. +fn gif_screen(side: u16) -> Vec { + let mut gif = b"GIF89a".to_vec(); + gif.extend(side.to_le_bytes()); + gif.extend(side.to_le_bytes()); + // Two-colour global table: black, white. + gif.extend([0x80, 0, 0, 0, 0, 0, 255, 255, 255]); + // Frame at the origin; LZW minimum code size 2, codes clear, 0, end; trailer. + gif.extend([0x2C, 0, 0, 0, 0, 1, 0, 1, 0, 0, 2, 2, 0x44, 0x01, 0, 0x3B]); + gif +} + +/// The header of an uncompressed 8-bit CMYK TIFF of `side` x `side` pixels, without the pixels. +fn cmyk_tiff_header(side: u32) -> Vec { + let entries: [(u16, u16, u32, u32); 9] = [ + (256, 4, 1, side), // width + (257, 4, 1, side), // height + (258, 3, 4, 122), // bits per sample, stored after the IFD + (259, 3, 1, 1), // no compression + (262, 3, 1, 5), // separated (CMYK) + (273, 4, 1, 130), // strip offset + (277, 3, 1, 4), // samples per pixel + (278, 4, 1, side), // rows per strip + (279, 4, 1, side * side * 4), // strip byte count + ]; + let mut t = b"II*\0".to_vec(); + t.extend(8u32.to_le_bytes()); + t.extend(9u16.to_le_bytes()); + for (tag, kind, count, value) in entries { + t.extend(tag.to_le_bytes()); + t.extend(kind.to_le_bytes()); + t.extend(count.to_le_bytes()); + t.extend(value.to_le_bytes()); + } + t.extend(0u32.to_le_bytes()); + assert_eq!(t.len(), 122); + t.extend([8u16; 4].iter().flat_map(|b| b.to_le_bytes())); + t +} + +/// GIF tones and CMYK inks check the RGBA budget too (#1586). +#[test] +fn gif_tone_and_cmyk_inks_check_the_rgba_budget() { + let gif = gif_screen(16_385); + assert!(too_large_to_decode(&gif)); + assert_eq!(tone(&gif), None); + assert_eq!(tone(&gif_screen(2)), Some(Tone::Bitmap)); + let tiff = cmyk_tiff_header(16_385); + assert!(is_cmyk_tiff(&tiff)); + assert_eq!(pixel_size(&tiff), Some((16_385, 16_385))); + assert!(too_large_to_decode(&tiff)); + assert_eq!(decode_cmyk_tiff(&tiff), None); +} diff --git a/crates/images/src/tone.rs b/crates/images/src/tone.rs index 10be68445..3d0b945ce 100644 --- a/crates/images/src/tone.rs +++ b/crates/images/src/tone.rs @@ -39,6 +39,9 @@ pub fn tone(bytes: &[u8]) -> Option { }, // Indexed: what the palette holds decides. Transparent pixels are left out of a bitmap. F::Gif => { + if crate::too_large_to_decode(bytes) { + return None; + } let img = image::load_from_memory_with_format(bytes, F::Gif).ok()?.into_rgba8(); let mut opaque = true; let mut two_level = true; From 9ee25b1561b57644cc9f91e557b76f10f8e2bbac Mon Sep 17 00:00:00 2001 From: Zaxaerith Date: Fri, 30 Oct 2026 11:52:30 +0800 Subject: [PATCH 0513/1349] fix(fonts): find document fonts with bare file paths (#2014) --- ROADMAP.md | 1 + crates/engine/src/cmd/file/open.rs | 71 ++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) diff --git a/ROADMAP.md b/ROADMAP.md index ad3f52a14..5bcc7b176 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -12,6 +12,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, open (documented JSON format + IDML), scriptable by agents (MCP), and available on the web. +- **2026-10-30** · Document Fonts lookup treats a bare document filename's empty parent as the current directory (#2014), preserving case-insensitive discovery and automation read-root checks. No readiness percentage change. - **2026-10-28** · Inline table rows leave room for column and spanning footnotes, continuing in the next column or frame when needed (#1901). Cell-local footnotes contribute to row height and sit inside the cell rather than outside its measuring frame. Vertical justification keeps diff --git a/crates/engine/src/cmd/file/open.rs b/crates/engine/src/cmd/file/open.rs index 75a7ce627..c7e8264ba 100644 --- a/crates/engine/src/cmd/file/open.rs +++ b/crates/engine/src/cmd/file/open.rs @@ -128,6 +128,8 @@ pub(crate) fn load_document_fonts(d: &mut Document, path: &str) -> (Option std::path::PathBuf { use designcraft_fonts::DOCUMENT_FONTS_FOLDER; + // A bare file name has an empty parent; directory traversal needs an explicit `.`. + let dir = if dir.as_os_str().is_empty() { std::path::Path::new(".") } else { dir }; let exact = dir.join(DOCUMENT_FONTS_FOLDER); if crate::io::is_dir(&exact) { return exact; @@ -286,6 +288,75 @@ mod document_fonts_tests { let _ = std::fs::remove_dir_all(&dir); } + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn document_fonts_are_found_for_bare_and_explicit_paths() { + // Only the child changes its working directory; parallel tests keep theirs. + let dir = tempfile::tempdir().unwrap(); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "cmd::file::open::document_fonts_tests::document_font_paths_child", "--ignored", "--nocapture"]) + .env("DESIGNCRAFT_TEST_DOCUMENT_FONT_PATHS", "1") + .current_dir(dir.path()) + .output() + .unwrap(); + assert!(output.status.success(), "child failed: {}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("test result: ok. 1 passed; 0 failed;"), "the subprocess helper must run exactly once: {stdout}"); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + #[ignore = "subprocess helper, executed by document_fonts_are_found_for_bare_and_explicit_paths"] + fn document_font_paths_child() { + const FAMILY: &str = "DocFont Bare Path Test"; + assert!(std::env::var_os("DESIGNCRAFT_TEST_DOCUMENT_FONT_PATHS").is_some(), "run through the parent test"); + let cwd = std::env::current_dir().unwrap(); + std::fs::create_dir("nested").unwrap(); + std::fs::create_dir("other").unwrap(); + for extension in ["idml", "designcraft"] { + let path = PathBuf::from(format!("t.{extension}")); + write_document(&cwd.join(&path), FAMILY); + write_document(&cwd.join("other").join(&path), FAMILY); + assert_eq!(open(&mut Session::new(), &path)["documentFonts"], 0, "no font folder: {path:?}"); + } + + let roots = crate::file_access::AutomationRoots::new(&[cwd.as_path()], &[]).unwrap(); + for folder in ["Document fonts", DOCUMENT_FONTS_FOLDER] { + std::fs::create_dir_all(folder).unwrap(); + std::fs::write(Path::new(folder).join("case.ttf"), font_with(FAMILY, &['H', 'e', 'l', 'o']).unwrap()).unwrap(); + if folder == DOCUMENT_FONTS_FOLDER { + // Both spellings exist on case-sensitive file systems; the exact name still wins. + assert_eq!(super::document_fonts_folder(Path::new("")), Path::new(".").join(DOCUMENT_FONTS_FOLDER)); + } + for extension in ["idml", "designcraft"] { + let name = format!("t.{extension}"); + for path in [PathBuf::from(&name), Path::new(".").join(&name), Path::new("nested/..").join(&name), cwd.join(&name)] { + let mut s = Session::new(); + let r = crate::file_access::confine(roots.as_ref(), || open(&mut s, &path)); + assert_eq!(r["documentFonts"], 1, "{folder}, {path:?}: {r}"); + let f = font_entry(&mut s, FAMILY); + assert_eq!((f["missing"].clone(), f["source"].clone()), (json!(false), json!("document")), "{path:?}: {f}"); + } + } + } + + // Opening a second document without the folder must not inherit the first one's font. + let mut s = Session::new(); + assert_eq!(open(&mut s, Path::new("t.idml"))["documentFonts"], 1); + assert_eq!(open(&mut s, Path::new("other/t.designcraft"))["documentFonts"], 0); + assert_eq!(font_entry(&mut s, FAMILY)["missing"], true); + s.execute("file.activate", &json!({"index": 0})).unwrap(); + assert_eq!(font_entry(&mut s, FAMILY)["source"], "document"); + + // Normalising the directory must not grant access outside the automation read root. + let restricted = crate::file_access::AutomationRoots::new(&[Path::new("other")], &[]).unwrap(); + let mut doc = s.doc().unwrap().doc.clone(); + let (scope, faces, _) = crate::file_access::confine(restricted.as_ref(), || super::load_document_fonts(&mut doc, "t.idml")); + assert!(scope.is_none()); + assert_eq!(faces, 0); + assert_eq!(doc.font_scope, 0); + } + #[test] fn a_document_without_the_folder_opens_as_before() { let dir = std::env::temp_dir().join(format!("dc-open-docfonts-none-{}", std::process::id())); From 15d13dde2083496b60f3e5a9bfaf89dd2efb9b1b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 30 Oct 2026 01:28:06 -0400 Subject: [PATCH 0514/1349] Update prompt shows the app icon and accent color instead of a letter (#2023) UPDATE_APP (native builds; craft-update is a native-only dependency) carries our 128 px icon and accent (#7bb51c, its colour in ArtCraft Launcher). The updater, the self-update helper and craft-update's startup prompt all get them through crate::UPDATE_APP; the prompt draws the icon, the accent and "by ArtCraft" (craft-update's default developer). craft-update is pinned to storytold/craft-libs main at 1065653e7 (#434). Clippy fixes for Rust 1.99 in untouched code (same logic): - crates/engine/src/cmd/export/text_tests.rs - crates/pdf/src/gradient_inks.rs --- Cargo.lock | 3 ++- Cargo.toml | 3 ++- apps/designcraft/src/main.rs | 2 +- crates/engine/src/cmd/export/text_tests.rs | 4 ++-- crates/pdf/src/gradient_inks.rs | 2 +- crates/ui-egui/src/lib.rs | 9 +++++++++ crates/ui-egui/src/updates_ui.rs | 2 +- 7 files changed, 18 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1c361aef2..6344685d7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1138,13 +1138,14 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=1065653e75854e9c17e1ff563acdd344c1b185f0#1065653e75854e9c17e1ff563acdd344c1b185f0" dependencies = [ "chrono", "dunce", "egui", "flate2", "getrandom 0.3.4", + "image", "log", "plist", "semver", diff --git a/Cargo.toml b/Cargo.toml index 139d06f01..fd8629f62 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,7 +17,8 @@ craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff1 craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.1.0", features = ["egui", "ui"] } # Separations, ink coverage and the ink manager; same revision as craft-pdf and the krilla patch. craft-prepress = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.1.0", features = ["flatten"] } -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] } +# craft-update with storytold/craft-libs#434: the update prompt shows the app's icon, accent and developer. +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1065653e75854e9c17e1ff563acdd344c1b185f0", features = ["egui"] } # internal designcraft-geom = { path = "crates/geom" } designcraft-color = { path = "crates/color" } diff --git a/apps/designcraft/src/main.rs b/apps/designcraft/src/main.rs index 5f056aab3..4b4a1ab7f 100644 --- a/apps/designcraft/src/main.rs +++ b/apps/designcraft/src/main.rs @@ -255,7 +255,7 @@ fn control_port_from(source: &str, value: Option) -> Option { fn main() -> std::process::ExitCode { // Windows: the update helper is a copy of this program started with `--finish-update`. #[cfg(windows)] - if let Some(result) = craft_update::self_update::finish(&craft_update::suite::DESIGNCRAFT, &std::env::args_os().skip(1).collect::>()) { + if let Some(result) = craft_update::self_update::finish(&designcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { std::process::exit(i32::from(result.is_err())); } // First, so every start-up record (and the engine's panic hook, installed with the first diff --git a/crates/engine/src/cmd/export/text_tests.rs b/crates/engine/src/cmd/export/text_tests.rs index e533320f8..2efcb2f92 100644 --- a/crates/engine/src/cmd/export/text_tests.rs +++ b/crates/engine/src/cmd/export/text_tests.rs @@ -204,12 +204,12 @@ fn black_and_gold(pdf: &[u8]) -> Vec<(u8, u8)> { let mut out = Vec::new(); for st in file.objects().into_iter().filter_map(|o| o.into_stream()) { let d = st.dict(); - if !d.get::>(b"Subtype").is_some_and(|n| n.as_ref() == b"Image") || d.get::(b"BitsPerComponent") != Some(8) { + if d.get::>(b"Subtype").is_none_or(|n| n.as_ref() != b"Image") || d.get::(b"BitsPerComponent") != Some(8) { continue; } let Some(cs) = d.get::>(b"ColorSpace") else { continue }; let mut it = cs.iter::>(); - if !it.next().and_then(|o| o.into_name()).is_some_and(|n| n.as_ref() == b"DeviceN") { + if it.next().and_then(|o| o.into_name()).is_none_or(|n| n.as_ref() != b"DeviceN") { continue; } let Some(Object::Array(names)) = it.next() else { continue }; diff --git a/crates/pdf/src/gradient_inks.rs b/crates/pdf/src/gradient_inks.rs index e889ee1d2..c92b80158 100644 --- a/crates/pdf/src/gradient_inks.rs +++ b/crates/pdf/src/gradient_inks.rs @@ -87,7 +87,7 @@ impl Exporter<'_> { let inks: Vec> = g.stops.iter().map(|s| self.stop_ink(s)).collect(); let has_spot = inks.iter().any(|i| matches!(i, Some(Ink::Spot { .. }))); let on_paper = g.stops.iter().any(|s| s.swatch.as_deref() == Some(designcraft_color::swatch::PAPER)); - if !has_spot && !overprint && !(on_paper && self.for_print() && !self.rgb_only) { + if !(has_spot || overprint || on_paper && self.for_print() && !self.rgb_only) { return None; } let Some(inks) = inks.into_iter().collect::>>() else { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 0221aa257..a53cffcfa 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -6,6 +6,15 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] +/// DesignCraft as craft-update knows it, with its 128 px icon and accent colour: the update +/// prompt shows both, and an AppImage's menu entry gets the icon. +#[cfg(not(target_arch = "wasm32"))] +pub const UPDATE_APP: craft_update::app::App = craft_update::app::App { + icon_png: Some(include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.designcraft.png")), + accent: Some([0x7b, 0xb5, 0x1c]), + ..craft_update::suite::DESIGNCRAFT +}; + pub mod about; pub mod canvas; pub mod chrome; diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index 43803c9a5..10d3b83a4 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -26,7 +26,7 @@ impl Default for Runtime { fn default() -> Self { Self { #[cfg(not(target_arch = "wasm32"))] - updater: Updater::new(&craft_update::suite::DESIGNCRAFT, env!("CARGO_PKG_VERSION")), + updater: Updater::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")), #[cfg(not(target_arch = "wasm32"))] startup_check: false, #[cfg(not(target_arch = "wasm32"))] From e5621e16e0fd9f122e18e0e06540d4d39dff8977 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Fri, 30 Oct 2026 04:18:21 +0000 Subject: [PATCH 0515/1349] fix: combine inline decoration overrides with the character style in EPUB export Co-Authored-By: Claude Sonnet 5.5 --- crates/epub/src/css.rs | 64 ++++++++++++++++++--------------- crates/epub/src/story_writer.rs | 2 +- crates/epub/src/tests.rs | 34 +++++++++++++++++- 3 files changed, 70 insertions(+), 30 deletions(-) diff --git a/crates/epub/src/css.rs b/crates/epub/src/css.rs index 3a8639cec..f066d6b3d 100644 --- a/crates/epub/src/css.rs +++ b/crates/epub/src/css.rs @@ -40,23 +40,7 @@ pub(crate) fn char_css(doc: &Document, c: &CharProps, base_size: f64, generics: let (weight, style) = css_weight_style(&c.font_style); let _ = write!(out, "font-weight: {weight}; font-style: {style}; "); let _ = write!(out, "font-size: {:.3}em; ", c.size / base_size); - if c.tracking != 0.0 { - let _ = write!(out, "letter-spacing: {:.3}em; ", c.tracking / 1000.0); - } - match c.capitalization { - designcraft_doc::Capitalization::AllCaps => out.push_str("text-transform: uppercase; "), - designcraft_doc::Capitalization::SmallCaps | designcraft_doc::Capitalization::OpenTypeAllSmallCaps => { - out.push_str("font-variant: small-caps; ") - } - _ => {} - } - // One declaration: a later `text-decoration` would replace the earlier one. - match (c.underline, c.strikethrough) { - (true, true) => out.push_str("text-decoration: underline line-through; "), - (true, false) => out.push_str("text-decoration: underline; "), - (false, true) => out.push_str("text-decoration: line-through; "), - (false, false) => {} - } + decor_css(c.tracking, c.capitalization, c.underline, c.strikethrough, out); if let Some(h) = hex(doc, &c.fill, c.fill_tint) { let _ = write!(out, "color: {h}; "); } @@ -150,7 +134,7 @@ pub(crate) fn stylesheet_with(doc: &Document, generics: &BTreeMap out.push_str("text-transform: uppercase; "), - Some(designcraft_doc::Capitalization::SmallCaps | designcraft_doc::Capitalization::OpenTypeAllSmallCaps) => { + match caps { + designcraft_doc::Capitalization::AllCaps => out.push_str("text-transform: uppercase; "), + designcraft_doc::Capitalization::SmallCaps | designcraft_doc::Capitalization::OpenTypeAllSmallCaps => { out.push_str("font-variant: small-caps; ") } _ => {} } // One declaration: a later `text-decoration` would replace the earlier one. - match (c.underline == Some(true), c.strikethrough == Some(true)) { + match (underline, strikethrough) { (true, true) => out.push_str("text-decoration: underline line-through; "), (true, false) => out.push_str("text-decoration: underline; "), (false, true) => out.push_str("text-decoration: line-through; "), @@ -182,7 +169,11 @@ fn attrs_decor_css(c: &CharAttrs, out: &mut String) { } } -pub(crate) fn override_css(doc: &Document, o: &CharAttrs) -> String { +/// Inline CSS for the local override `o` of a run in character style `style`. Tracking, caps and +/// line decorations are resolved against the style (and its Based On chain), so an override that +/// sets only one of underline/strikethrough keeps the other, and one that clears a value the +/// style sets writes the reset. +pub(crate) fn override_css(doc: &Document, style: &str, o: &CharAttrs) -> String { let mut s = String::new(); if let Some(f) = &o.font_style { let f = f.to_lowercase(); @@ -198,7 +189,24 @@ pub(crate) fn override_css(doc: &Document, o: &CharAttrs) -> String { { let _ = write!(s, "color: {h}; "); } - attrs_decor_css(o, &mut s); + let base = doc.styles.char_style_attrs(style); + let mut merged = base.clone(); + merged.merge(o); + let tracking = if o.tracking.is_some() { merged.tracking.unwrap_or(0.0) } else { 0.0 }; + let caps = if o.capitalization.is_some() { merged.capitalization.unwrap_or_default() } else { Default::default() }; + let lines = o.underline.is_some() || o.strikethrough.is_some(); + let (underline, strikethrough) = (lines && merged.underline == Some(true), lines && merged.strikethrough == Some(true)); + if o.tracking.is_some() && tracking == 0.0 && base.tracking.is_some_and(|t| t != 0.0) { + s.push_str("letter-spacing: 0em; "); + } + // The class rule's other caps property would still apply, so clear both before the new mode. + if o.capitalization.is_some() && caps != base.capitalization.unwrap_or_default() && base.capitalization.is_some_and(|c| c != Default::default()) { + s.push_str("text-transform: none; font-variant: normal; "); + } + decor_css(tracking, caps, underline, strikethrough, &mut s); + if lines && !underline && !strikethrough && (base.underline == Some(true) || base.strikethrough == Some(true)) { + s.push_str("text-decoration: none; "); + } s.trim_end().to_string() } diff --git a/crates/epub/src/story_writer.rs b/crates/epub/src/story_writer.rs index aed443d0b..40c95f135 100644 --- a/crates/epub/src/story_writer.rs +++ b/crates/epub/src/story_writer.rs @@ -223,7 +223,7 @@ impl<'a, 'f> StoryWriter<'a, 'f> { } else { ("span", String::new()) }; - let style = override_css(doc, &f.over); + let style = override_css(doc, &f.style, &f.over); let style_attr = if style.is_empty() { String::new() } else { format!(" style=\"{}\"", xml_attr(&style)) }; if cls.is_empty() && style_attr.is_empty() { out.push_str(&t); diff --git a/crates/epub/src/tests.rs b/crates/epub/src/tests.rs index 6cae6159f..4b0531967 100644 --- a/crates/epub/src/tests.rs +++ b/crates/epub/src/tests.rs @@ -943,5 +943,37 @@ fn character_styles_keep_decorations_caps_and_tracking() { assert!(css.contains("text-transform: uppercase;"), "{css}"); assert!(css.contains("letter-spacing: 0.100em;"), "{css}"); let o = CharAttrs { strikethrough: Some(true), ..Default::default() }; - assert_eq!(css::override_css(&d, &o), "text-decoration: line-through;"); + assert_eq!(css::override_css(&d, story::NO_CHAR_STYLE, &o), "text-decoration: line-through;"); +} + +fn char_style(name: &str, based_on: Option<&str>, chars: CharAttrs) -> designcraft_doc::CharacterStyle { + designcraft_doc::CharacterStyle { name: name.into(), based_on: based_on.map(Into::into), chars, shortcut: String::new() } +} + +#[test] +fn override_keeps_style_decorations_and_resets_tracking_and_caps() { + use designcraft_doc::Capitalization; + let mut d = Document::new(&NewDocument::default()); + let styles = d.styles_mut(); + styles.character.push(char_style( + "Base", + None, + CharAttrs { underline: Some(true), tracking: Some(100.0), capitalization: Some(Capitalization::AllCaps), ..Default::default() }, + )); + styles.character.push(char_style("Child", Some("Base"), CharAttrs::default())); + let strike = CharAttrs { strikethrough: Some(true), ..Default::default() }; + for style in ["Base", "Child"] { + assert_eq!(css::override_css(&d, style, &strike), "text-decoration: underline line-through;", "{style}"); + } + let off = CharAttrs { underline: Some(false), ..Default::default() }; + assert_eq!(css::override_css(&d, "Child", &off), "text-decoration: none;"); + let reset = CharAttrs { tracking: Some(0.0), capitalization: Some(Capitalization::Normal), ..Default::default() }; + assert_eq!(css::override_css(&d, "Child", &reset), "letter-spacing: 0em; text-transform: none; font-variant: normal;"); + assert_eq!(css::override_css(&d, story::NO_CHAR_STYLE, &reset), ""); + let styles = d.styles_mut(); + styles.character.push(char_style("Small", None, CharAttrs { capitalization: Some(Capitalization::SmallCaps), ..Default::default() })); + let small = CharAttrs { capitalization: Some(Capitalization::SmallCaps), ..Default::default() }; + let all = CharAttrs { capitalization: Some(Capitalization::AllCaps), ..Default::default() }; + assert_eq!(css::override_css(&d, "Base", &small), "text-transform: none; font-variant: normal; font-variant: small-caps;"); + assert_eq!(css::override_css(&d, "Small", &all), "text-transform: none; font-variant: normal; text-transform: uppercase;"); } From ea08e4c2ba290f092063c99d70c4bdd5afc45887 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 30 Oct 2026 02:37:30 -0400 Subject: [PATCH 0516/1349] UPD.1: honor app pretend versions in update checks (#2025) --- Cargo.lock | 2 +- Cargo.toml | 4 ++-- contributors/people.toml | 3 +++ 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6344685d7..935d51547 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1138,7 +1138,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1065653e75854e9c17e1ff563acdd344c1b185f0#1065653e75854e9c17e1ff563acdd344c1b185f0" +source = "git+https://github.com/storytold/craft-libs?rev=04aa1703b32d299e54f78fcde4182f2b393a9116#04aa1703b32d299e54f78fcde4182f2b393a9116" dependencies = [ "chrono", "dunce", diff --git a/Cargo.toml b/Cargo.toml index fd8629f62..22ab1e32d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,8 +17,8 @@ craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff1 craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.1.0", features = ["egui", "ui"] } # Separations, ink coverage and the ink manager; same revision as craft-pdf and the krilla patch. craft-prepress = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.1.0", features = ["flatten"] } -# craft-update with storytold/craft-libs#434: the update prompt shows the app's icon, accent and developer. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1065653e75854e9c17e1ff563acdd344c1b185f0", features = ["egui"] } +# craft-update: app-specific pretend versions apply to startup and manual checks. +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "04aa1703b32d299e54f78fcde4182f2b393a9116", features = ["egui"] } # internal designcraft-geom = { path = "crates/geom" } designcraft-color = { path = "crates/color" } diff --git a/contributors/people.toml b/contributors/people.toml index 79acd86b0..e5b22d268 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -71,3 +71,6 @@ real_name = "Paul Gemignani" [people.skylartaylor] display_name = "skylartaylor" + +[people.dylanmtaylor] +sync_github_name = true From b68885b990ab17eedd81cc7387c260c48a5e7c13 Mon Sep 17 00:00:00 2001 From: ashokram-si <347905169+ashokram-si@users.noreply.github.com> Date: Fri, 30 Oct 2026 14:37:18 +0530 Subject: [PATCH 0517/1349] Spread::page_seams: draw the spine only where pages meet The canvas worked out page boundaries itself, pairing pages in list order and drawing a line between each pair. Pages that don't touch (an imported spread can keep gaps between them) got a false spine in the gap, and list order isn't position order for every spread. Spread::page_seams, next to spine_x, now gives the edges where two of a spread's pages meet: pages in position order, facing edges that touch, each seam spanning both pages' heights. The canvas draws exactly those. Test: page_seams for a facing pair in either list order, three pages (two seams), a single page (none), a gap (none) and pages of different heights. --- crates/doc/src/page.rs | 37 +++++++++++++++++++++++++ crates/ui-egui/src/canvas/page_decor.rs | 14 +++------- 2 files changed, 41 insertions(+), 10 deletions(-) diff --git a/crates/doc/src/page.rs b/crates/doc/src/page.rs index 7041f7ed8..72024b3ff 100644 --- a/crates/doc/src/page.rs +++ b/crates/doc/src/page.rs @@ -433,6 +433,21 @@ impl Spread { None => self.bounds().center().x, } } + /// The edges where two pages of the spread meet, left to right: the x of each shared edge and + /// the vertical span of the two pages together. Pages are taken in position order, so + /// right-to-left binding and any page count work; pages that don't touch (an imported spread + /// can keep gaps between them) share no edge. + pub fn page_seams(&self) -> Vec<(f64, f64, f64)> { + /// Facing edges this close (in points) meet: page positions are sums of widths. + const TOUCH: f64 = 1e-6; + let mut pages: Vec = self.pages.iter().map(Page::bounds).collect(); + pages.sort_by(|a, b| a.x0.total_cmp(&b.x0)); + pages + .windows(2) + .filter(|w| (w[1].x0 - w[0].x1).abs() <= TOUCH * w[0].x1.abs().max(1.0)) + .map(|w| (w[1].x0, w[0].y0.min(w[1].y0), w[0].y1.max(w[1].y1))) + .collect() + } /// Indices of the leftmost and rightmost pages. A right-to-left bound spread lists its right /// page first, so list order says nothing about position. pub fn outer_page_indices(&self) -> Option<(usize, usize)> { @@ -674,6 +689,28 @@ mod tests { assert_eq!(s.page_at_x(5000.0), Some(1)); } + /// Seams are where two pages' facing edges meet, in position order: one per shared edge for + /// any page count or binding, none across a gap, spanning both pages' heights. + #[test] + fn page_seams_are_shared_edges_only() { + let spread = |pages| Spread { id: SpreadId(1), pages, items: vec![], parent: None, allow_shuffle: true }; + let full = (0.0, 792.0); + // A facing pair, listed in either order (right-to-left binding lists the right page first). + for pages in [vec![page(PageSide::Left, 0.0), page(PageSide::Right, 612.0)], vec![page(PageSide::Right, 612.0), page(PageSide::Left, 0.0)]] { + assert_eq!(spread(pages).page_seams(), vec![(612.0, full.0, full.1)]); + } + // Three pages: two seams; a single page: none. + let three = spread(vec![page(PageSide::Left, 0.0), page(PageSide::Right, 612.0), page(PageSide::Right, 1224.0)]); + assert_eq!(three.page_seams(), vec![(612.0, 0.0, 792.0), (1224.0, 0.0, 792.0)]); + assert!(spread(vec![page(PageSide::Single, 0.0)]).page_seams().is_empty()); + // A gap between the pages, as an import can keep: no shared edge. + assert!(spread(vec![page(PageSide::Left, 0.0), page(PageSide::Right, 700.0)]).page_seams().is_empty()); + // Pages of different heights: the seam spans both. + let mut tall = page(PageSide::Right, 612.0); + tall.height = 1000.0; + assert_eq!(spread(vec![page(PageSide::Left, 0.0), tall]).page_seams(), vec![(612.0, 0.0, 1000.0)]); + } + /// The outside bleed goes on the leftmost and rightmost pages, also when right-to-left /// binding lists the right page first. #[test] diff --git a/crates/ui-egui/src/canvas/page_decor.rs b/crates/ui-egui/src/canvas/page_decor.rs index cddb5fd56..39df15a78 100644 --- a/crates/ui-egui/src/canvas/page_decor.rs +++ b/crates/ui-egui/src/canvas/page_decor.rs @@ -86,18 +86,12 @@ fn draw_bleed_and_slug(painter: &egui::Painter, xf: &Xf, doc: &Document, slot: & } } -/// The spine: a hairline where the pages of a spread meet, the full height of the taller page, in -/// the spread edge's colour ([`PAGE_EDGE`]). Screen only, like the other guides; the paper is one -/// rectangle and exports never show a seam. +/// The spine: a hairline at each edge where two pages of a spread meet +/// ([`designcraft_doc::Spread::page_seams`]), in the spread edge's colour ([`PAGE_EDGE`]). Screen +/// only, like the other guides; the paper is one rectangle and exports never show a seam. fn draw_spine(painter: &egui::Painter, xf: &Xf, slot: &SpreadSlot, sp: &designcraft_doc::Spread) { let pt = |p: Point| xf.to_screen(slot.xf * p); - for pair in sp.pages.windows(2) { - // Bound right to left, a spread lists its right page first: take the two edges that - // meet, whichever page comes first. - let (a, b) = (pair[0].bounds(), pair[1].bounds()); - let (left, right) = if a.x0 <= b.x0 { (a, b) } else { (b, a) }; - let x = (left.x1 + right.x0) / 2.0; - let (y0, y1) = (a.y0.min(b.y0), a.y1.max(b.y1)); + for (x, y0, y1) in sp.page_seams() { painter.line_segment([pt(Point::new(x, y0)), pt(Point::new(x, y1))], Stroke::new(hair(painter), PAGE_EDGE)); } } From 7366589464ddf31e8c398af60966c3c8fdd28bea Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 11:41:28 +0100 Subject: [PATCH 0518/1349] Anchor point tests: transform_anchors from main's split Properties object module Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/properties/tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index ef4519688..6aa5b5c07 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -4,6 +4,7 @@ use egui_kittest::{ }; use super::*; +use super::object::transform_anchors; /// A link to a panel whose flyout is open leaves the flyout open. #[test] From 0403b988c160e374f6476273fb13545a1fbe081f Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 11:46:38 +0100 Subject: [PATCH 0519/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/properties/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 6aa5b5c07..65e4bc793 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -3,8 +3,8 @@ use egui_kittest::{ kittest::{NodeT, Queryable}, }; -use super::*; use super::object::transform_anchors; +use super::*; /// A link to a panel whose flyout is open leaves the flyout open. #[test] From fd3d2f4e4922cc1bf9c891848304bdb747de0e85 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 11:46:43 +0100 Subject: [PATCH 0520/1349] Document properties: the page box field in its own function Keeps document_sections within clippy's cognitive complexity limit. Co-Authored-By: Claude Opus 5.5 --- .../ui-egui/src/panels/properties/document.rs | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/document.rs b/crates/ui-egui/src/panels/properties/document.rs index f9ac002cb..d68d4531c 100644 --- a/crates/ui-egui/src/panels/properties/document.rs +++ b/crates/ui-egui/src/panels/properties/document.rs @@ -172,6 +172,15 @@ fn page_preset_menu(ui: &mut Ui, pw: f64, ph: f64) -> Option<(f64, f64)> { preset } +/// As the status bar's page box: the page, or the parent shown ("A-Parent"); then the parents. +fn page_box_field(app: &mut DesignApp, ui: &mut Ui, b: Rect) { + let Some(pb) = crate::canvas::page_box(app) else { return }; + let picked = place(ui, sub(b, 0.0, 0.0, 93.0, FIELD_H), |ui| widgets::dropdown_list(ui, pb.current_name(), 93.0, &pb.names, Some(pb.current))); + if let Some(i) = picked { + crate::canvas::page_box_go(app, &pb, i); + } +} + pub(super) fn document_sections(app: &mut DesignApp, ui: &mut Ui) { let u = units(app); let Some(st) = app.session.active() else { return }; @@ -287,14 +296,7 @@ pub(super) fn document_sections(app: &mut DesignApp, ui: &mut Ui) { // Page. section(ui, crate::i18n::tr(&app.ui.language, "Page"), true); let b = block(ui, FIELD_H); - // As the status bar's page box: the page, or the parent shown ("A-Parent"); then the parents. - if let Some(pb) = crate::canvas::page_box(app) { - let picked = - place(ui, sub(b, 0.0, 0.0, 93.0, FIELD_H), |ui| widgets::dropdown_list(ui, pb.current_name(), 93.0, &pb.names, Some(pb.current))); - if let Some(i) = picked { - crate::canvas::page_box_go(app, &pb, i); - } - } + page_box_field(app, ui, b); let (add, del) = place(ui, sub(b, 172.0, 0.0, 50.0, FIELD_H), |ui| { ui.spacing_mut().item_spacing.x = 4.0; let a = widgets::icon_toggle_sized(ui, "style-new", false, "Insert Page", vec2(22.0, 21.0)).clicked(); From d9a55d19d61e67788cc04acc763182c8910bf13f Mon Sep 17 00:00:00 2001 From: r31lin <257763872+r31lin@users.noreply.github.com> Date: Fri, 30 Oct 2026 11:52:42 +0100 Subject: [PATCH 0521/1349] Ask the graphics device for the adapter's largest buffer egui-wgpu doubles its vertex buffer when a frame outgrows it, and wgpu's default largest buffer is 256 MiB. Opening a 160-page InDesign catalogue produced a frame with 137 MB of vertices; egui-wgpu asked for a 275 MB buffer, the device refused it and the app stopped. The device now takes the adapter's own largest buffer, as it already did for the texture side (2047 MiB on DirectX 12 here), and the log says both limits. Co-Authored-By: Claude Opus 5.5 --- apps/designcraft/src/gpu_limits.rs | 40 +++++++++++++++++++++++------- apps/designcraft/src/main.rs | 8 +++++- 2 files changed, 38 insertions(+), 10 deletions(-) diff --git a/apps/designcraft/src/gpu_limits.rs b/apps/designcraft/src/gpu_limits.rs index 5615e5650..13eca4719 100644 --- a/apps/designcraft/src/gpu_limits.rs +++ b/apps/designcraft/src/gpu_limits.rs @@ -6,6 +6,11 @@ //! (9048×5757 between 250 % and 100 % monitors), then failed `Surface::configure`, and wgpu's //! default error handler panics: the app closed with the documents in it. DirectX 12, Vulkan and //! Metal hardware offer 16384. +//! +//! The same goes for buffers: egui-wgpu doubles its vertex buffer when a frame outgrows it, and +//! wgpu's default largest buffer is 256 MiB. A frame of a 160-page catalogue with 137 MB of vertices +//! asked for a 275 MB buffer, and egui-wgpu panicked when the device refused it. DirectX 12 and +//! Vulkan hardware offer far more. use eframe::{ NativeOptions, @@ -14,21 +19,23 @@ use eframe::{ }; use std::sync::{Arc, Mutex, PoisonError}; -/// `required` with the largest texture side the adapter's `supported` limits offer. Taking the -/// adapter's own value also never asks a smaller (downlevel) adapter for more than it has. -pub fn surface_texture_limits(mut required: Limits, supported: &Limits) -> Limits { +/// `required` with the largest texture side and buffer the adapter's `supported` limits offer. +/// Taking the adapter's own values also never asks a smaller (downlevel) adapter for more than it +/// has. +pub fn adapter_size_limits(mut required: Limits, supported: &Limits) -> Limits { required.max_texture_dimension_2d = supported.max_texture_dimension_2d; + required.max_buffer_size = supported.max_buffer_size; required } -/// Makes the device eframe creates ask for the adapter's largest texture side -/// ([`surface_texture_limits`]), keeping eframe's other device requirements. -pub fn request_adapter_texture_size(options: &mut NativeOptions) { +/// Makes the device eframe creates ask for the adapter's largest texture side and buffer +/// ([`adapter_size_limits`]), keeping eframe's other device requirements. +pub fn request_adapter_sizes(options: &mut NativeOptions) { if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup { let device_descriptor = Arc::clone(&create.device_descriptor); create.device_descriptor = Arc::new(move |adapter| { let mut descriptor = device_descriptor(adapter); - descriptor.required_limits = surface_texture_limits(descriptor.required_limits, &adapter.limits()); + descriptor.required_limits = adapter_size_limits(descriptor.required_limits, &adapter.limits()); descriptor }); } @@ -62,7 +69,7 @@ mod tests { let eframe_request = Limits { max_texture_dimension_2d: 8192, ..base.clone() }; for side in [4096, 8192, 16384, 32768] { let supported = Limits { max_texture_dimension_2d: side, ..base.clone() }; - let limits = surface_texture_limits(eframe_request.clone(), &supported); + let limits = adapter_size_limits(eframe_request.clone(), &supported); assert_eq!(limits.max_texture_dimension_2d, side); // The drag's 9048×5757 surface fits from 16384 up. assert_eq!(side >= 16384, 9048 <= limits.max_texture_dimension_2d); @@ -73,12 +80,27 @@ mod tests { } } + #[test] + fn largest_buffer_is_the_adapters_own() { + // egui-wgpu grew its vertex buffer to 275 MB for 137 MB of vertices: more than wgpu's + // default 256 MiB, within what DirectX 12 hardware offers. A downlevel adapter offering + // less is asked for no more. + let eframe_request = Limits::default(); + for size in [128 << 20, 256 << 20, 2 << 30] { + let supported = Limits { max_buffer_size: size, ..Limits::default() }; + let limits = adapter_size_limits(eframe_request.clone(), &supported); + assert_eq!(limits.max_buffer_size, size); + assert_eq!(size >= 2 << 30, limits.max_buffer_size >= 275_114_400); + assert!(limits.check_limits(&supported)); + } + } + #[test] fn native_options_keep_creating_their_own_device() { // The wrapper only replaces the device descriptor: eframe still creates the instance, // adapter and device, and main.rs can still choose the backends. let mut options = NativeOptions::default(); - request_adapter_texture_size(&mut options); + request_adapter_sizes(&mut options); assert!(matches!(options.wgpu_options.wgpu_setup, WgpuSetup::CreateNew(_))); } } diff --git a/apps/designcraft/src/main.rs b/apps/designcraft/src/main.rs index 4b4a1ab7f..180aca13e 100644 --- a/apps/designcraft/src/main.rs +++ b/apps/designcraft/src/main.rs @@ -316,7 +316,7 @@ fn main() -> std::process::ExitCode { } // The adapter's largest texture side instead of eframe's 8192, so a window across several // monitors keeps its surface (see `gpu_limits`). - gpu_limits::request_adapter_texture_size(&mut options); + gpu_limits::request_adapter_sizes(&mut options); // The graphics backend, decided before the window exists: a driver that faults takes the // process down before any Rust code can catch it (see `gpu::backend`). let fallback = gpu::backend::Fallback::begin( @@ -395,6 +395,12 @@ fn main() -> std::process::ExitCode { info.driver, info.driver_info ); + let limits = rs.device.limits(); + log::info!( + "graphics: largest texture side {}, largest buffer {} MiB", + limits.max_texture_dimension_2d, + limits.max_buffer_size >> 20 + ); created.started_with(info.backend); created.created(&cc.egui_ctx); if !skip.is_empty() { From 4652ad2bbcd4afafe98db36e92d41509bcf295bb Mon Sep 17 00:00:00 2001 From: tareq Date: Fri, 30 Oct 2026 12:00:47 +0100 Subject: [PATCH 0522/1349] Toolbar: Alt/Option-click cycles the flyout tool group. Matches InDesign/Photoshop: plain click keeps the shown tool; Alt-click advances the slot without opening the menu. --- crates/ui-egui/src/toolbar.rs | 14 ++++++++++++-- crates/ui-egui/src/toolbar/tests.rs | 29 +++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 4c6965ffc..ea5034219 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -103,19 +103,29 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { // on the tool (egui reports releases within 0.8 s as clicks). let hold_id = egui::Id::unique(("flyout_hold", gi)); let ended_hold = resp.clicked() && ui.data_mut(|d| d.remove_temp::(hold_id)).unwrap_or(false); + // Plain click selects the shown tool; Alt/Option-click cycles the flyout + // group (InDesign / Photoshop parity with the letter-key cycle). + let alt = ui.input(|i| i.modifiers.alt); if resp.clicked() && !ended_hold { - chosen = Some(shown.id); + chosen = Some(if g.len() > 1 && alt { + let from = g.iter().position(|tl| tl.id == current).unwrap_or(0); + g[(from + 1) % g.len()].id + } else { + shown.id + }); } if !resp.is_pointer_button_down_on() { ui.data_mut(|d| d.remove::(hold_id)); } // Double-click a polygon tool: Polygon Settings. - if resp.double_clicked() && matches!(shown.id, "polygon" | "polygonFrame") { + // Alt-clicks only cycle the group: exclude them from double-click dialogs. + if resp.double_clicked() && !alt && matches!(shown.id, "polygon" | "polygonFrame") { let cur = app.session.execute("tool.polygonSettings", &json!({})).unwrap_or_default(); app.ui.dialog = Some(crate::dialogs::Dialog::new("polygonSettings", cur)); } // Double-click a transform tool: its Object › Transform dialog. if resp.double_clicked() + && !alt && let Some(cmd) = transform_dialog_of(shown.id) { crate::menus::activate(app, cmd, &Value::Null); diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 6a8ea752c..97a3bf6c3 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -378,3 +378,32 @@ fn fill_stroke_proxy_keys() { press(&mut app, &ctx, Key::X, Modifiers::NONE); assert_eq!(app.ui.stroke_front, front, "X while typing leaves the proxy alone"); } + +/// Alt/Option-click cycles a tool group's flyout without opening the menu. +#[test] +fn alt_click_cycles_the_tool_flyout_group() { + use egui::{Event, Modifiers, PointerButton}; + use egui_kittest::kittest::Queryable; + let app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let mut h = crate::test_window::open(app, vec2(1400.0, 900.0)); + h.state_mut().app.select_tool("rectangleFrame"); + h.run_steps(2); + let at = h.get_by_label("Rectangle Frame Tool (F)").rect().center(); + let alt = Modifiers { alt: true, ..Default::default() }; + let click = |h: &mut egui_kittest::Harness<'static, crate::test_window::Window>, modifiers: Modifiers| { + h.input_mut().events.push(Event::ModifiersChanged(modifiers)); + h.input_mut().events.push(Event::PointerMoved(at)); + for pressed in [true, false] { + h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers }); + } + h.run_steps(3); + }; + click(&mut h, Modifiers::NONE); + assert_eq!(h.state().app.session.tool_id(), "rectangleFrame"); + assert!(h.state().app.ui.flyout.is_none()); + click(&mut h, alt); + assert_eq!(h.state().app.session.tool_id(), "ellipseFrame", "Alt-click advances the frame group"); + assert!(h.state().app.ui.flyout.is_none(), "Alt-click must not open the flyout"); + click(&mut h, alt); + assert_eq!(h.state().app.session.tool_id(), "polygonFrame"); +} From 9e1e9d079564170379c92c0c331f10de90b2bb54 Mon Sep 17 00:00:00 2001 From: macadminHU <51995175+macrobi@users.noreply.github.com> Date: Fri, 30 Oct 2026 12:04:03 +0100 Subject: [PATCH 0523/1349] HU1: retain upstream Georgian captions without duplicates Removed Georgian translations for 'File Info...' and 'Check for Updates...'. --- crates/ui-egui/src/i18n/ka.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index 7cb8699f7..14a9e6203 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -5,7 +5,6 @@ //! the code or the command table use. pub(super) const TABLE: &[(&str, &str)] = &[ ("File", "ფაილი"), - ("File Info…", "ფაილის ინფორმაცია…"), ("Edit", "რედაქტირება"), ("Layout", "განლაგება"), ("Type", "ტექსტი"), @@ -433,7 +432,6 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Ungroup Color Group", "ფერების ჯგუფის დაშლა"), ("Unmerge", "შერწყმის გაუქმება"), ("Update", "განახლება"), - ("Check for Updates…", "განახლებების შემოწმება…"), ("Update Numbering", "დანომვრის განახლება"), ("Use Global Light", "გლობალური განათების გამოყენება"), ("User Dictionary", "მომხმარებლის ლექსიკონი"), From 453a3256f9cde17384c31bf77a6dfc818da39248 Mon Sep 17 00:00:00 2001 From: macadminHU <51995175+macrobi@users.noreply.github.com> Date: Fri, 30 Oct 2026 12:06:41 +0100 Subject: [PATCH 0524/1349] HU1: translate the Story Editor depth-ruler caption --- crates/ui-egui/src/i18n/hu.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/i18n/hu.rs b/crates/ui-egui/src/i18n/hu.rs index 29406978c..890959761 100644 --- a/crates/ui-egui/src/i18n/hu.rs +++ b/crates/ui-egui/src/i18n/hu.rs @@ -1493,6 +1493,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Show in the text", "Megjelenítés a szövegben"), ("Show the Typography panel", "Tipográfia panel megjelenítése"), ("Show/Hide Baseline Grid", "Alapvonalrács megjelenítése/elrejtése"), + ("Show/Hide Depth Ruler", "Mélységmérő megjelenítése/elrejtése"), ("Show/Hide Frame Edges", "Keretélek megjelenítése/elrejtése"), ("Show/Hide Guides", "Segédvonalak megjelenítése/elrejtése"), ("Show/Hide Hidden Characters", "Rejtett karakterek megjelenítése/elrejtése"), From 4cb6ad4f8abf693035508f52cac6238d268afd53 Mon Sep 17 00:00:00 2001 From: macadminHU <51995175+macrobi@users.noreply.github.com> Date: Fri, 30 Oct 2026 12:07:19 +0100 Subject: [PATCH 0525/1349] HU1: retain menu assertions under the upstream complexity limit Introduced a new test function to check Georgian menu label translations and replaced the previous inline implementation with a call to this new function. --- crates/ui-egui/src/menus/tests.rs | 45 +++++++++++++++++-------------- 1 file changed, 25 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 2f5cdaf09..9fd0247c2 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -587,6 +587,30 @@ fn show_document_grid_toggles_from_the_grids_and_guides_menu() { assert!(!app.ui.document_grid); } +/// Checks every Georgian menu title, item and submenu, allowing language-neutral labels. +fn assert_georgian_menu_labels_are_translated() { + // Every menu title, item and submenu is translated into Georgian. + let mut untranslated = Vec::new(); + for (title, entries) in menu_tree() { + let mut labels = vec![title.to_string()]; + let mut stack: Vec<&Item> = entries.iter().collect(); + while let Some(entry) = stack.pop() { + match entry { + Item::Sub(label, children) => { + labels.push(label.clone()); + stack.extend(children.iter()); + } + Item::Cmd { label, id, .. } if id != "app.language" => labels.push(label.clone()), + _ => {} + } + } + // Labels without letters ("180°") or point sizes ("72 pt") read the same in every language. + let size = |l: &str| l.strip_suffix(" pt").is_some_and(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit())); + untranslated.extend(labels.into_iter().filter(|l| l.chars().any(char::is_alphabetic) && !size(l) && crate::i18n::tr("ka", l) == l.as_str())); + } + assert!(untranslated.is_empty(), "untranslated Georgian menu labels: {untranslated:?}"); +} + /// Checks language selection and rejection of unknown language codes, Preferences dispatch, /// translated menu labels and preservation of document data when switching to Arabic. #[test] @@ -651,26 +675,7 @@ fn interface_language_switches_and_validates() { run_ui(&mut app, "app.language", &json!({"lang": "ka"})).unwrap().unwrap(); assert_eq!(app.ui.language, "ka"); assert_eq!(checked(&app, "app.language", &json!({"lang": "ka"})), Some(true)); - // Every menu title, item and submenu is translated into Georgian. - let mut untranslated = Vec::new(); - for (title, entries) in menu_tree() { - let mut labels = vec![title.to_string()]; - let mut stack: Vec<&Item> = entries.iter().collect(); - while let Some(entry) = stack.pop() { - match entry { - Item::Sub(label, children) => { - labels.push(label.clone()); - stack.extend(children.iter()); - } - Item::Cmd { label, id, .. } if id != "app.language" => labels.push(label.clone()), - _ => {} - } - } - // Labels without letters ("180°") or point sizes ("72 pt") read the same in every language. - let size = |l: &str| l.strip_suffix(" pt").is_some_and(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit())); - untranslated.extend(labels.into_iter().filter(|l| l.chars().any(char::is_alphabetic) && !size(l) && crate::i18n::tr("ka", l) == l.as_str())); - } - assert!(untranslated.is_empty(), "untranslated Georgian menu labels: {untranslated:?}"); + assert_georgian_menu_labels_are_translated(); } /// Checks Hungarian selection, menu captions and saved UI preferences without changing From 745ba77fd00d254511ddc08e7321ec158cbfb065 Mon Sep 17 00:00:00 2001 From: macadminHU <51995175+macrobi@users.noreply.github.com> Date: Fri, 30 Oct 2026 12:08:20 +0100 Subject: [PATCH 0526/1349] HU1: document current-main integration and the depth-ruler caption Updated Hungarian localization entries and added Depth Ruler caption. --- docs/localization-parity.md | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/docs/localization-parity.md b/docs/localization-parity.md index a42ecb0c3..32a362ae4 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-27 · **Change:** minor (shared-module integration and retained localization regressions; older catalog counts retain their dated measurement) · **Target:** Adobe InDesign 2026 (21.6) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-30 · **Change:** minor (current-main integration with retained catalogs and regression tests; older catalog counts retain their dated measurement) · **Target:** Adobe InDesign 2026 (21.6) Per-language status of the DesignCraft interface and of document typesetting in each script. Script-specific typesetting detail: [cjk.md](cjk.md), [cjk-typography.md](cjk-typography.md), @@ -87,11 +87,22 @@ Hungarian catalog contents and the dated coverage measurements are unchanged. To coverage follows the current platform-specific keymap captions and checks a user-assigned chord alongside translated flyout text; row sizing measures the displayed shortcut. +Main integration (2026-10-30): retain every prior Hungarian entry and both branches’ +localization, menu and toolbar regressions while adopting upstream’s current file-dialog test +harness and toolbar proxy refactor. Add `Show/Hide Depth Ruler` as `Mélységmérő +megjelenítése/elrejtése`, bringing the catalog to **1,906 entries and four context captions**. +The upstream all-language depth-ruler assertion is retained. The unchanged complete Georgian +menu assertions run through a helper so the existing language-switch test meets upstream’s +new complexity limit. The two Georgian menu captions now also exist in main; retain each +identical translation once, keeping the direct lookup and complete-menu assertions. The +progress log keeps both branches’ dated entries; this targeted addition is not a new coverage +measurement. + ## Other shipped languages | Language | Code | UI strings translated | Status | |---|---|---|---| -| Hungarian | hu | 1,905 entries + 4 context captions (2026-10-25); initial native review | partial | +| Hungarian | hu | 1,906 entries + 4 context captions (2026-10-30); initial catalog native-reviewed | partial | | Czech | cs | 1,722 (99%), plural categories handled | partial | | Italian | it | 1,464 (85%) | partial | | Ukrainian | uk | 1,432 (83%), plural categories handled | partial | @@ -128,6 +139,7 @@ German variants have no automatic hyphenation; their German shaping and quotes a | Date | Change | Summary | |---|---|---| +| 2026-10-30 | minor | Integrate current main; retain both branches’ entries/tests; add Hungarian Depth Ruler caption (1,906 entries + four context captions) | | 2026-10-27 | minor | Adopt shared module layout; preserve both parents' tests and all Hungarian catalog entries | | 2026-10-25 | minor | Hungarian Data Merge arrangement caption added; 1,905 entries and four context captions; both merge parents' tests retained | | 2026-10-25 | minor | Georgian File Info and Check for Updates captions added; complete-menu regression retained | From b7f4612aa1d19f8f89488a21a33b1c0b2406c5dc Mon Sep 17 00:00:00 2001 From: macadminHU <51995175+macrobi@users.noreply.github.com> Date: Fri, 30 Oct 2026 12:09:00 +0100 Subject: [PATCH 0527/1349] HU1: preserve the verified roadmap without editor whitespace --- ROADMAP.md | 1 - 1 file changed, 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index cc59b2f01..113cab376 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -767,4 +767,3 @@ The shared craft-installer UI preserves this revision's install options and prov - **2026-10-15** · Windows recovery folders validate the identity of the live locked file without reading it through a second handle. Missing or replaced locks disable writes and cleanup; regression tests cover retained exclusive locking and replacement-file protection. No readiness percentage change. - PDF reader infrastructure: pinned shared parsing/rasterization, transformed page-box geometry and explicit failures for known incomplete layered-PDF exports. Application ownership and parity targets are unchanged. - \ No newline at end of file From d4b7e6659242b77150ad9596cbf494095b715fd8 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 12:33:53 +0100 Subject: [PATCH 0528/1349] Table convert dialogs: menu_enabled from main's split menu state module Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/menus/run.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index b88dfb4a1..c4b99e474 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -1,6 +1,6 @@ use super::export::{download_document, export_bytes, export_epub, export_idml, export_pdf, export_png, separations_view}; use super::invoke::guide_spread; -use super::state::{is_window_control, window_control_available}; +use super::state::{is_window_control, menu_enabled, window_control_available}; use super::tables::{CLASSIC_GROUPS, TYPOGRAPHY_GROUPS, workspace_open_panel}; use super::tree::recent_label; use super::{DesignApp, ScreenMode, Value, json}; From 5ec44d213e503544c12d3549d89155b4fe47908a Mon Sep 17 00:00:00 2001 From: tareq Date: Fri, 30 Oct 2026 12:43:59 +0100 Subject: [PATCH 0529/1349] Toolbar: ignore double-click dialogs after an Alt-click. egui pairs a plain click with a prior Alt-click as a double-click; remember the previous click's Alt so polygon/transform dialogs only open for two plain clicks. --- crates/ui-egui/src/toolbar.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index ea5034219..ea7b4d287 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -106,7 +106,12 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { // Plain click selects the shown tool; Alt/Option-click cycles the flyout // group (InDesign / Photoshop parity with the letter-key cycle). let alt = ui.input(|i| i.modifiers.alt); - if resp.clicked() && !ended_hold { + // egui's double-click ignores modifiers: remember the previous click's + // Alt so dialogs only open for two plain clicks (same as PhotoCraft). + let prev_alt_id = egui::Id::unique(("tool-click-alt", gi)); + let prev_alt = ui.data(|d| d.get_temp::(prev_alt_id)).unwrap_or(false); + let slot_click = resp.clicked() && !ended_hold; + if slot_click { chosen = Some(if g.len() > 1 && alt { let from = g.iter().position(|tl| tl.id == current).unwrap_or(0); g[(from + 1) % g.len()].id @@ -119,17 +124,20 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { } // Double-click a polygon tool: Polygon Settings. // Alt-clicks only cycle the group: exclude them from double-click dialogs. - if resp.double_clicked() && !alt && matches!(shown.id, "polygon" | "polygonFrame") { + let plain_double = resp.double_clicked() && !alt && !prev_alt; + if plain_double && matches!(shown.id, "polygon" | "polygonFrame") { let cur = app.session.execute("tool.polygonSettings", &json!({})).unwrap_or_default(); app.ui.dialog = Some(crate::dialogs::Dialog::new("polygonSettings", cur)); } // Double-click a transform tool: its Object › Transform dialog. - if resp.double_clicked() - && !alt + if plain_double && let Some(cmd) = transform_dialog_of(shown.id) { crate::menus::activate(app, cmd, &Value::Null); } + if slot_click { + ui.data_mut(|d| d.insert_temp(prev_alt_id, alt)); + } let held = resp.is_pointer_button_down_on() && ui.input(|i| i.pointer.press_start_time().is_some_and(|s| i.time - s > 0.35)); if g.len() > 1 && held { From 4880b917ee53fb63941a9d4533887c2d7c746a7c Mon Sep 17 00:00:00 2001 From: tareq Date: Fri, 30 Oct 2026 13:02:19 +0100 Subject: [PATCH 0530/1349] Toolbar: read click modifiers from the pointer release. Prefer the primary-release event's modifiers for Alt-cycle, and suppress polygon/transform dialogs when either click of a double was modified. --- crates/ui-egui/src/toolbar.rs | 34 ++++++++++++++++++++++++++-------- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index ea7b4d287..8362d2083 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -105,11 +105,29 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { let ended_hold = resp.clicked() && ui.data_mut(|d| d.remove_temp::(hold_id)).unwrap_or(false); // Plain click selects the shown tool; Alt/Option-click cycles the flyout // group (InDesign / Photoshop parity with the letter-key cycle). - let alt = ui.input(|i| i.modifiers.alt); - // egui's double-click ignores modifiers: remember the previous click's - // Alt so dialogs only open for two plain clicks (same as PhotoCraft). - let prev_alt_id = egui::Id::unique(("tool-click-alt", gi)); - let prev_alt = ui.data(|d| d.get_temp::(prev_alt_id)).unwrap_or(false); + // Prefer the primary-release event's modifiers: Alt may already be up + // by the time this frame reads i.modifiers. + let click_mods = ui.input(|i| { + i.events + .iter() + .rev() + .find_map(|e| match e { + egui::Event::PointerButton { + button: egui::PointerButton::Primary, + pressed: false, + modifiers, + .. + } => Some(*modifiers), + _ => None, + }) + .unwrap_or(i.modifiers) + }); + let alt = click_mods.alt; + let modified = click_mods.alt || click_mods.shift || click_mods.ctrl || click_mods.command; + // egui's double-click ignores modifiers: remember whether the previous + // click was modified so dialogs only open for two plain clicks. + let prev_mod_id = egui::Id::unique(("tool-click-mod", gi)); + let prev_modified = ui.data(|d| d.get_temp::(prev_mod_id)).unwrap_or(false); let slot_click = resp.clicked() && !ended_hold; if slot_click { chosen = Some(if g.len() > 1 && alt { @@ -123,8 +141,8 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { ui.data_mut(|d| d.remove::(hold_id)); } // Double-click a polygon tool: Polygon Settings. - // Alt-clicks only cycle the group: exclude them from double-click dialogs. - let plain_double = resp.double_clicked() && !alt && !prev_alt; + // Modified clicks only cycle / select: exclude them from dialogs. + let plain_double = resp.double_clicked() && !modified && !prev_modified; if plain_double && matches!(shown.id, "polygon" | "polygonFrame") { let cur = app.session.execute("tool.polygonSettings", &json!({})).unwrap_or_default(); app.ui.dialog = Some(crate::dialogs::Dialog::new("polygonSettings", cur)); @@ -136,7 +154,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { crate::menus::activate(app, cmd, &Value::Null); } if slot_click { - ui.data_mut(|d| d.insert_temp(prev_alt_id, alt)); + ui.data_mut(|d| d.insert_temp(prev_mod_id, modified)); } let held = resp.is_pointer_button_down_on() && ui.input(|i| i.pointer.press_start_time().is_some_and(|s| i.time - s > 0.35)); From d1b647ac8ca21059ee9779a721ef26996ddec27f Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 13:05:20 +0100 Subject: [PATCH 0531/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 2 +- crates/ui-egui/src/panels/properties/tests.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 5896fdfee..2beb7fe17 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -4700,7 +4700,7 @@ fn para_corners(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: let tip = crate::i18n::tr(lang, tip); let (r, resp) = ui.allocate_exact_size(egui::vec2(18.0, 18.0), egui::Sense::hover()); crate::icons::paint(ui.painter(), r, icon, crate::theme::Tokens::get(ui.ctx()).icon); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, tip)); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, tip)); resp.on_hover_text(tip); let id = format!("ps{key}{i}"); if let Some(v) = crate::widgets::NumField::measure(&id, Some(c.size), units).width(84.0).spinner().range(0.0, 10_000.0).show(ui) { diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 5c9feea47..4458dae4f 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -717,7 +717,7 @@ fn preview_rows_fit_long_translated_names() { let long = "Скругленный прямоугольник с обратным углом"; let mut widths = (0.0, 0.0); let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { - egui::Area::new(egui::Id::new("rows")).show(ui.ctx(), |ui| { + egui::Area::new(egui::Id::unique("rows")).show(ui.ctx(), |ui| { ui.set_max_width(10.0); let r = preview_row(ui, false, long, 40.0, |_, _, _| {}); let text = ui.fonts_mut(|f| f.layout_no_wrap(long.to_string(), egui::FontId::proportional(12.0), egui::Color32::WHITE).size().x); From 5b52b23b00f55a06f6f787063a990f4b8561130b Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 13:07:37 +0100 Subject: [PATCH 0532/1349] IDML export: the paragraph box overprints in their own function Keeps para_box_attrs within clippy's cognitive complexity limit. Co-Authored-By: Claude Opus 5.5 --- crates/idml/src/export/text_attrs.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/idml/src/export/text_attrs.rs b/crates/idml/src/export/text_attrs.rs index 557602a18..1c0def755 100644 --- a/crates/idml/src/export/text_attrs.rs +++ b/crates/idml/src/export/text_attrs.rs @@ -22,6 +22,13 @@ macro_rules! b { }; } +/// The Overprint switches of a paragraph's shading, border and border gap. +fn para_box_overprints(el: &mut El, a: &ParaAttrs) { + b!(a, el, shading_overprint, "ParagraphShadingOverprint"); + b!(a, el, border_overprint, "ParagraphBorderOverprint"); + b!(a, el, border_gap_overprint, "ParagraphBorderGapOverprint"); +} + impl<'a> Ex<'a> { pub(super) fn char_attrs(&mut self, el: &mut El, props: &mut Vec, a: &CharAttrs) { if let Some(v) = a.leading_aki { @@ -494,7 +501,7 @@ impl<'a> Ex<'a> { props.push(p("ParagraphShadingColor", "object", self.sw(c))); } n!(a, el, shading_tint, "ParagraphShadingTint", pct); - b!(a, el, shading_overprint, "ParagraphShadingOverprint"); + para_box_overprints(el, a); const SIDES: [&str; 4] = ["Top", "Left", "Bottom", "Right"]; if let Some(o) = a.shading_offsets { for (i, side) in SIDES.iter().enumerate() { @@ -506,7 +513,6 @@ impl<'a> Ex<'a> { props.push(p("ParagraphBorderColor", "object", self.sw(c))); } n!(a, el, border_tint, "ParagraphBorderTint", pct); - b!(a, el, border_overprint, "ParagraphBorderOverprint"); if let Some(w) = a.border_weights { for (i, side) in SIDES.iter().enumerate() { el.set(&format!("ParagraphBorder{side}LineWeight"), num(w[i])); @@ -542,7 +548,6 @@ impl<'a> Ex<'a> { props.push(p("ParagraphBorderGapColor", "object", self.sw(c))); } n!(a, el, border_gap_tint, "ParagraphBorderGapTint", pct); - b!(a, el, border_gap_overprint, "ParagraphBorderGapOverprint"); if let Some(w) = a.shading_width { el.set("ParagraphShadingWidth", names::box_width_out(w)); } From db4f8a4d6da05b548a1ed7447d8f42e1342c98b5 Mon Sep 17 00:00:00 2001 From: tareq Date: Fri, 30 Oct 2026 13:21:01 +0100 Subject: [PATCH 0533/1349] Toolbar: assert Alt-click wrap-around in the flyout cycle test. CodeRabbit nitpick: after the last group tool, the next Alt-click must return to the first and keep the flyout closed. --- crates/ui-egui/src/toolbar/tests.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 97a3bf6c3..5db130f63 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -406,4 +406,7 @@ fn alt_click_cycles_the_tool_flyout_group() { assert!(h.state().app.ui.flyout.is_none(), "Alt-click must not open the flyout"); click(&mut h, alt); assert_eq!(h.state().app.session.tool_id(), "polygonFrame"); + click(&mut h, alt); + assert_eq!(h.state().app.session.tool_id(), "rectangleFrame", "Alt-click after the last group tool wraps to the first"); + assert!(h.state().app.ui.flyout.is_none(), "wrap-around Alt-click must not open the flyout"); } From 278b8e8bf4529c84adf3e3f8baae3223dc0be584 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 13:21:04 +0100 Subject: [PATCH 0534/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 1802a1fcf..eeb67869a 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1999,7 +1999,8 @@ fn preferences(app: &crate::DesignApp, ui: &mut egui::Ui, d: &mut Dialog, max_he crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&lang, "Panels")).font(semibold(12.0))); ui.horizontal(|ui| { let name = crate::rtl::label(ui, crate::i18n::tr(&lang, "Tools Panel:")); - translated_combo(&lang, ui, d, "toolsColumns", &[("single", "Single Column"), ("double", "Double Column")]).labelled_by(name.id); + translated_combo(&lang, ui, d, "toolsColumns", &[("single", "Single Column"), ("double", "Double Column")]) + .labelled_by(name.id); }); } "uiScaling" => { From 9476b39e89db970b9b3bbae5a2b4f1da68c2a836 Mon Sep 17 00:00:00 2001 From: tareq Date: Fri, 30 Oct 2026 13:56:25 +0100 Subject: [PATCH 0535/1349] Toolbar: bind click modifiers to the slot rect. Ignore primary releases outside this tool button so another widget cannot steer Alt-cycle or suppress dialogs; harden the Alt-click test to clear i.modifiers before release. --- crates/ui-egui/src/toolbar.rs | 5 ++++- crates/ui-egui/src/toolbar/tests.rs | 31 ++++++++++++++++++++--------- 2 files changed, 26 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 8362d2083..1ba172004 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -107,17 +107,20 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { // group (InDesign / Photoshop parity with the letter-key cycle). // Prefer the primary-release event's modifiers: Alt may already be up // by the time this frame reads i.modifiers. + // Only a release on this slot: the frame's event list is shared, + // so a later release elsewhere must not steer Alt-cycle / dialogs. let click_mods = ui.input(|i| { i.events .iter() .rev() .find_map(|e| match e { egui::Event::PointerButton { + pos, button: egui::PointerButton::Primary, pressed: false, modifiers, .. - } => Some(*modifiers), + } if resp.rect.contains(*pos) => Some(*modifiers), _ => None, }) .unwrap_or(i.modifiers) diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 5db130f63..5551ba2dd 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -390,23 +390,36 @@ fn alt_click_cycles_the_tool_flyout_group() { h.run_steps(2); let at = h.get_by_label("Rectangle Frame Tool (F)").rect().center(); let alt = Modifiers { alt: true, ..Default::default() }; - let click = |h: &mut egui_kittest::Harness<'static, crate::test_window::Window>, modifiers: Modifiers| { - h.input_mut().events.push(Event::ModifiersChanged(modifiers)); + // Clear i.modifiers before the release while keeping Alt on the release event, so a + // regression that only reads i.modifiers (and ignores the pointer-release modifiers) fails. + let click = |h: &mut egui_kittest::Harness<'static, crate::test_window::Window>, press_modifiers: Modifiers, current_modifiers: Modifiers| { + h.input_mut().events.push(Event::ModifiersChanged(press_modifiers)); h.input_mut().events.push(Event::PointerMoved(at)); - for pressed in [true, false] { - h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers }); - } + h.input_mut().events.push(Event::PointerButton { + pos: at, + button: PointerButton::Primary, + pressed: true, + modifiers: press_modifiers, + }); + h.input_mut().events.push(Event::ModifiersChanged(current_modifiers)); + h.input_mut().events.push(Event::PointerButton { + pos: at, + button: PointerButton::Primary, + pressed: false, + modifiers: press_modifiers, + }); h.run_steps(3); }; - click(&mut h, Modifiers::NONE); + click(&mut h, Modifiers::NONE, Modifiers::NONE); assert_eq!(h.state().app.session.tool_id(), "rectangleFrame"); assert!(h.state().app.ui.flyout.is_none()); - click(&mut h, alt); + click(&mut h, alt, Modifiers::NONE); assert_eq!(h.state().app.session.tool_id(), "ellipseFrame", "Alt-click advances the frame group"); assert!(h.state().app.ui.flyout.is_none(), "Alt-click must not open the flyout"); - click(&mut h, alt); + click(&mut h, alt, Modifiers::NONE); assert_eq!(h.state().app.session.tool_id(), "polygonFrame"); - click(&mut h, alt); + assert!(h.state().app.ui.dialog.is_none(), "modified double-click must not open a dialog"); + click(&mut h, alt, Modifiers::NONE); assert_eq!(h.state().app.session.tool_id(), "rectangleFrame", "Alt-click after the last group tool wraps to the first"); assert!(h.state().app.ui.flyout.is_none(), "wrap-around Alt-click must not open the flyout"); } From 21267510dc2656959dffdd841ad1408be29df2a5 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 13:57:36 +0100 Subject: [PATCH 0536/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/item.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rs index fc997825b..30711b5d9 100644 --- a/crates/doc/src/item.rs +++ b/crates/doc/src/item.rs @@ -29,8 +29,8 @@ pub use paint::{ path_length_bound, }; pub use text_frame::{ - AutoSize, ColumnsKind, DEFAULT_ALPHA_THRESHOLD, ContourType, FirstBaseline, FrameBaselineGrid, FrameGridRelative, PathAlign, PathType, TextFrame, TextFrameOptions, - TextWrap, VerticalJustification, WrapMode, WrapSide, vertical_text_xf, + AutoSize, ColumnsKind, ContourType, DEFAULT_ALPHA_THRESHOLD, FirstBaseline, FrameBaselineGrid, FrameGridRelative, PathAlign, PathType, TextFrame, + TextFrameOptions, TextWrap, VerticalJustification, WrapMode, WrapSide, vertical_text_xf, }; fn is_zero_usize(v: &usize) -> bool { From 9eb11f3eeed58f38b1ef5122f2876a008bed385d Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 14:24:57 +0100 Subject: [PATCH 0537/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/find/tests.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/find/tests.rs b/crates/engine/src/cmd/find/tests.rs index e88c81a3a..7de29f8ea 100644 --- a/crates/engine/src/cmd/find/tests.rs +++ b/crates/engine/src/cmd/find/tests.rs @@ -795,9 +795,8 @@ fn change_format_styles_the_found_text_and_keeps_it() { fn a_find_format_finds_only_text_with_it() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); - let r = s - .execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "Break eggs; cook eggs.\nEggs and eggs"})) - .unwrap(); + let r = + s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "Break eggs; cook eggs.\nEggs and eggs"})).unwrap(); let sid = r["story"].as_u64().unwrap(); s.execute("style.character.create", &json!({"name": "eggs", "chars": {"fontStyle": "Bold"}})).unwrap(); s.execute("style.paragraph.create", &json!({"name": "Method"})).unwrap(); From 00604b74f27a84ebcb0d8d0c1af37977de0bb95c Mon Sep 17 00:00:00 2001 From: tareq Date: Fri, 30 Oct 2026 14:31:53 +0100 Subject: [PATCH 0538/1349] Toolbar: accept slot releases that drift outside the button. egui still counts a click when the pointer leaves the tool rect; keep the release modifiers when the press started on the slot. The Alt-cycle test now uses 1 ms frames so an Alt-then-plain pair is a real double-click that must not open Polygon Settings. --- crates/ui-egui/src/toolbar.rs | 8 +++++--- crates/ui-egui/src/toolbar/tests.rs | 20 ++++++++++++++++++-- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 1ba172004..de06cc26c 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -107,9 +107,11 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { // group (InDesign / Photoshop parity with the letter-key cycle). // Prefer the primary-release event's modifiers: Alt may already be up // by the time this frame reads i.modifiers. - // Only a release on this slot: the frame's event list is shared, - // so a later release elsewhere must not steer Alt-cycle / dialogs. + // Prefer a release on this slot; egui still counts a click when the + // pointer drifts a little outside, so also accept a release whose + // press started here. Ignore releases whose press was elsewhere. let click_mods = ui.input(|i| { + let press_here = i.pointer.press_origin().is_some_and(|o| resp.rect.contains(o)); i.events .iter() .rev() @@ -120,7 +122,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { pressed: false, modifiers, .. - } if resp.rect.contains(*pos) => Some(*modifiers), + } if resp.rect.contains(*pos) || press_here => Some(*modifiers), _ => None, }) .unwrap_or(i.modifiers) diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 5551ba2dd..899f4855b 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -385,7 +385,9 @@ fn alt_click_cycles_the_tool_flyout_group() { use egui::{Event, Modifiers, PointerButton}; use egui_kittest::kittest::Queryable; let app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let mut h = crate::test_window::open(app, vec2(1400.0, 900.0)); + // 1 ms frames so an Alt-click and a following plain click can form a real double-click + // (default open() spaces frames by 0.25 s, outside egui's double-click window). + let mut h = crate::test_window::open_stepped(app, vec2(1400.0, 900.0), 1.0, 0.001); h.state_mut().app.select_tool("rectangleFrame"); h.run_steps(2); let at = h.get_by_label("Rectangle Frame Tool (F)").rect().center(); @@ -410,16 +412,30 @@ fn alt_click_cycles_the_tool_flyout_group() { }); h.run_steps(3); }; + // Break the double-click window between independent clicks (~0.4 s at 1 ms/step). + let settle = |h: &mut egui_kittest::Harness<'static, crate::test_window::Window>| h.run_steps(400); click(&mut h, Modifiers::NONE, Modifiers::NONE); assert_eq!(h.state().app.session.tool_id(), "rectangleFrame"); assert!(h.state().app.ui.flyout.is_none()); + settle(&mut h); click(&mut h, alt, Modifiers::NONE); assert_eq!(h.state().app.session.tool_id(), "ellipseFrame", "Alt-click advances the frame group"); assert!(h.state().app.ui.flyout.is_none(), "Alt-click must not open the flyout"); + settle(&mut h); click(&mut h, alt, Modifiers::NONE); assert_eq!(h.state().app.session.tool_id(), "polygonFrame"); - assert!(h.state().app.ui.dialog.is_none(), "modified double-click must not open a dialog"); + settle(&mut h); click(&mut h, alt, Modifiers::NONE); assert_eq!(h.state().app.session.tool_id(), "rectangleFrame", "Alt-click after the last group tool wraps to the first"); assert!(h.state().app.ui.flyout.is_none(), "wrap-around Alt-click must not open the flyout"); + settle(&mut h); + // Alt-click onto polygonFrame, then a plain click inside the double-click window: egui + // reports double_clicked, but prev_modified must keep Polygon Settings closed. + h.state_mut().app.select_tool("ellipseFrame"); + h.run_steps(2); + click(&mut h, alt, Modifiers::NONE); + assert_eq!(h.state().app.session.tool_id(), "polygonFrame"); + click(&mut h, Modifiers::NONE, Modifiers::NONE); + assert!(h.state().app.ui.dialog.is_none(), "plain click after Alt-click must not open Polygon Settings"); + assert_eq!(h.state().app.session.tool_id(), "polygonFrame"); } From cd84bd903ae92530eb0ce6cf248629d491b51e20 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 14:36:10 +0100 Subject: [PATCH 0539/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 4 ++-- crates/ui-egui/src/dialogs/tests.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 35031149a..d6da8e43e 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -3305,7 +3305,7 @@ const FORMAT_SECTIONS: &[(&str, &str)] = &[ fn info_icon(ui: &mut egui::Ui, tip: &str) { let (r, resp) = ui.allocate_exact_size(egui::vec2(16.0, 16.0), egui::Sense::hover()); crate::icons::paint(ui.painter(), r, "info", crate::theme::Tokens::get(ui.ctx()).icon); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, tip)); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, tip)); resp.on_hover_text(tip); } @@ -3383,7 +3383,7 @@ fn format_settings(app: &mut DesignApp, ctx: &egui::Context, d: &mut Dialog) { let find = fd.s("for") == "find"; let popup_open = egui::Popup::is_any_open(ctx); let mut result = None; - let host = egui::Id::new("format_settings"); + let host = egui::Id::unique("format_settings"); crate::modal_drag::modal(ctx, host, host).backdrop_color(egui::Color32::TRANSPARENT).show(ctx, |ui| { let title_top = ui.cursor().top(); let title = if find { "Find Format Settings" } else { "Change Format Settings" }; diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index c80127706..e1ce3f2dd 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3542,7 +3542,7 @@ fn find_change_gives_the_found_text_a_change_format() { } let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state( |ui, app: &mut DesignApp| { - let key = egui::Id::new("change_format_test_fonts"); + let key = egui::Id::unique("change_format_test_fonts"); if ui.data(|d| d.get_temp::(key)).is_none() { crate::theme::install_fonts(ui.ctx(), ""); ui.data_mut(|d| d.insert_temp(key, true)); @@ -3632,7 +3632,7 @@ fn find_format_finds_only_text_with_it() { } let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state( |ui, app: &mut DesignApp| { - let key = egui::Id::new("find_format_test_fonts"); + let key = egui::Id::unique("find_format_test_fonts"); if ui.data(|d| d.get_temp::(key)).is_none() { crate::theme::install_fonts(ui.ctx(), ""); ui.data_mut(|d| d.insert_temp(key, true)); From 930d96dc0e41f3126a15143c70c4de6d1c030e7b Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 14:40:58 +0100 Subject: [PATCH 0540/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/find/tests.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/find/tests.rs b/crates/engine/src/cmd/find/tests.rs index 8a679269e..65dad887b 100644 --- a/crates/engine/src/cmd/find/tests.rs +++ b/crates/engine/src/cmd/find/tests.rs @@ -816,9 +816,8 @@ fn change_format_styles_the_found_text_and_keeps_it() { fn a_find_format_finds_only_text_with_it() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); - let r = s - .execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "Break eggs; cook eggs.\nEggs and eggs"})) - .unwrap(); + let r = + s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "Break eggs; cook eggs.\nEggs and eggs"})).unwrap(); let sid = r["story"].as_u64().unwrap(); s.execute("style.character.create", &json!({"name": "eggs", "chars": {"fontStyle": "Bold"}})).unwrap(); s.execute("style.paragraph.create", &json!({"name": "Method"})).unwrap(); From 9f591ab6faab85c57161abba7231e741ec38224b Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 14:45:50 +0100 Subject: [PATCH 0541/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 4 ++-- crates/ui-egui/src/dialogs/tests.rs | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index f3832a9d7..49932fc70 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -3340,7 +3340,7 @@ const FORMAT_SECTIONS: &[(&str, &str)] = &[ fn info_icon(ui: &mut egui::Ui, tip: &str) { let (r, resp) = ui.allocate_exact_size(egui::vec2(16.0, 16.0), egui::Sense::hover()); crate::icons::paint(ui.painter(), r, "info", crate::theme::Tokens::get(ui.ctx()).icon); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, tip)); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, tip)); resp.on_hover_text(tip); } @@ -3418,7 +3418,7 @@ fn format_settings(app: &mut DesignApp, ctx: &egui::Context, d: &mut Dialog) { let find = fd.s("for") == "find"; let popup_open = egui::Popup::is_any_open(ctx); let mut result = None; - let host = egui::Id::new("format_settings"); + let host = egui::Id::unique("format_settings"); crate::modal_drag::modal(ctx, host, host).backdrop_color(egui::Color32::TRANSPARENT).show(ctx, |ui| { let title_top = ui.cursor().top(); let title = if find { "Find Format Settings" } else { "Change Format Settings" }; diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 153a83486..8bb581d14 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3551,7 +3551,7 @@ fn find_change_gives_the_found_text_a_change_format() { } let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state( |ui, app: &mut DesignApp| { - let key = egui::Id::new("change_format_test_fonts"); + let key = egui::Id::unique("change_format_test_fonts"); if ui.data(|d| d.get_temp::(key)).is_none() { crate::theme::install_fonts(ui.ctx(), ""); ui.data_mut(|d| d.insert_temp(key, true)); @@ -3641,7 +3641,7 @@ fn find_format_finds_only_text_with_it() { } let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state( |ui, app: &mut DesignApp| { - let key = egui::Id::new("find_format_test_fonts"); + let key = egui::Id::unique("find_format_test_fonts"); if ui.data(|d| d.get_temp::(key)).is_none() { crate::theme::install_fonts(ui.ctx(), ""); ui.data_mut(|d| d.insert_temp(key, true)); @@ -3701,7 +3701,7 @@ fn change_and_change_find_change_the_found_text() { } let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state( |ui, app: &mut DesignApp| { - let key = egui::Id::new("change_find_test_fonts"); + let key = egui::Id::unique("change_find_test_fonts"); if ui.data(|d| d.get_temp::(key)).is_none() { crate::theme::install_fonts(ui.ctx(), ""); ui.data_mut(|d| d.insert_temp(key, true)); From 620f83d44a08c0b21fcbc1352a8440f71182c3df Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 14:46:10 +0100 Subject: [PATCH 0542/1349] Find/Change: the Search label's name apart from the branch's scope_name closure Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 49932fc70..5752703ac 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -2491,7 +2491,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { }); text_field_named(ui, &mut d, "change", 260.0, crate::i18n::tr(&app.ui.language, "Change to:")); ui.end_row(); - let scope_name = crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Search:")); + let search_label = crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Search:")); let cur = d.s("scope"); // InDesign's names for the scopes. let scope_name = |v: &str| match v { @@ -2513,7 +2513,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { } }) .response - .labelled_by(scope_name.id); + .labelled_by(search_label.id); ui.end_row(); }); ui.horizontal(|ui| { From 00e26ce428a10ea1a3cd9a8f183301a661cc4c07 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 15:11:34 +0100 Subject: [PATCH 0543/1349] Paragraph Style Options: Next Style named by its label, for screen readers; craft_ui dropdown Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 256cfeaef..6a48de653 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -4404,7 +4404,7 @@ fn paragraph_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo let _ = crate::widgets::name_combo(combo, crate::i18n::tr(&app.ui.language, "Based On")); ui.end_row(); // Next Style: the style of the paragraph that follows when Enter ends this one. - crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Next Style:")); + let next_name = crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Next Style:")); let next = match d.fields.get("nextStyle") { Some(Value::String(n)) => Some(n.clone()), Some(_) => None, @@ -4424,7 +4424,9 @@ fn paragraph_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo d.fields.insert("nextStyle".into(), json!(n)); } } - }); + }) + .response + .labelled_by(next_name.id); ui.end_row(); }); // Reset To Base: the style keeps nothing of its own (the edits made here stay). From 4d30380930a6122268bcf73baf05181753fcfa5a Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 15:19:33 +0100 Subject: [PATCH 0544/1349] IDML export: no unused HashSet import in main's split item module Co-Authored-By: Claude Opus 5.5 --- crates/idml/src/export/item.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/idml/src/export/item.rs b/crates/idml/src/export/item.rs index 83d689d47..f53c70465 100644 --- a/crates/idml/src/export/item.rs +++ b/crates/idml/src/export/item.rs @@ -1,6 +1,6 @@ use super::common::{affine_s, bool_s, p, pct, uid, with_props}; use super::{ - Affine, ColumnsKind, Content, El, Ex, HashSet, Item, Node, OBJECT_BUILTINS, PathData, Shape, TextFrameOptions, base64_encode, escape_id, names, + Affine, ColumnsKind, Content, El, Ex, Item, Node, OBJECT_BUILTINS, PathData, Shape, TextFrameOptions, base64_encode, escape_id, names, num, pt, }; From 1fe2e6b7e5f664359f87dcaa998577c946ff34b0 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 15:26:28 +0100 Subject: [PATCH 0545/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/idml/src/export/item.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/idml/src/export/item.rs b/crates/idml/src/export/item.rs index f53c70465..0f6b73307 100644 --- a/crates/idml/src/export/item.rs +++ b/crates/idml/src/export/item.rs @@ -1,7 +1,6 @@ use super::common::{affine_s, bool_s, p, pct, uid, with_props}; use super::{ - Affine, ColumnsKind, Content, El, Ex, Item, Node, OBJECT_BUILTINS, PathData, Shape, TextFrameOptions, base64_encode, escape_id, names, - num, pt, + Affine, ColumnsKind, Content, El, Ex, Item, Node, OBJECT_BUILTINS, PathData, Shape, TextFrameOptions, base64_encode, escape_id, names, num, pt, }; impl<'a> Ex<'a> { From 2ea8aa673930e86a014c2adb3effea291ded0a84 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 15:31:56 +0100 Subject: [PATCH 0546/1349] Object styles: the paragraph style and text frame parameter helpers in main's split module; Object Styles in the styles icon family Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/style/object.rs | 31 +++++++++++++++++++++++ crates/ui-egui/src/panel_docking.rs | 2 +- crates/ui-egui/src/panel_docking/tests.rs | 2 +- 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/style/object.rs b/crates/engine/src/cmd/style/object.rs index 7fcc3d1f3..fb2467e5f 100644 --- a/crates/engine/src/cmd/style/object.rs +++ b/crates/engine/src/cmd/style/object.rs @@ -159,6 +159,37 @@ pub(super) fn create_object(s: &mut Session, p: &Value) -> Result { }) } +/// `paragraphStyle`: a paragraph style's name, or null (the object style sets none). +fn paragraph_style_param(cmd: &str, s: &Session, p: &Value) -> Result>> { + match p.get("paragraphStyle") { + None => Ok(None), + Some(Value::Null) => Ok(Some(None)), + Some(Value::String(n)) if s.doc()?.doc.styles.para(n).is_some() => Ok(Some(Some(n.clone()))), + Some(Value::String(n)) => Err(bad(cmd, format!("no paragraph style `{n}`"))), + Some(_) => Err(bad(cmd, "`paragraphStyle` must be a paragraph style's name or null")), + } +} + +/// `textFrame` (a text frame's options, as `document.inspect` shows them) merged over `base`, or +/// null; refused when the columns aren't 1–40 or a gutter, width or inset isn't 0–15552 pt. +fn text_frame_param( + cmd: &str, + p: &Value, + base: Option<&designcraft_doc::TextFrameOptions>, +) -> Result>> { + let tf = group_param(cmd, p, "textFrame", base.unwrap_or(&designcraft_doc::TextFrameOptions::default()))?; + if let Some(Some(o)) = &tf { + if !(1..=40).contains(&o.columns) { + return Err(bad(cmd, "text frame columns must be 1–40")); + } + let mut lengths = [o.gutter, o.column_width, o.vj_paragraph_spacing_limit, o.first_baseline_min].into_iter().chain(o.inset); + if !lengths.all(|v| v.is_finite() && (0.0..=15552.0).contains(&v)) { + return Err(bad(cmd, "a text frame's gutter, widths and insets must be 0–15552 pt")); + } + } + Ok(tf) +} + /// A true/false parameter, when given. fn bool_param(cmd: &str, p: &Value, key: &str) -> Result> { match p.get(key) { diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 801a96ae3..709eb0d02 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -114,7 +114,7 @@ impl Placed { const ICON_GROUPS: &[&[&str]] = &[ &["stroke", "color", "swatches", "gradient"], &["effects"], - &["characterStyles", "paragraphStyles"], + &["characterStyles", "paragraphStyles", "objectStyles"], &["character", "paragraph", "typography"], &["glyphs", "story"], &["table"], diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index 77b721098..a4e7f97ef 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -881,7 +881,7 @@ fn placed_panels_leave_their_icon_groups() { let column = icon_column(None, &mut placed).unwrap(); let groups: Vec> = column.groups.iter().map(|g| g.panels.iter().map(String::as_str).collect()).collect(); assert_eq!(groups.first().unwrap(), &["stroke", "color", "gradient"]); - assert_eq!(groups.get(1).unwrap(), &["characterStyles", "paragraphStyles"]); + assert_eq!(groups.get(1).unwrap(), &["characterStyles", "paragraphStyles", "objectStyles"]); assert_eq!(groups.len(), ICON_GROUPS.len() - 1); } From b77a1c29bde398920f978b7491b6d13e95bb30ce Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 15:33:46 +0100 Subject: [PATCH 0547/1349] Eyedropper: the renderer's size as one (width, height) argument, as main's render takes it Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/render.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/render.rs b/crates/ui-egui/src/canvas/render.rs index 5b7358996..07983944e 100644 --- a/crates/ui-egui/src/canvas/render.rs +++ b/crates/ui-egui/src/canvas/render.rs @@ -25,7 +25,7 @@ pub fn color_at(app: &mut DesignApp, ctx: &egui::Context, pos: Pos2) -> Option<[ let ppp = ctx.pixels_per_point() as f64; let view = Affine::scale(ppp) * Affine::scale(xf.zoom) * Affine::translate((-at.x, -at.y)); let opts = screen_options(app, &layout, app.ui.screen_mode != ScreenMode::Normal, ppp); - let mut img = app.canvas.patcher.render(&doc, &app.session.cache, &placed, 1, 1, view, &opts); + let mut img = app.canvas.patcher.render(&doc, &app.session.cache, &placed, (1, 1), view, &opts); // The colour as the canvas shows it (proofed). screen_post(app, &mut img); let [r, g, b, a] = <[u8; 4]>::try_from(img.pixels.get(..4)?).ok()?; From dd0b891ef0c8e058fb72eb7d84cf49a7e9548240 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 15:35:16 +0100 Subject: [PATCH 0548/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6a48de653..3044479cf 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -4412,21 +4412,27 @@ fn paragraph_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo }; let same = crate::i18n::tr(&app.ui.language, "[Same style]").to_string(); let shown = next.as_deref().map_or(same.clone(), |n| crate::i18n::style_name(&app.ui.language, n).to_string()); - craft_ui::ComboBox::from_id_salt("psnext").selected_text(crate::rtl::widget(ui, shown)).width(220.0).show_ui(ui, |ui| { - if ui.selectable_label(next.is_none(), crate::rtl::widget(ui, &same)).clicked() { - d.fields.insert("nextStyle".into(), Value::Null); - } - for n in names.iter().filter(|n| *n != designcraft_doc::NO_PARA_STYLE) { - if ui - .selectable_label(next.as_deref() == Some(n), crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, n))) - .clicked() - { - d.fields.insert("nextStyle".into(), json!(n)); + craft_ui::ComboBox::from_id_salt("psnext") + .selected_text(crate::rtl::widget(ui, shown)) + .width(220.0) + .show_ui(ui, |ui| { + if ui.selectable_label(next.is_none(), crate::rtl::widget(ui, &same)).clicked() { + d.fields.insert("nextStyle".into(), Value::Null); } - } - }) - .response - .labelled_by(next_name.id); + for n in names.iter().filter(|n| *n != designcraft_doc::NO_PARA_STYLE) { + if ui + .selectable_label( + next.as_deref() == Some(n), + crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, n)), + ) + .clicked() + { + d.fields.insert("nextStyle".into(), json!(n)); + } + } + }) + .response + .labelled_by(next_name.id); ui.end_row(); }); // Reset To Base: the style keeps nothing of its own (the edits made here stay). From f4e12a5b5048d1aac24342fb06209e86709cf27d Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 15:42:16 +0100 Subject: [PATCH 0549/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index b0c46f5ad..4997453b4 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3588,7 +3588,7 @@ fn a_new_character_style_starts_from_the_selected_text() { assert!(d.b("apply")); let mut h = Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_ui_state( |ui, app: &mut DesignApp| { - let key = egui::Id::new("new_character_style_test_fonts"); + let key = egui::Id::unique("new_character_style_test_fonts"); if ui.data(|d| d.get_temp::(key)).is_none() { crate::theme::install_fonts(ui.ctx(), ""); ui.data_mut(|d| d.insert_temp(key, true)); From e73209a4e59cc73716f6d128d8d4a4bf890bce9a Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 15:50:46 +0100 Subject: [PATCH 0550/1349] Table of Contents: every field named by its label, for screen readers Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 40 ++++++++++++++++++++--------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 85ad65dce..773aab2c7 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -6858,7 +6858,7 @@ fn toc_params(app: &DesignApp, d: &Dialog) -> Value { /// A style menu whose first choice, stored as "", is `auto` (the generated paragraph style, or /// [None] for a character style). -fn toc_style_combo(ui: &mut egui::Ui, salt: &str, styles: &[String], auto: &str, cur: &mut String) -> bool { +fn toc_style_combo(ui: &mut egui::Ui, salt: &str, styles: &[String], auto: &str, cur: &mut String, name: egui::Id) -> bool { let shown = if cur.is_empty() { auto.to_string() } else { cur.clone() }; let mut changed = false; craft_ui::ComboBox::from_id_salt(("toc_style", salt)).selected_text(shown).width(200.0).show_ui(ui, |ui| { @@ -6872,7 +6872,9 @@ fn toc_style_combo(ui: &mut egui::Ui, salt: &str, styles: &[String], auto: &str, changed = true; } } - }); + }) + .response + .labelled_by(name); changed } @@ -6891,9 +6893,9 @@ fn toc_dialog(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { let mut title_style = d.s("titleStyle"); egui::Grid::new("toc_title").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| { crate::rtl::label(ui, tr("Title:")); - text_field(ui, d, "title", 200.0); - crate::rtl::label(ui, tr("Style:")); - toc_style_combo(ui, "title", &styles, "TOC Title", &mut title_style); + text_field_named(ui, d, "title", 200.0, &tr("Title:")); + let name = crate::rtl::label(ui, tr("Style:")).id; + toc_style_combo(ui, "title", &styles, "TOC Title", &mut title_style, name); ui.end_row(); }); ui.add_space(8.0); @@ -6957,14 +6959,14 @@ fn toc_dialog(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { crate::rtl::label(ui, egui::RichText::new(format!("{} {}", tr("Style:"), r.style)).font(semibold(12.0))); let none = designcraft_doc::NO_CHAR_STYLE; egui::Grid::new("toc_entry").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| { - crate::rtl::label(ui, tr("Entry Style:")); + let name = crate::rtl::label(ui, tr("Entry Style:")).id; let auto = format!("TOC Level {}", r.level.clamp(1, 9)); - toc_style_combo(ui, "entry", &styles, &auto, &mut r.entry_style); + toc_style_combo(ui, "entry", &styles, &auto, &mut r.entry_style, name); ui.end_row(); if !expanded { return; } - crate::rtl::label(ui, tr("Page Number:")); + let page_number = crate::rtl::label(ui, tr("Page Number:")).id; let choices = [("after", "After Entry"), ("before", "Before Entry"), ("none", "No Page Number")]; let cur = choices.iter().find(|(v, _)| *v == r.page_number).map_or("After Entry", |(_, l)| l); craft_ui::ComboBox::from_id_salt("toc_page_number").selected_text(tr(cur)).width(200.0).show_ui(ui, |ui| { @@ -6973,26 +6975,30 @@ fn toc_dialog(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { r.page_number = v.into(); } } - }); - crate::rtl::label(ui, tr("Style:")); - toc_style_combo(ui, "page_number", &char_styles, none, &mut r.page_number_style); + }) + .response + .labelled_by(page_number); + let name = crate::rtl::label(ui, tr("Style:")).id; + toc_style_combo(ui, "page_number", &char_styles, none, &mut r.page_number_style, name); ui.end_row(); - crate::rtl::label(ui, tr("Between Entry and Number:")); - ui.add(egui::TextEdit::singleline(&mut r.separator).desired_width(80.0).align(egui::Align2::LEFT_TOP)); - crate::rtl::label(ui, tr("Style:")); - toc_style_combo(ui, "separator", &char_styles, none, &mut r.separator_style); + let between = crate::rtl::label(ui, tr("Between Entry and Number:")).id; + ui.add(egui::TextEdit::singleline(&mut r.separator).desired_width(80.0).align(egui::Align2::LEFT_TOP)).labelled_by(between); + let name = crate::rtl::label(ui, tr("Style:")).id; + toc_style_combo(ui, "separator", &char_styles, none, &mut r.separator_style, name); ui.end_row(); crate::rtl::label(ui, ""); ui.checkbox(&mut r.sort, tr("Sort Entries in Alphabetical Order")); ui.end_row(); - crate::rtl::label(ui, tr("Level:")); + let level = crate::rtl::label(ui, tr("Level:")).id; craft_ui::ComboBox::from_id_salt("toc_level").selected_text(r.level.to_string()).width(60.0).show_ui(ui, |ui| { for l in 1..=9u8 { if ui.selectable_label(r.level == l, l.to_string()).clicked() { r.level = l; } } - }); + }) + .response + .labelled_by(level); ui.end_row(); }); } From 559f8f590bea8bf959be6baea03195ce507c1b82 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 15:56:16 +0100 Subject: [PATCH 0551/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/package_dialog.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/package_dialog.rs b/crates/ui-egui/src/package_dialog.rs index 536c5e4ac..a2eac5824 100644 --- a/crates/ui-egui/src/package_dialog.rs +++ b/crates/ui-egui/src/package_dialog.rs @@ -280,18 +280,18 @@ pub fn show(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { ui.add_space(24.0); let name = crate::rtl::label(ui, tr("PDF Preset:")); let cur = d.s("pdfPreset"); - craft_ui::ComboBox::from_id_salt("package_pdf_preset").selected_text(crate::rtl::widget(ui, tr(&cur))).width(180.0).show_ui( - ui, - |ui| { + craft_ui::ComboBox::from_id_salt("package_pdf_preset") + .selected_text(crate::rtl::widget(ui, tr(&cur))) + .width(180.0) + .show_ui(ui, |ui| { for p in crate::dialogs::pdf_presets() { if ui.selectable_label(cur == p, crate::rtl::widget(ui, tr(p))).clicked() { d.fields.insert("pdfPreset".into(), json!(p)); } } - }, - ) - .response - .labelled_by(name.id); + }) + .response + .labelled_by(name.id); }); }); } From 7cb620608a2959687497796298348f8537a6e06a Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 16:23:18 +0100 Subject: [PATCH 0552/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6c3690625..d7ded3ac6 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -179,18 +179,18 @@ fn insert_pages_dialog(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { // The page, by name: At Start and At End need none. ui.add_enabled_ui(matches!(d.s("insert").as_str(), "after" | "before"), |ui| { let cur = (d.n("page").unwrap_or(0.0).max(0.0) as usize).min(pages.len().saturating_sub(1)); - craft_ui::ComboBox::from_id_salt("insert_page").selected_text(pages.get(cur).cloned().unwrap_or_default()).width(64.0).show_ui( - ui, - |ui| { + craft_ui::ComboBox::from_id_salt("insert_page") + .selected_text(pages.get(cur).cloned().unwrap_or_default()) + .width(64.0) + .show_ui(ui, |ui| { for (i, name) in pages.iter().enumerate() { if ui.selectable_label(i == cur, name).clicked() { d.fields.insert("page".into(), json!(i)); } } - }, - ) - .response - .accessible_name(crate::i18n::tr(&lang, "Page").to_owned()); + }) + .response + .accessible_name(crate::i18n::tr(&lang, "Page").to_owned()); }); }); ui.end_row(); From 7e3bca3d916ccd5af8cb0a513c575813b6393123 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 16:32:41 +0100 Subject: [PATCH 0553/1349] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index d7ded3ac6..f6fc489aa 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -276,7 +276,7 @@ mod color_theme_tests { assert_eq!(app.ui.dialog.as_ref().unwrap().id, "insertPages"); let mut h = Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_ui_state( |ui, app: &mut DesignApp| { - let key = egui::Id::new("insert_pages_test_fonts"); + let key = egui::Id::unique("insert_pages_test_fonts"); if ui.data(|d| d.get_temp::(key)).is_none() { crate::theme::install_fonts(ui.ctx(), ""); ui.data_mut(|d| d.insert_temp(key, true)); From cdb2057aab9afb9ec787373fcf6cb327de6a7fce Mon Sep 17 00:00:00 2001 From: Zinadin Zidan Date: Fri, 30 Oct 2026 21:36:32 +0600 Subject: [PATCH 0554/1349] Rectangle dialog: width and height in the ruler units, not always picas (#1964) A click with a frame tool opened the Rectangle dialog in picas whatever Preferences > Units & Increments or the rulers' unit menus said. It now shows the width in the horizontal ruler unit and the height in the vertical one, and reads bare numbers typed in each field the same way. The properties panel and the control channel open it the same way. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/app/commands.rs | 1 + crates/ui-egui/src/control.rs | 3 +- crates/ui-egui/src/dialogs.rs | 34 ++++++++++++++----- crates/ui-egui/src/dialogs/tests.rs | 34 +++++++++++++++++++ .../ui-egui/src/panels/properties/object.rs | 2 +- 5 files changed, 63 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 44e35ef15..bb75c102e 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -83,6 +83,7 @@ impl DesignApp { let was_find = self.ui.dialog.as_ref().is_some_and(|d| d.id == "findChange"); match r { UiRequest::Dialog { id, params } if id == "colorTheme" => dialogs::open_color_theme(self, params), + UiRequest::Dialog { id, params } if id == "frameSize" => self.ui.dialog = Some(dialogs::frame_size_dialog(self, params)), UiRequest::Dialog { id, params } => self.ui.dialog = Some(dialogs::Dialog::new(&id, params)), UiRequest::View { params } => canvas::apply_view_request(self, ¶ms), UiRequest::Pick { purpose, params } => { diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index e4c6fe723..97a99f925 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -389,7 +389,8 @@ fn handle_request(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest if id == "findChange" || app.ui.dialog.as_ref().is_some_and(|d| d.id == "findChange") { app.session.reset_find_scope(); } - let d = crate::dialogs::Dialog::new(id, p.get("fields").cloned().unwrap_or(Value::Null)); + let fields = p.get("fields").cloned().unwrap_or(Value::Null); + let d = if id == "frameSize" { crate::dialogs::frame_size_dialog(app, fields) } else { crate::dialogs::Dialog::new(id, fields) }; let v = serde_json::to_value(&d).unwrap_or_default(); app.ui.dialog = Some(d); ok(v) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index bb3077103..63619da5e 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -79,13 +79,6 @@ impl Dialog { if id == "ruby" { fields.entry("section".to_string()).or_insert(json!("cjk.rubyPlacement")); } - if id == "frameSize" { - for k in ["width", "height"] { - if let Some(v) = fields.get(k).and_then(Value::as_f64) { - fields.insert(k.into(), json!(format_measure(v, Unit::Picas))); - } - } - } Dialog { id: id.into(), fields, unit: Unit::Picas } } /// Set a field and report a genuine Find domain/mode transition to the caller. @@ -106,9 +99,13 @@ impl Dialog { } } fn m(&self, k: &str) -> Option { + self.m_in(k, self.unit) + } + /// A measure where a bare number is in `unit`. + fn m_in(&self, k: &str, unit: Unit) -> Option { match self.fields.get(k) { Some(Value::Number(n)) => n.as_f64(), - Some(Value::String(s)) => parse_measure(s, self.unit).ok(), + Some(Value::String(s)) => parse_measure(s, unit).ok(), _ => None, } } @@ -934,6 +931,25 @@ fn doc_unit(app: &DesignApp) -> Unit { app.session.active().map(|s| s.doc.settings.horizontal_units).unwrap_or(Unit::Picas) } +/// The document's vertical ruler unit: what a bare number means in a height field. +fn doc_vertical_unit(app: &DesignApp) -> Unit { + app.session.active().map(|s| s.doc.settings.vertical_units).unwrap_or(Unit::Picas) +} + +/// The Rectangle dialog a click with a frame tool opens: the width (points in `params`) shown in +/// the horizontal ruler unit, the height in the vertical one, as Preferences › Units & +/// Increments and the rulers' menus set them (#1964). +pub fn frame_size_dialog(app: &DesignApp, params: Value) -> Dialog { + let mut d = Dialog::new("frameSize", params); + for (k, unit) in [("width", doc_unit(app)), ("height", doc_vertical_unit(app))] { + if let Some(v) = d.fields.get(k).and_then(Value::as_f64) { + d.fields.insert(k.into(), json!(format_measure(v, unit))); + } + } + d.unit = doc_unit(app); + d +} + /// Layout › Create Guides…: guides go on the page in view (or the parent page being edited), not /// on the first page, and the gutters are typed in the document's ruler unit. pub fn open_create_guides(app: &mut DesignApp) { @@ -3277,7 +3293,7 @@ fn confirm_part1(app: &mut DesignApp, d: Dialog) -> Result { let x = d.fields.get("x").and_then(Value::as_f64).unwrap_or(0.0); let y = d.fields.get("y").and_then(Value::as_f64).unwrap_or(0.0); let w = d.m("width").unwrap_or(72.0); - let h = d.m("height").unwrap_or(72.0); + let h = d.m_in("height", doc_vertical_unit(app)).unwrap_or(72.0); app.run( "frame.create", json!({"spread": d.fields.get("spread").cloned().unwrap_or(json!(0)), "shape": d.s("shape"), "content": d.s("content"), "rect": [x, y, x + w, y + h]}), diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 84cbf3bea..0bd29e02d 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3521,3 +3521,37 @@ fn character_style_options_set_the_digits() { assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi)); } + +/// The Rectangle dialog a frame-tool click opens shows the width in the horizontal ruler unit and +/// the height in the vertical one, not always picas, and reads bare numbers the same way (#1964). +#[test] +fn frame_size_dialog_follows_the_ruler_units() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("document.preferences", json!({"horizontalUnits": "inches", "verticalUnits": "millimeters"})).unwrap(); + // As the frame tool asks: a click at (36, 36), 72 pt by 72 pt. + app.session.ui_requests.push(designcraft_engine::UiRequest::Dialog { + id: "frameSize".into(), + params: json!({"spread": 0, "shape": "rectangle", "content": "graphic", "x": 36.0, "y": 36.0, "width": 72.0, "height": 72.0}), + }); + app.after_engine(); + let d = app.ui.dialog.as_ref().expect("the Rectangle dialog"); + assert_eq!((d.id.as_str(), d.unit), ("frameSize", Unit::Inches)); + assert_eq!(d.s("width"), format_measure(72.0, Unit::Inches)); + assert_eq!(d.s("height"), format_measure(72.0, Unit::Millimeters)); + assert!(!d.s("width").contains('p') && !d.s("height").contains('p'), "no picas: {} x {}", d.s("width"), d.s("height")); + // Bare numbers typed in each field are in that field's unit: 2 in by 50 mm. + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("width".into(), json!("2")); + d.fields.insert("height".into(), json!("50")); + let before = app.session.doc().unwrap().doc.clone(); + confirm(&mut app).unwrap(); + let after = &app.session.doc().unwrap().doc; + let added: Vec<_> = after.spreads[0].items.iter().filter(|i| !before.spreads[0].items.iter().any(|b| b.id == i.id)).collect(); + assert_eq!(added.len(), 1, "one frame"); + let b = added[0].bounds(); + assert!((b.width() - 144.0).abs() < 0.01 && (b.height() - 50.0 / 25.4 * 72.0).abs() < 0.01, "{b:?}"); + // The properties panel's link opens it in the same units. + let d = frame_size_dialog(&app, json!({"width": 36.0, "height": 36.0})); + assert_eq!((d.s("width"), d.s("height")), (format_measure(36.0, Unit::Inches), format_measure(36.0, Unit::Millimeters))); +} diff --git a/crates/ui-egui/src/panels/properties/object.rs b/crates/ui-egui/src/panels/properties/object.rs index 3819894fe..6b142e0d4 100644 --- a/crates/ui-egui/src/panels/properties/object.rs +++ b/crates/ui-egui/src/panels/properties/object.rs @@ -327,7 +327,7 @@ pub(super) fn appearance_section(app: &mut DesignApp, ui: &mut Ui, i: &SelInfo) let b = block(ui, FIELD_H); icons::paint(ui.painter(), sub(b, 3.0, 1.0, 19.0, 19.0), "corner", t.accent); if place(ui, sub(b, 34.0, 0.0, 56.0, FIELD_H), |ui| link_label(ui, crate::i18n::tr(&app.ui.language, "Corner"), 56.0)).clicked() { - app.ui.dialog = Some(crate::dialogs::Dialog::new("frameSize", json!({}))); + app.ui.dialog = Some(crate::dialogs::frame_size_dialog(app, json!({}))); } let (shape, size) = i.corner; if let Some(v) = place(ui, sub(b, 96.0, 0.0, 69.0, FIELD_H), |ui| { From 93d21bc0899522bcb1f39ec9a0bcecdef51555a2 Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Fri, 30 Oct 2026 16:37:44 +0100 Subject: [PATCH 0555/1349] Add File > Quit to the in-window menu on Windows and Linux (#2044) --- crates/ui-egui/src/menus/tables.rs | 2 ++ crates/ui-egui/src/menus/tests.rs | 14 ++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/crates/ui-egui/src/menus/tables.rs b/crates/ui-egui/src/menus/tables.rs index 4d63d485f..1fee25f3f 100644 --- a/crates/ui-egui/src/menus/tables.rs +++ b/crates/ui-egui/src/menus/tables.rs @@ -36,6 +36,8 @@ pub const MENUS: &[(&str, &[&str])] = &[ "-", "cmd:layout.documentSetup", "cmd:file.info", + "-", + "ui:app.quit", ], ), ( diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 5e82f6d3f..58251a5fe 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -2976,3 +2976,17 @@ fn forwarded_keys_run_shortcuts() { forwarded_shortcuts(&mut app, &ctx, press(Key::Delete), Modifiers::NONE); assert!(app.session.active().unwrap().doc.item(designcraft_doc::ItemId(frame["id"].as_u64().unwrap())).is_none(), "Delete clears the selection"); } + +#[test] +fn file_menu_ends_with_quit_but_the_macos_menu_bar_leaves_it_to_the_app_menu() { + let file = |tree: Vec<(&'static str, Vec)>| { + let mut out = Vec::new(); + walk(&tree.into_iter().find(|(t, _)| *t == "File").map(|(_, e)| e).unwrap_or_default(), &mut out); + out.into_iter().map(|(_, id, _)| id).collect::>() + }; + assert_eq!(file(menu_tree()).last().map(String::as_str), Some("app.quit"), "File ends with the quit item"); + assert!(!file(native_menu_tree()).iter().any(|id| id == "app.quit"), "macOS has Quit only in the app menu"); + let native = native_menu_tree(); + let file_items = native.iter().find(|(t, _)| *t == "File").map(|(_, e)| e); + assert!(!matches!(file_items.and_then(|e| e.last()), Some(Item::Sep)), "no separator left at the end of File"); +} From 69cadd9aa925e4c1ca74b64361b64432070c33e3 Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Fri, 30 Oct 2026 16:36:53 +0100 Subject: [PATCH 0556/1349] Spellcheck squiggles follow the text frame rotation (#2042) --- crates/ui-egui/src/canvas/text_overlay.rs | 59 +++++++++++++++++++++-- 1 file changed, 54 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/canvas/text_overlay.rs b/crates/ui-egui/src/canvas/text_overlay.rs index dc48ae720..89d0101f7 100644 --- a/crates/ui-egui/src/canvas/text_overlay.rs +++ b/crates/ui-egui/src/canvas/text_overlay.rs @@ -346,17 +346,31 @@ pub(super) fn draw_dynamic_spelling(app: &DesignApp, ctx: &egui::Context, painte }; let y = l.baseline + l.descent * 0.5; let (p0, p1) = (xf.to_screen(m * Point::new(x0, y)), xf.to_screen(m * Point::new(x1, y))); - // A zigzag 2 px high, 4 px per wave. - let n = ((p1.x - p0.x) / 2.0).max(1.0) as usize; - let pts: Vec = - (0..=n).map(|k| pos2(p0.x + (p1.x - p0.x) * k as f32 / n as f32, p0.y + if k % 2 == 0 { 0.0 } else { 2.0 })).collect(); - painter.add(egui::Shape::line(pts, red)); + // Screen direction of the text's own "down", so the wave hangs below the baseline in rotated, flipped and vertical frames. + let down = xf.to_screen(m * Point::new(x0, y + 1.0)) - p0; + painter.add(egui::Shape::line(squiggle_points(p0, p1, down), red)); } } } } } +/// Zigzag points for a spelling squiggle from `p0` to `p1` (screen space): 2 px high, 4 px per wave, +/// offset along `down` (the screen direction of the text's own "down") so it follows the text frame's +/// rotation and flips. +pub(super) fn squiggle_points(p0: Pos2, p1: Pos2, down: egui::Vec2) -> Vec { + let d = p1 - p0; + let n = (d.length() / 2.0).max(1.0) as usize; + let len = down.length(); + let off = if len > 1e-6 { down / len } else { egui::vec2(0.0, 1.0) }; + (0..=n) + .map(|k| { + let wave = if k % 2 == 0 { 0.0 } else { 2.0 }; + p0 + d * (k as f32 / n as f32) + off * wave + }) + .collect() +} + /// Plain text of the current text selection (story markers resolved to readable characters). pub fn selected_text(app: &DesignApp) -> Option { let st = app.session.active()?; @@ -368,3 +382,38 @@ pub fn selected_text(app: &DesignApp) -> Option { } Some(s.replace(designcraft_doc::story::FORCED_LINE_BREAK, "\n")) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn squiggle_horizontal_offsets_down() { + let pts = squiggle_points(pos2(0.0, 10.0), pos2(20.0, 10.0), egui::vec2(0.0, 1.0)); + assert_eq!(pts.len(), 11); + assert!((pts[0].y - 10.0).abs() < 1e-4); + assert!((pts[1].y - 12.0).abs() < 1e-4); + assert!((pts[1].x - 2.0).abs() < 1e-4); + } + + #[test] + fn squiggle_follows_rotation() { + // Frame rotated 90 degrees: the line runs down the screen and the text's "down" points left, + // so the wave must move sideways, not along y. + let pts = squiggle_points(pos2(10.0, 0.0), pos2(10.0, 20.0), egui::vec2(-3.0, 0.0)); + assert_eq!(pts.len(), 11); + assert!((pts[1].y - 2.0).abs() < 1e-4); + assert!((pts[1].x - 8.0).abs() < 1e-4); + assert!((pts[0].x - 10.0).abs() < 1e-4); + } + + #[test] + fn squiggle_follows_horizontal_flip() { + // A horizontally flipped frame runs the word right to left; the wave still hangs below it. + let pts = squiggle_points(pos2(20.0, 10.0), pos2(0.0, 10.0), egui::vec2(0.0, 1.0)); + assert_eq!(pts.len(), 11); + assert!((pts[1].x - 18.0).abs() < 1e-4); + assert!((pts[1].y - 12.0).abs() < 1e-4); + assert!(pts[10].x.abs() < 1e-4); + } +} From 759ab3ba7cce46e2b6eed40f2aa453807231a6de Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Fri, 30 Oct 2026 16:37:32 +0100 Subject: [PATCH 0557/1349] Separate the CJK commands from Insert Math Expression in the Type menu (#2043) --- apps/designcraft/src/native_menu.rs | 6 ++++-- crates/ui-egui/src/menus.rs | 3 ++- crates/ui-egui/src/menus/tables.rs | 1 + crates/ui-egui/src/menus/tests.rs | 16 ++++++++++++++++ crates/ui-egui/src/menus/tree.rs | 16 ++++++++++++++-- 5 files changed, 37 insertions(+), 5 deletions(-) diff --git a/apps/designcraft/src/native_menu.rs b/apps/designcraft/src/native_menu.rs index e127776ba..ba92e0031 100644 --- a/apps/designcraft/src/native_menu.rs +++ b/apps/designcraft/src/native_menu.rs @@ -230,10 +230,12 @@ fn build( path: &str, recent: &mut Option, ) { - for e in entries { + for (i, e) in entries.iter().enumerate() { match e { Item::Sep => { - let _ = parent.append(&PredefinedMenuItem::separator()); + if menus::has_shown_item(app, &entries[i + 1..]) { + let _ = parent.append(&PredefinedMenuItem::separator()); + } } Item::Sub(label, children) => { let sub = Submenu::new(menu_title(app, label), true); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index ffcfa0988..d1e41d549 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -39,7 +39,8 @@ pub use tables::{CLASSIC_GROUPS, MENUS, TYPOGRAPHY_GROUPS, WORKSPACE_OPEN_PANELS #[cfg(test)] use tree::menu_items; pub use tree::{ - AppMenuItem, MAC_APP_MENU, OPEN_RECENT, all_menu_items, menu_key, menu_tree, native_label, native_menu_tree, recent_items, recent_label, + AppMenuItem, MAC_APP_MENU, OPEN_RECENT, all_menu_items, has_shown_item, menu_key, menu_tree, native_label, native_menu_tree, recent_items, + recent_label, }; pub use ui_commands::{CJK_ONLY, UI_COMMANDS, shown, ui_label}; diff --git a/crates/ui-egui/src/menus/tables.rs b/crates/ui-egui/src/menus/tables.rs index 4d63d485f..f3c725585 100644 --- a/crates/ui-egui/src/menus/tables.rs +++ b/crates/ui-egui/src/menus/tables.rs @@ -274,6 +274,7 @@ pub const MENUS: &[(&str, &[&str])] = &[ "cmd:type.storyDirection|Horizontal|{\"vertical\": false}", "cmd:type.storyDirection|Vertical|{\"vertical\": true}", "<", + "-", "cmd:type.tateChuYoko", "ui:app.rubyDialog", "cmd:type.kenten", diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 5e82f6d3f..8b86cf81e 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -2437,6 +2437,22 @@ fn cjk_menu_items_follow_show_cjk_features() { assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("ruby"), "hidden, not removed"); } +/// The CJK commands sit in a group of their own, after a separator, and hiding them leaves no +/// separator at the end of the menu. +#[test] +fn cjk_menu_items_have_their_own_group() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ty = menu_tree().into_iter().find(|(m, _)| *m == "Type").unwrap().1; + let first = ty.iter().position(|i| matches!(i, Item::Cmd { id, .. } if CJK_ONLY.contains(&id.as_str()))).unwrap(); + assert!(matches!(ty[first - 1], Item::Sep), "separator before the CJK group"); + assert!(matches!(ty[first - 2], Item::Sub(..)), "the group comes after Story Direction"); + app.ui.language = String::new(); + app.run("prefs.set", json!({"cjkFeatures": false})).unwrap(); + assert!(!has_shown_item(&app, &ty[first..]), "nothing left after the separator"); + app.run("prefs.set", json!({"cjkFeatures": true})).unwrap(); + assert!(has_shown_item(&app, &ty[first..])); +} + /// Preferences › Type › Show CJK Features: left as it is, it keeps following the interface /// language; changed, it is kept in prefs.json. #[test] diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index b711b8376..6ab2e1765 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -175,13 +175,25 @@ pub fn menu_key(menu: &str, label: &str) -> String { format!("{menu}/{label}") } +/// Whether any shown item is in `rest`, the entries after a separator: the separator is drawn only then, so hidden +/// CJK commands leave no separator at the end of a menu (in the window and in the native macOS menu bar). +pub fn has_shown_item(app: &DesignApp, rest: &[Item]) -> bool { + rest.iter().any(|e| match e { + Item::Cmd { id, .. } => shown(app, id), + Item::Sep => false, + Item::Sub(..) => true, + }) +} + /// Draws a menu's items; returns how many were hidden. pub(super) fn menu_items(app: &mut DesignApp, ui: &mut egui::Ui, items: &[Item], path: &str) -> usize { let mut hidden = 0; - for it in items { + for (i, it) in items.iter().enumerate() { match it { Item::Sep => { - ui.separator(); + if has_shown_item(app, &items[i + 1..]) { + ui.separator(); + } } Item::Sub(name, children) => { let sub = format!("{path}/{name}"); From 133536f0e7d614cd576806b12fbe94ff5765462f Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 16:48:55 +0100 Subject: [PATCH 0558/1349] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 13d7e54b3..8e52ac46c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -4404,21 +4404,27 @@ fn paragraph_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo }; let same = crate::i18n::tr(&app.ui.language, "[Same style]").to_string(); let shown = next.as_deref().map_or(same.clone(), |n| crate::i18n::style_name(&app.ui.language, n).to_string()); - craft_ui::ComboBox::from_id_salt("psnext").selected_text(crate::rtl::widget(ui, shown)).width(220.0).show_ui(ui, |ui| { - if ui.selectable_label(next.is_none(), crate::rtl::widget(ui, &same)).clicked() { - d.fields.insert("nextStyle".into(), Value::Null); - } - for n in names.iter().filter(|n| *n != designcraft_doc::NO_PARA_STYLE) { - if ui - .selectable_label(next.as_deref() == Some(n), crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, n))) - .clicked() - { - d.fields.insert("nextStyle".into(), json!(n)); + craft_ui::ComboBox::from_id_salt("psnext") + .selected_text(crate::rtl::widget(ui, shown)) + .width(220.0) + .show_ui(ui, |ui| { + if ui.selectable_label(next.is_none(), crate::rtl::widget(ui, &same)).clicked() { + d.fields.insert("nextStyle".into(), Value::Null); } - } - }) - .response - .labelled_by(next_name.id); + for n in names.iter().filter(|n| *n != designcraft_doc::NO_PARA_STYLE) { + if ui + .selectable_label( + next.as_deref() == Some(n), + crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, n)), + ) + .clicked() + { + d.fields.insert("nextStyle".into(), json!(n)); + } + } + }) + .response + .labelled_by(next_name.id); ui.end_row(); }); // Reset To Base: the style keeps nothing of its own (the edits made here stay). From 4461ebd8866dd1463a8e3313172fb461f9c02853 Mon Sep 17 00:00:00 2001 From: texjer Date: Fri, 30 Oct 2026 11:50:41 -0400 Subject: [PATCH 0559/1349] Import warnings: Show selects the frame a story warning is about --- ROADMAP.md | 1 + crates/engine/src/cmd/file/registry.rs | 2 +- crates/engine/src/cmd/interchange.rs | 44 ++++++++++++++++++++++---- crates/idml/src/import.rs | 6 +++- crates/ui-egui/src/app/files.rs | 19 +++++++---- crates/ui-egui/src/dialogs.rs | 41 +++++++++++++++++++++++- crates/ui-egui/src/dialogs/tests.rs | 34 ++++++++++++++++++++ 7 files changed, 132 insertions(+), 15 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index ad3f52a14..06668b9de 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -384,6 +384,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-10-30** · Import warnings about a story have a Show button: it closes the warnings (the status line keeps them) and selects the story's first frame, fitted in the window. `file.open` returns `warningItems`, the frame each IDML or InDesign warning is about (or null), matching the converter's INDD story numbers (`story 30892`, written to IDML as `u78ac`) and IDML `Self` names to the imported stories. No readiness percentage change. - **2026-10-29** · Inserting text with many returns no longer takes time that grows with their square (part of #1588): each return copied its paragraph's format with its own insert, moving every format after it. Splitting 20,000 returns into paragraphs took 15.8 s; placing a text file of them now takes 0.2 s, and one of a million returns 5.5 s. No readiness percentage change. - **2026-10-28** · Discretionary hyphens (U+00AD) break in the single-line composer with automatic hyphenation on or off, matching the paragraph composer. Unbroken soft hyphens remain invisible and zero-width, and words containing them keep only their discretionary break points (#1955). No readiness percentage change. - **2026-10-28** · Autoflow no longer sizes the rest of a story by a frame that a Start Paragraph option (next column, frame, page, or odd or even page) ends early (#1209). With a title before a chapter that starts on the next odd page, it estimated a page per few characters, added up to 2000 pages (the autoflow limit) and removed them again: placing 2000 words took 36 s in the app, now 0.4 s, with the same pages. It looks past tracked-deleted paragraphs for the option, as composing does, and asks for every frame that start options and breaks force in one round: 200 one-line chapters on their own pages take 9 ms (58 ms before). A break and the start option it meets count once, and breaks that tracked changes delete or a hidden condition hides don't count. No readiness percentage change. diff --git a/crates/engine/src/cmd/file/registry.rs b/crates/engine/src/cmd/file/registry.rs index 216f12bdb..c1f522956 100644 --- a/crates/engine/src/cmd/file/registry.rs +++ b/crates/engine/src/cmd/file/registry.rs @@ -37,7 +37,7 @@ pub fn specs() -> Vec { ok() }), cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"), - "{path} — a DesignCraft or IDML file (recognised by its content, so the extension may be missing), or an InDesign .indd/.indt (recognised by its signature or extension, converted to IDML; its conversion warnings join `warnings`); the fonts in a `Document Fonts` folder beside it load first → {index, documentFonts: faces loaded, warnings: font files skipped, GREP styles whose pattern can't compile, Based on Parent links cleared and, for IDML and InDesign files, package parts missing}", + "{path} — a DesignCraft or IDML file (recognised by its content, so the extension may be missing), or an InDesign .indd/.indt (recognised by its signature or extension, converted to IDML; its conversion warnings join `warnings`); the fonts in a `Document Fonts` folder beside it load first → {index, documentFonts: faces loaded, warnings: font files skipped, GREP styles whose pattern can't compile, Based on Parent links cleared and, for IDML and InDesign files, package parts missing; warningItems (IDML and InDesign files): per warning, the id of the frame it is about, or null}", always, file_open), cmd!(noundo "file.openBytes", "Open Bytes", [], None, "{name, base64} — DesignCraft JSON, an IDML package or an InDesign .indd/.indt → {index, warnings}", always, file_open_bytes), cmd!(noundo "file.openRecent", "Open Recent File", [], None, diff --git a/crates/engine/src/cmd/interchange.rs b/crates/engine/src/cmd/interchange.rs index 0ddb6a1aa..4ca22309c 100644 --- a/crates/engine/src/cmd/interchange.rs +++ b/crates/engine/src/cmd/interchange.rs @@ -160,7 +160,7 @@ pub fn import(bytes: &[u8], package: Option<&std::path::Path>) -> Result) -> Result<(Document, Vec)> { - import_report_with_previews(bytes, package, &std::collections::HashMap::new()) + import_report_with_previews(bytes, package, &std::collections::HashMap::new()).map(|(document, warnings, _)| (document, warnings)) } /// [`import_report`], showing `previews` (graphic `Self` → image) for linked files that can't be read. @@ -168,7 +168,7 @@ fn import_report_with_previews( bytes: &[u8], package: Option<&std::path::Path>, previews: &std::collections::HashMap>>, -) -> Result<(Document, Vec)> { +) -> Result<(Document, Vec, std::collections::HashMap)> { #[cfg(not(target_arch = "wasm32"))] let resolved = std::cell::RefCell::new(std::collections::HashMap::new()); let read = |link: &str| -> Option> { @@ -184,7 +184,7 @@ fn import_report_with_previews( None } }; - let designcraft_idml::Imported { mut document, warnings } = + let designcraft_idml::Imported { mut document, warnings, story_ids } = designcraft_idml::import_idml_report_with_previews(bytes, &read, previews).map_err(|e| EngineError::Other(e.to_string()))?; resolve_pdf_crops(&mut document); #[cfg(not(target_arch = "wasm32"))] @@ -199,7 +199,7 @@ fn import_report_with_previews( resolve_packaged_links(&mut document, package); document }; - Ok((document, warnings)) + Ok((document, warnings, story_ids)) } /// Placed PDFs read from IDML name their crop (`PDFCrop`): find where each box sits on its page, @@ -422,7 +422,7 @@ pub(crate) fn open_idml(s: &mut Session, p: &Value) -> Result { } else { bytes }; - let (mut d, import_warnings) = import_report_with_previews(&bytes, package.as_deref(), &previews)?; + let (mut d, import_warnings, story_ids) = import_report_with_previews(&bytes, package.as_deref(), &previews)?; warnings.extend(import_warnings); if !title.is_empty() { d.title = title; @@ -433,11 +433,25 @@ pub(crate) fn open_idml(s: &mut Session, p: &Value) -> Result { }; warnings.extend(font_warnings); warnings.extend(super::style::grep_style_warnings(&d)); + let warning_items: Vec = warnings.iter().map(|w| warning_item(&d, &story_ids, w).map_or(Value::Null, |i| json!(i.0))).collect(); // Never save over the .idml or .indd with the native format: the document starts unsaved. let mut st = DocState::new(d, None); st.fonts = fonts; let i = s.add_document(st); - Ok(json!({"index": i, "documentFonts": faces, "warnings": warnings})) + Ok(json!({"index": i, "documentFonts": faces, "warnings": warnings, "warningItems": warning_items})) +} + +/// The frame an import warning is about, so it can be shown: the first frame of the story a +/// "story …: …" warning names, by the converter's INDD id (`story 30892`, which it writes to the +/// IDML as `u78ac`) or by its IDML `Self` (`story u78ac`). +fn warning_item( + d: &Document, + story_ids: &std::collections::HashMap, + warning: &str, +) -> Option { + let name = warning.strip_prefix("story ")?.split([':', ' ']).next()?; + let self_id = name.parse::().map_or_else(|_| name.to_string(), |uid| format!("u{uid:x}")); + d.stories.get(story_ids.get(&self_id)?)?.frames.first().copied() } /// An InDesign document or template (.indd, .indt): known by its signature, or by its name when @@ -479,6 +493,24 @@ mod tests { Ok((bytes, png)) } + #[test] + fn story_warnings_point_at_the_story_frame() { + let mut session = Session::new(); + session.execute("file.new", &json!({})).unwrap(); + session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap(); + let idml = designcraft_idml::export_idml_with(&session.doc().unwrap().doc, &designcraft_idml::ExportOptions { embed_images: true }); + let (d, _, story_ids) = import_report_with_previews(&idml, None, &std::collections::HashMap::new()).unwrap(); + let (self_id, sid) = story_ids.iter().find(|(_, sid)| d.stories.get(*sid).is_some_and(|s| !s.frames.is_empty())).unwrap(); + let frame = d.stories[sid].frames[0]; + assert_eq!(warning_item(&d, &story_ids, &format!("story {self_id}: something")), Some(frame)); + // The INDD converter names stories by their number, which it writes as `u` + hex. + if let Some(uid) = self_id.strip_prefix('u').and_then(|h| u32::from_str_radix(h, 16).ok()) { + assert_eq!(warning_item(&d, &story_ids, &format!("story {uid}: text orientation of its frames is not known")), Some(frame)); + } + assert_eq!(warning_item(&d, &story_ids, "story 999999999: unknown"), None); + assert_eq!(warning_item(&d, &story_ids, "a table of 2 rows was read as 1"), None); + } + #[test] fn opens_nested_packaged_links_from_a_different_computer() { let dir = std::env::temp_dir().join(format!("dc-idml-nested-links-{}", std::process::id())); diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs index 2c6185c5c..51cda9c5b 100644 --- a/crates/idml/src/import.rs +++ b/crates/idml/src/import.rs @@ -60,6 +60,9 @@ pub struct Imported { /// One line per problem that did not stop the import (a part listed in `designmap.xml` but /// absent from the package, …). pub warnings: Vec, + /// Each story's IDML `Self` → its id in `document`, so a warning that names a story can + /// point at it. + pub story_ids: HashMap, } /// Import with a custom reader for linked files, reporting the problems that did not stop it. @@ -119,6 +122,7 @@ pub fn import_idml_report_with_previews( )); } warnings.append(&mut im.warnings); + let story_ids = im.story_ids.clone(); let mut document = im.finish(&root).map_err(|e| match e { // Without its spread parts there is nothing to open: say which parts were missing. IdmlError::Invalid(msg) if !warnings.is_empty() => IdmlError::Invalid(format!("{msg} ({})", warnings.join("; "))), @@ -126,7 +130,7 @@ pub fn import_idml_report_with_previews( })?; warnings.extend(document.fix_parent_bases()); document.check().map_err(|e| IdmlError::Invalid(e.to_string()))?; - Ok(Imported { document, warnings }) + Ok(Imported { document, warnings, story_ids }) } struct ItemCtx { diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 49d2bd757..b5de53ab1 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -258,21 +258,27 @@ impl DesignApp { } self.ui.dialog = Some(dialogs::Dialog::new("alert", json!({"title": title, "file": file, "message": e}))); } else if let Ok(result) = &r { - let warnings: Vec<&str> = result + // Each warning with the frame it is about (`warningItems`), if any. + let items = result.get("warningItems").and_then(Value::as_array); + let (warnings, lines): (Vec<&str>, Vec) = result .get("warnings") .and_then(Value::as_array) .into_iter() .flatten() - .filter_map(Value::as_str) - .filter(|warning| !warning.is_empty()) - .collect(); + .enumerate() + .filter_map(|(i, w)| Some((i, w.as_str()?))) + .filter(|(_, warning)| !warning.is_empty()) + .map(|(i, w)| (w, json!({"text": w, "item": items.and_then(|a| a.get(i)).cloned().unwrap_or(Value::Null)}))) + .unzip(); if !warnings.is_empty() { self.status(format!("{file}: {}", warnings.join("; "))); // Find Font, offered for the document's missing fonts, stays up: the status line // keeps the warnings. if self.ui.dialog.as_ref().is_none_or(|d| d.id != "findFont") { - self.ui.dialog = - Some(dialogs::Dialog::new("alert", json!({"title": "Import Warnings", "file": file, "message": warnings.join("\n")}))); + self.ui.dialog = Some(dialogs::Dialog::new( + "alert", + json!({"title": "Import Warnings", "file": file, "message": warnings.join("\n"), "lines": lines}), + )); } } } @@ -326,6 +332,7 @@ mod import_warning_tests { assert_eq!(dialog.id, "alert"); assert_eq!(dialog.fields["title"], "Import Warnings"); assert_eq!(dialog.fields["file"], file); + assert!(dialog.fields["lines"].as_array().unwrap().iter().all(|l| l["item"].is_null()), "missing parts name no frame"); for part in ["Spreads/missing.xml", "Stories/missing.xml"] { assert!(dialog.fields["message"].as_str().unwrap().contains(part), "every missing part is named"); assert!(app.ui.status.contains(part), "the status line retains the warning"); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index bb3077103..0a60ef18f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -2187,6 +2187,36 @@ fn check(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str) { } /// Draw the active localized dialog; open popups own Enter/Escape, and result handling drives confirm or cancel. +/// An alert's message. Import warnings (`lines`: `{text, item}`) list one per line, scrolling +/// when there are many, with Show beside each that names a frame (sets `show`). +fn alert_message(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { + let lines: Vec<(String, Option)> = d + .fields + .get("lines") + .and_then(Value::as_array) + .into_iter() + .flatten() + .map(|l| (l.get("text").and_then(Value::as_str).unwrap_or_default().to_string(), l.get("item").and_then(Value::as_u64))) + .collect(); + if lines.iter().all(|(_, item)| item.is_none()) { + crate::rtl::label(ui, d.s("message")); + return; + } + let show = crate::i18n::tr(&app.ui.language, "Show"); + egui::ScrollArea::vertical().max_height(360.0).auto_shrink([false, true]).show(ui, |ui| { + for (text, item) in &lines { + ui.horizontal_wrapped(|ui| { + if let Some(item) = item + && ui.small_button(crate::rtl::widget(ui, show)).clicked() + { + d.fields.insert("show".into(), json!(item)); + } + crate::rtl::label(ui, text.as_str()); + }); + } + }); +} + pub fn show(app: &mut DesignApp, ctx: &egui::Context) { let shortcuts = app.ui.dialog.as_ref().is_some_and(|d| d.id == crate::shortcuts_dialog::DIALOG_ID); if shortcuts { @@ -2999,7 +3029,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { crate::rtl::label(ui, egui::RichText::new(crate::rtl::isolate(&file)).font(semibold(13.0))); ui.add_space(4.0); } - crate::rtl::label(ui, d.s("message")); + alert_message(app, ui, &mut d); } _ => {} } @@ -3058,6 +3088,15 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { }); }); }); + // Show on an import warning: close the warnings (the status line keeps them) and select the + // frame the warning is about, in view, so it can be fixed. + if let Some(item) = d.fields.remove("show").and_then(|v| v.as_u64()) { + app.ui.dialog = None; + if app.run("selection.set", json!({"ids": [item]})).is_ok() { + let _ = app.run("view.fitSelection", json!({})); + } + return; + } // Preferences › General › Interface Language takes effect at once, like any other app setting. if let Some(lang) = d.fields.remove("applyLanguage") && let Err(e) = app.run("app.language", json!({"lang": lang})) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 84cbf3bea..61aeea6a7 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3521,3 +3521,37 @@ fn character_style_options_set_the_digits() { assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi)); } + +#[test] +fn import_warning_show_selects_the_frame_it_is_about() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let f = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap(); + app.run("selection.set", json!({"ids": []})).unwrap(); + let lines = json!([ + {"text": "a table of 2 rows was read as 1", "item": null}, + {"text": "story 30892: text orientation of its frames is not known or differs; written as horizontal", "item": f["id"]}, + ]); + app.ui.dialog = Some(Dialog::new("alert", json!({"title": "Import Warnings", "file": "book.indd", "message": "", "lines": lines}))); + let mut h = Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let key = egui::Id::unique("import_warning_show_fonts"); + if ui.data(|d| d.get_temp::(key)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(key, true)); + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(3); + // Only the warning that names a frame offers Show. + assert_eq!(h.query_all_by_label("Show").count(), 1); + h.get_by_label("Show").click(); + h.run_steps(3); + let app = h.state(); + assert!(app.ui.dialog.is_none(), "Show closes the warnings"); + assert_eq!(app.session.doc().unwrap().selection.items, vec![designcraft_doc::ItemId(f["id"].as_u64().unwrap())]); +} From fc46bf20b399696f69dc80f7e1a550d8134139b8 Mon Sep 17 00:00:00 2001 From: texjer Date: Fri, 30 Oct 2026 11:50:41 -0400 Subject: [PATCH 0560/1349] macOS: Finder opens .indd and .indt files with DesignCraft --- packaging/macos/Info.plist.in | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/packaging/macos/Info.plist.in b/packaging/macos/Info.plist.in index cf80fbba8..03d7cb8e4 100644 --- a/packaging/macos/Info.plist.in +++ b/packaging/macos/Info.plist.in @@ -106,6 +106,18 @@ CFBundleTypeExtensions idml + + + CFBundleTypeName + InDesign Document + CFBundleTypeRole + Viewer + LSHandlerRank + Alternate + CFBundleTypeExtensions + inddindt + +## House rules + +These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy. + +1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments. +2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish. +3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location. +4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix. +5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true. +6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why. +7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready. +8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception. +9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop. +10. **Keep secrets and personal details out** of the repository, logs and requests. +11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there. +12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it. +13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it. +14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit. +15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that. + + +## Rust Craft repositories + +These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib). + +1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix. +2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it. +3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository. +4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build. +5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md). +6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`. + +## Licence allowlist + +Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules. + +- `ISC` +- `MIT` +- `BSD-2-Clause` +- `BSD-3-Clause` +- `Apache-2.0` +- `OFL-1.1` +- `Ubuntu-font-1.0` +- `Bitstream-Vera` +- `CC0-1.0` +- `CC-BY-4.0` +- `CC-BY-SA-4.0` +- `LicenseRef-Public-Domain` + +`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so. + + # DesignCraft — instructions for agents DesignCraft is a clean-room, open-source, Rust-native page-layout application targeting Adobe InDesign parity — and superiority (speed, openness, agent control). It runs natively on macOS, Windows and Linux, and on the web via WASM. Siblings with the same conventions: `../vectorcraft` (Illustrator-class), `../photocraft` (Photoshop), `../pdfcraft` (Acrobat), `../filmcraft` (Premiere), `../lightcraft` (Lightroom). ## Start every session here -1. Read `plan/STATUS.md` (current milestone, next task), then the task in `plan/execution-plan.md` and the relevant `plan/architecture.md` section. Behaviour reference: `plan/indesign/*.md` (`11-observed-ui.md` holds measured observations of the running app). -2. Follow the autonomous operation protocol (`plan/execution-plan.md` §7). Don't stop to ask unless §7 lists the decision as the user's. - -`plan/` is gitignored (local only). +Read [`ROADMAP.md`](ROADMAP.md) and [`docs/gaps.md`](docs/gaps.md). `plan/` is an optional gitignored notebook (status, execution notes, `plan/indesign/*.md`). Do not ask for it and do not stop when it is absent. ## Never crash People trust DesignCraft with their layouts; a crash loses their work. **This outranks feature work**: never ship a feature through a panic path, and fix a crash before building on top of it. @@ -26,7 +76,6 @@ People trust DesignCraft with their layouts; a crash loses their work. **This ou - **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` (id, label, menu path, shortcut, params doc, `enabled`, `run`) + tests. Tools emit commands (Begin/Preview/Commit). UI-only commands live in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). The control channel and MCP reach all of them. - **Layering** is enforced by `cargo xtask layers`. Nothing below L6 depends on egui/eframe/winit/rfd. The UI crate is swappable. - **The UI is thin**: panels read engine state and act through `app.run(id, params)`. Colours come from `theme::Tokens`. -- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math). A crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic). - **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`). - **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, assets, layers, wasm). One task id per commit (`M2.1: type tool caret navigation`). @@ -60,3 +109,5 @@ People trust DesignCraft with their layouts; a crash loses their work. **This ou - Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. - Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. - Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. + +New workspace crates include `[lints] workspace = true` in `Cargo.toml`. Production crate roots declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them. diff --git a/CLAUDE.md b/CLAUDE.md index 76e6ac6d3..43c994c2d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,46 +1 @@ -# DesignCraft — instructions for agents - -DesignCraft is a clean-room, open-source, Rust-native page-layout application targeting Adobe InDesign parity — and superiority (speed, openness, agent control). It runs natively on macOS, Windows and Linux, and on the web via WASM. Siblings with the same conventions: `../vectorcraft` (Illustrator-class), `../photocraft` (Photoshop), `../pdfcraft` (Acrobat), `../filmcraft` (Premiere), `../lightcraft` (Lightroom). - -## Start every session here -1. Read `plan/STATUS.md` (current milestone, next task), then the task in `plan/execution-plan.md` and the relevant `plan/architecture.md` section. Behaviour reference: `plan/indesign/*.md` (`11-observed-ui.md` holds measured observations of the running app). -2. Follow the autonomous operation protocol (`plan/execution-plan.md` §7). Don't stop to ask unless §7 lists the decision as the user's. - -`plan/` is gitignored (local only). - -## Never crash -People trust DesignCraft with their layouts; a crash loses their work. **This outranks feature work**: never ship a feature through a panic path, and fix a crash before building on top of it. -- **No panics in non-test code:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`; no `unsafe` (`unsafe_code = "forbid"`). The one exception is a provably infallible literal (a constant regex, `write!` to a `String`): `#[allow(clippy::expect_used)]` + `.expect("why it cannot fail")`. -- **Errors are `Result`** through the crate's error type and `?` (`ok_or(..)?`, `let … else`, `if let`, `map_err` for context). An unfinished feature returns an "unsupported" error. Don't `unwrap_or_default()` where a silent default would corrupt a document; return an error. -- **Input-derived numbers are hostile** (files, commands, MCP/control params, settings): `get()` instead of `[i]`/`[a..b]`, slice strings at char boundaries, checked/saturating arithmetic for lengths and offsets, no division by zero or NaN casts, cap input-sized allocations. -- **Bound recursion** (seen-sets or depth limits for nested or cyclic documents). **Locks:** `lock().unwrap_or_else(PoisonError::into_inner)` or an error; thread joins are `Result`s. -- **Last-resort guard:** escaped panics during command execution and file import/export become an error, never a lost document. It's a safety net, not a licence. -- **Prove it:** every crash fix lands with a small synthetic regression test that panicked before the fix. -- Clean crates carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`; new production crate roots must include the attribute before modules or other crate items, with crate-level `//!` documentation allowed before it. Every new workspace crate must also include `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`. Tests may `unwrap` (`clippy.toml`). - -## Non-negotiables -- **Clean-room.** InDesign is installed on the dev machine and may be *observed* black-box: run it, use its UI with synthetic documents, take screenshots (by window id) stored only under `plan/indesign/screenshots/` (never committed). Never read, disassemble or copy anything inside the InDesign bundle (names/listings only), never copy Adobe icons, artwork, presets or wording beyond feature names, never commit files produced by InDesign. Never copy GPL/AGPL/LGPL code (Scribus, LibreOffice, Ghostscript…). -- **Assets:** no Adobe iconography or images — ever. Every asset is original / OSI / CC0 / redistributable CC (except the ArtCraft trademarks in `docs/brand/`, under `docs/brand/LICENSE-brand.txt`) and has a row in `ASSETS.md` (`cargo xtask assets` enforces it). Prefer art generated in code. -- **Fonts live in [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts)**, never in this repo: don't commit new font files (the Latin UI/document fonts already in `assets/fonts/` stay). It is an optional build input, never a `Cargo.toml` dependency: `CRAFT_FONTS_DIR=/abs/path/to/craft-fonts cargo build` makes `crates/fonts/build.rs` embed its fonts as `designcraft_fonts::CRAFT_FONTS` (Japanese: BIZ UDPGothic for the UI, Mincho first for document text; web builds embed BIZ UDPGothic Regular only). Unset, `CRAFT_FONTS` is empty and the app uses its bundled and system fonts; code and tests must work that way (tests on its glyphs skip). Releases build with it. -- **Shared test corpora.** Real-file test oracles (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`. -- **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` (id, label, menu path, shortcut, params doc, `enabled`, `run`) + tests. Tools emit commands (Begin/Preview/Commit). UI-only commands live in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). The control channel and MCP reach all of them. -- **Layering** is enforced by `cargo xtask layers`. Nothing below L6 depends on egui/eframe/winit/rfd. The UI crate is swappable. -- **The UI is thin**: panels read engine state and act through `app.run(id, params)`. Colours come from `theme::Tokens`. -- **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`). -- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, assets, layers, wasm). One task id per commit (`M2.1: type tool caret navigation`). - -## Running and looking at the app -- `cargo run --release -p designcraft -- --sample --control 7979` (sample magazine + control channel). -- Drive it: JSON lines on `127.0.0.1:7979`, e.g. `{"id":1,"method":"engine.execute","params":{"command":"frame.create","params":{"rect":[36,36,300,200],"content":"text"}}}` then `{"id":2,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}`. Methods: `crates/ui-egui/src/control.rs`, docs: `docs/control-protocol.md`. -- **For UI work, look at the result** (take `ui.screenshot`, read the PNG) and compare with `plan/indesign/02-ui-ux.md` / `11-observed-ui.md`. If no frame is presented (screen locked) use `ui.render` or `designcraft-cli run --sample --all-pages DIR`. -- Headless: `designcraft-cli run --sample --cmd 'frame.create={"rect":[0,0,100,100]}' --export out.png`. -- Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`. -- Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; delete your target dir when done (disk). - -## Roadmap -`ROADMAP.md` (committed) is the one-page summary: stage, headline numbers, dimensions, languages, progress log. Details: `docs/target-app-parity.md` (assessment), `docs/gaps.md` (ranked work list: pick from the top), `docs/roadmap.md` (milestones, current focus), `docs/parity-checklist.md` (presence checklist, `cargo xtask parity`), and the typography, file-format, UI, hardware and localization parity docs in `docs/`. When work lands, update the affected docs and their status lines, delete or shrink the closed gap, and add a progress-log line to ROADMAP.md. - -## CI workflows -- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. -- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. -- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. +@AGENTS.md From d1ed395688896c516030bc6e5d010035e16effee Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 6 Nov 2026 12:36:55 +0100 Subject: [PATCH 0853/1349] docs: preserve local guidance in house-rules rollout --- AGENTS.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 4960ce6b0..d2eebf491 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -82,9 +82,8 @@ People trust DesignCraft with their layouts; a crash loses their work. **This ou ## Running and looking at the app - `cargo run --release -p designcraft -- --sample --control 7979` (sample magazine + control channel). - Drive it: JSON lines on `127.0.0.1:7979`, e.g. `{"id":1,"method":"engine.execute","params":{"command":"frame.create","params":{"rect":[36,36,300,200],"content":"text"}}}` then `{"id":2,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}`. Methods: `crates/ui-egui/src/control.rs`, docs: `docs/control-protocol.md`. -- **For UI work, look at the result** (take `ui.screenshot`, read the PNG) and compare with `plan/indesign/02-ui-ux.md` / `11-observed-ui.md`. If no frame is presented (screen locked) use `ui.render` or `designcraft-cli run --sample --all-pages DIR`. +- **For UI work, look at the result** (take `ui.screenshot`, read the PNG) and, when available, compare with `plan/indesign/02-ui-ux.md` / `11-observed-ui.md`. Without those optional notes, verify the intended behaviour against the task and committed documentation. If no frame is presented (screen locked) use `ui.render` or `designcraft-cli run --sample --all-pages DIR`. - Headless: `designcraft-cli run --sample --cmd 'frame.create={"rect":[0,0,100,100]}' --export out.png`. -- Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`. - Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; delete your target dir when done (disk). ## Roadmap @@ -110,4 +109,4 @@ People trust DesignCraft with their layouts; a crash loses their work. **This ou - Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. - Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. -New workspace crates include `[lints] workspace = true` in `Cargo.toml`. Production crate roots declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them. +New workspace crates include `workspace = true` under `[lints]` in `Cargo.toml`. Production crate roots declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them. From 085a1206067dca338b62e54e611412eeda449f4a Mon Sep 17 00:00:00 2001 From: Zinadin Zidan Date: Sat, 7 Nov 2026 00:27:10 +0600 Subject: [PATCH 0854/1349] Preflight: white or [Paper] set to overprint is reported (#2401) A fill, stroke or stroke gap set to overprint in [Paper] or in a process colour that lays down no ink (C=0 M=0 Y=0 K=0, gray 0, RGB white, a 0% tint) disappears on press. Preflight now reports it as whiteOverprint, and ruby and kenten set to overprint in such a colour too. A spot ink (a white ink or a varnish) prints whatever colour stands in for it, so it isn't reported. Text has no overprint of its own, so white text knocks out and prints, and isn't reported. The old Preflight note that PDF export drops ruby and kenten overprint is gone: export writes it. --- ROADMAP.md | 3 +- crates/engine/src/cmd/preflight.rs | 23 +-- .../src/cmd/preflight/white_overprint.rs | 127 ++++++++++++++++ .../cmd/preflight/white_overprint/tests.rs | 135 ++++++++++++++++++ docs/cjk.md | 4 +- docs/target-app-parity.md | 2 +- 6 files changed, 282 insertions(+), 12 deletions(-) create mode 100644 crates/engine/src/cmd/preflight/white_overprint.rs create mode 100644 crates/engine/src/cmd/preflight/white_overprint/tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index 963b8b855..81e87eea3 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -91,7 +91,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope - Control panel scale X/Y, rotation and shear fields (`transform.info`, absolute `transform.set {scaleX, scaleY, rotation, shear}` about the reference point) and Preferences › Transformations are Totals for nested objects and placed graphics. - Variable fonts: each named instance is a style (Font menu, shaping with feature variations, metrics, outlines) and embeds at its axis settings in PDF; free axis sliders still to come. - Object ▸ Select (first/next above, next/last below, container, content, previous/next in group), full Object ▸ Convert Shape (`object.convertShape`), Table ▸ Split Cell Horizontally/Vertically. -- Attributes panel (`object.attributes`: Overprint Fill/Stroke/Gap, Nonprinting), with Overprint Gap in Overprint Preview and IDML; PDF export writes them as `/op` and `/OP` with `/OPM 1`. +- Attributes panel (`object.attributes`: Overprint Fill/Stroke/Gap, Nonprinting), with Overprint Gap in Overprint Preview and IDML; PDF export writes them as `/op` and `/OP` with `/OPM 1`. Preflight warns about white or [Paper] set to overprint (`whiteOverprint`): a fill, stroke or gap, or ruby and kenten, that lays down no ink and would vanish on press. - Page Numbering View (Preferences: section or absolute): page labels everywhere follow it; Go to Page takes section names, numbers or `+n`. - Preferences › Advanced Type (document `advancedType`: superscript/subscript size and position; IDML TextPreference); subscripts now drop 33.3% like InDesign. - Preferences › Composition › Highlight: keep violations, H&J violations (three shades), custom tracking/kerning, substituted fonts. @@ -401,6 +401,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-11-06** · Preflight warns about white or [Paper] set to overprint (#2401): a fill, stroke or stroke gap, or ruby and kenten, in [Paper] or a colour that lays down no ink (C=0 M=0 Y=0 K=0, a 0% tint; a spot ink, such as a white ink or a varnish, prints whatever colour stands in for it), is reported as `whiteOverprint`, since it disappears on press. Text itself has no overprint, so white text in a frame set to Overprint Fill still knocks out and prints, and is not reported. Preflight no longer says PDF export drops ruby and kenten overprint, which it writes. No readiness percentage change. - **2026-11-03** · `type.char` says when the font it applies isn't available (#2189): it returns `{"warnings": ["Missing font: Courier Prime (using Source Sans 3)"]}`, or `Missing font style: …` for a style the family doesn't have, in preflight's words. The font is still applied, as before, so Find Font and preflight list it. A script that asked for a font the machine doesn't have exported in the substitute with no word about it. No readiness percentage change. - **2026-11-02** · Packaged PDFs report their export warnings in the package result and Instructions.txt, and soft drop shadows and feathers in them are tested. Frame and text-range hyperlinks keep their source bounds when the frame is rasterized, including inside groups. No readiness percentage change. - **2026-11-01** · Parent page resizing (#1620): Properties, the Page Tool Control panel and on-page handles resize the selected parent page independently of document pages. Stable parent IDs, repeated resizing, anchors and liquid rules are preserved on the current command modules. Inline parent margin editing targets only the selected parent page and preserves opposite-page margins and document overrides; document commands retain their first-page default before the canvas is initialized. No readiness percentage change. diff --git a/crates/engine/src/cmd/preflight.rs b/crates/engine/src/cmd/preflight.rs index 45fb8bc40..81886aec0 100644 --- a/crates/engine/src/cmd/preflight.rs +++ b/crates/engine/src/cmd/preflight.rs @@ -1,6 +1,6 @@ //! Live preflight (the Preflight panel and the status-bar indicator): overset text, missing //! fonts and glyphs, missing or low-resolution graphics, RGB content in print documents, empty -//! text frames. +//! text frames, white or [Paper] set to overprint. use designcraft_compose::ComposedStory; use designcraft_doc::{Content, Document, Intent, Item, SpreadRef}; @@ -12,6 +12,8 @@ use serde_json::{Value, json}; use super::{CommandSpec, cmd, has_doc}; use crate::{Result, Session}; +mod white_overprint; + #[derive(Clone, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Issue { @@ -268,6 +270,9 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec { let mut missing_fonts: Vec = Vec::new(); let mut unsupported_typography = std::collections::BTreeSet::new(); let mut missing: Vec<(FaceRef, Vec, designcraft_doc::ItemId)> = Vec::new(); + // Ruby and kenten set to overprint in white, by the frame that shows them (`None`: a note's + // or a cell's story, which has no frame of its own). + let mut white_text: std::collections::BTreeMap, Vec<&'static str>> = std::collections::BTreeMap::new(); for story in d.stories.values() { let cs = s.cache.get(d, story.id, None); missing_glyphs(&cs, None, 0, &mut missing); @@ -327,13 +332,10 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec { } for (run, f) in story.runs().filter(|(run, _)| run.start < range.end && run.end > range.start) { let props = d.styles.resolve_char(&base, f); - { - use designcraft_doc::cjk_settings::AdornmentOverprint as O; - let kenten = props.kenten && (props.kenten_overprint_fill == O::On || props.kenten_overprint_stroke == O::On); - let ruby = !props.ruby.is_empty() && (props.ruby_overprint_fill == O::On || props.ruby_overprint_stroke == O::On); - if kenten || ruby { - unsupported_typography - .insert("Ruby and kenten overprint show in Overprint Preview, but PDF export doesn't write overprint".to_string()); + for part in white_overprint::adornments(d, &props) { + let parts = white_text.entry(story.frames.first().copied()).or_default(); + if !parts.contains(&part) { + parts.push(part); } } if has_rtl @@ -376,6 +378,10 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec { for message in unsupported_typography { out.push(Issue { severity: "warning", kind: "unsupportedTypography", message, item: None, page: None }); } + for (item, parts) in white_text { + let page = item.and_then(|id| d.find(id).zip(d.item(id))).and_then(|(loc, it)| page_of(d, loc.spread, it, d.parent_xf(&loc))); + out.extend(white_overprint::issue(&parts, item.map(|i| i.0), page)); + } for (face, chars, item) in missing { let listed: Vec = chars.iter().take(MISSING_GLYPHS_LISTED).map(char::to_string).collect(); let more = chars.len().saturating_sub(MISSING_GLYPHS_LISTED); @@ -395,6 +401,7 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec { let xf = parent * it.xf; pending.extend(it.children().iter().rev().map(|child| (child.as_ref(), xf))); let page = page_of(d, SpreadRef::Doc(si), it, parent); + out.extend(white_overprint::item_issue(d, it, page)); if let Content::Graphic(g) = &it.content && g.layer_options.as_ref().is_some_and(designcraft_doc::GraphicLayerOptions::has_visibility_overrides) { diff --git a/crates/engine/src/cmd/preflight/white_overprint.rs b/crates/engine/src/cmd/preflight/white_overprint.rs new file mode 100644 index 000000000..d6d50ce52 --- /dev/null +++ b/crates/engine/src/cmd/preflight/white_overprint.rs @@ -0,0 +1,127 @@ +//! White or [Paper] set to overprint (#2401). A paint that lays down no ink knocks out what is +//! beneath it, which is how white shows on press. Set to overprint, it leaves the inks beneath +//! alone instead, so the object is gone from the printed page while the screen, without +//! Overprint Preview, still shows it. +//! +//! What can overprint: a page item's fill, stroke and stroke gap (Attributes panel), and ruby and +//! kenten set to overprint. Text itself has no overprint attribute, so white text knocks out and +//! prints; the frame's Overprint Fill covers the frame's own fill only. + +use designcraft_color::{Color, ColorType, SwatchValue, swatch}; +use designcraft_doc::cjk_settings::AdornmentOverprint; +use designcraft_doc::{CharProps, Document, Item, StrokeType}; + +use super::Issue; + +/// The issue's `kind`. +pub(super) const KIND: &str = "whiteOverprint"; + +/// Swatch tints that refer to tints, followed before giving up (as `swatch::resolve` does). +const MAX_TINT_DEPTH: usize = 8; + +/// Whether a paint lays down no ink: [Paper] (whatever colour it is shown in), or a colour or +/// tint that comes out white (C=0 M=0 Y=0 K=0, a 0% tint, RGB white). A spot colour prints on +/// its own plate whatever colour stands in for it (a white ink, a varnish), so only a 0% tint of +/// it is white. [None] and gradients are not white. +fn prints_no_ink(d: &Document, name: &str, tint: f32) -> bool { + const INK: f32 = 0.001; + let (mut base, mut t) = (name, tint); + for _ in 0..=MAX_TINT_DEPTH { + match d.swatches.iter().find(|s| s.name == base).map(|s| &s.value) { + Some(SwatchValue::Paper { .. }) => return true, + Some(SwatchValue::Tint { base: b, tint: bt }) => (base, t) = (b, t * bt), + // A NaN tint compares false: not white. + Some(SwatchValue::Color { color_type: ColorType::Spot, .. }) => return t <= INK, + Some(SwatchValue::Color { .. } | SwatchValue::Registration) => break, + Some(SwatchValue::None | SwatchValue::Gradient { .. }) | None => return false, + } + } + // A NaN component compares false: not white. + match d.resolve_color(name, tint) { + Some(Color::Cmyk { c, m, y, k }) => [c, m, y, k].iter().all(|v| *v <= INK), + Some(Color::Gray { k }) => k <= INK, + Some(Color::Rgb { r, g, b }) => [r, g, b].iter().all(|v| *v >= 1.0 - INK), + None => false, + } +} + +/// "fill", "fill and stroke", "fill, stroke and stroke gap". +fn list(parts: &[&str]) -> String { + match parts.split_last() { + Some((last, rest)) if !rest.is_empty() => format!("{} and {last}", rest.join(", ")), + Some((last, _)) => (*last).to_string(), + None => String::new(), + } +} + +/// The warning for `parts` (paints, or ruby and kenten) of one item; none for no parts. +pub(super) fn issue(parts: &[&str], item: Option, page: Option) -> Option { + (!parts.is_empty()).then(|| Issue { + severity: "warning", + kind: KIND, + message: format!("White or [Paper] {} set to overprint will not print", list(parts)), + item, + page, + }) +} + +/// A page item's fill, stroke or stroke gap that is white and set to overprint. +pub(super) fn item_issue(d: &Document, it: &Item, page: Option) -> Option { + if it.nonprinting { + return None; + } + let mut parts = Vec::new(); + if it.fill.overprint && !it.fill.is_none() && prints_no_ink(d, &it.fill.swatch, it.fill.tint) { + parts.push("fill"); + } + let st = &it.stroke; + if st.overprint && !st.is_none() && prints_no_ink(d, &st.swatch, st.tint) { + parts.push("stroke"); + } + // The gap colour shows between dashes, dots and stripes only. + if st.gap_overprint && !st.is_none() && !matches!(d.stroke_kind(&st.kind), StrokeType::Solid) && prints_no_ink(d, &st.gap_swatch, st.gap_tint) { + parts.push("stroke gap"); + } + issue(&parts, Some(it.id.0), page) +} + +/// Ruby and kenten of a run that are white and set to overprint, with the colours composition +/// gives them (`kenten::mark_props`, `ruby::ruby_style`): an empty swatch is the text's. +pub(super) fn adornments(d: &Document, p: &CharProps) -> Vec<&'static str> { + let tint = |t: Option| t.filter(|t| t.is_finite()).map(|t| t.clamp(0.0, 1.0)); + let white = |on: AdornmentOverprint, name: &str, tint: f32, weight: Option| { + on == AdornmentOverprint::On && name != swatch::NONE && weight.is_none_or(|w| w.is_finite() && w > 0.0) && prints_no_ink(d, name, tint) + }; + let mut out = Vec::new(); + if p.kenten { + let fill = if p.kenten_fill.is_empty() { &p.fill } else { &p.kenten_fill }; + let stroke = if p.kenten_stroke.is_empty() { &p.stroke } else { &p.kenten_stroke }; + let weight = p.kenten_stroke_weight.filter(|w| w.is_finite()).unwrap_or(p.stroke_weight); + if white(p.kenten_overprint_fill, fill, tint(p.kenten_fill_tint).unwrap_or(p.fill_tint), None) + || white(p.kenten_overprint_stroke, stroke, tint(p.kenten_stroke_tint).unwrap_or(p.stroke_tint), Some(weight)) + { + out.push("kenten"); + } + } + if !p.ruby.is_empty() { + // A ruby colour of its own is at 100% unless it has a tint; without one, the text's. + let (fill, fill_tint) = if p.ruby_fill.is_empty() { + (&p.fill, tint(p.ruby_fill_tint).unwrap_or(p.fill_tint)) + } else { + (&p.ruby_fill, tint(p.ruby_fill_tint).unwrap_or(1.0)) + }; + let (stroke, stroke_tint) = if p.ruby_stroke.is_empty() { + (&p.stroke, tint(p.ruby_stroke_tint).unwrap_or(p.stroke_tint)) + } else { + (&p.ruby_stroke, tint(p.ruby_stroke_tint).unwrap_or(1.0)) + }; + let weight = p.ruby_stroke_weight.filter(|w| w.is_finite()).unwrap_or(p.stroke_weight); + if white(p.ruby_overprint_fill, fill, fill_tint, None) || white(p.ruby_overprint_stroke, stroke, stroke_tint, Some(weight)) { + out.push("ruby"); + } + } + out +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/preflight/white_overprint/tests.rs b/crates/engine/src/cmd/preflight/white_overprint/tests.rs new file mode 100644 index 000000000..70fac3e1c --- /dev/null +++ b/crates/engine/src/cmd/preflight/white_overprint/tests.rs @@ -0,0 +1,135 @@ +use std::sync::Arc; + +use serde_json::json; + +use crate::Session; + +/// The `whiteOverprint` issues of the active document: (message, item). +fn white_overprints(s: &mut Session) -> Vec<(String, Option)> { + let r = s.execute("preflight.run", &json!({})).unwrap(); + r["issues"] + .as_array() + .unwrap() + .iter() + .filter(|i| i["kind"] == "whiteOverprint") + .inspect(|i| assert_eq!(i["severity"], "warning")) + .map(|i| (i["message"].as_str().unwrap().to_string(), i["item"].as_u64())) + .collect() +} + +fn rect(s: &mut Session, r: [f64; 4]) -> u64 { + s.execute("frame.create", &json!({"rect": r})).unwrap()["id"].as_u64().unwrap() +} + +/// A [Paper] fill set to overprint is gone on press: preflight said nothing about it. +#[test] +fn a_paper_fill_set_to_overprint_is_reported() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = rect(&mut s, [72.0, 72.0, 200.0, 200.0]); + s.execute("object.fill", &json!({"ids": [id], "swatch": "[Paper]"})).unwrap(); + assert!(white_overprints(&mut s).is_empty(), "a white fill that knocks out prints"); + s.execute("object.attributes", &json!({"ids": [id], "overprintFill": true})).unwrap(); + assert_eq!(white_overprints(&mut s), [("White or [Paper] fill set to overprint will not print".to_string(), Some(id))]); + // A coloured fill set to overprint is ordinary trapping. + s.execute("object.fill", &json!({"ids": [id], "swatch": "[Black]"})).unwrap(); + assert!(white_overprints(&mut s).is_empty()); + // Nonprinting: nothing of it prints anyway. + s.execute("object.fill", &json!({"ids": [id], "swatch": "[Paper]"})).unwrap(); + s.execute("object.attributes", &json!({"ids": [id], "nonprinting": true})).unwrap(); + assert!(white_overprints(&mut s).is_empty()); +} + +/// White is any paint that lays down no ink: C=0 M=0 Y=0 K=0, or a 0% tint. +#[test] +fn white_colours_and_strokes_are_reported() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + Arc::make_mut(&mut s.doc_mut().unwrap().doc).swatches.push(designcraft_color::swatch::Swatch::cmyk(0.0, 0.0, 0.0, 0.0)); + let a = rect(&mut s, [72.0, 72.0, 200.0, 200.0]); + s.execute("object.fill", &json!({"ids": [a], "swatch": "[Black]", "tint": 0.0})).unwrap(); + s.execute("object.stroke", &json!({"ids": [a], "swatch": "C=0 M=0 Y=0 K=0", "weight": 4})).unwrap(); + s.execute("object.attributes", &json!({"ids": [a], "overprintFill": true, "overprintStroke": true})).unwrap(); + // A gap colour shows only between dashes: on a solid stroke it is not drawn. + let b = rect(&mut s, [300.0, 72.0, 400.0, 200.0]); + s.execute("object.stroke", &json!({"ids": [b], "swatch": "[Black]", "weight": 4, "gapSwatch": "[Paper]", "gapOverprint": true})).unwrap(); + assert_eq!(white_overprints(&mut s), [("White or [Paper] fill and stroke set to overprint will not print".to_string(), Some(a))]); + s.execute("object.stroke", &json!({"ids": [b], "type": {"kind": "dotted"}})).unwrap(); + let found = white_overprints(&mut s); + assert!(found.contains(&("White or [Paper] stroke gap set to overprint will not print".to_string(), Some(b))), "{found:?}"); +} + +/// A spot ink prints on its own plate whatever colour stands in for it: a white ink or a varnish +/// set to overprint, as they usually are, is not white. A 0% tint of one lays down no ink. +#[test] +fn a_spot_ink_with_a_white_alternate_prints() { + use designcraft_color::{Color, ColorType, Swatch, SwatchValue}; + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let swatches = &mut Arc::make_mut(&mut s.doc_mut().unwrap().doc).swatches; + for (name, color) in [("Opaque White", Color::cmyk(0.0, 0.0, 0.0, 0.0)), ("Varnish", Color::rgb(1.0, 1.0, 1.0))] { + swatches.push(Swatch { + name: name.into(), + value: SwatchValue::Color { color, color_type: ColorType::Spot }, + locked: false, + named: true, + hidden: false, + }); + } + swatches.push(Swatch { + name: "Varnish 50%".into(), + value: SwatchValue::Tint { base: "Varnish".into(), tint: 0.5 }, + locked: false, + named: true, + hidden: false, + }); + let a = rect(&mut s, [72.0, 72.0, 200.0, 200.0]); + s.execute("object.fill", &json!({"ids": [a], "swatch": "Opaque White"})).unwrap(); + s.execute("object.stroke", &json!({"ids": [a], "swatch": "Varnish 50%", "weight": 4})).unwrap(); + s.execute("object.attributes", &json!({"ids": [a], "overprintFill": true, "overprintStroke": true})).unwrap(); + assert!(white_overprints(&mut s).is_empty()); + s.execute("object.fill", &json!({"ids": [a], "swatch": "Opaque White", "tint": 0.0})).unwrap(); + assert_eq!(white_overprints(&mut s), [("White or [Paper] fill set to overprint will not print".to_string(), Some(a))]); +} + +/// The issue's steps: text in [Paper], and Overprint Fill applied to its frame. Text has no +/// overprint of its own, and the frame's Overprint Fill is for the frame's fill, which is [None]: +/// the text knocks out and prints, so there is nothing to report. With a [Paper] fill on the +/// frame, the frame is what disappears. +#[test] +fn paper_text_in_a_frame_set_to_overprint() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [72, 72, 300, 200], "content": "text", "text": "White"})).unwrap(); + let id = r["id"].as_u64().unwrap(); + s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 5})).unwrap(); + s.execute("type.char", &json!({"attrs": {"fill": "[Paper]"}})).unwrap(); + s.execute("object.attributes", &json!({"ids": [id], "overprintFill": true})).unwrap(); + assert!(white_overprints(&mut s).is_empty()); + s.execute("object.fill", &json!({"ids": [id], "swatch": "[Paper]"})).unwrap(); + assert_eq!(white_overprints(&mut s), [("White or [Paper] fill set to overprint will not print".to_string(), Some(id))]); +} + +/// Ruby and kenten are the text that can overprint; in [Paper] they then disappear. +#[test] +fn white_ruby_and_kenten_set_to_overprint_are_reported() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [72, 72, 300, 200], "content": "text", "text": "漢字"})).unwrap(); + let id = r["id"].as_u64(); + let select = |s: &mut Session| s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": "漢字".len()})).unwrap(); + select(&mut s); + s.execute("type.char", &json!({"attrs": {"kenten": true, "kentenFill": "[Paper]"}})).unwrap(); + assert!(white_overprints(&mut s).is_empty(), "`Auto` follows the text, which knocks out"); + select(&mut s); + s.execute("type.char", &json!({"attrs": {"kentenOverprintFill": "on"}})).unwrap(); + assert_eq!(white_overprints(&mut s), [("White or [Paper] kenten set to overprint will not print".to_string(), id)]); + // Ruby in the text's colour, [Paper], with the ruby's stroke set to overprint and none: fine. + select(&mut s); + s.execute("type.char", &json!({"attrs": {"ruby": "かんじ", "fill": "[Paper]", "rubyOverprintStroke": "on"}})).unwrap(); + assert_eq!(white_overprints(&mut s), [("White or [Paper] kenten set to overprint will not print".to_string(), id)]); + select(&mut s); + s.execute("type.char", &json!({"attrs": {"rubyOverprintFill": "on"}})).unwrap(); + let found = white_overprints(&mut s); + assert_eq!(found, [("White or [Paper] kenten and ruby set to overprint will not print".to_string(), id)]); +} diff --git a/docs/cjk.md b/docs/cjk.md index 68839e0e8..e5782d8ae 100644 --- a/docs/cjk.md +++ b/docs/cjk.md @@ -41,8 +41,8 @@ presets or tables are copied. Our default mojikumi and kinsoku tables are built | Aki, tsume, jidori | done ([cjk-typography.md](cjk-typography.md)) | | Character alignment, leading model | em box top / centre / bottom, ICF top / bottom (`BASE` `icft`/`icfb`, else the em box inset by 5%), roman baseline; aki above / below, centre (centre down as centre); under aki below a line's leading is the space to the line below it; with the Japanese composers (`Composer::Japanese`, `JapaneseSingleLine`, IDML `HL Composer J` / `HL Single J`), the others set lines baseline to baseline on the Roman baseline | | Tate-chu-yoko | manual, with offsets; auto tate-chu-yoko of short digit runs (with roman letters when asked) in vertical text, narrowed to fit the em (`type.autoTateChuYoko`, IDML `AutoTcy`, `AutoTcyIncludeRoman`); manual groups of 3+ digits overflow the em | -| Ruby | group and per-character (jukugo) ruby; alignment (shoulder, centre, end, justify, JIS 1-2-1, equal aki, 1 ruby-character aki); above/right or below/left with offsets; font, size (½ by default), scales, OpenType `ruby` glyphs, auto tate-chu-yoko of digits; overhang onto kana and punctuation; parent spacing and automatic narrowing when the ruby is longer; flush with the line edge (a group stays on the line of each neighbour its ruby overhangs, so the reserved spacing holds at line edges); set beyond kenten on the same side; fill, stroke, tint, weight, and overprint in Overprint Preview; every setting through `type.ruby` and IDML. Doesn't affect leading; PDF export writes no overprint (Preflight and the export say so) | -| Kenten | the kinds and a custom mark (up to 8 characters) in its own font; size, x/y scale, distance, above/right or below/left, centred or at the character's start; fill, stroke, tints, weight, and overprint in Overprint Preview (`type.kenten`, IDML `Kenten*`). The character set (input mode) is kept, not converted; PDF export writes no overprint | +| Ruby | group and per-character (jukugo) ruby; alignment (shoulder, centre, end, justify, JIS 1-2-1, equal aki, 1 ruby-character aki); above/right or below/left with offsets; font, size (½ by default), scales, OpenType `ruby` glyphs, auto tate-chu-yoko of digits; overhang onto kana and punctuation; parent spacing and automatic narrowing when the ruby is longer; flush with the line edge (a group stays on the line of each neighbour its ruby overhangs, so the reserved spacing holds at line edges); set beyond kenten on the same side; fill, stroke, tint, weight, and overprint in Overprint Preview; every setting through `type.ruby` and IDML. Doesn't affect leading; PDF export writes the overprint | +| Kenten | the kinds and a custom mark (up to 8 characters) in its own font; size, x/y scale, distance, above/right or below/left, centred or at the character's start; fill, stroke, tints, weight, and overprint in Overprint Preview (`type.kenten`, IDML `Kenten*`). The character set (input mode) is kept, not converted; PDF export writes the overprint | | Shatai | magnification, angle, adjust rotation and adjust tsume on screen, in PDF, outlines and type on a path (`type.shatai`, IDML `Shatai*`) | | Rotate roman, roman word break | half-width characters upright in vertical text (`type.rotateRoman`, IDML `RotateSingleByteCharacters`); breaks between Latin, Greek or Cyrillic letters without a hyphen (`type.romanWordBreak`, IDML `AllowArbitraryHyphenation`) | | Grid alignment | against the baseline grid: roman baseline, em box top / centre / bottom, ICF top / bottom; first line only; gyoudori (auto or N grid lines) and paragraph gyoudori (`type.gridSettings`, IDML `GridAlignment`, `GridGyoudori`, `ParagraphGyoudori`). No frame grid; vertical frames have no baseline grid | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 03a7726d1..cb57677a2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -315,7 +315,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - Control panel scale X/Y, rotation and shear fields (`transform.info`, absolute `transform.set {scaleX, scaleY, rotation, shear}` about the reference point) and Preferences › Transformations are Totals for nested objects and placed graphics. - Variable fonts: each named instance is a style (Font menu, shaping with feature variations, metrics, outlines) and embeds at its axis settings in PDF; free axis sliders still to come. - Object ▸ Select (first/next above, next/last below, container, content, previous/next in group), full Object ▸ Convert Shape (`object.convertShape`), Table ▸ Split Cell Horizontally/Vertically. -- Attributes panel (`object.attributes`: Overprint Fill/Stroke/Gap, Nonprinting), with Overprint Gap in Overprint Preview and IDML; PDF export writes them as `/op` and `/OP` with `/OPM 1`. +- Attributes panel (`object.attributes`: Overprint Fill/Stroke/Gap, Nonprinting), with Overprint Gap in Overprint Preview and IDML; PDF export writes them as `/op` and `/OP` with `/OPM 1`. Preflight warns about white or [Paper] set to overprint (`whiteOverprint`): a fill, stroke or gap, or ruby and kenten, that lays down no ink and would vanish on press. - Page Numbering View (Preferences: section or absolute): page labels everywhere follow it; Go to Page takes section names, numbers or `+n`. - Preferences › Advanced Type (document `advancedType`: superscript/subscript size and position; IDML TextPreference); subscripts now drop 33.3% like InDesign. - Preferences › Composition › Highlight: keep violations, H&J violations (three shades), custom tracking/kerning, substituted fonts. From c99a41af449a0410887851d9426d1e914330a74a Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:28:53 -0500 Subject: [PATCH 0855/1349] =?UTF-8?q?Fix=20iDML=20import=20drops=20a=20tab?= =?UTF-8?q?le=20cell's=20insets=20written=20as=20`TextTopInset`=20?= =?UTF-8?q?=E2=80=A6=20(#2414)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #2410. - crates/idml/src/import/table.rs - crates/idml/src/import/styles.rs - crates/idml/src/export/table.rs - crates/idml/src/export/styles.rs - crates/idml/tests/autocraft_regression_2410.rs --- crates/idml/src/export/styles.rs | 12 ++- crates/idml/src/export/table.rs | 4 + crates/idml/src/import/styles.rs | 4 +- crates/idml/src/import/table.rs | 7 +- .../idml/tests/autocraft_regression_2410.rs | 82 +++++++++++++++++++ 5 files changed, 102 insertions(+), 7 deletions(-) create mode 100644 crates/idml/tests/autocraft_regression_2410.rs diff --git a/crates/idml/src/export/styles.rs b/crates/idml/src/export/styles.rs index 8977af787..0965a351f 100644 --- a/crates/idml/src/export/styles.rs +++ b/crates/idml/src/export/styles.rs @@ -194,14 +194,18 @@ impl<'a> Ex<'a> { if let Some(t) = cs.fill_tint { el.set("FillTint", pct(t as f64)); } + let inset_names = + [("TextTopInset", "TopInset"), ("TextLeftInset", "LeftInset"), ("TextBottomInset", "BottomInset"), ("TextRightInset", "RightInset")]; if let Some(i) = cs.insets { - for (k, v) in ["TopInset", "LeftInset", "BottomInset", "RightInset"].iter().zip(i) { - el.set(k, num(v)); + for ((text, old), v) in inset_names.iter().zip(i) { + el.set(text, num(v)); + el.set(old, num(v)); } } - for (key, value) in ["TopInset", "LeftInset", "BottomInset", "RightInset"].iter().zip(cs.inset_overrides) { + for ((text, old), value) in inset_names.iter().zip(cs.inset_overrides) { if let Some(value) = value { - el.set(key, num(value)); + el.set(text, num(value)); + el.set(old, num(value)); } } if let Some(vj) = cs.vj { diff --git a/crates/idml/src/export/table.rs b/crates/idml/src/export/table.rs index 1e81a811a..737b7c224 100644 --- a/crates/idml/src/export/table.rs +++ b/crates/idml/src/export/table.rs @@ -188,6 +188,10 @@ impl<'a> Ex<'a> { .attr("LeftInset", num(cell.insets[1])) .attr("BottomInset", num(cell.insets[2])) .attr("RightInset", num(cell.insets[3])) + .attr("TextTopInset", num(cell.insets[0])) + .attr("TextLeftInset", num(cell.insets[1])) + .attr("TextBottomInset", num(cell.insets[2])) + .attr("TextRightInset", num(cell.insets[3])) .attr("VerticalJustification", vj) .attr("FirstBaselineOffset", names::first_baseline_out(cell.first_baseline)) .attr("MinimumFirstBaselineOffset", num(cell.first_baseline_min)) diff --git a/crates/idml/src/import/styles.rs b/crates/idml/src/import/styles.rs index 4519d8931..d7721899d 100644 --- a/crates/idml/src/import/styles.rs +++ b/crates/idml/src/import/styles.rs @@ -117,7 +117,9 @@ impl<'r> Importer<'r> { e.prop("BasedOn").map(|r| self.cell_style_ref(&r)).or_else(|| Some(designcraft_doc::NO_CELL_STYLE.into())).filter(|n| *n != name); cs.fill = e.prop("FillColor").map(|c| self.swatch_ref(&c)); cs.fill_tint = tint(e.num("FillTint")); - cs.inset_overrides = ["TopInset", "LeftInset", "BottomInset", "RightInset"].map(|k| e.num(k).map(|v| v.max(0.0))); + let inset_names = + [("TextTopInset", "TopInset"), ("TextLeftInset", "LeftInset"), ("TextBottomInset", "BottomInset"), ("TextRightInset", "RightInset")]; + cs.inset_overrides = inset_names.map(|(text, old)| e.num(text).or_else(|| e.num(old)).map(|v| v.max(0.0))); if let [Some(top), Some(left), Some(bottom), Some(right)] = cs.inset_overrides { cs.insets = Some([top, left, bottom, right]); cs.inset_overrides = [None; 4]; diff --git a/crates/idml/src/import/table.rs b/crates/idml/src/import/table.rs index 268f1af97..1f6e029ca 100644 --- a/crates/idml/src/import/table.rs +++ b/crates/idml/src/import/table.rs @@ -189,8 +189,11 @@ impl<'r> Importer<'r> { if let Some(tint) = tint(ce.num("FillTint")) { cell.fill_tint = tint; } - for (i, k) in ["TopInset", "LeftInset", "BottomInset", "RightInset"].iter().enumerate() { - if let Some(v) = ce.num(k) { + // Current InDesign writes `TextTopInset` and so on; the older `TopInset` names are the fallback. + let inset_names = + [("TextTopInset", "TopInset"), ("TextLeftInset", "LeftInset"), ("TextBottomInset", "BottomInset"), ("TextRightInset", "RightInset")]; + for (i, (text, old)) in inset_names.iter().enumerate() { + if let Some(v) = ce.num(text).or_else(|| ce.num(old)) { cell.insets[i] = v.max(0.0); } } diff --git a/crates/idml/tests/autocraft_regression_2410.rs b/crates/idml/tests/autocraft_regression_2410.rs new file mode 100644 index 000000000..dc42bc7b1 --- /dev/null +++ b/crates/idml/tests/autocraft_regression_2410.rs @@ -0,0 +1,82 @@ +//! A table cell's insets written as `TextTopInset` ... (current InDesign) are read, and a cell +//! style's too; they survive a round trip. + +use std::io::Write; + +use designcraft_doc::{Document, Table}; +use designcraft_idml::{MIMETYPE, export_idml, import_idml}; + +const DESIGNMAP: &str = r#" + + + + +"#; + +const STYLES: &str = r#" + + + + +"#; + +const SPREAD: &str = r#" + + + + + + + + +"#; + +/// Cells: 0 uses the current names, 1 carries both (the current ones win), 2 only the older +/// names, 3 takes its insets from a cell style written with the current names. +const STORY: &str = r#" + + + +A +B +C +D +
"#; + +fn package() -> Vec { + use zip::write::SimpleFileOptions; + let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let stored = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); + w.start_file("mimetype", stored).unwrap(); + w.write_all(MIMETYPE.as_bytes()).unwrap(); + for (name, content) in + [("designmap.xml", DESIGNMAP), ("Resources/Styles.xml", STYLES), ("Spreads/Spread_sp1.xml", SPREAD), ("Stories/Story_s1.xml", STORY)] + { + w.start_file(name, SimpleFileOptions::default()).unwrap(); + w.write_all(content.as_bytes()).unwrap(); + } + w.finish().unwrap().into_inner() +} + +fn table(doc: &Document) -> &Table { + doc.stories.values().flat_map(|s| s.tables.values()).next().unwrap() +} + +fn insets(doc: &Document) -> Vec<[f64; 4]> { + let t = table(doc); + (0..4).map(|c| t.cell(0, c).unwrap().insets).collect() +} + +#[test] +fn current_text_inset_names_are_read_and_round_trip() { + let doc = import_idml(&package()).unwrap(); + let got = insets(&doc); + assert_eq!(got[0], [11.0, 12.0, 13.0, 14.0], "a cell's current-named insets"); + assert_eq!(got[2], [31.0, 32.0, 33.0, 34.0], "a cell's older-named insets still work"); + assert_eq!(got[3], [6.0, 7.0, 8.0, 9.0], "a cell style's current-named insets"); + assert_eq!(got[1][0], 21.0, "the current name wins over the older one"); + assert_eq!(got[1][1], 2.0, "a side only the older name sets falls back to it"); + + let back = import_idml(&export_idml(&doc)).unwrap(); + assert_eq!(insets(&back), got, "the insets survive a round trip"); +} From 83d11697dbbdab2db0fe84f13aedc94760095f48 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:37:05 +0000 Subject: [PATCH 0856/1349] Apply review fixes - crates/engine/src/cmd/preflight.rs --- crates/engine/src/cmd/preflight.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/preflight.rs b/crates/engine/src/cmd/preflight.rs index 81886aec0..0437fc3ca 100644 --- a/crates/engine/src/cmd/preflight.rs +++ b/crates/engine/src/cmd/preflight.rs @@ -297,6 +297,7 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec { // Nested note and cell text uses paragraph rules too. super::fonts::for_each_story(d, &mut |story| { let ranges = story.para_ranges(); + let shown = (!story.frames.is_empty()).then(|| s.cache.get(d, story.id, None)); for (pi, pf) in story.paras.iter().enumerate() { let (para, base) = d.styles.resolve_para(pf); let Some(range) = ranges.get(pi) else { continue }; @@ -333,7 +334,12 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec { for (run, f) in story.runs().filter(|(run, _)| run.start < range.end && run.end > range.start) { let props = d.styles.resolve_char(&base, f); for part in white_overprint::adornments(d, &props) { - let parts = white_text.entry(story.frames.first().copied()).or_default(); + let at = run.start.max(range.start); + let frame = shown + .as_ref() + .and_then(|cs| cs.frames.iter().find(|f| f.range.contains(&at)).map(|f| f.frame)) + .or_else(|| story.frames.first().copied()); + let parts = white_text.entry(frame).or_default(); if !parts.contains(&part) { parts.push(part); } From 231ee6d4c39e25b65d9ce5b00ca44538980764dd Mon Sep 17 00:00:00 2001 From: Zinadin Zidan Date: Sat, 7 Nov 2026 02:09:42 +0600 Subject: [PATCH 0857/1349] Preflight: white overprint is looked for where PDF export prints (review) Ruby and kenten in a threaded story were reported against the story's first frame, on its page, wherever the text was; they are now reported against the frame that shows them, and text no frame has room for isn't. Parent pages' items and anchored objects print too and weren't looked at; items on a hidden or nonprintable layer, or in a hidden or nonprinting group, don't print and were reported. The check now walks the items as PDF export draws them, with its rules (the parent page items a page shows now come from one function both use), and a frame PDF export leaves out reports none of its ruby and kenten. --- crates/engine/src/cmd/preflight.rs | 33 ++++-- .../src/cmd/preflight/white_overprint.rs | 104 +++++++++++++++++- .../cmd/preflight/white_overprint/tests.rs | 104 +++++++++++++++++- crates/pdf/src/export.rs | 2 +- crates/pdf/src/export/pipeline.rs | 31 +++++- crates/pdf/src/export/walk.rs | 29 ++--- crates/pdf/src/lib.rs | 3 +- 7 files changed, 268 insertions(+), 38 deletions(-) diff --git a/crates/engine/src/cmd/preflight.rs b/crates/engine/src/cmd/preflight.rs index 81886aec0..6fada503d 100644 --- a/crates/engine/src/cmd/preflight.rs +++ b/crates/engine/src/cmd/preflight.rs @@ -270,8 +270,8 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec { let mut missing_fonts: Vec = Vec::new(); let mut unsupported_typography = std::collections::BTreeSet::new(); let mut missing: Vec<(FaceRef, Vec, designcraft_doc::ItemId)> = Vec::new(); - // Ruby and kenten set to overprint in white, by the frame that shows them (`None`: a note's - // or a cell's story, which has no frame of its own). + // Ruby and kenten set to overprint in white, by the frame that shows them (`None`: a note's, + // a cell's or an unplaced story, which has no frame of its own). let mut white_text: std::collections::BTreeMap, Vec<&'static str>> = std::collections::BTreeMap::new(); for story in d.stories.values() { let cs = s.cache.get(d, story.id, None); @@ -297,6 +297,8 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec { // Nested note and cell text uses paragraph rules too. super::fonts::for_each_story(d, &mut |story| { let ranges = story.para_ranges(); + // The byte ranges its frames show, asked for at the first white ruby or kenten. + let mut shown = None; for (pi, pf) in story.paras.iter().enumerate() { let (para, base) = d.styles.resolve_para(pf); let Some(range) = ranges.get(pi) else { continue }; @@ -332,10 +334,16 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec { } for (run, f) in story.runs().filter(|(run, _)| run.start < range.end && run.end > range.start) { let props = d.styles.resolve_char(&base, f); - for part in white_overprint::adornments(d, &props) { - let parts = white_text.entry(story.frames.first().copied()).or_default(); - if !parts.contains(&part) { - parts.push(part); + let white = white_overprint::adornments(d, &props); + if !white.is_empty() { + let shown = shown.get_or_insert_with(|| white_overprint::frame_ranges(s, d, story)); + for frame in white_overprint::frames_showing(story, shown, run.start.max(range.start)..run.end.min(range.end)) { + let parts = white_text.entry(frame).or_default(); + for part in &white { + if !parts.contains(part) { + parts.push(part); + } + } } } if has_rtl @@ -378,10 +386,20 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec { for message in unsupported_typography { out.push(Issue { severity: "warning", kind: "unsupportedTypography", message, item: None, page: None }); } + let (white_items, printed_frames) = white_overprint::printed(s, d); for (item, parts) in white_text { - let page = item.and_then(|id| d.find(id).zip(d.item(id))).and_then(|(loc, it)| page_of(d, loc.spread, it, d.parent_xf(&loc))); + // A frame PDF export leaves out (hidden, nonprinting, on a hidden or nonprintable layer, + // on a parent page no page shows) prints none of its text. + let page = match item { + Some(id) => match printed_frames.get(&id) { + Some(page) => *page, + None => continue, + }, + None => None, + }; out.extend(white_overprint::issue(&parts, item.map(|i| i.0), page)); } + out.extend(white_items); for (face, chars, item) in missing { let listed: Vec = chars.iter().take(MISSING_GLYPHS_LISTED).map(char::to_string).collect(); let more = chars.len().saturating_sub(MISSING_GLYPHS_LISTED); @@ -401,7 +419,6 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec { let xf = parent * it.xf; pending.extend(it.children().iter().rev().map(|child| (child.as_ref(), xf))); let page = page_of(d, SpreadRef::Doc(si), it, parent); - out.extend(white_overprint::item_issue(d, it, page)); if let Content::Graphic(g) = &it.content && g.layer_options.as_ref().is_some_and(designcraft_doc::GraphicLayerOptions::has_visibility_overrides) { diff --git a/crates/engine/src/cmd/preflight/white_overprint.rs b/crates/engine/src/cmd/preflight/white_overprint.rs index d6d50ce52..3dd784bdd 100644 --- a/crates/engine/src/cmd/preflight/white_overprint.rs +++ b/crates/engine/src/cmd/preflight/white_overprint.rs @@ -7,11 +7,18 @@ //! kenten set to overprint. Text itself has no overprint attribute, so white text knocks out and //! prints; the frame's Overprint Fill covers the frame's own fill only. +use std::collections::{BTreeMap, HashSet}; +use std::ops::Range; +use std::sync::Arc; + use designcraft_color::{Color, ColorType, SwatchValue, swatch}; use designcraft_doc::cjk_settings::AdornmentOverprint; -use designcraft_doc::{CharProps, Document, Item, StrokeType}; +use designcraft_doc::{AnchoredObject, CharProps, Content, Document, Item, ItemId, SpreadRef, Story, StrokeType}; +use designcraft_geom::Affine; +use designcraft_pdf::{item_exported, layer_exported, shown_parent_items}; -use super::Issue; +use super::{Issue, page_of}; +use crate::Session; /// The issue's `kind`. pub(super) const KIND: &str = "whiteOverprint"; @@ -65,8 +72,99 @@ pub(super) fn issue(parts: &[&str], item: Option, page: Option) -> O }) } +/// A page item to look at: a spread's or a parent page's (or inside one), or an anchored object. +enum Node { + Item(Arc), + Anchored(Arc), +} + +impl Node { + fn item(&self) -> &Item { + match self { + Node::Item(it) => it, + Node::Anchored(o) => &o.item, + } + } +} + +/// Where an item is drawn: on spread `si` under its parent's transform (the page is the one it +/// sits on), or on a page given (a parent page's item, an anchored object). +#[derive(Clone, Copy)] +enum On { + Spread(usize, Affine), + Page(Option), +} + +/// The page items PDF export draws, as it draws them: on visible, printable layers, without the +/// hidden and nonprinting ones and everything inside them, the parent pages' items on the pages +/// that show them, and anchored objects in the frames that place them. Returns the white +/// overprint issues of those items, and the page each text frame among them is first drawn on +/// (the frames whose ruby and kenten print). +pub(super) fn printed(s: &Session, d: &Document) -> (Vec, BTreeMap>) { + let mut issues = Vec::new(); + let mut frames = BTreeMap::new(); + // A parent page's item shows on every page based on it: it is reported once, on the first. + // This also stops an anchored object that would contain its own frame. + let mut seen = HashSet::new(); + for (si, sp) in d.spreads.iter().enumerate() { + let first = d.first_page_of_spread(si); + // With the page the PDF composes the item's text for (a parent page's, per page). + let mut stack: Vec<(Node, On, Option)> = Vec::new(); + for pi in (0..sp.pages.len()).rev() { + let page = Some(first + pi); + stack.extend(shown_parent_items(d, si, pi).into_iter().rev().map(|(_, it)| (Node::Item(it.clone()), On::Page(page), page))); + } + let exported = sp.items.iter().rev().filter(|it| d.layer(it.layer).is_some_and(layer_exported)); + stack.extend(exported.map(|it| (Node::Item(it.clone()), On::Spread(si, Affine::IDENTITY), None))); + while let Some((node, on, composed)) = stack.pop() { + let it = node.item(); + if !item_exported(it) || !seen.insert(it.id) { + continue; + } + let (page, inside) = match on { + On::Spread(si, parent) => (page_of(d, SpreadRef::Doc(si), it, parent), On::Spread(si, parent * it.xf)), + On::Page(page) => (page, on), + }; + issues.extend(item_issue(d, it, page)); + let children: Vec<_> = it.shown_children().map(|c| (Node::Item(c.clone()), inside, composed)).collect(); + if let Content::Text(tf) = &it.content { + frames.entry(it.id).or_insert(page); + let cs = s.cache.get(d, tf.story, composed); + // The frame's anchored objects, and those in its footnotes and table cells. + let mut pending: Vec<_> = cs.frame(it.id).into_iter().collect(); + while let Some(frame) = pending.pop() { + stack.extend(frame.objects.iter().map(|o| (Node::Anchored(o.object.clone()), On::Page(page), composed))); + pending.extend(frame.notes.iter().filter_map(|n| n.text.frames.first())); + pending.extend(frame.tables.iter().flat_map(|t| &t.cells).filter_map(|c| c.text.frames.first())); + } + } + stack.extend(children.into_iter().rev()); + } + } + (issues, frames) +} + +/// The byte ranges `story`'s frames show, for [`frames_showing`]: none for a story with no frame +/// of its own. +pub(super) fn frame_ranges(s: &Session, d: &Document, story: &Story) -> Vec<(ItemId, Range)> { + if story.frames.is_empty() { + return Vec::new(); + } + s.cache.get(d, story.id, None).frames.iter().map(|f| (f.frame, f.range.clone())).collect() +} + +/// The frames of `story` that show the bytes `run` (`shown`: [`frame_ranges`]). `None` stands +/// for a story with no frame of its own (a note's, a cell's, an unplaced one); text no frame has +/// room for (overset) is in none. +pub(super) fn frames_showing(story: &Story, shown: &[(ItemId, Range)], run: Range) -> Vec> { + if story.frames.is_empty() { + return vec![None]; + } + shown.iter().filter(|(_, r)| r.start < run.end && r.end > run.start).map(|(id, _)| Some(*id)).collect() +} + /// A page item's fill, stroke or stroke gap that is white and set to overprint. -pub(super) fn item_issue(d: &Document, it: &Item, page: Option) -> Option { +fn item_issue(d: &Document, it: &Item, page: Option) -> Option { if it.nonprinting { return None; } diff --git a/crates/engine/src/cmd/preflight/white_overprint/tests.rs b/crates/engine/src/cmd/preflight/white_overprint/tests.rs index 70fac3e1c..e09f85287 100644 --- a/crates/engine/src/cmd/preflight/white_overprint/tests.rs +++ b/crates/engine/src/cmd/preflight/white_overprint/tests.rs @@ -6,6 +6,11 @@ use crate::Session; /// The `whiteOverprint` issues of the active document: (message, item). fn white_overprints(s: &mut Session) -> Vec<(String, Option)> { + white_overprints_on(s).into_iter().map(|(message, item, _)| (message, item)).collect() +} + +/// The `whiteOverprint` issues of the active document: (message, item, page). +fn white_overprints_on(s: &mut Session) -> Vec<(String, Option, Option)> { let r = s.execute("preflight.run", &json!({})).unwrap(); r["issues"] .as_array() @@ -13,10 +18,19 @@ fn white_overprints(s: &mut Session) -> Vec<(String, Option)> { .iter() .filter(|i| i["kind"] == "whiteOverprint") .inspect(|i| assert_eq!(i["severity"], "warning")) - .map(|i| (i["message"].as_str().unwrap().to_string(), i["item"].as_u64())) + .map(|i| (i["message"].as_str().unwrap().to_string(), i["item"].as_u64(), i["page"].as_u64())) .collect() } +const PAPER_FILL: &str = "White or [Paper] fill set to overprint will not print"; +const PAPER_KENTEN: &str = "White or [Paper] kenten set to overprint will not print"; + +/// A [Paper] fill set to overprint on `id`. +fn paper_overprint(s: &mut Session, id: u64) { + s.execute("object.fill", &json!({"ids": [id], "swatch": "[Paper]"})).unwrap(); + s.execute("object.attributes", &json!({"ids": [id], "overprintFill": true})).unwrap(); +} + fn rect(s: &mut Session, r: [f64; 4]) -> u64 { s.execute("frame.create", &json!({"rect": r})).unwrap()["id"].as_u64().unwrap() } @@ -133,3 +147,91 @@ fn white_ruby_and_kenten_set_to_overprint_are_reported() { let found = white_overprints(&mut s); assert_eq!(found, [("White or [Paper] kenten and ruby set to overprint will not print".to_string(), id)]); } + +/// Kenten in the second frame of a thread was reported against the first, which doesn't show +/// it, and on the first frame's page (noted in review). +#[test] +fn ruby_and_kenten_are_reported_on_the_frame_that_shows_them() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 2, "facingPages": false})).unwrap(); + let text = "漢字".repeat(200); + let r = s.execute("frame.create", &json!({"rect": [72, 72, 200, 100], "content": "text", "text": text})).unwrap(); + let a = r["id"].as_u64().unwrap(); + let b = s.execute("frame.create", &json!({"spread": 1, "rect": [72, 72, 400, 600], "content": "text"})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.thread", &json!({"from": a, "to": b})).unwrap(); + let d = s.doc().unwrap().doc.clone(); + let sid = d.item(designcraft_doc::ItemId(a)).unwrap().text_frame().unwrap().story; + let cs = s.cache.get(&d, sid, None); + let second = cs.frames.iter().find(|f| f.frame.0 == b).unwrap().range.clone(); + assert!(second.start > 0 && second.end > second.start, "{second:?}"); + s.execute("text.select", &json!({"story": r["story"], "anchor": second.start, "focus": second.end})).unwrap(); + s.execute("type.char", &json!({"attrs": {"kenten": true, "kentenFill": "[Paper]", "kentenOverprintFill": "on"}})).unwrap(); + assert_eq!(white_overprints_on(&mut s), [(PAPER_KENTEN.to_string(), Some(b), Some(1))]); + // Across the threshold: both frames show some of it. + s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": second.end})).unwrap(); + s.execute("type.char", &json!({"attrs": {"kenten": true, "kentenFill": "[Paper]", "kentenOverprintFill": "on"}})).unwrap(); + let found = white_overprints_on(&mut s); + assert_eq!(found, [(PAPER_KENTEN.to_string(), Some(a), Some(0)), (PAPER_KENTEN.to_string(), Some(b), Some(1))]); +} + +/// A parent page's item prints on every page that shows it: it was never looked at (noted in +/// review). It is reported once, on the first page that shows it, and not when no page does. +#[test] +fn a_parent_page_item_is_reported_on_the_pages_that_show_it() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 2, "facingPages": false})).unwrap(); + let parent = json!({"kind": "parent", "index": 0}); + let id = s.execute("frame.create", &json!({"spread": parent, "rect": [72, 72, 200, 200]})).unwrap()["id"].as_u64().unwrap(); + paper_overprint(&mut s, id); + assert_eq!(white_overprints_on(&mut s), [(PAPER_FILL.to_string(), Some(id), Some(0))]); + for page in &mut Arc::make_mut(&mut s.doc_mut().unwrap().doc).spreads { + Arc::make_mut(page).pages[0].show_parent_items = false; + } + assert!(white_overprints(&mut s).is_empty(), "no page shows the parent's items"); +} + +/// An anchored object prints in the frame that places it: it was never looked at (noted in +/// review). +#[test] +fn an_anchored_object_is_reported() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Before after."})).unwrap(); + let id = rect(&mut s, [450.0, 450.0, 474.0, 490.0]); + paper_overprint(&mut s, id); + let d = s.doc().unwrap().doc.clone(); + let sid = d.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story; + s.execute("anchored.insert", &json!({"ids": [id], "story": sid.0, "pos": 7})).unwrap(); + assert_eq!(white_overprints_on(&mut s), [(PAPER_FILL.to_string(), Some(id), Some(0))]); + s.execute("object.attributes", &json!({"ids": [r["id"]], "nonprinting": true})).unwrap(); + assert!(white_overprints(&mut s).is_empty(), "its frame doesn't print"); +} + +/// PDF export leaves out a hidden or nonprintable layer and a hidden or nonprinting group with +/// everything in it: what is in them doesn't print, and was reported (noted in review). +#[test] +fn what_pdf_export_leaves_out_is_not_reported() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let layer = s.execute("layer.new", &json!({"name": "Notes"})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.activate", &json!({"id": layer})).unwrap(); + let id = rect(&mut s, [72.0, 72.0, 200.0, 200.0]); + paper_overprint(&mut s, id); + let r = s.execute("frame.create", &json!({"rect": [72, 300, 300, 400], "content": "text", "text": "漢字"})).unwrap(); + s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": "漢字".len()})).unwrap(); + s.execute("type.char", &json!({"attrs": {"kenten": true, "kentenFill": "[Paper]", "kentenOverprintFill": "on"}})).unwrap(); + assert_eq!(white_overprints(&mut s).len(), 2); + for (key, value) in [("visible", false), ("printable", false)] { + s.execute("layer.set", &json!({"id": layer, key: value})).unwrap(); + assert!(white_overprints(&mut s).is_empty(), "{key}: {value}"); + s.execute("layer.set", &json!({"id": layer, key: !value})).unwrap(); + } + let other = rect(&mut s, [300.0, 72.0, 400.0, 200.0]); + let group = s.execute("object.group", &json!({"ids": [id, other]})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(white_overprints(&mut s).len(), 2, "in a group"); + s.execute("object.attributes", &json!({"ids": [group], "nonprinting": true})).unwrap(); + assert_eq!(white_overprints(&mut s), [(PAPER_KENTEN.to_string(), r["id"].as_u64())]); + s.execute("object.attributes", &json!({"ids": [group], "nonprinting": false})).unwrap(); + s.execute("object.hide", &json!({"ids": [group]})).unwrap(); + assert_eq!(white_overprints(&mut s), [(PAPER_KENTEN.to_string(), r["id"].as_u64())]); +} diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index 164e4c8f4..aa834eadb 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -46,7 +46,7 @@ pub(crate) use images::SRGB_ICC; use images::{CmykImage, GreyImage, ImageContentCache, RasterMode, SrgbImage, embedded_icc, is_grey, is_grey_icc}; pub(crate) use metadata::civil; pub(crate) use pipeline::{MARK_LEN, Sheet, exported_items, mark_start}; -pub use pipeline::{export_pdf, export_pdf_with_report, print_color, sheet_spreads}; +pub use pipeline::{export_pdf, export_pdf_with_report, item_exported, layer_exported, print_color, sheet_spreads, shown_parent_items}; #[cfg(test)] impl std::hash::Hasher for ConstantImageHasher { fn finish(&self) -> u64 { diff --git a/crates/pdf/src/export/pipeline.rs b/crates/pdf/src/export/pipeline.rs index ffef45c87..415e2db4a 100644 --- a/crates/pdf/src/export/pipeline.rs +++ b/crates/pdf/src/export/pipeline.rs @@ -21,15 +21,42 @@ pub(crate) struct Sheet { pub(crate) const MARK_LEN: f64 = 18.0; /// Whether a layer's items go into the PDF. -pub(crate) fn layer_exported(layer: &designcraft_doc::Layer) -> bool { +pub fn layer_exported(layer: &designcraft_doc::Layer) -> bool { layer.visible && layer.printable } /// Whether an item and everything inside it go into the PDF, its layer aside. -pub(crate) fn item_exported(it: &Item) -> bool { +pub fn item_exported(it: &Item) -> bool { !it.hidden && !it.nonprinting } +/// The parent pages' items that page `pi` of spread `si` shows, on exported layers, each with the +/// offset that moves it onto the page: the parent's bases first, then the parent. None when the +/// page hides parent items; the items the page overrides are left out (their overrides are the +/// spread's own items). +pub fn shown_parent_items(doc: &Document, si: usize, pi: usize) -> Vec<(Affine, &Arc)> { + let Some(page) = doc.spreads.get(si).and_then(|sp| sp.pages.get(pi)).filter(|page| page.show_parent_items) else { return Vec::new() }; + // What the canvas hides: this page's overrides and those of the parent pages behind it. + let overridden = doc.overridden_parent_items(SpreadRef::Doc(si), pi); + let mut out = Vec::new(); + for (ppi, ppage) in doc.shown_parent_pages(SpreadRef::Doc(si), pi) { + let Some(parent) = doc.parents.get(ppi) else { continue }; + let Some(ppg) = parent.pages.get(ppage) else { continue }; + let dx = page.x - ppg.x; + for it in &parent.items { + if overridden.contains(&it.id) || !doc.layer(it.layer).is_some_and(layer_exported) { + continue; + } + // Parent items belong to the parent page they sit on. + if parent.page_at_x(it.bounds().center().x) != Some(ppage) && parent.pages.len() > 1 { + continue; + } + out.push((Affine::translate((dx, 0.0)), it)); + } + } + out +} + /// Every item of spread `si` that goes into the PDF, with its parent's transform: the items on /// exported layers, leaving out hidden and non-printing items with everything inside them. pub(crate) fn exported_items(doc: &Document, si: usize) -> Vec<(Affine, &Item)> { diff --git a/crates/pdf/src/export/walk.rs b/crates/pdf/src/export/walk.rs index 48e1c87f1..6eda58334 100644 --- a/crates/pdf/src/export/walk.rs +++ b/crates/pdf/src/export/walk.rs @@ -1,6 +1,6 @@ use super::common::{TagEntry, blend, norm, rects_overlap, solid_fill, tf, to_path}; use super::graphics::draw_coverage; -use super::pipeline::{item_exported, layer_exported}; +use super::pipeline::{item_exported, layer_exported, shown_parent_items}; use super::*; impl Exporter<'_> { @@ -12,23 +12,10 @@ impl Exporter<'_> { /// The parent pages' items on `layer` shown on page `pi` of spread `si`: the parent's bases /// first, then the parent. - fn parent_items(&mut self, s: &mut Surface, si: usize, pi: usize, page: &designcraft_doc::Page, layer: &designcraft_doc::Layer, first: usize) { - let doc = self.doc; - // What the canvas hides: this page's overrides and those of the parent pages behind it. - let overridden = doc.overridden_parent_items(SpreadRef::Doc(si), pi); - for (ppi, ppage) in doc.shown_parent_pages(SpreadRef::Doc(si), pi) { - let Some(parent) = doc.parents.get(ppi) else { continue }; - let Some(ppg) = parent.pages.get(ppage) else { continue }; - let dx = page.x - ppg.x; - for it in &parent.items { - if it.layer != layer.id || overridden.contains(&it.id) { - continue; - } - // Parent items belong to the parent page they sit on. - if parent.page_at_x(it.bounds().center().x) != Some(ppage) && parent.pages.len() > 1 { - continue; - } - self.top_item(s, it, Affine::translate((dx, 0.0)), Some(first + pi), true); + fn parent_items(&mut self, s: &mut Surface, si: usize, pi: usize, layer: &designcraft_doc::Layer, first: usize) { + for (xf, it) in shown_parent_items(self.doc, si, pi) { + if it.layer == layer.id { + self.top_item(s, it, xf, Some(first + pi), true); } } } @@ -41,10 +28,8 @@ impl Exporter<'_> { if !layer_exported(layer) { continue; } - for (pi, page) in sp.pages.iter().enumerate() { - if page.show_parent_items { - self.parent_items(s, si, pi, page, layer, first); - } + for pi in 0..sp.pages.len() { + self.parent_items(s, si, pi, layer, first); } for it in &sp.items { if it.layer == layer.id { diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index f1e598967..363509c33 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -49,7 +49,8 @@ mod pdfx; mod pdfx1a; mod transitions; pub use export::{ - BookletKind, BookletOptions, booklet_pairs, export_booklet, export_pdf, export_pdf_with_report, merge_pdfs, print_color, sheet_spreads, + BookletKind, BookletOptions, booklet_pairs, export_booklet, export_pdf, export_pdf_with_report, item_exported, layer_exported, merge_pdfs, + print_color, sheet_spreads, shown_parent_items, }; pub use pdfx::{check_pdfx4, has_rgb_groups, make_pdfx4, pdfx_version}; pub use pdfx1a::check_pdfx1a; From cd315908aae3aa7b13f89225cda1af0d69f842a7 Mon Sep 17 00:00:00 2001 From: Zinadin Zidan Date: Sat, 7 Nov 2026 03:07:28 +0600 Subject: [PATCH 0858/1349] Preflight: a frame with states is looked at as PDF export draws it (review) Flex Layout's convert turns a multi-state group into a frame that keeps its states. PDF export draws every object pasted into a frame, but the white overprint check walked only the active state, so a white overprint in another state printed unreported. Which children export draws is now one function, drawn_children, used by both. --- .../src/cmd/preflight/white_overprint.rs | 4 ++-- .../cmd/preflight/white_overprint/tests.rs | 19 +++++++++++++++++++ crates/pdf/src/export.rs | 4 +++- crates/pdf/src/export/pipeline.rs | 8 ++++++++ crates/pdf/src/export/walk.rs | 6 +++--- crates/pdf/src/lib.rs | 4 ++-- 6 files changed, 37 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/preflight/white_overprint.rs b/crates/engine/src/cmd/preflight/white_overprint.rs index 3dd784bdd..5df0d1fa2 100644 --- a/crates/engine/src/cmd/preflight/white_overprint.rs +++ b/crates/engine/src/cmd/preflight/white_overprint.rs @@ -15,7 +15,7 @@ use designcraft_color::{Color, ColorType, SwatchValue, swatch}; use designcraft_doc::cjk_settings::AdornmentOverprint; use designcraft_doc::{AnchoredObject, CharProps, Content, Document, Item, ItemId, SpreadRef, Story, StrokeType}; use designcraft_geom::Affine; -use designcraft_pdf::{item_exported, layer_exported, shown_parent_items}; +use designcraft_pdf::{drawn_children, item_exported, layer_exported, shown_parent_items}; use super::{Issue, page_of}; use crate::Session; @@ -126,7 +126,7 @@ pub(super) fn printed(s: &Session, d: &Document) -> (Vec, BTreeMap (page, on), }; issues.extend(item_issue(d, it, page)); - let children: Vec<_> = it.shown_children().map(|c| (Node::Item(c.clone()), inside, composed)).collect(); + let children: Vec<_> = drawn_children(it).map(|c| (Node::Item(c.clone()), inside, composed)).collect(); if let Content::Text(tf) = &it.content { frames.entry(it.id).or_insert(page); let cs = s.cache.get(d, tf.story, composed); diff --git a/crates/engine/src/cmd/preflight/white_overprint/tests.rs b/crates/engine/src/cmd/preflight/white_overprint/tests.rs index e09f85287..2e8e8360d 100644 --- a/crates/engine/src/cmd/preflight/white_overprint/tests.rs +++ b/crates/engine/src/cmd/preflight/white_overprint/tests.rs @@ -235,3 +235,22 @@ fn what_pdf_export_leaves_out_is_not_reported() { s.execute("object.hide", &json!({"ids": [group]})).unwrap(); assert_eq!(white_overprints(&mut s), [(PAPER_KENTEN.to_string(), r["id"].as_u64())]); } + +/// A multi-state object prints its active state only, but a frame made from one (Flex Layout's +/// convert keeps the states) prints every object in it, as PDF export draws a frame's pasted-in +/// objects: the inactive state's white overprint was left out (noted in review). +#[test] +fn a_frame_with_states_is_looked_at_as_pdf_export_draws_it() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let a = rect(&mut s, [72.0, 72.0, 200.0, 200.0]); + paper_overprint(&mut s, a); + let b = rect(&mut s, [300.0, 72.0, 400.0, 200.0]); + let ms = s.execute("states.create", &json!({"ids": [a, b]})).unwrap()["id"].as_u64().unwrap(); + let at = s.doc().unwrap().doc.item(designcraft_doc::ItemId(ms)).unwrap().children().iter().position(|c| c.id.0 == a).unwrap(); + s.execute("states.show", &json!({"id": ms, "index": 1 - at})).unwrap(); + assert!(white_overprints(&mut s).is_empty(), "an inactive state doesn't print"); + s.execute("flex.convert", &json!({"ids": [ms]})).unwrap(); + assert!(!s.doc().unwrap().doc.item(designcraft_doc::ItemId(ms)).unwrap().states.is_empty(), "the frame keeps its states"); + assert_eq!(white_overprints(&mut s), [(PAPER_FILL.to_string(), Some(a))]); +} diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index aa834eadb..e4fa19e5c 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -46,7 +46,9 @@ pub(crate) use images::SRGB_ICC; use images::{CmykImage, GreyImage, ImageContentCache, RasterMode, SrgbImage, embedded_icc, is_grey, is_grey_icc}; pub(crate) use metadata::civil; pub(crate) use pipeline::{MARK_LEN, Sheet, exported_items, mark_start}; -pub use pipeline::{export_pdf, export_pdf_with_report, item_exported, layer_exported, print_color, sheet_spreads, shown_parent_items}; +pub use pipeline::{ + drawn_children, export_pdf, export_pdf_with_report, item_exported, layer_exported, print_color, sheet_spreads, shown_parent_items, +}; #[cfg(test)] impl std::hash::Hasher for ConstantImageHasher { fn finish(&self) -> u64 { diff --git a/crates/pdf/src/export/pipeline.rs b/crates/pdf/src/export/pipeline.rs index 415e2db4a..85d39c2e9 100644 --- a/crates/pdf/src/export/pipeline.rs +++ b/crates/pdf/src/export/pipeline.rs @@ -30,6 +30,14 @@ pub fn item_exported(it: &Item) -> bool { !it.hidden && !it.nonprinting } +/// The items PDF export draws inside `it`: every item pasted into a frame (a frame keeps the +/// states of a multi-state group converted to it, and draws them all), or a group's shown +/// children (only the active state of a multi-state object). +pub fn drawn_children(it: &Item) -> impl Iterator> { + let nested = it.has_nested_items(); + it.children().iter().filter(move |_| nested).chain(it.shown_children().filter(move |_| !nested)) +} + /// The parent pages' items that page `pi` of spread `si` shows, on exported layers, each with the /// offset that moves it onto the page: the parent's bases first, then the parent. None when the /// page hides parent items; the items the page overrides are left out (their overrides are the diff --git a/crates/pdf/src/export/walk.rs b/crates/pdf/src/export/walk.rs index 6eda58334..b34b82232 100644 --- a/crates/pdf/src/export/walk.rs +++ b/crates/pdf/src/export/walk.rs @@ -1,6 +1,6 @@ use super::common::{TagEntry, blend, norm, rects_overlap, solid_fill, tf, to_path}; use super::graphics::draw_coverage; -use super::pipeline::{item_exported, layer_exported, shown_parent_items}; +use super::pipeline::{drawn_children, item_exported, layer_exported, shown_parent_items}; use super::*; impl Exporter<'_> { @@ -249,7 +249,7 @@ impl Exporter<'_> { if let Some(c) = &clip { s.push_clip_path(c, &FillRule::NonZero); } - for child in it.children() { + for child in drawn_children(it) { self.item(s, child, xf, page); } if clip.is_some() { @@ -269,7 +269,7 @@ impl Exporter<'_> { fn draw_group_children(&mut self, s: &mut Surface, it: &Item, xf: Affine, page: Option) { let pushes = Self::push_group(s, it.opacity, it.blend) + Self::push_isolation(s, it); - for child in it.shown_children() { + for child in drawn_children(it) { self.item(s, child, xf, page); } for _ in 0..pushes { diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 363509c33..b0ceaefff 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -49,8 +49,8 @@ mod pdfx; mod pdfx1a; mod transitions; pub use export::{ - BookletKind, BookletOptions, booklet_pairs, export_booklet, export_pdf, export_pdf_with_report, item_exported, layer_exported, merge_pdfs, - print_color, sheet_spreads, shown_parent_items, + BookletKind, BookletOptions, booklet_pairs, drawn_children, export_booklet, export_pdf, export_pdf_with_report, item_exported, layer_exported, + merge_pdfs, print_color, sheet_spreads, shown_parent_items, }; pub use pdfx::{check_pdfx4, has_rgb_groups, make_pdfx4, pdfx_version}; pub use pdfx1a::check_pdfx1a; From e977f825583f85f6a34cebdc45adad100c7f9e68 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:21:30 -0500 Subject: [PATCH 0859/1349] Fix [Bug Report] [DesignCraft] Image content and frame don't move together (#2423) Fixes #2422. - crates/engine/src/cmd/object.rs - crates/engine/tests/autocraft_regression_2422.rs --- crates/engine/src/cmd/object.rs | 7 +++ .../engine/tests/autocraft_regression_2422.rs | 45 +++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 crates/engine/tests/autocraft_regression_2422.rs diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 2ac2bf221..634c90a61 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -1704,6 +1704,13 @@ fn transform_set(s: &mut Session, p: &Value) -> Result { } else { let inner = it.xf.inverse() * m * it.xf; bake(it, inner); + // A pure move carries the placed graphic along; a resize leaves it at its size. + let c = inner.as_coeffs(); + if let Content::Graphic(g) = &mut it.content + && [c[0] - 1.0, c[1], c[2], c[3] - 1.0].iter().all(|v| v.abs() < 1e-9) + { + g.xf = inner * g.xf; + } } } } diff --git a/crates/engine/tests/autocraft_regression_2422.rs b/crates/engine/tests/autocraft_regression_2422.rs new file mode 100644 index 000000000..2c66b42b3 --- /dev/null +++ b/crates/engine/tests/autocraft_regression_2422.rs @@ -0,0 +1,45 @@ +//! Typing a new position for a selected placed image moves the frame and its content together. +use designcraft_engine::Session; +use designcraft_engine::cmd::base64_encode; +use designcraft_geom::Rect; +use designcraft_render::Rendered; +use serde_json::json; + +/// The frame's top-left and the placed graphic's top-left on the spread. +fn corners(s: &Session, f: u64) -> ((f64, f64), (f64, f64)) { + let d = &s.doc().unwrap().doc; + let id = designcraft_doc::ItemId(f); + let loc = d.find(id).unwrap(); + let it = d.item(id).unwrap(); + let g = it.graphic().unwrap(); + let b = (d.parent_xf(&loc) * it.xf * g.xf).transform_rect_bbox(Rect::new(0.0, 0.0, g.size.0, g.size.1)); + let fb = it.bounds(); + ((fb.x0, fb.y0), (b.x0, b.y0)) +} + +#[test] +fn moving_a_frame_through_the_position_fields_moves_its_image() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let f = s.execute("frame.create", &json!({"rect": [100, 100, 300, 300], "content": "graphic"})).unwrap()["id"].as_u64().unwrap(); + let png = Rendered { width: 200, height: 100, pixels: vec![200u8; 200 * 100 * 4] }.to_png(); + s.execute("file.place", &json!({"base64": base64_encode(&png), "name": "a.png", "frame": f})).unwrap(); + s.execute("selection.set", &json!({"ids": [f]})).unwrap(); + let (frame0, graphic0) = corners(&s, f); + + s.execute("transform.set", &json!({"x": 150, "y": 170, "ref": 0})).unwrap(); + + let (frame1, graphic1) = corners(&s, f); + assert!((frame1.0 - 150.0).abs() < 1e-6 && (frame1.1 - 170.0).abs() < 1e-6, "the frame moved to the typed position: {frame1:?}"); + let (fdx, fdy) = (frame1.0 - frame0.0, frame1.1 - frame0.1); + assert!(fdx.abs() > 1.0 && fdy.abs() > 1.0, "the frame moved: {frame0:?} -> {frame1:?}"); + assert!( + (graphic1.0 - graphic0.0 - fdx).abs() < 1e-6 && (graphic1.1 - graphic0.1 - fdy).abs() < 1e-6, + "the image stayed behind: {graphic0:?} -> {graphic1:?} while the frame went {frame0:?} -> {frame1:?}" + ); + + // Undo puts both back. + s.execute("edit.undo", &json!({})).unwrap(); + let (frame2, graphic2) = corners(&s, f); + assert!((frame2.0 - frame0.0).abs() < 1e-6 && (graphic2.0 - graphic0.0).abs() < 1e-6, "{frame2:?} {graphic2:?}"); +} From 2fb2689efedda11909a8aa0dbb5c1869a0082a25 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 7 Nov 2026 11:14:34 +0100 Subject: [PATCH 0860/1349] Normalize marquee rect in hit::intersects_rect Found while testing crates/geom/src/hit.rs:28-35 (intersects_rect: `path.anchors().any(|(_, _, a)| r.contains(a.p))` and the early-out using `b.intersect(r)`) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/geom/src/hit.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/crates/geom/src/hit.rs b/crates/geom/src/hit.rs index 096e0e1e3..feb770e47 100644 --- a/crates/geom/src/hit.rs +++ b/crates/geom/src/hit.rs @@ -26,6 +26,7 @@ pub fn stroke_contains(path: &BezPath, width: f64, tol: f64, p: Point) -> bool { /// Does the path intersect (or lie inside) the rect? Used for marquee selection. pub fn intersects_rect(path: &PathData, r: Rect) -> bool { + let r = r.abs(); let Some(b) = path.bounds() else { return false }; let flat = |q: Rect| q.width() == 0.0 || q.height() == 0.0; if b.intersect(r).area() <= 0.0 && !flat(b) && !flat(r) { @@ -92,6 +93,15 @@ mod tests { assert!(intersects_rect(&l, Rect::new(4.0, 0.0, 6.0, 10.0))); } + #[test] + fn reversed_marquee() { + let p = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); + assert!(intersects_rect(&p, Rect::new(15.0, 15.0, 5.0, 5.0))); + assert!(intersects_rect(&p, Rect::new(15.0, 5.0, 5.0, 15.0))); + assert!(intersects_rect(&p, Rect::new(6.0, 6.0, 4.0, 4.0))); + assert!(!intersects_rect(&p, Rect::new(30.0, 30.0, 20.0, 20.0))); + } + #[test] fn flat_marquee() { let p = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); From 6365f98abebdff3615abf692f79f475fdcdeea11 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 7 Nov 2026 12:56:41 +0000 Subject: [PATCH 0861/1349] Keep Lab::hue within 0..360 for tiny negative b Found while testing crates/color/src/cms/lab.rs:25-27 (Lab::hue) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/color/src/cms/lab.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/color/src/cms/lab.rs b/crates/color/src/cms/lab.rs index 0cbbace7d..5ba921276 100644 --- a/crates/color/src/cms/lab.rs +++ b/crates/color/src/cms/lab.rs @@ -23,7 +23,9 @@ impl Lab { } /// Hue angle in degrees 0..360. pub fn hue(&self) -> f32 { - self.b.atan2(self.a).to_degrees().rem_euclid(360.0) + let h = self.b.atan2(self.a).to_degrees().rem_euclid(360.0); + // f32 rounding can turn a tiny negative angle into exactly 360.0. + if h >= 360.0 { 0.0 } else { h } } pub fn from_lch(l: f32, c: f32, h_deg: f32) -> Self { let h = h_deg.to_radians(); @@ -174,6 +176,13 @@ pub fn delta_e2000(x: Lab, y: Lab) -> f32 { mod tests { use super::*; + #[test] + fn hue_tiny_negative_b_stays_below_360() { + let h = Lab::new(50.0, 10.0, -1e-6).hue(); + assert!((0.0..360.0).contains(&h), "hue {h}"); + assert_eq!(h, 0.0); + } + #[test] fn white_and_black() { let w = srgb_to_lab([1.0, 1.0, 1.0]); From 1da6effdeb7adac662d1579368e11f8aa72bea0e Mon Sep 17 00:00:00 2001 From: Luis <43929895+Luis-0508@users.noreply.github.com> Date: Sun, 8 Nov 2026 01:32:13 +0100 Subject: [PATCH 0862/1349] Release: refresh contributor credits for each release (#2424) (#2426) About > Contributors still showed an old snapshot, because nothing regenerated contributors/contributors.json before a release. Opt in to the shared refresh from craft-common-actions: a read-only credits job regenerates the snapshot for the release commit, and the shared release workflow installs it before every source build. The snapshot is not committed back. --- .github/workflows/release.yml | 9 ++++++++- docs/contributors.md | 3 ++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1b43fdaa0..722f30145 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -18,6 +18,12 @@ concurrency: cancel-in-progress: false jobs: + # Regenerates contributors/contributors.json for the release commit; every build bundles it. + credits: + permissions: + contents: read + pull-requests: read + uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main git-sources: name: Git dependencies come from storytold runs-on: ubuntu-latest @@ -60,7 +66,7 @@ jobs: PY release: - needs: git-sources + needs: [git-sources, credits] permissions: contents: write packages: write @@ -72,6 +78,7 @@ jobs: craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 web-craft-fonts: true version: ${{ inputs.version }} + contributors-artifact: ${{ needs.credits.outputs.artifact-name }} secrets: APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} diff --git a/docs/contributors.md b/docs/contributors.md index 1728c4727..5b55f7e1b 100644 --- a/docs/contributors.md +++ b/docs/contributors.md @@ -8,7 +8,8 @@ the AI models named in `Co-Authored-By` trailers. - Two files, both **compiled into the binary** by the UI crate's `build.rs` (nothing is read from disk or the network at run time; the web build has them too): - [`contributors/contributors.json`](../contributors/contributors.json): commit stats per GitHub - username. + username. Release builds regenerate it for the release commit + (`.github/workflows/release.yml`, `credits` job); the copy in the repository is not updated. - [`contributors/people.toml`](../contributors/people.toml): the names people chose for themselves. **Each contributor adds only their own entry**, in their own PR. - Each contributor gets one line: GitHub username (always), display name (opt-in, or their synced From f9cfd99adc0865814e8ca4c0f478cc05fc9830b0 Mon Sep 17 00:00:00 2001 From: Kushagra Kumar <38453569+kk376@users.noreply.github.com> Date: Sun, 8 Nov 2026 07:24:00 +0530 Subject: [PATCH 0863/1349] Text: adjust hyperlink and placeholder source ranges on story edits (#1219) (#1229) * Text: adjust hyperlink and placeholder source ranges on story edits (#1219) Text-anchored hyperlinks and data-merge placeholders store byte ranges (`start..end`) pointing into story text. When text earlier in the story is inserted or deleted, these offsets remained unchanged, causing hyperlink targets and data-merge placeholders to drift across unrelated text or point to invalid UTF-8 boundaries. This change: - Implements `Document::adjust_text_ranges` in `designcraft-doc` to shift or resize text hyperlinks and placeholders when story text is edited. Pure insertions at or before the link shift it forward; insertions inside expand the link's span; deletions before shift it back; deletions consuming or overlapping the link clamp to surviving text or prune it if entirely consumed. - Cleans up obsolete hyperlinks and placeholders in `set_story_text`. - Wires range adjustment into engine text commands: typing, deleting, selection replacement, autocorrect, `story.replaceRange`, find/change, and spelling change. - Adds comprehensive unit tests in `designcraft-doc` and 7 integration regression tests in `crates/engine/tests/hyperlink_offsets.rs`. * fix(engine): adjust hyperlink and placeholder ranges for physically removed text under track changes * fix(engine): adjust text ranges for formatted paste, case change, and drag move * fix(engine): record change case adjustments per character to preserve enclosed hyperlinks * fix(engine): adjust text ranges for track changes, inline markers, and preserve zero-length ranges - Route Track Changes accept/reject deletions through adjust_text_ranges, and transfer replaced text hyperlinks to inserted text so links survive accept. - Hook inline marker operations to adjust_text_ranges (notes, endnotes, xref, anchored objects, index markers, tables, editorial notes, unvar, and place text). - Replace datamerge::shift_after with adjust_text_ranges. - Only prune ranges that the edit emptied (s < e && s_new >= e_new), preserving zero-length ranges. - Drop inverted ranges first and use saturating arithmetic in remap_range. - Preserve doc.hyperlinks and placeholders ordering in move_text_ranges by mutating in place. - Remove dead wrapper mark_deleted and call mark_deleted_reporting. - Fix changes.track invocation parameter to 'on'. - Add comprehensive regression tests in doc and engine covering all review items. * fix(text): guard cell find/change, pre-record tracked replaces, shift para xref anchors * fix(text): record stable IDs for tracked replacement redirects * fix(text): reconcile range adjustments for review feedback * fix(text): adjust ranges on delete surrounding and clean up dead auto edit * Prune text ranges on TOC index and live caption regeneration * test(engine): format regenerating_index_prunes_story_hyperlinks line wrap --- crates/doc/src/edit.rs | 112 ++++ crates/doc/src/tests.rs | 179 ++++++ crates/engine/src/cmd/anchored.rs | 6 +- crates/engine/src/cmd/captions.rs | 1 + crates/engine/src/cmd/changes.rs | 86 ++- crates/engine/src/cmd/datamerge.rs | 33 +- crates/engine/src/cmd/edit.rs | 21 +- crates/engine/src/cmd/editorial.rs | 66 ++- crates/engine/src/cmd/endnotes.rs | 7 +- crates/engine/src/cmd/find.rs | 8 +- crates/engine/src/cmd/index.rs | 18 +- crates/engine/src/cmd/linked.rs | 1 + crates/engine/src/cmd/mathexpr.rs | 4 +- crates/engine/src/cmd/notes.rs | 7 +- crates/engine/src/cmd/place_text.rs | 3 + crates/engine/src/cmd/spelling.rs | 9 +- crates/engine/src/cmd/table/structure.rs | 44 +- crates/engine/src/cmd/text.rs | 25 +- crates/engine/src/cmd/text/caret.rs | 30 +- crates/engine/src/cmd/text/edit.rs | 130 ++++- crates/engine/src/cmd/toc.rs | 27 +- crates/engine/src/cmd/variables.rs | 17 +- crates/engine/src/cmd/xref.rs | 16 +- crates/engine/tests/hyperlink_offsets.rs | 712 +++++++++++++++++++++++ 24 files changed, 1368 insertions(+), 194 deletions(-) create mode 100644 crates/engine/tests/hyperlink_offsets.rs diff --git a/crates/doc/src/edit.rs b/crates/doc/src/edit.rs index bd8e82bb2..cadc3d419 100644 --- a/crates/doc/src/edit.rs +++ b/crates/doc/src/edit.rs @@ -793,8 +793,120 @@ impl Document { st.editorial.clear(); st.fix_marks(); st.rev = st.rev.wrapping_add(1); + self.prune_story_text_ranges(sid); Ok(()) } + + /// Prune text-anchored hyperlinks and placeholders for `story` (e.g. after wholesale story replacement). + pub fn prune_story_text_ranges(&mut self, story: StoryId) { + self.hyperlinks.retain(|h| match &h.source { + crate::HyperlinkSource::Text { story: sid, .. } => *sid != story, + _ => true, + }); + self.data_merge.placeholders.retain(|ph| match &ph.anchor { + crate::PlaceholderAnchor::Text { story: sid, .. } => *sid != story, + _ => true, + }); + } + + /// Remaps text range `s..e` when `del_range` is replaced by `ins_len` bytes. + /// Returns `None` if the range is inverted (`s > e`) or emptied by the edit (`s < e && s_new >= e_new`). + pub fn remap_range(del_range: std::ops::Range, ins_len: usize, s: usize, e: usize) -> Option<(usize, usize)> { + if s > e { + return None; + } + let (da, db) = (del_range.start, del_range.end); + let del_before = db.min(s).saturating_sub(da); + let del_inside = db.min(e).saturating_sub(da.max(s)); + let mut s_new = s.saturating_sub(del_before); + let mut e_new = e.saturating_sub(del_before).saturating_sub(del_inside); + if da < s || (da == s && db == s) { + s_new = s_new.saturating_add(ins_len); + e_new = e_new.saturating_add(ins_len); + } else if da < e { + e_new = e_new.saturating_add(ins_len); + } + if s < e && s_new >= e_new { None } else { Some((s_new, e_new)) } + } + + /// Adjust story-external text references (hyperlinks and data-merge placeholders) after text + /// in `story` has `del_range` replaced by `ins_len` bytes. + pub fn adjust_text_ranges(&mut self, story: StoryId, del_range: std::ops::Range, ins_len: usize) { + self.hyperlinks.retain_mut(|h| { + if let crate::HyperlinkSource::Text { story: sid, start, end } = &mut h.source + && *sid == story + { + if let Some((ns, ne)) = Self::remap_range(del_range.clone(), ins_len, *start, *end) { + *start = ns; + *end = ne; + return true; + } + return false; + } + true + }); + + self.data_merge.placeholders.retain_mut(|ph| { + if let crate::PlaceholderAnchor::Text { story: sid, start, end } = &mut ph.anchor + && *sid == story + { + if let Some((ns, ne)) = Self::remap_range(del_range.clone(), ins_len, *start, *end) { + *start = ns; + *end = ne; + return true; + } + return false; + } + true + }); + } + + /// Shifts text ranges when a block of text in `story` is moved from `from` to `to` (the insertion offset after deletion). + /// Preserves the existing order of items in `hyperlinks` and `placeholders`. + pub fn move_text_ranges(&mut self, story: StoryId, from: std::ops::Range, to: usize) { + if from.is_empty() { + return; + } + let (da, db) = (from.start, from.end); + let len = db - da; + + let remap_moved = |s: usize, e: usize| -> Option<(usize, usize)> { + if s >= da && e <= db { + Some((to + (s - da), to + (e - da))) + } else { + let (s1, e1) = Self::remap_range(da..db, 0, s, e)?; + Self::remap_range(to..to, len, s1, e1) + } + }; + + self.hyperlinks.retain_mut(|h| { + if let crate::HyperlinkSource::Text { story: sid, start, end } = &mut h.source + && *sid == story + { + if let Some((ns, ne)) = remap_moved(*start, *end) { + *start = ns; + *end = ne; + return true; + } + return false; + } + true + }); + + self.data_merge.placeholders.retain_mut(|ph| { + if let crate::PlaceholderAnchor::Text { story: sid, start, end } = &mut ph.anchor + && *sid == story + { + if let Some((ns, ne)) = remap_moved(*start, *end) { + *start = ns; + *end = ne; + return true; + } + return false; + } + true + }); + } } /// How deep nested stories (a cell's text, a footnote's text, an endnote's text) are followed diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 44926d51b..08a525251 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -370,6 +370,185 @@ fn placed_pdf_without_a_crop_choice_loads_with_the_crop_box() { assert_eq!(Asset { pdf_box: Some([0.5, 0.5, 0.5, 0.9]), ..back }.shown_box(), None); } +#[test] +fn adjust_text_ranges_tracks_and_prunes_hyperlinks_and_placeholders() { + let mut d = doc(); + let sid = StoryId(1); + d.hyperlinks.push(Hyperlink { + id: 10, + name: "Link".into(), + source: HyperlinkSource::Text { story: sid, start: 10, end: 20 }, + dest: HyperlinkDest::Url("https://example.com".into()), + }); + d.data_merge.placeholders.push(crate::Placeholder { + id: 20, + source_id: 1, + field: "Name".into(), + role: crate::PlaceholderRole::Text, + anchor: crate::PlaceholderAnchor::Text { story: sid, start: 10, end: 20 }, + }); + + // 1. Insert before range (at 5, length 3) -> both move by 3: 13..23 + d.adjust_text_ranges(sid, 5..5, 3); + assert_eq!(d.hyperlinks[0].source, HyperlinkSource::Text { story: sid, start: 13, end: 23 }); + assert_eq!(d.data_merge.placeholders[0].anchor, crate::PlaceholderAnchor::Text { story: sid, start: 13, end: 23 }); + + // 2. Pure insert at start (at 13, length 2) -> shifts forward: 15..25 + d.adjust_text_ranges(sid, 13..13, 2); + assert_eq!(d.hyperlinks[0].source, HyperlinkSource::Text { story: sid, start: 15, end: 25 }); + + // 3. Insert inside range (at 18, length 4) -> end expands: 15..29 + d.adjust_text_ranges(sid, 18..18, 4); + assert_eq!(d.hyperlinks[0].source, HyperlinkSource::Text { story: sid, start: 15, end: 29 }); + + // 4. Typing at the very end of the range (at 29, length 3) -> does not expand range + d.adjust_text_ranges(sid, 29..29, 3); + assert_eq!(d.hyperlinks[0].source, HyperlinkSource::Text { story: sid, start: 15, end: 29 }); + + // 5. Insert after range (at 35, length 5) -> no change + d.adjust_text_ranges(sid, 35..35, 5); + assert_eq!(d.hyperlinks[0].source, HyperlinkSource::Text { story: sid, start: 15, end: 29 }); + + // 6. Delete before range (0..5, length 0) -> shifts back by 5: 10..24 + d.adjust_text_ranges(sid, 0..5, 0); + assert_eq!(d.hyperlinks[0].source, HyperlinkSource::Text { story: sid, start: 10, end: 24 }); + + // 7. Delete inside range (12..16, length 0) -> end shrinks by 4: 10..20 + d.adjust_text_ranges(sid, 12..16, 0); + assert_eq!(d.hyperlinks[0].source, HyperlinkSource::Text { story: sid, start: 10, end: 20 }); + + // 8. Delete across start boundary (8..14, length 0) -> surviving start is 8, end is 14 + d.adjust_text_ranges(sid, 8..14, 0); + assert_eq!(d.hyperlinks[0].source, HyperlinkSource::Text { story: sid, start: 8, end: 14 }); + + // 9. Delete entire range (5..20, length 0) -> pruned + d.adjust_text_ranges(sid, 5..20, 0); + assert!(d.hyperlinks.is_empty()); + assert!(d.data_merge.placeholders.is_empty()); +} + +#[test] +fn adjust_text_ranges_preserves_zero_length_ranges_and_drops_inverted() { + let mut d = doc(); + let sid = StoryId(1); + // Zero-length placeholder (e.g. created at caret) + d.data_merge.placeholders.push(crate::Placeholder { + id: 1, + source_id: 1, + field: "CaretPh".into(), + role: crate::PlaceholderRole::Hyperlink, + anchor: crate::PlaceholderAnchor::Text { story: sid, start: 10, end: 10 }, + }); + // Inverted hyperlink from corrupt input + d.hyperlinks.push(Hyperlink { + id: 2, + name: "Inverted".into(), + source: HyperlinkSource::Text { story: sid, start: 25, end: 15 }, + dest: HyperlinkDest::Url("https://example.com".into()), + }); + + // 1. Inverted range is pruned on edit + d.adjust_text_ranges(sid, 0..0, 2); + assert!(d.hyperlinks.is_empty(), "inverted range must be dropped"); + + // 2. Zero-length placeholder shifts when text is inserted before it (at 0, len 5) -> 15..15 + assert_eq!(d.data_merge.placeholders[0].anchor, crate::PlaceholderAnchor::Text { story: sid, start: 12, end: 12 }); + d.adjust_text_ranges(sid, 0..0, 5); + assert_eq!(d.data_merge.placeholders[0].anchor, crate::PlaceholderAnchor::Text { story: sid, start: 17, end: 17 }); + + // 3. Zero-length placeholder shifts when text is deleted before it (0..7) -> 10..10 + d.adjust_text_ranges(sid, 0..7, 0); + assert_eq!(d.data_merge.placeholders[0].anchor, crate::PlaceholderAnchor::Text { story: sid, start: 10, end: 10 }); + + // 4. Deleting text enclosing the zero-length placeholder collapses it to the deletion start without pruning + d.adjust_text_ranges(sid, 5..15, 0); + assert_eq!(d.data_merge.placeholders[0].anchor, crate::PlaceholderAnchor::Text { story: sid, start: 5, end: 5 }); +} + +#[test] +fn move_text_ranges_tracks_hyperlinks_and_placeholders() { + let mut d = doc(); + let sid = StoryId(1); + d.hyperlinks.push(Hyperlink { + id: 1, + name: "Inside".into(), + source: HyperlinkSource::Text { story: sid, start: 22, end: 28 }, + dest: HyperlinkDest::Url("https://example.com/inside".into()), + }); + d.hyperlinks.push(Hyperlink { + id: 2, + name: "Between".into(), + source: HyperlinkSource::Text { story: sid, start: 5, end: 10 }, + dest: HyperlinkDest::Url("https://example.com/between".into()), + }); + + // Move block 20..30 to position 0 (before both links). + // The moved block (length 10) lands at 0..10. + // The link inside (22..28, relative offset +2..+8) becomes 2..8. + // The link originally at 5..10 shifts forward by 10 to 15..20. + d.move_text_ranges(sid, 20..30, 0); + + let inside = d.hyperlinks.iter().find(|h| h.id == 1).unwrap(); + let between = d.hyperlinks.iter().find(|h| h.id == 2).unwrap(); + assert_eq!(inside.source, HyperlinkSource::Text { story: sid, start: 2, end: 8 }); + assert_eq!(between.source, HyperlinkSource::Text { story: sid, start: 15, end: 20 }); + assert_eq!(d.hyperlinks[0].id, 1, "original list order in doc.hyperlinks must be preserved"); + assert_eq!(d.hyperlinks[1].id, 2); +} + +#[test] +fn set_story_text_prunes_story_hyperlinks_and_placeholders() { + let mut d = doc(); + let lid = d.default_layer(); + let (_, sid1) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 100.0, 100.0), lid, "initial one", ParaFormat::default()).unwrap(); + let (_, sid2) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(110.0, 10.0, 200.0, 100.0), lid, "initial two", ParaFormat::default()).unwrap(); + + d.hyperlinks.push(Hyperlink { + id: 1, + name: "Link1".into(), + source: HyperlinkSource::Text { story: sid1, start: 0, end: 7 }, + dest: HyperlinkDest::Url("https://example.com/1".into()), + }); + d.hyperlinks.push(Hyperlink { + id: 2, + name: "Link2".into(), + source: HyperlinkSource::Text { story: sid2, start: 0, end: 7 }, + dest: HyperlinkDest::Url("https://example.com/2".into()), + }); + d.data_merge.placeholders.push(crate::Placeholder { + id: 10, + source_id: 1, + field: "Ph1".into(), + role: crate::PlaceholderRole::Text, + anchor: crate::PlaceholderAnchor::Text { story: sid1, start: 0, end: 7 }, + }); + d.data_merge.placeholders.push(crate::Placeholder { + id: 20, + source_id: 1, + field: "Ph2".into(), + role: crate::PlaceholderRole::Text, + anchor: crate::PlaceholderAnchor::Text { story: sid2, start: 0, end: 7 }, + }); + + d.set_story_text(sid1, "Replacement story text").unwrap(); + + // sid1 hyperlinks and placeholders must be pruned + assert!(d.hyperlinks.iter().all(|h| match &h.source { + HyperlinkSource::Text { story, .. } => *story != sid1, + _ => true, + })); + assert!(d.data_merge.placeholders.iter().all(|ph| match &ph.anchor { + crate::PlaceholderAnchor::Text { story, .. } => *story != sid1, + _ => true, + })); + + // sid2 hyperlinks and placeholders must be preserved + assert_eq!(d.hyperlinks.len(), 1); + assert_eq!(d.hyperlinks[0].id, 2); + assert_eq!(d.data_merge.placeholders.len(), 1); + assert_eq!(d.data_merge.placeholders[0].id, 20); +} + /// Exceptions are read in one pass: breaks are char positions of the lowercased word, a break /// at the start, at the end or twice in a row counts once or not at all, and a long exception /// full of breaks takes no longer than its length. diff --git a/crates/engine/src/cmd/anchored.rs b/crates/engine/src/cmd/anchored.rs index 1e00585ca..48bb8bb85 100644 --- a/crates/engine/src/cmd/anchored.rs +++ b/crates/engine/src/cmd/anchored.rs @@ -125,12 +125,14 @@ pub(crate) fn check_item(it: &Item) -> Result<()> { /// Anchor copies of `items` (in spread coordinates) at `pos` of `sid`; returns the end position. pub(crate) fn anchor_items(d: &mut Document, sid: StoryId, pos: usize, items: Vec, position: &AnchorPosition) -> Result { + let count = items.len(); let st = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; let mut at = pos.min(st.len()); for it in items { st.insert_object(at, AnchoredObject::new(it, position.clone())); at += OBJECT_MARK.len_utf8(); } + d.adjust_text_ranges(sid, pos..pos, count * OBJECT_MARK.len_utf8()); Ok(at) } @@ -229,7 +231,9 @@ fn release(s: &mut Session, p: &Value) -> Result { } let id = d.insert_item(spread, it, None)?; let st = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; - st.delete(pos..pos + OBJECT_MARK.len_utf8()); + let len = OBJECT_MARK.len_utf8(); + st.delete(pos..pos + len); + d.adjust_text_ranges(sid, pos..pos + len, 0); *sel = designcraft_doc::Selection::items(vec![id]); Ok(json!({"id": id.0})) }) diff --git a/crates/engine/src/cmd/captions.rs b/crates/engine/src/cmd/captions.rs index d35dc3e60..c2fbbc6ee 100644 --- a/crates/engine/src/cmd/captions.rs +++ b/crates/engine/src/cmd/captions.rs @@ -131,6 +131,7 @@ pub(crate) fn refresh_live(d: &mut Document) -> bool { let len = st.len(); st.replace(0..len, &text); } + d.prune_story_text_ranges(sid); } changed } diff --git a/crates/engine/src/cmd/changes.rs b/crates/engine/src/cmd/changes.rs index e471c4b6e..328bcf186 100644 --- a/crates/engine/src/cmd/changes.rs +++ b/crates/engine/src/cmd/changes.rs @@ -1,16 +1,16 @@ //! Type › Track Changes: record edits as inserted / deleted text; accept or reject them. -use designcraft_doc::{ChangeMark, Story, StoryId}; +use designcraft_doc::{ChangeMark, Document, Story, StoryId}; use serde_json::{Value, json}; use super::{CommandSpec, cmd, has_doc}; use crate::{Result, Session}; -/// Mark `r` deleted (text this session inserted while tracking is simply removed). Returns where -/// the text after the range now starts. -pub(crate) fn mark_deleted(st: &mut Story, r: std::ops::Range) -> usize { +/// Returns the new start of text after `r` and the list of physically removed byte ranges (in original offsets, last first) +/// so callers can reconcile document-level text ranges. +pub(crate) fn mark_deleted_reporting(st: &mut Story, r: std::ops::Range) -> (usize, Vec>) { if r.is_empty() { - return r.start; + return (r.start, Vec::new()); } // Inserted pieces inside the range go away; the rest is marked deleted. let mut ins: Vec> = st @@ -20,6 +20,7 @@ pub(crate) fn mark_deleted(st: &mut Story, r: std::ops::Range) -> usize { .collect(); let mut end = r.end; ins.sort_by_key(|x| std::cmp::Reverse(x.start)); + let removed = ins.clone(); for x in ins { st.delete(x.clone()); end -= x.len(); @@ -27,7 +28,14 @@ pub(crate) fn mark_deleted(st: &mut Story, r: std::ops::Range) -> usize { if end > r.start { st.format_chars(r.start..end, |f| f.over.change = Some(ChangeMark::Deleted)); } - end + (end, removed) +} + +/// Mark `r` deleted (text this session inserted while tracking is simply removed). Returns where +/// the text after the range now starts. +#[cfg(test)] +pub(crate) fn mark_deleted(st: &mut Story, r: std::ops::Range) -> usize { + mark_deleted_reporting(st, r).0 } /// Ranges of `mark` in `st`, last first. @@ -37,20 +45,31 @@ fn ranges(st: &Story, mark: ChangeMark) -> Vec> { v } -/// Accept (or reject) every change in `st`. -fn resolve(st: &mut Story, accept: bool) -> usize { +/// Accept (or reject) every change in `sid`. +fn resolve(d: &mut Document, sid: StoryId, accept: bool) -> usize { let (remove, keep) = if accept { (ChangeMark::Deleted, ChangeMark::Inserted) } else { (ChangeMark::Inserted, ChangeMark::Deleted) }; - let removed = ranges(st, remove); - let n = removed.len() + ranges(st, keep).len(); - for r in removed { - st.delete(r); - } - let len = st.len(); - st.format_chars(0..len, |f| { - if f.over.change.is_some() { - f.over.change = None; + let (removed, keep_count) = { + let st = match d.story(sid) { + Some(st) => st, + None => return 0, + }; + (ranges(st, remove), ranges(st, keep).len()) + }; + let n = removed.len() + keep_count; + if let Some(st) = d.story_mut(sid) { + for r in &removed { + st.delete(r.clone()); } - }); + let len = st.len(); + st.format_chars(0..len, |f| { + if f.over.change.is_some() { + f.over.change = None; + } + }); + } + for r in removed { + d.adjust_text_ranges(sid, r, 0); + } n } @@ -60,17 +79,24 @@ fn one(s: &mut Session, p: &Value, accept: bool) -> Result { let sid = p.get("story").and_then(Value::as_u64).map(StoryId).ok_or_else(|| super::bad(id, "`story` required"))?; let start = p.get("start").and_then(Value::as_u64).ok_or_else(|| super::bad(id, "`start` required"))? as usize; s.edit(|d, sel| { - let st = d.story_mut(sid).ok_or_else(|| super::bad(id, "no such story"))?; - let (r, mark) = st - .runs() - .find(|(r, f)| matches!(f.over.change, Some(ChangeMark::Inserted | ChangeMark::Deleted)) && r.start <= start && start < r.end) - .map(|(r, f)| (r, f.over.change.unwrap_or_default())) - .ok_or_else(|| super::bad(id, "no change there"))?; + let (r, mark) = { + let st = d.story(sid).ok_or_else(|| super::bad(id, "no such story"))?; + st.runs() + .find(|(r, f)| matches!(f.over.change, Some(ChangeMark::Inserted | ChangeMark::Deleted)) && r.start <= start && start < r.end) + .map(|(r, f)| (r, f.over.change.unwrap_or_default())) + .ok_or_else(|| super::bad(id, "no change there"))? + }; // Accepting a deletion or rejecting an insertion removes the text; otherwise it stays, unmarked. - if (mark == ChangeMark::Deleted) == accept { - st.delete(r.clone()); - } else { - st.format_chars(r.clone(), |f| f.over.change = None); + let delete = (mark == ChangeMark::Deleted) == accept; + if let Some(st) = d.story_mut(sid) { + if delete { + st.delete(r.clone()); + } else { + st.format_chars(r.clone(), |f| f.over.change = None); + } + } + if delete { + d.adjust_text_ranges(sid, r.clone(), 0); } if let Some(t) = &mut sel.text && t.story == sid @@ -137,9 +163,7 @@ fn all(s: &mut Session, p: &Value, accept: bool) -> Result { let ids: Vec = d.stories.keys().copied().filter(|id| only.is_none_or(|o| o == *id)).collect(); let mut n = 0; for id in ids { - if let Some(st) = d.story_mut(id) { - n += resolve(st, accept); - } + n += resolve(d, id, accept); } // The caret may now be past the end. if let Some(t) = &mut sel.text diff --git a/crates/engine/src/cmd/datamerge.rs b/crates/engine/src/cmd/datamerge.rs index 4d3cd5dd6..5b42e6c1e 100644 --- a/crates/engine/src/cmd/datamerge.rs +++ b/crates/engine/src/cmd/datamerge.rs @@ -10,8 +10,8 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; use designcraft_doc::{ - DataField, DataFieldKind, DataSource, Delimiter, Document, HyperlinkSource, ItemId, MergeOptions, Page, Placeholder, PlaceholderAnchor, - PlaceholderRole, Selection, SourceStatus, SpreadRef, StoryId, + DataField, DataFieldKind, DataSource, Delimiter, Document, ItemId, MergeOptions, Page, Placeholder, PlaceholderAnchor, PlaceholderRole, + Selection, SourceStatus, SpreadRef, StoryId, }; use designcraft_geom::{Rect, Vec2}; use serde_json::{Value, json}; @@ -172,8 +172,7 @@ fn placeholder_remove(s: &mut Session, p: &Value) -> Result { let start = start.min(end); st.replace(start..end, ""); } - let removed = end.saturating_sub(start); - shift_after(d, story, end, -(removed as isize)); + d.adjust_text_ranges(story, start..end, 0); } } d.data_merge.placeholders.retain(|ph| ph.id != id); @@ -495,7 +494,7 @@ fn add_placeholder(d: &mut Document, sel: &Selection, p: &Value, name: &str) -> if let Some(st) = d.story_mut(story) { st.replace(at..at, &marker); } - shift_after(d, story, at, marker.len() as isize); + d.adjust_text_ranges(story, at..at, marker.len()); PlaceholderAnchor::Text { story, start: at, end: at.saturating_add(marker.len()) } } else { let text = d.story(story).map(|st| st.text.clone()).unwrap_or_default(); @@ -521,30 +520,6 @@ fn text_target(p: &Value, sel: &Selection) -> Option<(StoryId, usize, usize)> { }) } -fn shift_after(doc: &mut Document, story: StoryId, at: usize, delta: isize) { - if delta == 0 { - return; - } - for ph in &mut doc.data_merge.placeholders { - if let PlaceholderAnchor::Text { story: s, start, end } = &mut ph.anchor - && *s == story - && *start >= at - { - *start = fill::add_delta(*start, delta); - *end = fill::add_delta(*end, delta); - } - } - for link in &mut doc.hyperlinks { - if let HyperlinkSource::Text { story: s, start, end } = &mut link.source - && *s == story - && *start >= at - { - *start = fill::add_delta(*start, delta); - *end = fill::add_delta(*end, delta); - } - } -} - /// After an edit, drop a text placeholder whose marker is gone unless the story still has exactly /// one copy of it, and drop an item placeholder whose frame is gone. pub(crate) fn sync_placeholders(doc: &mut Document) { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 62b176cea..a87c9b501 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -101,7 +101,9 @@ fn paste_text(s: &mut Session, text: Option, formatted: bool) -> Result< return s.edit(|d, sel| { let st = d.story_mut(t.story).ok_or(designcraft_doc::DocError::NoStory(t.story))?; let r = t.range(); - st.delete(r.start.min(st.len())..r.end.min(st.len())); + let del = r.start.min(st.len())..r.end.min(st.len()); + st.delete(del.clone()); + d.adjust_text_ranges(t.story, del, 0); // Fresh ids, story and asset copies for every paste, as on the page. let mut stories = std::collections::HashMap::new(); let fresh: Vec = list @@ -125,12 +127,19 @@ fn paste_text(s: &mut Session, text: Option, formatted: bool) -> Result< // Footnotes, endnotes, editorial notes, cross-references and tables cannot be pasted into cells or footnotes. if use_clip && let Some((slice, _)) = clip { let slice = if t.cell.is_some() { strip_objects(&slice) } else { (*slice).clone() }; + let slice_len = slice.text.len(); return s.edit(|d, sel| { - let st = d.text_story_mut(t.story, t.cell).ok_or(designcraft_doc::DocError::NoStory(t.story))?; - let r = t.range(); - let r = r.start.min(st.len())..r.end.min(st.len()); - st.delete(r.clone()); - let end = st.insert_story(r.start, &slice); + let (end, r) = { + let st = d.text_story_mut(t.story, t.cell).ok_or(designcraft_doc::DocError::NoStory(t.story))?; + let r = t.range(); + let r = r.start.min(st.len())..r.end.min(st.len()); + st.delete(r.clone()); + let end = st.insert_story(r.start, &slice); + (end, r) + }; + if t.cell.is_none() { + d.adjust_text_ranges(t.story, r, slice_len); + } sel.text = Some(designcraft_doc::TextSel { anchor: end, focus: end, ..t }); Ok(json!({"pos": end, "formatted": true})) }); diff --git a/crates/engine/src/cmd/editorial.rs b/crates/engine/src/cmd/editorial.rs index 5b09cbcb6..7392d2da8 100644 --- a/crates/engine/src/cmd/editorial.rs +++ b/crates/engine/src/cmd/editorial.rs @@ -20,16 +20,19 @@ pub fn specs() -> Vec { let author = str_param(p, "author").unwrap_or("").to_string(); let at = ts.anchor.max(ts.focus); s.edit(|d, sel| { - let story = d.story_mut(ts.story).ok_or_else(|| bad("note.new", "no such story"))?; - let fmt = story.char_format_at(at).clone(); - story.insert_with(at, &NOTE_MARK.to_string(), fmt); - // A file may hold fewer notes than anchors; give every anchor one. - story.fix_marks(); - let k = story.text[..at].matches(NOTE_MARK).count(); - let n = story.editorial.get_mut(k).ok_or_else(|| bad("note.new", "the story's notes don't match their anchors"))?; - let n = Arc::make_mut(n); - (n.text, n.author) = (text, author); - let id = n.id; + let id = { + let story = d.story_mut(ts.story).ok_or_else(|| bad("note.new", "no such story"))?; + let fmt = story.char_format_at(at).clone(); + story.insert_with(at, &NOTE_MARK.to_string(), fmt); + // A file may hold fewer notes than anchors; give every anchor one. + story.fix_marks(); + let k = story.text[..at].matches(NOTE_MARK).count(); + let n = story.editorial.get_mut(k).ok_or_else(|| bad("note.new", "the story's notes don't match their anchors"))?; + let n = Arc::make_mut(n); + (n.text, n.author) = (text, author); + n.id + }; + d.adjust_text_ranges(ts.story, at..at, NOTE_MARK.len_utf8()); if let Some(t) = &mut sel.text { let c = at + NOTE_MARK.len_utf8(); (t.anchor, t.focus) = (c, c); @@ -68,8 +71,10 @@ pub fn specs() -> Vec { s.edit(|d, sel| { let st = d.story_mut(sid).ok_or_else(|| bad("note.delete", "no such story"))?; let at = anchor(st, id).ok_or_else(|| bad("note.delete", format!("no note {id}")))?; - follow_replace(sel, sid, at..at + NOTE_MARK.len_utf8(), 0); - st.delete(at..at + NOTE_MARK.len_utf8()); + let len = NOTE_MARK.len_utf8(); + follow_replace(sel, sid, at..at + len, 0); + st.delete(at..at + len); + d.adjust_text_ranges(sid, at..at + len, 0); ok() }) }), @@ -86,8 +91,10 @@ pub fn specs() -> Vec { let st = d.story_mut(sid).ok_or_else(|| bad("note.convertToText", "no such story"))?; let at = anchor(st, id).ok_or_else(|| bad("note.convertToText", format!("no note {id}")))?; let text = st.editorial.iter().find(|n| n.id == id).map(|n| n.text.clone()).unwrap_or_default(); - follow_replace(sel, sid, at..at + NOTE_MARK.len_utf8(), text.len()); - st.replace(at..at + NOTE_MARK.len_utf8(), &text); + let len = NOTE_MARK.len_utf8(); + follow_replace(sel, sid, at..at + len, text.len()); + st.replace(at..at + len, &text); + d.adjust_text_ranges(sid, at..at + len, text.len()); ok() }) } @@ -161,20 +168,23 @@ fn convert_from_text(s: &mut Session, p: &Value) -> Result { } let author = str_param(p, "author").unwrap_or("").to_string(); s.edit(|d, sel| { - let story = d.story_mut(ts.story).ok_or_else(|| bad(ID, "no such story"))?; - let text = story.text.get(r.clone()).ok_or_else(|| bad(ID, "the selection is outside the story"))?.to_string(); - if text.contains(MARKS) { - return Err(bad(ID, "the selection holds a table, an anchored object, a note, a footnote, an endnote or a marker")); - } - let fmt = story.format_after(r.start).clone(); - story.delete(r.clone()); - story.insert_with(r.start, &NOTE_MARK.to_string(), fmt); - story.fix_marks(); - let k = story.text[..r.start].matches(NOTE_MARK).count(); - let n = story.editorial.get_mut(k).ok_or_else(|| bad(ID, "the story's notes don't match their anchors"))?; - let n = Arc::make_mut(n); - (n.text, n.author) = (text, author); - let id = n.id; + let id = { + let story = d.story_mut(ts.story).ok_or_else(|| bad(ID, "no such story"))?; + let text = story.text.get(r.clone()).ok_or_else(|| bad(ID, "the selection is outside the story"))?.to_string(); + if text.contains(MARKS) { + return Err(bad(ID, "the selection holds a table, an anchored object, a note, a footnote, an endnote or a marker")); + } + let fmt = story.format_after(r.start).clone(); + story.delete(r.clone()); + story.insert_with(r.start, &NOTE_MARK.to_string(), fmt); + story.fix_marks(); + let k = story.text[..r.start].matches(NOTE_MARK).count(); + let n = story.editorial.get_mut(k).ok_or_else(|| bad(ID, "the story's notes don't match their anchors"))?; + let n = Arc::make_mut(n); + (n.text, n.author) = (text, author); + n.id + }; + d.adjust_text_ranges(ts.story, r.clone(), NOTE_MARK.len_utf8()); if let Some(t) = &mut sel.text { let c = r.start + NOTE_MARK.len_utf8(); (t.anchor, t.focus) = (c, c); diff --git a/crates/engine/src/cmd/endnotes.rs b/crates/engine/src/cmd/endnotes.rs index 9b02d2c87..decd6b097 100644 --- a/crates/engine/src/cmd/endnotes.rs +++ b/crates/engine/src/cmd/endnotes.rs @@ -40,8 +40,10 @@ pub fn specs() -> Vec { .nth(k) .map(|(i, _)| i) .ok_or_else(|| bad("endnote.delete", format!("endnote {id} has no reference in the text")))?; - super::notes::follow_delete(sel, sid, at..at + designcraft_doc::ENDNOTE_REF.len_utf8()); - st.delete(at..at + designcraft_doc::ENDNOTE_REF.len_utf8()); + let len = designcraft_doc::ENDNOTE_REF.len_utf8(); + super::notes::follow_delete(sel, sid, at..at + len); + st.delete(at..at + len); + d.adjust_text_ranges(sid, at..at + len, 0); ok() }) }), @@ -125,6 +127,7 @@ fn insert(s: &mut Session, p: &Value) -> Result { let id = story .insert_endnote(at, &text, ParaFormat { style, ..Default::default() }) .ok_or_else(|| bad(ID, "the story's endnotes don't match its references"))?; + d.adjust_text_ranges(ts.story, at..at, designcraft_doc::ENDNOTE_REF.len_utf8()); let caret = at + designcraft_doc::ENDNOTE_REF.len_utf8(); if let Some(t) = &mut sel.text { (t.anchor, t.focus) = (caret, caret); diff --git a/crates/engine/src/cmd/find.rs b/crates/engine/src/cmd/find.rs index 371b89012..b9ab42550 100644 --- a/crates/engine/src/cmd/find.rs +++ b/crates/engine/src/cmd/find.rs @@ -659,7 +659,7 @@ fn change(s: &mut Session, p: &Value) -> Result { let Some(story) = d.text_story(sid, cell) else { continue }; // Collect matches first (positions refer to the original text), apply back to front. let text = story.text.get(r.clone()).ok_or_else(|| bad("find", "invalid selection bounds or UTF-8 boundary"))?; - let edits: Vec<(std::ops::Range, String)> = match (&found, &found_out) { + let mut edits: Vec<(std::ops::Range, String)> = match (&found, &found_out) { // Change: the found text alone, in the target it lies in. (Some((_, _, range)), Some(out)) => { if r.start <= range.start && range.end <= r.end { @@ -674,6 +674,7 @@ fn change(s: &mut Session, p: &Value) -> Result { .map(|(m, out)| (r.start + m.start..r.start + m.end, out)) .collect(), }; + edits.sort_by_key(|(range, _)| range.start); let Some(st) = d.text_story_mut(sid, cell) else { continue }; for (range, new) in edits.iter().rev() { let changed = if format_only { @@ -705,6 +706,11 @@ fn change(s: &mut Session, p: &Value) -> Result { if let Some(t) = sel.text.as_mut().filter(|t| t.story == sid && t.cell == cell) { repair_selection(t, st); } + if cell.is_none() && !format_only { + for (range, new) in edits.iter().rev() { + d.adjust_text_ranges(sid, range.clone(), new.len()); + } + } // Change leaves the changed text selected. if let Some((_, _, range)) = &found && let Some((_, new)) = edits.first() diff --git a/crates/engine/src/cmd/index.rs b/crates/engine/src/cmd/index.rs index 38a6bc49d..fa43d4d1b 100644 --- a/crates/engine/src/cmd/index.rs +++ b/crates/engine/src/cmd/index.rs @@ -88,6 +88,9 @@ fn add_reference(s: &mut Session, p: &Value) -> Result { let at = t.range().start.min(st.len()); st.insert_index_ref(at, r.clone()); let shift = INDEX_MARK.len_utf8(); + if t.cell.is_none() { + d.adjust_text_ranges(t.story, at..at, shift); + } sel.text = Some(TextSel { anchor: t.anchor + shift, focus: t.focus + shift, ..t }); Ok(json!({"pos": at})) }) @@ -184,14 +187,17 @@ fn fill_index(s: &mut Session, spec: IndexSpec, new_frame: Option<(usize, Option } }; let text = paras.iter().map(|(_, t)| t.as_str()).collect::>().join("\n"); - let st = d.story_mut(story).ok_or(designcraft_doc::DocError::NoStory(story))?; - let len = st.len(); - st.replace(0..len, &text); - for (pi, r) in st.para_ranges().into_iter().enumerate() { - if let Some((name, _)) = paras.get(pi) { - st.format_paras(r.start..r.start, |f| *f = ParaFormat { style: name.clone(), ..Default::default() }); + { + let st = d.story_mut(story).ok_or(designcraft_doc::DocError::NoStory(story))?; + let len = st.len(); + st.replace(0..len, &text); + for (pi, r) in st.para_ranges().into_iter().enumerate() { + if let Some((name, _)) = paras.get(pi) { + st.format_paras(r.start..r.start, |f| *f = ParaFormat { style: name.clone(), ..Default::default() }); + } } } + d.prune_story_text_ranges(story); d.index = Some(IndexSpec { story, ..spec.clone() }); Ok(json!({"story": story.0, "entries": paras.iter().filter(|(s, _)| s.starts_with("Index Level")).count()})) }) diff --git a/crates/engine/src/cmd/linked.rs b/crates/engine/src/cmd/linked.rs index 0b80e3aab..43695d1f5 100644 --- a/crates/engine/src/cmd/linked.rs +++ b/crates/engine/src/cmd/linked.rs @@ -13,6 +13,7 @@ fn copy_into(d: &mut Document, parent: StoryId, child: StoryId) -> Result<()> { let st = d.story_mut(child).ok_or_else(|| bad("story.link", format!("no story {}", child.0)))?; let (frames, rev, file_link) = (std::mem::take(&mut st.frames), st.rev, st.file_link.take()); *st = Story { id: child, frames, rev: rev.wrapping_add(1), link: Some((parent, src.rev)), file_link, ..src }; + d.prune_story_text_ranges(child); Ok(()) } diff --git a/crates/engine/src/cmd/mathexpr.rs b/crates/engine/src/cmd/mathexpr.rs index d6b4a9e95..0c8a120c3 100644 --- a/crates/engine/src/cmd/mathexpr.rs +++ b/crates/engine/src/cmd/mathexpr.rs @@ -85,9 +85,11 @@ fn insert(s: &mut Session, p: &Value) -> Result { if let Some(t) = text { let it = math_item(d, &latex, size, lid, (0.0, 0.0)); let r = t.range(); + let del = r.start.min(d.story(t.story).map_or(0, |st| st.len()))..r.end.min(d.story(t.story).map_or(0, |st| st.len())); if let Some(st) = d.story_mut(t.story) { - st.delete(r.start.min(st.len())..r.end.min(st.len())); + st.delete(del.clone()); } + d.adjust_text_ranges(t.story, del, 0); let end = super::anchored::anchor_items(d, t.story, r.start, vec![it], &Default::default())?; sel.text = Some(designcraft_doc::TextSel { anchor: end, focus: end, ..t }); return Ok(json!({"inline": true, "pos": end})); diff --git a/crates/engine/src/cmd/notes.rs b/crates/engine/src/cmd/notes.rs index 008f0a98f..3c4552340 100644 --- a/crates/engine/src/cmd/notes.rs +++ b/crates/engine/src/cmd/notes.rs @@ -67,6 +67,7 @@ fn insert(s: &mut Session, p: &Value) -> Result { let r = r.start.min(st.len())..r.end.min(st.len()); st.delete(r.clone()); let id = st.insert_note(r.start, &text, para).ok_or_else(|| bad("footnote.insert", "the story's footnotes don't match their references"))?; + d.adjust_text_ranges(t.story, r, designcraft_doc::FOOTNOTE_REF.len_utf8()); sel.text = Some(TextSel { story: t.story, anchor: text.len(), focus: text.len(), frame: t.frame, cell: Some(CellAddr::footnote(id)) }); Ok(json!({"story": t.story.0, "id": id})) })?; @@ -162,8 +163,10 @@ fn delete(s: &mut Session, p: &Value) -> Result { let moved = s.edit(|d, sel| { let st = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; let at = st.note_anchor(id).ok_or_else(|| bad("footnote.delete", format!("no footnote {id}")))?; - follow_delete(sel, sid, at..at + designcraft_doc::FOOTNOTE_REF.len_utf8()); - st.delete(at..at + designcraft_doc::FOOTNOTE_REF.len_utf8()); + let len = designcraft_doc::FOOTNOTE_REF.len_utf8(); + follow_delete(sel, sid, at..at + len); + st.delete(at..at + len); + d.adjust_text_ranges(sid, at..at + len, 0); let moved = sel.text.is_some_and(|t| t.story == sid && t.cell == Some(CellAddr::footnote(id))); if moved { sel.text = Some(TextSel::caret(sid, at)); diff --git a/crates/engine/src/cmd/place_text.rs b/crates/engine/src/cmd/place_text.rs index 852db171e..f80d3fba8 100644 --- a/crates/engine/src/cmd/place_text.rs +++ b/crates/engine/src/cmd/place_text.rs @@ -457,6 +457,8 @@ pub(super) fn place_text( if blank && let (Some(first), Some(p)) = (imp.story.paras.first(), story.paras.get_mut(p0)) { *p = ParaFormat { table: p.table, ..first.clone() }; } + let ins_len = end.saturating_sub(r.start); + d.adjust_text_ranges(t.story, r, ins_len); sel.text = Some(TextSel { anchor: end, focus: end, ..t }); if link.is_some() { warnings.push("not linked: a linked text file fills a whole story, not an insertion point".into()); @@ -491,6 +493,7 @@ pub(super) fn place_text( } None => return Err(bad("file.place", "no such frame")), }; + d.prune_story_text_ranges(sid); let story = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; fill(story, &imp.story); story.file_link = link.as_deref().map(|path| text_link(path, bytes, before, map.clone(), conflict, remove, story)); diff --git a/crates/engine/src/cmd/spelling.rs b/crates/engine/src/cmd/spelling.rs index 5e7a425ea..4a43ab752 100644 --- a/crates/engine/src/cmd/spelling.rs +++ b/crates/engine/src/cmd/spelling.rs @@ -73,8 +73,13 @@ pub fn specs() -> Vec { let (a, b) = (p.get("start").and_then(Value::as_u64).unwrap_or(0) as usize, p.get("end").and_then(Value::as_u64).unwrap_or(0) as usize); let to = str_param(p, "to").unwrap_or("").to_string(); s.edit(|d, _| { - let st = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; - st.replace(a.min(st.len())..b.min(st.len()), &to); + let r = { + let st = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; + let r = a.min(st.len())..b.min(st.len()); + st.replace(r.clone(), &to); + r + }; + d.adjust_text_ranges(sid, r, to.len()); Ok(Value::Null) }) }), diff --git a/crates/engine/src/cmd/table/structure.rs b/crates/engine/src/cmd/table/structure.rs index 0eb0302df..f969d96ef 100644 --- a/crates/engine/src/cmd/table/structure.rs +++ b/crates/engine/src/cmd/table/structure.rs @@ -67,8 +67,11 @@ pub(super) fn insert(s: &mut Session, p: &Value) -> Result { ts.apply_to(&mut table, cells); } let r = t.range(); + let len0 = st.len(); st.delete(r.clone()); st.insert_table(r.start, table); + let ins_len = st.len().saturating_sub(len0.saturating_sub(r.len())); + d.adjust_text_ranges(t.story, r, ins_len); *sel = Selection::text(TextSel { story: t.story, anchor: 0, focus: 0, frame: t.frame, cell: Some(CellAddr { table: id, row: 0, col: 0 }) }); Ok(json!({"story": t.story.0, "table": id})) }) @@ -147,8 +150,11 @@ pub(super) fn convert_from_text(s: &mut Session, p: &Value) -> Result { if let Some((ts, cells)) = &style { ts.apply_to(&mut table, cells); } + let len0 = st.len(); st.delete(a..b); let anchor = st.insert_table(a, table); + let ins_len = st.len().saturating_sub(len0.saturating_sub(b - a)); + d.adjust_text_ranges(t.story, a..b, ins_len); *sel = Selection::text(TextSel::caret(t.story, anchor)); Ok(json!({"table": id, "rows": data.len()})) }) @@ -162,7 +168,9 @@ pub(super) fn convert_to_text(s: &mut Session, p: &Value) -> Result { let st = d.story_mut(g.story).ok_or_else(|| bad("table.convertToText", "no story"))?; let text = st.tables.get(&g.table).map(|t| t.text_with(&col_sep, &row_sep)).unwrap_or_default(); let a = st.table_anchor(g.table).ok_or_else(|| bad("table.convertToText", "no anchor"))?; - st.replace(a..a + designcraft_doc::TABLE_ANCHOR.len_utf8(), &text); + let len0 = designcraft_doc::TABLE_ANCHOR.len_utf8(); + st.replace(a..a + len0, &text); + d.adjust_text_ranges(g.story, a..a + len0, text.len()); *sel = Selection::text(TextSel::caret(g.story, a + text.len())); ok() }) @@ -171,22 +179,26 @@ pub(super) fn convert_to_text(s: &mut Session, p: &Value) -> Result { pub(super) fn delete_table(s: &mut Session, p: &Value) -> Result { let g = target(s, p, "table.delete")?; s.edit(|d, sel| { - let st = d.story_mut(g.story).ok_or_else(|| bad("table.delete", "no story"))?; - let a = st.table_anchor(g.table).ok_or_else(|| bad("table.delete", "no anchor"))?; - // Remove the anchor paragraph (with one separator) so no empty paragraph is left behind. - let end = a + designcraft_doc::TABLE_ANCHOR.len_utf8(); - let r = if &st.text[end..] == "\n" && a > 0 && st.text[..a].ends_with('\n') { - // Inserted at the end of the story: remove the empty paragraph after it too. - a - 1..end + 1 - } else if st.text[end..].starts_with('\n') { - a..end + 1 - } else if a > 0 && st.text[..a].ends_with('\n') { - a - 1..end - } else { - a..end + let (r, len) = { + let st = d.story_mut(g.story).ok_or_else(|| bad("table.delete", "no story"))?; + let a = st.table_anchor(g.table).ok_or_else(|| bad("table.delete", "no anchor"))?; + // Remove the anchor paragraph (with one separator) so no empty paragraph is left behind. + let end = a + designcraft_doc::TABLE_ANCHOR.len_utf8(); + let r = if &st.text[end..] == "\n" && a > 0 && st.text[..a].ends_with('\n') { + // Inserted at the end of the story: remove the empty paragraph after it too. + a - 1..end + 1 + } else if st.text[end..].starts_with('\n') { + a..end + 1 + } else if a > 0 && st.text[..a].ends_with('\n') { + a - 1..end + } else { + a..end + }; + st.delete(r.clone()); + (r, st.len()) }; - st.delete(r.clone()); - *sel = Selection::text(TextSel::caret(g.story, r.start.min(st.len()))); + d.adjust_text_ranges(g.story, r.clone(), 0); + *sel = Selection::text(TextSel::caret(g.story, r.start.min(len))); ok() }) } diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index eecdab5e3..bee08c167 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -175,17 +175,22 @@ pub fn specs() -> Vec { }; let text = super::text_param(p, "text"); s.edit(|d, sel| { - let st = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; - let n = st.len(); - if a > b || b > n || !st.text.is_char_boundary(a) || !st.text.is_char_boundary(b) { - let msg = format!("range {a}..{b} must be UTF-8 byte offsets on character boundaries, start <= end; the story is {n} bytes"); - return Err(bad("story.replaceRange", msg)); - } - st.replace(a..b, &text); - let len = st.len(); + let len = { + let st = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; + let n = st.len(); + if a > b || b > n || !st.text.is_char_boundary(a) || !st.text.is_char_boundary(b) { + let msg = + format!("range {a}..{b} must be UTF-8 byte offsets on character boundaries, start <= end; the story is {n} bytes"); + return Err(bad("story.replaceRange", msg)); + } + st.replace(a..b, &text); + st.len() + }; + d.adjust_text_ranges(sid, a..b, text.len()); if let Some(t) = sel.text.as_mut().filter(|t| t.story == sid) { - t.anchor = floor_char_boundary(&st.text, t.anchor); - t.focus = floor_char_boundary(&st.text, t.focus); + let st_text = d.story(sid).map(|st| st.text.as_str()).unwrap_or(""); + t.anchor = floor_char_boundary(st_text, t.anchor); + t.focus = floor_char_boundary(st_text, t.focus); } Ok(json!({"length": len})) }) diff --git a/crates/engine/src/cmd/text/caret.rs b/crates/engine/src/cmd/text/caret.rs index 0621e30de..29fa08cdc 100644 --- a/crates/engine/src/cmd/text/caret.rs +++ b/crates/engine/src/cmd/text/caret.rs @@ -215,18 +215,28 @@ pub(super) fn release(s: &mut Session, p: &Value) -> Result { return ok(); } s.edit(|d, sel| { - let st = d.text_story_mut(sid, cell).ok_or(designcraft_doc::DocError::NoStory(sid))?; - let piece = st.extract(r.clone()); - let mut at = b; - if !copy { - st.delete(r.clone()); - if at > r.start { - at -= r.len().min(at - r.start); + let (piece_len, at, r) = { + let st = d.text_story_mut(sid, cell).ok_or(designcraft_doc::DocError::NoStory(sid))?; + let piece = st.extract(r.clone()); + let mut at = b; + if !copy { + st.delete(r.clone()); + if at > r.start { + at -= r.len().min(at - r.start); + } + } + let end = st.insert_story(at, &piece); + sel.text = Some(TextSel { story: sid, anchor: at, focus: end, frame: Some(frame), cell }); + (piece.text.len(), at, r) + }; + if cell.is_none() { + if copy { + d.adjust_text_ranges(sid, at..at, piece_len); + } else { + d.move_text_ranges(sid, r, at); } } - let end = st.insert_story(at, &piece); - sel.text = Some(TextSel { story: sid, anchor: at, focus: end, frame: Some(frame), cell }); - Ok(json!({"moved": piece.text.len(), "at": at})) + Ok(json!({"moved": piece_len, "at": at})) }) } diff --git a/crates/engine/src/cmd/text/edit.rs b/crates/engine/src/cmd/text/edit.rs index c987e3a57..e2e06ea40 100644 --- a/crates/engine/src/cmd/text/edit.rs +++ b/crates/engine/src/cmd/text/edit.rs @@ -38,6 +38,7 @@ pub(super) fn insert(s: &mut Session, p: &Value) -> Result { { r = r.start + 1..r.start + 1; } + let mut auto_edit = None; // Autocorrect: a word ended by a space or punctuation is looked up. if let Some(list) = &autocorrect && r.is_empty() @@ -56,6 +57,7 @@ pub(super) fn insert(s: &mut Session, p: &Value) -> Result { to.clone() }; st.replace(ws..r.start, &to); + auto_edit = Some((ws..r.start, to.len())); r = ws + to.len()..ws + to.len(); } } @@ -83,7 +85,7 @@ pub(super) fn insert(s: &mut Session, p: &Value) -> Result { } if tracking && t.cell.is_none() { // Track Changes: the replaced text is marked deleted, the typing inserted after it. - let at = crate::cmd::changes::mark_deleted(st, r.clone()); + let (at, removed) = crate::cmd::changes::mark_deleted_reporting(st, r.clone()); reserve_command_text(st, text.len())?; let mut fmt = st.insert_format_at(at).clone(); if let Some(f) = &typing { @@ -93,6 +95,11 @@ pub(super) fn insert(s: &mut Session, p: &Value) -> Result { st.insert_with(at, &text, fmt); let pos = at + text.len() - trail; sel.text = Some(TextSel { anchor: pos, focus: pos, ..t }); + + for rr in removed { + d.adjust_text_ranges(t.story, rr, 0); + } + d.adjust_text_ranges(t.story, at..at, text.len()); return Ok(json!({"pos": pos})); } let a = floor_char_boundary(&st.text, r.start.min(st.len())); @@ -106,6 +113,12 @@ pub(super) fn insert(s: &mut Session, p: &Value) -> Result { } let pos = r.start + text.len() - trail; sel.text = Some(TextSel { anchor: pos, focus: pos, ..t }); + if t.cell.is_none() { + if let Some((range, len)) = auto_edit { + d.adjust_text_ranges(t.story, range, len); + } + d.adjust_text_ranges(t.story, a..b, text.len()); + } Ok(json!({"pos": pos})) }); // A preview (IME marked text) leaves the typing format to the text typed in the end. @@ -142,24 +155,46 @@ pub(super) fn delete_surrounding(s: &mut Session, p: &Value) -> Result { }; s.edit(|d, sel| { let t = sel.text.ok_or_else(|| bad("text.deleteSurrounding", "no text insertion point"))?; - let story = d.text_story_mut(t.story, t.cell).ok_or(designcraft_doc::DocError::NoStory(t.story))?; - if !after_range.is_empty() { - if tracking { - crate::cmd::changes::mark_deleted(story, after_range.clone()); + let (shift, after_removed, before_removed) = { + let story = d.text_story_mut(t.story, t.cell).ok_or(designcraft_doc::DocError::NoStory(t.story))?; + let after_removed = if !after_range.is_empty() { + if tracking { + let (_, removed) = crate::cmd::changes::mark_deleted_reporting(story, after_range.clone()); + removed + } else { + story.delete(after_range.clone()); + Vec::new() + } } else { - story.delete(after_range.clone()); + Vec::new() + }; + let (shift, before_removed) = if !before_range.is_empty() { + if tracking { + // Tracked changes keep the text and mark it deleted: the selection does not move. + let (new_end, removed) = crate::cmd::changes::mark_deleted_reporting(story, before_range.clone()); + (before_range.end.saturating_sub(new_end), removed) + } else { + story.delete(before_range.clone()); + (before_range.len(), Vec::new()) + } + } else { + (0, Vec::new()) + }; + (shift, after_removed, before_removed) + }; + if tracking { + for rr in after_removed { + d.adjust_text_ranges(t.story, rr, 0); } + } else if t.cell.is_none() && !after_range.is_empty() { + d.adjust_text_ranges(t.story, after_range.clone(), 0); } - let mut shift = 0usize; - if !before_range.is_empty() { - if tracking { - // Tracked changes keep the text and mark it deleted: the selection does not move. - let new_end = crate::cmd::changes::mark_deleted(story, before_range.clone()); - shift = before_range.end.saturating_sub(new_end); - } else { - shift = before_range.len(); - story.delete(before_range.clone()); + if tracking { + for rr in before_removed { + d.adjust_text_ranges(t.story, rr, 0); } + } else if t.cell.is_none() && !before_range.is_empty() { + d.adjust_text_ranges(t.story, before_range.clone(), 0); } sel.text = Some(TextSel { anchor: t.anchor.saturating_sub(shift), focus: t.focus.saturating_sub(shift), ..t }); Ok(()) @@ -264,13 +299,24 @@ pub(crate) fn delete_selection(s: &mut Session) -> Result { s.edit(|d, sel| { let t = sel.text.ok_or_else(|| bad("text.delete", "no text"))?; let r = t.range(); + let mut removed_ranges = Vec::new(); if let Some(st) = d.text_story_mut(t.story, t.cell) { if tracking && t.cell.is_none() { - crate::cmd::changes::mark_deleted(st, r.clone()); + let (_, removed) = crate::cmd::changes::mark_deleted_reporting(st, r.clone()); + removed_ranges = removed; } else { st.delete(r.clone()); } } + if t.cell.is_none() { + if tracking { + for rr in removed_ranges { + d.adjust_text_ranges(t.story, rr, 0); + } + } else { + d.adjust_text_ranges(t.story, r.clone(), 0); + } + } sel.text = Some(TextSel { anchor: r.start, focus: r.start, ..t }); ok() }) @@ -296,12 +342,18 @@ pub(super) fn delete(s: &mut Session, p: &Value) -> Result { let r = with_break_pair(&st.text, r); if tracking && t.cell.is_none() { // Marked, not removed: the caret steps over the deleted text. - let at = crate::cmd::changes::mark_deleted(st, r.clone()); + let (at, removed) = crate::cmd::changes::mark_deleted_reporting(st, r.clone()); let pos = if forward { at.max(r.end.min(st.len())) } else { r.start.min(at) }; sel.text = Some(TextSel { anchor: pos, focus: pos, ..t }); + for rr in removed { + d.adjust_text_ranges(t.story, rr, 0); + } return ok(); } st.delete(r.clone()); + if t.cell.is_none() { + d.adjust_text_ranges(t.story, r.clone(), 0); + } sel.text = Some(TextSel { anchor: r.start, focus: r.start, ..t }); ok() }) @@ -423,20 +475,36 @@ pub(super) fn change_case(s: &mut Session, p: &Value) -> Result { let targets = format_targets(s); s.edit(|d, sel| { for t in &targets { - let Some(st) = d.text_story_mut(t.story, t.cell) else { continue }; - let r = t.range.start.min(st.len())..t.range.end.min(st.len()); - let mapped = case_map(st.slice(r.clone()), &case); - // Replace run by run (from the end) so every run keeps its formatting. - let segs: Vec> = - st.runs().map(|(rr, _)| rr.start.max(r.start)..rr.end.min(r.end)).filter(|x| x.start < x.end).collect(); - let starts: Vec = st.slice(r.clone()).char_indices().map(|(i, _)| r.start + i).collect(); - let mut delta: isize = 0; - for seg in segs.iter().rev() { - let old = st.slice(seg.clone()).to_string(); - let new: String = starts.iter().zip(&mapped).filter(|(b, _)| seg.contains(b)).map(|(_, m)| m.as_str()).collect(); - if new != old { - delta += new.len() as isize - old.len() as isize; - st.replace(seg.clone(), &new); + let (delta, r, changes) = { + let Some(st) = d.text_story_mut(t.story, t.cell) else { continue }; + let r = t.range.start.min(st.len())..t.range.end.min(st.len()); + let mapped = case_map(st.slice(r.clone()), &case); + // Replace run by run (from the end) so every run keeps its formatting. + let segs: Vec> = + st.runs().map(|(rr, _)| rr.start.max(r.start)..rr.end.min(r.end)).filter(|x| x.start < x.end).collect(); + let starts: Vec = st.slice(r.clone()).char_indices().map(|(i, _)| r.start + i).collect(); + let mut delta: isize = 0; + let mut changes = Vec::new(); + for seg in segs.iter().rev() { + let old = st.slice(seg.clone()).to_string(); + let new: String = starts.iter().zip(&mapped).filter(|(b, _)| seg.contains(b)).map(|(_, m)| m.as_str()).collect(); + if new != old { + delta += new.len() as isize - old.len() as isize; + st.replace(seg.clone(), &new); + // Per-character changes (back to front), so ranges inside the run keep their boundaries. + for (i, (b, m)) in starts.iter().zip(&mapped).enumerate().rev().filter(|(_, (b, _))| seg.contains(b)) { + let ce = starts.get(i + 1).copied().unwrap_or(r.end); + if m.len() != ce - b { + changes.push((*b..ce, m.len())); + } + } + } + } + (delta, r, changes) + }; + if t.cell.is_none() { + for (range, new_len) in changes { + d.adjust_text_ranges(t.story, range, new_len); } } if let Some(ts) = sel.text.as_mut().filter(|ts| ts.story == t.story && ts.cell == t.cell && !ts.is_caret()) { diff --git a/crates/engine/src/cmd/toc.rs b/crates/engine/src/cmd/toc.rs index b69d17e26..566602d94 100644 --- a/crates/engine/src/cmd/toc.rs +++ b/crates/engine/src/cmd/toc.rs @@ -289,20 +289,23 @@ fn fill(d: &mut Document, toc: &Toc, width: Option) -> Result { } styles.push(e.entry_style.clone().unwrap_or_else(|| format!("TOC Level {}", f.level.max(1)))); } - let st = d.story_mut(toc.story).ok_or(designcraft_doc::DocError::NoStory(toc.story))?; - let len = st.len(); - st.replace(0..len, &text); - // The text takes the format of the old first character: its character style would spread - // over the whole table (a page number before the first entry, without a title). - st.format_chars(0..st.len(), |f| f.style = NO_CHAR_STYLE.into()); - for (r, style) in spans { - st.format_chars(r, |f| f.style.clone_from(&style)); - } - for (pi, r) in st.para_ranges().into_iter().enumerate() { - if let Some(name) = styles.get(pi) { - st.format_paras(r.start..r.start, |f| *f = ParaFormat { style: name.clone(), ..Default::default() }); + { + let st = d.story_mut(toc.story).ok_or(designcraft_doc::DocError::NoStory(toc.story))?; + let len = st.len(); + st.replace(0..len, &text); + // The text takes the format of the old first character: its character style would spread + // over the whole table (a page number before the first entry, without a title). + st.format_chars(0..st.len(), |f| f.style = NO_CHAR_STYLE.into()); + for (r, style) in spans { + st.format_chars(r, |f| f.style.clone_from(&style)); + } + for (pi, r) in st.para_ranges().into_iter().enumerate() { + if let Some(name) = styles.get(pi) { + st.format_paras(r.start..r.start, |f| *f = ParaFormat { style: name.clone(), ..Default::default() }); + } } } + d.prune_story_text_ranges(toc.story); let insertion = d.bookmarks.iter().position(|b| b.generated_by_toc).unwrap_or(d.bookmarks.len()); d.bookmarks.retain(|b| !b.generated_by_toc); if toc.create_bookmarks { diff --git a/crates/engine/src/cmd/variables.rs b/crates/engine/src/cmd/variables.rs index 33c3c8821..e2bf23e9a 100644 --- a/crates/engine/src/cmd/variables.rs +++ b/crates/engine/src/cmd/variables.rs @@ -52,7 +52,11 @@ pub fn specs() -> Vec { continue; } let st = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; - unvar(st, i, n, &value, 0); + let mut replacements = Vec::new(); + unvar(st, i, n, &value, 0, &mut |pos, len| replacements.push((pos, len))); + for (pos, tlen) in replacements { + d.adjust_text_ranges(sid, pos..pos + tlen, value.len()); + } } d.text_variables.remove(i); Ok(Value::Null) @@ -352,14 +356,17 @@ fn needs_unvar(st: &designcraft_doc::Story, i: usize, depth: usize) -> bool { /// `i + 1..n` down by one, including table cells and foot/endnotes nested in the story. Only /// touches (and unshares) the parts that hold such instances; a story whose nested text changed /// gets a new revision. -fn unvar(st: &mut designcraft_doc::Story, i: usize, n: usize, value: &str, depth: usize) { +fn unvar(st: &mut designcraft_doc::Story, i: usize, n: usize, value: &str, depth: usize, on_replace: &mut dyn FnMut(usize, usize)) { if depth > MAX_DEPTH { return; } if st.text.chars().any(|c| designcraft_doc::vars::var_index(c).is_some_and(|k| k >= i)) { let target = var_char(i).unwrap_or(' ').to_string(); - while let Some(pos) = st.text.find(&target) { + let mut occurrences: Vec = st.text.match_indices(&target).map(|(pos, _)| pos).collect(); + occurrences.reverse(); + for pos in occurrences { st.replace(pos..pos + target.len(), value); + on_replace(pos, target.len()); } for k in i + 1..n { let (from, to) = (var_char(k).unwrap_or(' ').to_string(), var_char(k - 1).unwrap_or(' ').to_string()); @@ -375,14 +382,14 @@ fn unvar(st: &mut designcraft_doc::Story, i: usize, n: usize, value: &str, depth } for c in &mut std::sync::Arc::make_mut(t).cells { if needs_unvar(&c.text, i, depth + 1) { - unvar(&mut c.text, i, n, value, depth + 1); + unvar(&mut c.text, i, n, value, depth + 1, &mut |_, _| {}); } } nested = true; } for note in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { if needs_unvar(¬e.text, i, depth + 1) { - unvar(&mut std::sync::Arc::make_mut(note).text, i, n, value, depth + 1); + unvar(&mut std::sync::Arc::make_mut(note).text, i, n, value, depth + 1, &mut |_, _| {}); nested = true; } } diff --git a/crates/engine/src/cmd/xref.rs b/crates/engine/src/cmd/xref.rs index 7106b1ed0..68653c105 100644 --- a/crates/engine/src/cmd/xref.rs +++ b/crates/engine/src/cmd/xref.rs @@ -67,7 +67,15 @@ fn destination(d: &mut designcraft_doc::Document, p: &Value) -> Result { } else { return Err(bad("xref.insert", "give `anchor`, `paragraph` or `story` + `para`")); }; - d.paragraph_anchor(sid, pos).ok_or_else(|| bad("xref.insert", "could not anchor the paragraph")) + let before = d.story(sid).map_or(0, |st| st.len()); + let id = d.paragraph_anchor(sid, pos).ok_or_else(|| bad("xref.insert", "could not anchor the paragraph"))?; + let grew = d.story(sid).map_or(0, |st| st.len()).saturating_sub(before); + if grew > 0 + && let Some((asid, apos)) = d.find_anchor(id) + { + d.adjust_text_ranges(asid, apos..apos, grew); + } + Ok(id) } fn insert(s: &mut Session, p: &Value) -> Result { @@ -95,6 +103,9 @@ fn insert(s: &mut Session, p: &Value) -> Result { let r = r.start.min(st.len())..r.end.min(st.len()); st.delete(r.clone()); st.insert_xref(r.start, CrossRef { target, format, ..Default::default() }); + if t.cell.is_none() { + d.adjust_text_ranges(t.story, r.clone(), designcraft_doc::XREF_MARK.len_utf8()); + } let pos = r.start + designcraft_doc::XREF_MARK.len_utf8(); sel.text = Some(TextSel { anchor: pos, focus: pos, ..t2 }); Ok(json!({"target": target, "pos": r.start})) @@ -116,6 +127,9 @@ fn create_anchor(s: &mut Session, p: &Value) -> Result { let st = d.story_mut(t.story).ok_or(designcraft_doc::DocError::NoStory(t.story))?; let at = t.range().start.min(st.len()); let id = st.insert_anchor(at, &name); + if t.cell.is_none() { + d.adjust_text_ranges(t.story, at..at, designcraft_doc::ANCHOR_MARK.len_utf8()); + } let pos = t.focus + designcraft_doc::ANCHOR_MARK.len_utf8(); sel.text = Some(TextSel { anchor: pos, focus: pos, ..t }); Ok(json!({"id": id})) diff --git a/crates/engine/tests/hyperlink_offsets.rs b/crates/engine/tests/hyperlink_offsets.rs new file mode 100644 index 000000000..1862221e5 --- /dev/null +++ b/crates/engine/tests/hyperlink_offsets.rs @@ -0,0 +1,712 @@ +//! Hyperlink text source range adjustments across text editing (#1219). + +use designcraft_doc::{HyperlinkSource, StoryId}; +use designcraft_engine::Session; +use serde_json::json; + +fn fixture(text: &str) -> (Session, StoryId, u64) { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 36, 500, 700], "content": "text", "text": text})).unwrap(); + let sid = StoryId(r["story"].as_u64().unwrap()); + (s, sid, r["id"].as_u64().unwrap()) +} + +fn text_hyperlink_range(s: &Session, hid: u64) -> (usize, usize) { + let doc = &s.doc().unwrap().doc; + let link = doc.hyperlinks.iter().find(|h| h.id == hid).expect("hyperlink exists"); + match link.source { + HyperlinkSource::Text { start, end, .. } => (start, end), + _ => panic!("expected text hyperlink source"), + } +} + +#[test] +fn typing_before_hyperlink_shifts_source_range() { + let initial = "Hello world. See page 2 for details."; + let (mut s, sid, _) = fixture(initial); + + // "page 2" is at bytes 17..23 + assert_eq!(&initial[17..23], "page 2"); + s.execute("text.select", &json!({"story": sid.0, "anchor": 17, "focus": 23})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com"})).unwrap()["ids"][0].as_u64().unwrap(); + + assert_eq!(text_hyperlink_range(&s, hid), (17, 23)); + + // Type "ABC " at the start of the story (offset 0) + s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap(); + s.execute("text.insert", &json!({"text": "ABC ", "raw": true})).unwrap(); + + let text = &s.doc().unwrap().doc.story(sid).unwrap().text; + assert_eq!(text, "ABC Hello world. See page 2 for details."); + + // The hyperlink must now be at bytes 21..27, covering "page 2" + let (start, end) = text_hyperlink_range(&s, hid); + assert_eq!((start, end), (21, 27)); + assert_eq!(&text[start..end], "page 2"); +} + +#[test] +fn multibyte_utf8_inserted_before_hyperlink_shifts_by_byte_length() { + let initial = "Hello world. See page 2 for details."; + let (mut s, sid, _) = fixture(initial); + + s.execute("text.select", &json!({"story": sid.0, "anchor": 17, "focus": 23})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com"})).unwrap()["ids"][0].as_u64().unwrap(); + + // Insert soft hyphen U+00AD (2 UTF-8 bytes) at offset 0 + s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap(); + s.execute("text.insert", &json!({"text": "\u{00AD}", "raw": true})).unwrap(); + + let text = &s.doc().unwrap().doc.story(sid).unwrap().text; + let (start, end) = text_hyperlink_range(&s, hid); + assert_eq!((start, end), (19, 25)); + assert_eq!(&text[start..end], "page 2"); + + // Insert German umlaut word "Größe " (8 UTF-8 bytes: G, r, ö (2B), ß (2B), e, space) at offset 0 + s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap(); + s.execute("text.insert", &json!({"text": "Größe ", "raw": true})).unwrap(); + + let text = &s.doc().unwrap().doc.story(sid).unwrap().text; + let (start, end) = text_hyperlink_range(&s, hid); + assert_eq!((start, end), (27, 33)); + assert_eq!(&text[start..end], "page 2"); +} + +#[test] +fn typing_inside_hyperlink_expands_source_range() { + let initial = "Hello world. See page 2 for details."; + let (mut s, sid, _) = fixture(initial); + + s.execute("text.select", &json!({"story": sid.0, "anchor": 17, "focus": 23})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com"})).unwrap()["ids"][0].as_u64().unwrap(); + + // Type "XYZ " inside the link between "page " and "2" (offset 22) + s.execute("text.select", &json!({"story": sid.0, "anchor": 22, "focus": 22})).unwrap(); + s.execute("text.insert", &json!({"text": "XYZ ", "raw": true})).unwrap(); + + let text = &s.doc().unwrap().doc.story(sid).unwrap().text; + assert_eq!(text, "Hello world. See page XYZ 2 for details."); + + let (start, end) = text_hyperlink_range(&s, hid); + assert_eq!((start, end), (17, 27)); + assert_eq!(&text[start..end], "page XYZ 2"); +} + +#[test] +fn deleting_before_and_across_hyperlink() { + let initial = "ABC Hello world. See page 2 for details."; + let (mut s, sid, _) = fixture(initial); + + // "page 2" is at bytes 21..27 + assert_eq!(&initial[21..27], "page 2"); + s.execute("text.select", &json!({"story": sid.0, "anchor": 21, "focus": 27})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com"})).unwrap()["ids"][0].as_u64().unwrap(); + + // Delete "ABC " (4 bytes) before the link + s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 4})).unwrap(); + s.execute("text.delete", &json!({})).unwrap(); + + let text = &s.doc().unwrap().doc.story(sid).unwrap().text; + assert_eq!(text, "Hello world. See page 2 for details."); + + let (start, end) = text_hyperlink_range(&s, hid); + assert_eq!((start, end), (17, 23)); + assert_eq!(&text[start..end], "page 2"); + + // Delete across the link: from offset 13 ("See ") through 22 ("page") + s.execute("text.select", &json!({"story": sid.0, "anchor": 13, "focus": 22})).unwrap(); + s.execute("text.delete", &json!({})).unwrap(); + + let text = &s.doc().unwrap().doc.story(sid).unwrap().text; + assert_eq!(text, "Hello world. 2 for details."); + + // "2" survived the deletion, starting at offset 13 + let (start, end) = text_hyperlink_range(&s, hid); + assert_eq!((start, end), (13, 14)); + assert_eq!(&text[start..end], "2"); +} + +#[test] +fn deleting_entire_hyperlink_removes_it() { + let initial = "Hello world. See page 2 for details."; + let (mut s, sid, _) = fixture(initial); + + s.execute("text.select", &json!({"story": sid.0, "anchor": 17, "focus": 23})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com"})).unwrap()["ids"][0].as_u64().unwrap(); + + // Select text encompassing the entire link (13..27: "See page 2 for") and delete + s.execute("text.select", &json!({"story": sid.0, "anchor": 13, "focus": 27})).unwrap(); + s.execute("text.delete", &json!({})).unwrap(); + + let doc = &s.doc().unwrap().doc; + assert!(!doc.hyperlinks.iter().any(|h| h.id == hid), "hyperlink should be pruned when text is deleted"); +} + +#[test] +fn replacing_hyperlink_text_updates_source_range() { + let initial = "Hello world. See page 2 for details."; + let (mut s, sid, _) = fixture(initial); + + s.execute("text.select", &json!({"story": sid.0, "anchor": 17, "focus": 23})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com"})).unwrap()["ids"][0].as_u64().unwrap(); + + // Select "page 2" and replace with "chapter 5" (9 bytes) + s.execute("text.select", &json!({"story": sid.0, "anchor": 17, "focus": 23})).unwrap(); + s.execute("text.insert", &json!({"text": "chapter 5", "raw": true})).unwrap(); + + let text = &s.doc().unwrap().doc.story(sid).unwrap().text; + assert_eq!(text, "Hello world. See chapter 5 for details."); + + let (start, end) = text_hyperlink_range(&s, hid); + assert_eq!((start, end), (17, 26)); + assert_eq!(&text[start..end], "chapter 5"); +} + +#[test] +fn undo_and_redo_restore_hyperlink_ranges() { + let initial = "Hello world. See page 2 for details."; + let (mut s, sid, _) = fixture(initial); + + s.execute("text.select", &json!({"story": sid.0, "anchor": 17, "focus": 23})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com"})).unwrap()["ids"][0].as_u64().unwrap(); + + assert_eq!(text_hyperlink_range(&s, hid), (17, 23)); + + // Type "ABC " at 0 + s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap(); + s.execute("text.insert", &json!({"text": "ABC ", "raw": true})).unwrap(); + assert_eq!(text_hyperlink_range(&s, hid), (21, 27)); + + // Undo + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(text_hyperlink_range(&s, hid), (17, 23)); + + // Redo + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(text_hyperlink_range(&s, hid), (21, 27)); +} + +#[test] +fn track_changes_deleting_inserted_text_reconciles_hyperlink_ranges() { + let initial = "Hello world. See page 2 for details."; + let (mut s, sid, _) = fixture(initial); + + s.execute("text.select", &json!({"story": sid.0, "anchor": 17, "focus": 23})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com"})).unwrap()["ids"][0].as_u64().unwrap(); + assert_eq!(text_hyperlink_range(&s, hid), (17, 23)); + + // Enable Track Changes + s.execute("changes.track", &json!({"on": true})).unwrap(); + + // Type "Draft " (6 bytes) at offset 0 while tracking + s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap(); + s.execute("text.insert", &json!({"text": "Draft ", "raw": true})).unwrap(); + + // Hyperlink shifts to 23..29 + assert_eq!(text_hyperlink_range(&s, hid), (23, 29)); + + // Now select and delete the inserted "Draft " (0..6) while tracking is on + s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 6})).unwrap(); + s.execute("text.delete", &json!({})).unwrap(); + + // The inserted text was physically removed, so the hyperlink must reconcile back to 17..23 + let text = &s.doc().unwrap().doc.story(sid).unwrap().text; + assert_eq!(text, "Hello world. See page 2 for details."); + assert_eq!(text_hyperlink_range(&s, hid), (17, 23)); +} + +#[test] +fn change_case_adjusts_hyperlink_offsets_when_text_length_changes() { + let initial = "Look at \u{FB01} and see page 2 for details."; + let (mut s, sid, _) = fixture(initial); + + // "\u{FB01}" (fi ligature) is at bytes 8..11 (3 bytes). + // "page 2" is at bytes 20..26. + s.execute("text.select", &json!({"story": sid.0, "anchor": 20, "focus": 26})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com"})).unwrap()["ids"][0].as_u64().unwrap(); + assert_eq!(text_hyperlink_range(&s, hid), (20, 26)); + + // Select "\u{FB01}" (8..11) and convert to uppercase ("FI", 2 bytes) + s.execute("text.select", &json!({"story": sid.0, "anchor": 8, "focus": 11})).unwrap(); + s.execute("type.changeCase", &json!({"case": "upper"})).unwrap(); + + let text = &s.doc().unwrap().doc.story(sid).unwrap().text; + assert_eq!(text, "Look at FI and see page 2 for details."); + + // Hyperlink should shift backward by 1 byte: 19..25 + let (start, end) = text_hyperlink_range(&s, hid); + assert_eq!((start, end), (19, 25)); + assert_eq!(&text[start..end], "page 2"); +} + +#[test] +fn change_case_preserves_hyperlink_strictly_inside_selection() { + let initial = "Hello world"; + let (mut s, sid, _) = fixture(initial); + + // Hyperlink on "world" (6..11) + s.execute("text.select", &json!({"story": sid.0, "anchor": 6, "focus": 11})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com/world"})).unwrap()["ids"][0].as_u64().unwrap(); + assert_eq!(text_hyperlink_range(&s, hid), (6, 11)); + + // Select entire line (0..11) containing the hyperlink inside it and uppercase + s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 11})).unwrap(); + s.execute("type.changeCase", &json!({"case": "upper"})).unwrap(); + + let text = &s.doc().unwrap().doc.story(sid).unwrap().text; + assert_eq!(text, "HELLO WORLD"); + + // Hyperlink must remain intact at 6..11 + let (start, end) = text_hyperlink_range(&s, hid); + assert_eq!((start, end), (6, 11)); + assert_eq!(&text[start..end], "WORLD"); +} + +#[test] +fn formatted_paste_adjusts_hyperlinks_and_placeholders() { + let initial = "Hello world. See page 2 for details."; + let (mut s, sid, _) = fixture(initial); + + s.execute("text.select", &json!({"story": sid.0, "anchor": 17, "focus": 23})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com"})).unwrap()["ids"][0].as_u64().unwrap(); + assert_eq!(text_hyperlink_range(&s, hid), (17, 23)); + + // Select "Hello " (0..6) and copy it + s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 6})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + + // Move caret to start and paste formatted + s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap(); + s.execute("edit.paste", &json!({"formatted": true})).unwrap(); + + let text = &s.doc().unwrap().doc.story(sid).unwrap().text; + assert_eq!(text, "Hello Hello world. See page 2 for details."); + + // Hyperlink shifts forward by 6 bytes: 23..29 + let (start, end) = text_hyperlink_range(&s, hid); + assert_eq!((start, end), (23, 29)); + assert_eq!(&text[start..end], "page 2"); +} + +#[test] +fn drag_move_preserves_hyperlink_and_adjusts_intervening_ranges() { + let initial = "Hello brave world."; + let (mut s, sid, fid) = fixture(initial); + + // Hyperlink on "brave" (6..11) + s.execute("text.select", &json!({"story": sid.0, "anchor": 6, "focus": 11})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com/brave"})).unwrap()["ids"][0].as_u64().unwrap(); + assert_eq!(text_hyperlink_range(&s, hid), (6, 11)); + + let at = |s: &Session, b: usize| { + let d = &s.doc().unwrap().doc; + let cs = designcraft_compose::compose_story(d, sid, &Default::default()); + let l = &cs.frames[0].lines[0]; + let g = l.glyphs.iter().find(|g| g.byte == b).unwrap(); + json!([g.x + g.adv * 0.25, l.baseline - 3.0]) + }; + let end = |s: &Session| { + let d = &s.doc().unwrap().doc; + let cs = designcraft_compose::compose_story(d, sid, &Default::default()); + let l = &cs.frames[0].lines[0]; + json!([l.end_x + 2.0, l.baseline - 3.0]) + }; + + // Drag "brave " (6..12) to the end of the line + s.execute("text.select", &json!({"story": sid.0, "anchor": 6, "focus": 12})).unwrap(); + s.execute("text.placeCaret", &json!({"frame": fid, "point": at(&s, 8)})).unwrap(); + s.execute("text.release", &json!({"frame": fid, "point": end(&s), "moved": true})).unwrap(); + + let text = &s.doc().unwrap().doc.story(sid).unwrap().text; + assert_eq!(text, "Hello world.brave "); + + // The hyperlink on "brave" must follow the moved text to 12..17 + let (start, end_pos) = text_hyperlink_range(&s, hid); + assert_eq!((start, end_pos), (12, 17)); + assert_eq!(&text[start..end_pos], "brave"); +} + +#[test] +fn typing_at_end_of_hyperlink_does_not_expand_range() { + let initial = "Click here for details."; + let (mut s, sid, _) = fixture(initial); + + // "here" is at bytes 6..10 + s.execute("text.select", &json!({"story": sid.0, "anchor": 6, "focus": 10})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com"})).unwrap()["ids"][0].as_u64().unwrap(); + assert_eq!(text_hyperlink_range(&s, hid), (6, 10)); + + // Place caret at the very end of "here" (offset 10) and type + s.execute("text.select", &json!({"story": sid.0, "anchor": 10, "focus": 10})).unwrap(); + s.execute("text.insert", &json!({"text": " right now", "raw": true})).unwrap(); + + let text = &s.doc().unwrap().doc.story(sid).unwrap().text; + assert_eq!(text, "Click here right now for details."); + // The hyperlink on "here" must NOT expand; it must stay 6..10 + assert_eq!(text_hyperlink_range(&s, hid), (6, 10)); + assert_eq!(&text[6..10], "here"); +} + +#[test] +fn track_changes_accept_all_shifts_later_hyperlinks() { + let initial = "Hello world. See page 2 for details."; + let (mut s, sid, _) = fixture(initial); + + // "page 2" at 17..23 + s.execute("text.select", &json!({"story": sid.0, "anchor": 17, "focus": 23})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com"})).unwrap()["ids"][0].as_u64().unwrap(); + assert_eq!(text_hyperlink_range(&s, hid), (17, 23)); + + // Track Changes on + s.execute("changes.track", &json!({"on": true})).unwrap(); + + // Delete "Hello " (0..6) while tracking + s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 6})).unwrap(); + s.execute("text.delete", &json!({})).unwrap(); + + // While tracked change is pending, "Hello " is marked deleted but still in text + assert_eq!(text_hyperlink_range(&s, hid), (17, 23)); + + // Accept All + s.execute("changes.acceptAll", &json!({})).unwrap(); + + let text = &s.doc().unwrap().doc.story(sid).unwrap().text; + assert_eq!(text, "world. See page 2 for details."); + // Link must shift by 6 bytes to 11..17 + assert_eq!(text_hyperlink_range(&s, hid), (11, 17)); + assert_eq!(&text[11..17], "page 2"); +} + +#[test] +fn track_changes_replacing_hyperlink_text_leaves_link_on_deleted_span_until_resolved() { + let initial = "Hello world. See page 2 for details."; + let (mut s, sid, _) = fixture(initial); + + // "page 2" at 17..23 + s.execute("text.select", &json!({"story": sid.0, "anchor": 17, "focus": 23})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com"})).unwrap()["ids"][0].as_u64().unwrap(); + assert_eq!(text_hyperlink_range(&s, hid), (17, 23)); + + // Track Changes on + s.execute("changes.track", &json!({"on": true})).unwrap(); + + // Select "page 2" (17..23) and replace with "p. 2" (length 4) + s.execute("text.select", &json!({"story": sid.0, "anchor": 17, "focus": 23})).unwrap(); + s.execute("text.insert", &json!({"text": "p. 2", "raw": true})).unwrap(); + + // While pending, "page 2" remains in text (marked Deleted). Link stays on 17..23. + assert_eq!(text_hyperlink_range(&s, hid), (17, 23)); + + // Reject All restores original text and keeps the link intact. + s.execute("changes.rejectAll", &json!({})).unwrap(); + let text = &s.doc().unwrap().doc.story(sid).unwrap().text; + assert_eq!(text, "Hello world. See page 2 for details."); + assert_eq!(text_hyperlink_range(&s, hid), (17, 23)); +} + +#[test] +fn track_changes_accepting_deletion_of_hyperlink_text_prunes_link() { + let initial = "Hello world. See page 2 for details."; + let (mut s, sid, _) = fixture(initial); + + // "page 2" at 17..23 + s.execute("text.select", &json!({"story": sid.0, "anchor": 17, "focus": 23})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com"})).unwrap()["ids"][0].as_u64().unwrap(); + assert_eq!(text_hyperlink_range(&s, hid), (17, 23)); + + // Track Changes on + s.execute("changes.track", &json!({"on": true})).unwrap(); + + // Select "page 2" (17..23) and replace with "p. 2" (length 4) + s.execute("text.select", &json!({"story": sid.0, "anchor": 17, "focus": 23})).unwrap(); + s.execute("text.insert", &json!({"text": "p. 2", "raw": true})).unwrap(); + + // Accepting all removes the deleted text, pruning the link + s.execute("changes.acceptAll", &json!({})).unwrap(); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.story(sid).unwrap().text, "Hello world. See p. 2 for details."); + assert!(doc.hyperlinks.iter().all(|h| h.id != hid)); +} + +#[test] +fn inline_markers_shift_subsequent_hyperlinks() { + let initial = "Hello world. See page 2 for details."; + let (mut s, sid, _) = fixture(initial); + + // "page 2" at 17..23 + s.execute("text.select", &json!({"story": sid.0, "anchor": 17, "focus": 23})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com"})).unwrap()["ids"][0].as_u64().unwrap(); + assert_eq!(text_hyperlink_range(&s, hid), (17, 23)); + + // 1. Create a text anchor at offset 5 ("anchor.create") + s.execute("text.select", &json!({"story": sid.0, "anchor": 5, "focus": 5})).unwrap(); + let aid = s.execute("anchor.create", &json!({"name": "TargetAnchor"})).unwrap()["id"].as_u64().unwrap(); + let anchor_shift = designcraft_doc::ANCHOR_MARK.len_utf8(); + assert_eq!(text_hyperlink_range(&s, hid), (17 + anchor_shift, 23 + anchor_shift)); + + // 2. Insert a cross-reference at offset 0 ("xref.insert") + s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap(); + s.execute("xref.insert", &json!({"anchor": aid})).unwrap(); + let xref_shift = designcraft_doc::XREF_MARK.len_utf8(); + assert_eq!(text_hyperlink_range(&s, hid), (17 + anchor_shift + xref_shift, 23 + anchor_shift + xref_shift)); + + // 3. Insert an editorial note at offset 2 ("note.new") + s.execute("text.select", &json!({"story": sid.0, "anchor": 2, "focus": 2})).unwrap(); + let nid = s.execute("note.new", &json!({"text": "review this"})).unwrap()["id"].as_u64().unwrap(); + let note_shift = designcraft_doc::NOTE_MARK.len_utf8(); + assert_eq!(text_hyperlink_range(&s, hid), (17 + anchor_shift + xref_shift + note_shift, 23 + anchor_shift + xref_shift + note_shift)); + + // 4. Delete the editorial note ("note.delete") + s.execute("note.delete", &json!({"story": sid.0, "id": nid})).unwrap(); + assert_eq!(text_hyperlink_range(&s, hid), (17 + anchor_shift + xref_shift, 23 + anchor_shift + xref_shift)); +} + +#[test] +fn zero_length_placeholder_at_caret_is_preserved_on_story_edits() { + let initial = "Hello world. See page 2 for details."; + let (mut s, sid, _) = fixture(initial); + + s.execute("data.source.select", &json!({"bytes": "TmFtZQpBZGEK", "name": "people.csv"})).unwrap(); + s.execute("text.select", &json!({"story": sid.0, "anchor": 6, "focus": 6})).unwrap(); + let ph_id = s.execute("data.placeholder.add", &json!({"field": "Name", "role": "hyperlink"})).unwrap()["id"].as_u64().unwrap(); + + let doc = &s.doc().unwrap().doc; + let ph = doc.data_merge.placeholders.iter().find(|p| p.id == ph_id).unwrap(); + assert_eq!(ph.anchor, designcraft_doc::PlaceholderAnchor::Text { story: sid, start: 6, end: 6 }); + + // Type text at offset 0 + s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap(); + s.execute("text.insert", &json!({"text": "Prefix: ", "raw": true})).unwrap(); + + // Placeholder must shift forward and NOT be pruned + let doc = &s.doc().unwrap().doc; + let ph = doc.data_merge.placeholders.iter().find(|p| p.id == ph_id).expect("placeholder must survive edit"); + assert_eq!(ph.anchor, designcraft_doc::PlaceholderAnchor::Text { story: sid, start: 14, end: 14 }); +} + +#[test] +fn find_change_in_table_cell_does_not_shift_story_hyperlinks() { + let initial = "Before table. "; + let (mut s, sid, _) = fixture(initial); + + // Insert a table with 1 row and 1 col, typing "apple" into the cell + s.execute("text.select", &json!({"story": sid.0, "anchor": 14, "focus": 14})).unwrap(); + s.execute("table.insert", &json!({"rows": 1, "cols": 1})).unwrap(); + s.execute("text.insert", &json!({"text": "apple", "raw": true})).unwrap(); + + // Add more text and a hyperlink to the parent story + s.execute("text.select", &json!({"story": sid.0, "anchor": 15, "focus": 15})).unwrap(); + s.execute("text.insert", &json!({"text": "After table link text.", "raw": true})).unwrap(); + + // Link covers "link" in parent story + let st_text = &s.doc().unwrap().doc.story(sid).unwrap().text; + let link_start = st_text.find("link").unwrap(); + let link_end = link_start + 4; + s.execute("text.select", &json!({"story": sid.0, "anchor": link_start, "focus": link_end})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com"})).unwrap()["ids"][0].as_u64().unwrap(); + assert_eq!(text_hyperlink_range(&s, hid), (link_start, link_end)); + + // Run find.change on document scope to replace "apple" with "longer replacement" in the cell + let r = s.execute("find.change", &json!({"find": "apple", "change": "longer replacement", "scope": "document"})).unwrap(); + assert_eq!(r["count"], 1); + + // The cell was changed, but the parent story hyperlink offsets MUST remain intact + assert_eq!(text_hyperlink_range(&s, hid), (link_start, link_end)); +} + +#[test] +fn xref_insert_paragraph_target_shifts_subsequent_hyperlinks() { + let initial = "First target paragraph.\nSecond paragraph with a link here."; + let (mut s, sid, _) = fixture(initial); + + // "link" in second paragraph + let link_start = initial.find("link").unwrap(); + let link_end = link_start + 4; + s.execute("text.select", &json!({"story": sid.0, "anchor": link_start, "focus": link_end})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com"})).unwrap()["ids"][0].as_u64().unwrap(); + assert_eq!(text_hyperlink_range(&s, hid), (link_start, link_end)); + + // Insert cross reference at the end of the second paragraph targeting the first paragraph + s.execute("text.select", &json!({"story": sid.0, "anchor": initial.len(), "focus": initial.len()})).unwrap(); + s.execute("xref.insert", &json!({"paragraph": "First target"})).unwrap(); + + // The first paragraph now has an ANCHOR_MARK inserted at offset 0. + // The hyperlink in the second paragraph is after offset 0, so it must shift by ANCHOR_MARK.len_utf8()! + let anchor_shift = designcraft_doc::ANCHOR_MARK.len_utf8(); + assert_eq!(text_hyperlink_range(&s, hid), (link_start + anchor_shift, link_end + anchor_shift)); +} + +#[test] +fn tracked_replacement_pruning_selected_entry_does_not_corrupt_unrelated_entry() { + let initial = "Initial text. "; + let (mut s, sid, _) = fixture(initial); + + // Track Changes on + s.execute("changes.track", &json!({"on": true})).unwrap(); + + // Type text under track changes at offset 14: "Tracked link. Unrelated link." + s.execute("text.select", &json!({"story": sid.0, "anchor": 14, "focus": 14})).unwrap(); + s.execute("text.insert", &json!({"text": "Tracked link. Unrelated link.", "raw": true})).unwrap(); + + // "Tracked link" is at 14..26 (marked Inserted). Add a hyperlink on it. + s.execute("text.select", &json!({"story": sid.0, "anchor": 14, "focus": 26})).unwrap(); + let h1 = s.execute("hyperlink.create", &json!({"url": "https://example.com/tracked"})).unwrap()["ids"][0].as_u64().unwrap(); + + // "Unrelated link" is at 28..42. Add a hyperlink on it. + s.execute("text.select", &json!({"story": sid.0, "anchor": 28, "focus": 42})).unwrap(); + let h2 = s.execute("hyperlink.create", &json!({"url": "https://example.com/unrelated"})).unwrap()["ids"][0].as_u64().unwrap(); + + assert_eq!(text_hyperlink_range(&s, h1), (14, 26)); + assert_eq!(text_hyperlink_range(&s, h2), (28, 42)); + + // Now select "Tracked link." (14..27) which has ChangeMark::Inserted and replace it with "New." + s.execute("text.select", &json!({"story": sid.0, "anchor": 14, "focus": 27})).unwrap(); + s.execute("text.insert", &json!({"text": "New.", "raw": true})).unwrap(); + + // The old tracked text (14..27) was physically removed by mark_deleted_reporting. + // h1 covered (14..26) inside that removed range, and was pruned. + // h2 must NOT have been corrupted by taking on the insertion span! + // It should simply have shifted with the edit (14..27 removed, 4 bytes inserted -> net delta -9). + assert_eq!(text_hyperlink_range(&s, h2), (19, 33)); + let doc = &s.doc().unwrap().doc; + let st_text = &doc.story(sid).unwrap().text; + assert_eq!(&st_text[19..33], "Unrelated link"); +} + +#[test] +fn place_text_at_caret_shifts_subsequent_hyperlinks_by_actual_inserted_length() { + let initial = "Hello world. See link here."; + let (mut s, sid, _) = fixture(initial); + + let link_start = initial.find("link").unwrap(); + let link_end = link_start + 4; + s.execute("text.select", &json!({"story": sid.0, "anchor": link_start, "focus": link_end})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com"})).unwrap()["ids"][0].as_u64().unwrap(); + assert_eq!(text_hyperlink_range(&s, hid), (link_start, link_end)); + + // Place caret at offset 6 ("world.") + s.execute("text.select", &json!({"story": sid.0, "anchor": 6, "focus": 6})).unwrap(); + // Base64 for "amazing new " (12 bytes) + let b64 = "YW1hemluZyBuZXcg"; + s.execute("file.place", &json!({"base64": b64, "name": "insert.txt"})).unwrap(); + + let doc = &s.doc().unwrap().doc; + let text = &doc.story(sid).unwrap().text; + assert!(text.contains("amazing new ")); + // Subsequent hyperlink must shift by 12 bytes + assert_eq!(text_hyperlink_range(&s, hid), (link_start + 12, link_end + 12)); +} + +#[test] +fn wholesale_story_replacement_prunes_links_and_undo_restores_them() { + let initial = "Hello world. See page 2 for details."; + let (mut s, sid, _) = fixture(initial); + + s.execute("text.select", &json!({"story": sid.0, "anchor": 17, "focus": 23})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com"})).unwrap()["ids"][0].as_u64().unwrap(); + assert_eq!(text_hyperlink_range(&s, hid), (17, 23)); + + // Replace the entire story text via story.setText + s.execute("story.setText", &json!({"story": sid.0, "text": "Brand new story content entirely."})).unwrap(); + + // Hyperlink in sid must be pruned + assert!(s.doc().unwrap().doc.hyperlinks.iter().all(|h| h.id != hid)); + + // Undo restores the document snapshot including the hyperlink + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(text_hyperlink_range(&s, hid), (17, 23)); +} + +#[test] +fn delete_surrounding_adjusts_hyperlink_ranges() { + let initial = "Prefix Keep Caret Suffix LinkText"; + let (mut s, sid, _) = fixture(initial); + + let link_start = initial.find("LinkText").unwrap(); + let link_end = link_start + "LinkText".len(); + s.execute("text.select", &json!({"story": sid.0, "anchor": link_start, "focus": link_end})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com"})).unwrap()["ids"][0].as_u64().unwrap(); + assert_eq!(text_hyperlink_range(&s, hid), (link_start, link_end)); + + // Place caret between "Keep" and " Caret" (offset 11) + let caret = initial.find(" Caret").unwrap(); + s.execute("text.select", &json!({"story": sid.0, "anchor": caret, "focus": caret})).unwrap(); + + // Delete 4 chars before ("Keep") and 6 chars after (" Caret") + s.execute("text.deleteSurrounding", &json!({"before": 4, "after": 6})).unwrap(); + + let doc = &s.doc().unwrap().doc; + let text = &doc.story(sid).unwrap().text; + assert_eq!(text, "Prefix Suffix LinkText"); + // Link must shift down by 10 bytes (4 before + 6 after) + assert_eq!(text_hyperlink_range(&s, hid), (link_start - 10, link_end - 10)); + assert_eq!(&text[link_start - 10..link_end - 10], "LinkText"); +} + +#[test] +fn regenerating_toc_prunes_story_hyperlinks() { + let mut s = Session::new(); + s.execute("file.newSample", &json!({})).unwrap(); + let pages = s.doc().unwrap().doc.page_count(); + s.execute("layout.pages.insert", &json!({"count": 1})).unwrap(); + let r = s.execute("toc.generate", &json!({"styles": ["Headline", "Cover Title"], "page": pages + 1})).unwrap(); + let sid = StoryId(r["story"].as_u64().unwrap()); + + s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 8})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com"})).unwrap()["ids"][0].as_u64().unwrap(); + assert!(s.doc().unwrap().doc.hyperlinks.iter().any(|h| h.id == hid)); + + let d = &s.doc().unwrap().doc; + let hid_heading = d.stories.iter().find(|(_, st)| st.text.starts_with("Notes on the Grid")).map(|(id, _)| *id).unwrap(); + s.execute("story.replaceRange", &json!({"story": hid_heading.0, "start": 0, "end": 5, "text": "Thoughts"})).unwrap(); + s.execute("toc.update", &json!({})).unwrap(); + + assert!(s.doc().unwrap().doc.hyperlinks.iter().all(|h| h.id != hid)); + s.doc().unwrap().doc.check().unwrap(); +} + +#[test] +fn regenerating_index_prunes_story_hyperlinks() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 2, "facingPages": false})).unwrap(); + let sp = s.doc().unwrap().doc.page_loc(0).unwrap().0; + let r = + s.execute("frame.create", &json!({"spread": sp, "rect": [72, 72, 400, 300], "content": "text", "text": "Typography topic here."})).unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story; + + s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 10})).unwrap(); + s.execute("index.addReference", &json!({})).unwrap(); + + let r_idx = s.execute("index.generate", &json!({"page": 2})).unwrap(); + let idx_sid = StoryId(r_idx["story"].as_u64().unwrap()); + + s.execute("text.select", &json!({"story": idx_sid.0, "anchor": 0, "focus": 5})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com"})).unwrap()["ids"][0].as_u64().unwrap(); + assert!(s.doc().unwrap().doc.hyperlinks.iter().any(|h| h.id == hid)); + + s.execute("index.update", &json!({})).unwrap(); + + assert!(s.doc().unwrap().doc.hyperlinks.iter().all(|h| h.id != hid)); + s.doc().unwrap().doc.check().unwrap(); +} + +#[test] +fn refreshing_live_caption_prunes_story_hyperlinks() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let a = s.execute("frame.create", &json!({"rect": [72, 72, 272, 172]})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.altText", &json!({"text": "Initial photo caption", "ids": [a]})).unwrap(); + let r = s.execute("object.caption", &json!({"ids": [a], "text": "Photo: {altText}", "live": true})).unwrap(); + let cid = designcraft_doc::ItemId(r["ids"][0].as_u64().unwrap()); + let sid = s.doc().unwrap().doc.item(cid).unwrap().text_frame().unwrap().story; + + s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 5})).unwrap(); + let hid = s.execute("hyperlink.create", &json!({"url": "https://example.com"})).unwrap()["ids"][0].as_u64().unwrap(); + assert!(s.doc().unwrap().doc.hyperlinks.iter().any(|h| h.id == hid)); + + s.execute("object.altText", &json!({"text": "Updated photo caption", "ids": [a]})).unwrap(); + + assert!(s.doc().unwrap().doc.hyperlinks.iter().all(|h| h.id != hid)); + s.doc().unwrap().doc.check().unwrap(); +} From 88a45f5d586ad38d79f9cee23b350d2a6455ef1d Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sun, 8 Nov 2026 06:10:10 +0100 Subject: [PATCH 0864/1349] Apply typographic quotes when xref format has an unterminated '<' Found while testing crates/doc/src/xref.rs:~100 (expand, early `return out` in the `tag_end` None branch) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/doc/src/xref.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/xref.rs b/crates/doc/src/xref.rs index 080112c2f..cd518c02c 100644 --- a/crates/doc/src/xref.rs +++ b/crates/doc/src/xref.rs @@ -101,7 +101,8 @@ pub fn expand(definition: &str, v: &XrefValues) -> String { out.push_str(&rest[..i]); let Some(j) = tag_end(&rest[i..]) else { out.push_str(&rest[i..]); - return out; + rest = ""; + break; }; let tag = rest[i + 1..i + j].trim().trim_end_matches('/').trim(); let name = tag.split_whitespace().next().unwrap_or(""); @@ -452,6 +453,12 @@ mod tests { assert_eq!(expand("\" includeDelim=\"false\" />|", &v), "Intro |"); } + #[test] + fn unterminated_lt_still_gets_typographic_quotes() { + let v = XrefValues { para: "Intro".into(), ..Default::default() }; + assert_eq!(expand("\"\" <", &v), "\u{201C}Intro\u{201D} <"); + } + #[test] fn unterminated_quote_only_affects_its_own_tag() { let v = XrefValues { para: "Intro > the start".into(), ..Default::default() }; From 8e5e40d76b897fe0d944dc1af1272521121df679 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sun, 8 Nov 2026 08:32:16 +0000 Subject: [PATCH 0865/1349] Drop signed numeric character references in DOCX XML parser Found while testing crates/textimport/src/docx.rs:132-133 (parse, Event::GeneralRef branch) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/textimport/src/docx.rs | 8 ++++++-- crates/textimport/src/docx/tests.rs | 8 ++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/textimport/src/docx.rs b/crates/textimport/src/docx.rs index 6218a567d..fb76d366a 100644 --- a/crates/textimport/src/docx.rs +++ b/crates/textimport/src/docx.rs @@ -129,8 +129,12 @@ pub(crate) fn parse(xml: &str) -> Result { "gt" => ">".into(), "quot" => "\"".into(), "apos" => "'".into(), - n if n.starts_with("#x") => u32::from_str_radix(&n[2..], 16).ok().and_then(char::from_u32).map(String::from).unwrap_or_default(), - n if n.starts_with('#') => n[1..].parse::().ok().and_then(char::from_u32).map(String::from).unwrap_or_default(), + n if n.starts_with("#x") && n[2..].bytes().all(|b| b.is_ascii_hexdigit()) => { + u32::from_str_radix(&n[2..], 16).ok().and_then(char::from_u32).map(String::from).unwrap_or_default() + } + n if n.starts_with('#') && !n.starts_with("#x") && n[1..].bytes().all(|b| b.is_ascii_digit()) => { + n[1..].parse::().ok().and_then(char::from_u32).map(String::from).unwrap_or_default() + } _ => String::new(), }; if let Some(p) = stack.last_mut() { diff --git a/crates/textimport/src/docx/tests.rs b/crates/textimport/src/docx/tests.rs index 7f1e425cf..fdaa79a11 100644 --- a/crates/textimport/src/docx/tests.rs +++ b/crates/textimport/src/docx/tests.rs @@ -638,3 +638,11 @@ fn off_valued_toggles_stay_off() { let on = st.format_after(st.text.find("bold").unwrap()).clone().over; assert_eq!(on.font_style.as_deref(), Some("Bold"), "`on` is still on"); } + +#[test] +fn signed_numeric_character_references_are_dropped() { + let el = parse("
&#+65;&#x+42;&#-65;&#x-42;&#;&#x;").unwrap(); + assert_eq!(el.text(), ""); + let ok = parse("AB").unwrap(); + assert_eq!(ok.text(), "AB"); +} From c73699374f6f99cda5f3f02fde7028fd6d45ed36 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sun, 8 Nov 2026 12:49:47 +0000 Subject: [PATCH 0866/1349] Clamp midpoint in Gradient::expanded_stops like sample does Found while testing crates/color/src/gradient.rs:~101-110 (expanded_stops); the unclamped value comes from crates/idml/src/import/swatches.rs:128-129 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/color/src/gradient.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index 6243101ef..29f710627 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -100,10 +100,11 @@ impl Gradient { let mut out = Vec::new(); for (i, s) in self.stops.iter().enumerate() { out.push((s.offset, s.color, s.opacity)); + let mid = s.midpoint.clamp(0.01, 0.99); if let Some(n) = self.stops.get(i + 1) - && (s.midpoint - 0.5).abs() > 1e-3 + && (mid - 0.5).abs() > 1e-3 { - let t = s.offset + (n.offset - s.offset) * s.midpoint; + let t = s.offset + (n.offset - s.offset) * mid; let (c, o) = self.sample(t); out.push((t, c, o)); } @@ -217,6 +218,17 @@ impl GradientPaint { mod tests { use super::*; + #[test] + fn expanded_stops_clamp_out_of_range_midpoint() { + for mid in [2.0, -1.0] { + let mut g = Gradient::default(); + g.stops[0].midpoint = mid; + let offsets: Vec = g.expanded_stops().iter().map(|s| s.0).collect(); + assert!(offsets.windows(2).all(|w| w[0] <= w[1]), "{offsets:?}"); + assert!(offsets.iter().all(|o| (0.0..=1.0).contains(o)), "{offsets:?}"); + } + } + #[test] fn sample_endpoints_and_mid() { let g = Gradient::default(); From 8ca6149325ebd28d9999e49cb8ca4ab6fd7ce06d Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sun, 8 Nov 2026 13:06:21 +0000 Subject: [PATCH 0867/1349] Apply review fixes - crates/pdf/src/gradient_inks.rs --- crates/pdf/src/gradient_inks.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/pdf/src/gradient_inks.rs b/crates/pdf/src/gradient_inks.rs index c92b80158..5cc72f7ce 100644 --- a/crates/pdf/src/gradient_inks.rs +++ b/crates/pdf/src/gradient_inks.rs @@ -165,11 +165,12 @@ impl Exporter<'_> { let mut expanded: Vec<(f32, Vec, f32)> = Vec::with_capacity(tints.len() * 2); for (k, (s, v)) in g.stops.iter().zip(&tints).enumerate() { expanded.push((s.offset, v.clone(), s.opacity)); + let midpoint = s.midpoint.clamp(0.01, 0.99); if let (Some(n), Some(nv)) = (g.stops.get(k + 1), tints.get(k + 1)) - && (s.midpoint - 0.5).abs() > 1e-3 + && (midpoint - 0.5).abs() > 1e-3 { let mid: Vec = v.iter().zip(nv).map(|(a, b)| (a + b) / 2.0).collect(); - expanded.push((s.offset + (n.offset - s.offset) * s.midpoint, mid, (s.opacity + n.opacity) / 2.0)); + expanded.push((s.offset + (n.offset - s.offset) * midpoint, mid, (s.opacity + n.opacity) / 2.0)); } } let mut stops = Vec::with_capacity(expanded.len()); From 4a7fc340f8af2c09ab5cb67e5f9a1e5869e9ec9e Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sun, 8 Nov 2026 15:10:20 +0100 Subject: [PATCH 0868/1349] Clamp negative gutter in file.new and file.savePreset to 0 Found while testing crates/engine/src/cmd/file/new.rs:179 (apply_settings: `nd.gutter = f64_or(p, "gutter", nd.gutter)`); compare crates/engine/src/cmd/layout/margins.rs:101 (`g.max(0.0)`) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/file/new.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/file/new.rs b/crates/engine/src/cmd/file/new.rs index e02ce11e4..c59783442 100644 --- a/crates/engine/src/cmd/file/new.rs +++ b/crates/engine/src/cmd/file/new.rs @@ -176,7 +176,7 @@ fn apply_settings(nd: &mut NewDocument, p: &Value) { nd.start_page = p.get("startPage").and_then(Value::as_u64).map(|v| v.clamp(1, 99_999) as u32).unwrap_or(nd.start_page); nd.facing_pages = p.get("facingPages").and_then(Value::as_bool).unwrap_or(nd.facing_pages); nd.columns = p.get("columns").and_then(Value::as_u64).map(|v| v.clamp(1, 216) as u32).unwrap_or(nd.columns); - nd.gutter = f64_or(p, "gutter", nd.gutter); + nd.gutter = p.get("gutter").and_then(Value::as_f64).filter(|g| g.is_finite()).map_or(nd.gutter, |g| g.max(0.0)); nd.primary_text_frame = p.get("primaryTextFrame").and_then(Value::as_bool).unwrap_or(nd.primary_text_frame); match p.get("margins") { Some(Value::Number(n)) => nd.margins = designcraft_doc::Margins::uniform(n.as_f64().unwrap_or(36.0)), @@ -254,6 +254,16 @@ mod new_document_tests { assert!(s.execute("file.new", &json!({"preset": "Newsletter"})).is_err()); } + #[test] + fn negative_gutter_is_clamped_to_zero() { + let mut s = Session::new(); + s.execute("file.new", &json!({"gutter": -50, "columns": 2})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.page(0).unwrap().columns.gutter, 0.0); + s.execute("file.savePreset", &json!({"name": "Tight", "gutter": -50, "columns": 2})).unwrap(); + assert_eq!(s.prefs.document_presets[0].gutter, 0.0); + } + #[test] fn new_document_takes_intent_units_start_page_bleed_and_slug() { let mut s = Session::new(); From 8e341179226fb42c28da1aef982c9d3cee4f7a50 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sun, 8 Nov 2026 14:29:02 +0000 Subject: [PATCH 0869/1349] Apply review fixes - crates/engine/src/cmd/file/new.rs --- crates/engine/src/cmd/file/new.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/file/new.rs b/crates/engine/src/cmd/file/new.rs index c59783442..62f596d00 100644 --- a/crates/engine/src/cmd/file/new.rs +++ b/crates/engine/src/cmd/file/new.rs @@ -176,7 +176,7 @@ fn apply_settings(nd: &mut NewDocument, p: &Value) { nd.start_page = p.get("startPage").and_then(Value::as_u64).map(|v| v.clamp(1, 99_999) as u32).unwrap_or(nd.start_page); nd.facing_pages = p.get("facingPages").and_then(Value::as_bool).unwrap_or(nd.facing_pages); nd.columns = p.get("columns").and_then(Value::as_u64).map(|v| v.clamp(1, 216) as u32).unwrap_or(nd.columns); - nd.gutter = p.get("gutter").and_then(Value::as_f64).filter(|g| g.is_finite()).map_or(nd.gutter, |g| g.max(0.0)); + nd.gutter = p.get("gutter").and_then(Value::as_f64).filter(|g| g.is_finite()).unwrap_or(nd.gutter).max(0.0); nd.primary_text_frame = p.get("primaryTextFrame").and_then(Value::as_bool).unwrap_or(nd.primary_text_frame); match p.get("margins") { Some(Value::Number(n)) => nd.margins = designcraft_doc::Margins::uniform(n.as_f64().unwrap_or(36.0)), From 241d0a41db589ace21db1ebd6672854b576a2995 Mon Sep 17 00:00:00 2001 From: Youssef Azriouil Date: Sun, 8 Nov 2026 16:13:58 +0100 Subject: [PATCH 0870/1349] Copy: drop the second pass over anchored stories in the clipping --- crates/engine/src/cmd/edit.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index d40e59d15..ef7e95224 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -638,11 +638,7 @@ pub(crate) fn clip_doc(s: &Session) -> Result { for p in d.parents.iter_mut() { Arc::make_mut(p).items.clear(); } - // Stories shown by text frames anchored in the kept stories go along (and theirs). - let anchored: std::collections::HashSet = - d.stories.values().filter(|st| st.frames.iter().any(|f| frames.contains(f))).flat_map(|st| d.anchored_stories(st).into_keys()).collect(); - d.stories.retain(|id, st| st.frames.iter().any(|f| frames.contains(f)) || anchored.contains(id)); - frames.extend(d.anchored_items().into_iter().map(|(_, i)| i.id)); + d.stories.retain(|_, st| st.frames.iter().any(|f| frames.contains(f))); for st in d.stories.values_mut() { Arc::make_mut(st).frames.retain(|f| frames.contains(f)); } From 5da2393e28c4504bc7416c94c3afd2dafccf6e14 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sun, 8 Nov 2026 18:14:57 +0100 Subject: [PATCH 0871/1349] Reject signed row numbers in XLSX cell references Found while testing crates/textimport/src/xlsx.rs:15 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/textimport/src/xlsx.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/textimport/src/xlsx.rs b/crates/textimport/src/xlsx.rs index 2356f9e0b..8ad1bb004 100644 --- a/crates/textimport/src/xlsx.rs +++ b/crates/textimport/src/xlsx.rs @@ -12,7 +12,11 @@ use crate::{ImportError, Imported}; /// "B12" → (row 11, column 1). fn cell_ref(r: &str) -> Option<(usize, usize)> { let letters: String = r.chars().take_while(char::is_ascii_alphabetic).collect(); - let row: usize = r[letters.len()..].parse().ok()?; + let digits = &r[letters.len()..]; + if !digits.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + let row: usize = digits.parse().ok()?; let col = letters.chars().try_fold(0usize, |acc, c| { let digit = (c.to_ascii_uppercase() as u8).checked_sub(b'A')? as usize + 1; acc.checked_mul(26)?.checked_add(digit) @@ -331,6 +335,15 @@ mod tests { buf.into_inner() } + #[test] + fn cell_ref_rejects_signed_or_malformed_rows() { + assert_eq!(cell_ref("B12"), Some((11, 1))); + assert_eq!(cell_ref("A+1"), None); + assert_eq!(cell_ref("A-1"), None); + assert_eq!(cell_ref("A"), None); + assert_eq!(cell_ref("A1x"), None); + } + /// A `t="s"` cell materialises its own copy of the shared string, so one big string with many /// references multiplies: the audit's case is a 1 MB string and 3M cells, terabytes, built /// before the grid cap applies (#1584). Collection now carries its own byte budget. From 076c6b1afce0238b6e7b4c6ba8027e7efa8d8a46 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 12:46:13 -0800 Subject: [PATCH 0872/1349] Updates: the updater reports installing, ready, installed and failed, and installs at exit craft-update moves from c5a1cbfb to c7c84230 on dotCooCoo/craft-libs, a branch that merges storytold/craft-libs#687 and #696 into craft-libs main. The check result window shows for every status but idle and stays closed while the startup prompt is open. At the first start after an update it reports that the update installed or why it failed. Its Restart to Update calls Updater::restart_to_update. The install helper now starts when the app exits and drops the updater. --- Cargo.lock | 3 +-- Cargo.toml | 2 +- crates/ui-egui/src/updates_ui.rs | 46 +++++++++++++++++++++++++++----- 3 files changed, 41 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 98b181d66..c0df56599 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1138,7 +1138,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=c7c84230631cbc01ee928f0a0e0d838b1ed612ae#c7c84230631cbc01ee928f0a0e0d838b1ed612ae" dependencies = [ "chrono", "dunce", @@ -7945,7 +7945,6 @@ dependencies = [ "nix", "typed-path", "windows-sys 0.61.2", - "zopfli", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index dbf070673..47b925a23 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,7 +18,7 @@ craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "92d392c # Separations, ink coverage and the ink manager; same revision as craft-pdf and the krilla patch. craft-prepress = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.1.0", features = ["flatten"] } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } +craft-update = { git = "https://github.com/dotCooCoo/craft-libs", version = "=0.1.0", rev = "c7c84230631cbc01ee928f0a0e0d838b1ed612ae", features = ["egui"] } # internal designcraft-geom = { path = "crates/geom" } designcraft-color = { path = "crates/color" } diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index 24a056247..53bae1502 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -4,7 +4,7 @@ use serde_json::Value; use crate::DesignApp; -#[cfg(all(not(target_arch = "wasm32"), test))] +#[cfg(not(target_arch = "wasm32"))] use craft_update::updater::Status; #[cfg(not(target_arch = "wasm32"))] use craft_update::updater::{Action, Updater}; @@ -84,10 +84,18 @@ pub(crate) fn tick(app: &mut DesignApp, ctx: &egui::Context) { let _ = (app, ctx); } +/// Whether the check result window shows: for every status but idle (a requested check, and the +/// first start after an update, which reports that it installed or why it failed), and never over +/// the startup prompt. +#[cfg(not(target_arch = "wasm32"))] +fn result_window_shows(status: &Status, prompt_open: bool) -> bool { + !prompt_open && !matches!(status, Status::Idle) +} + pub(crate) fn show(app: &mut DesignApp, ctx: &egui::Context) { #[cfg(not(target_arch = "wasm32"))] { - // The restart helper is scheduled before the app closes, so no update starts over unsaved work. + // The updater asks to close only when no document has unsaved changes; the install starts when the app exits. let clean = !app.session.documents().iter().any(|d| d.is_dirty()); match app.updates_rt.updater.show_if(ctx, clean) { Action::OpenUrl(url) => ctx.open_url(egui::OpenUrl::new_tab(url)), @@ -95,11 +103,15 @@ pub(crate) fn show(app: &mut DesignApp, ctx: &egui::Context) { Action::None => {} } // Help ▸ Check for Updates answers in the shared dialog, which follows the updater's status. - let dialog = CheckResultDialog::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")); - match dialog.show(ctx, app.updates_rt.updater.status()) { - CheckResultResponse::None => {} - CheckResultResponse::Close => app.updates_rt.updater.dismiss_status(), - CheckResultResponse::CheckAgain => app.updates_rt.check_requested = true, + if result_window_shows(app.updates_rt.updater.status(), app.updates_rt.updater.prompt_open()) { + let dialog = CheckResultDialog::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")); + match dialog.show(ctx, app.updates_rt.updater.status()) { + CheckResultResponse::None => {} + CheckResultResponse::Close => app.updates_rt.updater.dismiss_status(), + CheckResultResponse::CheckAgain => app.updates_rt.check_requested = true, + // The next `show_if` asks the window to close once no document has unsaved changes. + CheckResultResponse::RestartToUpdate => app.updates_rt.updater.restart_to_update(), + } } } @@ -165,4 +177,24 @@ mod tests { output.textures_delta.clear(); assert!(app.updates_rt.updater.prompt_open()); } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn result_window_shows_every_status_but_idle() { + let shown = [ + Status::Checking, + Status::UpToDate, + Status::Failed("no network".into()), + Status::Installing, + Status::Ready, + Status::Managed, + Status::Updated("0.2.0".into()), + Status::InstallFailed("disk full".into()), + ]; + for status in &shown { + assert!(result_window_shows(status, false), "{status:?}"); + assert!(!result_window_shows(status, true), "{status:?} over the prompt"); + } + assert!(!result_window_shows(&Status::Idle, false)); + } } From a337204cfe5fdca1a8bedcea29cc7279077e14bb Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 8 Nov 2026 17:56:03 -0500 Subject: [PATCH 0873/1349] Geom: step budget in Pencil fit, stripe band cap, balanced Pathfinder union (#2251) * geom: step budget in freehand fit, stripe band cap, balanced unions * move test --- crates/geom/src/freehand.rs | 18 ++++++++++++++++++ crates/geom/src/pathfinder.rs | 33 +++++++++++++++++++++++++++++++++ crates/geom/src/stroke_style.rs | 21 ++++++++++++++++++++- 3 files changed, 71 insertions(+), 1 deletion(-) diff --git a/crates/geom/src/freehand.rs b/crates/geom/src/freehand.rs index 53ddf9611..278898239 100644 --- a/crates/geom/src/freehand.rs +++ b/crates/geom/src/freehand.rs @@ -3,6 +3,10 @@ use crate::Point; use crate::path::{Anchor, AnchorKind}; +/// Distance tests [`simplify`] may make. Worst-case input splits one point off at a time (quadratic); +/// past this the spans still waiting keep only their end points, a coarser fit rather than a stall. +const MAX_SIMPLIFY_STEPS: usize = 16 * 1024 * 1024; + /// Ramer–Douglas–Peucker: the points that keep the polyline within `tol`. fn simplify(pts: &[Point], tol: f64) -> Vec { if pts.len() < 3 { @@ -12,7 +16,12 @@ fn simplify(pts: &[Point], tol: f64) -> Vec { keep[0] = true; keep[pts.len() - 1] = true; let mut stack = vec![(0, pts.len() - 1)]; + let mut steps = 0usize; while let Some((a, b)) = stack.pop() { + steps = steps.saturating_add(b - a); + if steps > MAX_SIMPLIFY_STEPS { + break; + } let (pa, pb) = (pts[a], pts[b]); let d = pb - pa; let len = d.hypot(); @@ -113,4 +122,13 @@ mod tests { assert!(c.iter().all(|x| x.kind == AnchorKind::Smooth)); assert!((c[0].p - c[c.len() - 1].p).hypot() > 1.0); } + + /// A convex curve splits one point at a time (quadratic): fitting stops at the step budget. + #[test] + fn unbalanced_input_stops_at_the_step_budget() { + let n = 100_000; + let curve: Vec = (0..n).map(|i| Point::new(f64::from(i), (f64::from(i) * 1e-3).powi(4))).collect(); + let a = fit(&curve, 1e-9, false); + assert!(a.len() >= 2 && a.len() < n as usize); + } } diff --git a/crates/geom/src/pathfinder.rs b/crates/geom/src/pathfinder.rs index 75aa1afce..0b8237024 100644 --- a/crates/geom/src/pathfinder.rs +++ b/crates/geom/src/pathfinder.rs @@ -92,11 +92,31 @@ fn from_flo(paths: &[SimpleBezierPath]) -> PathData { PathData::new(subpaths) } +/// Unions of more shapes than this combine in pairs; up to it each is added in turn (as always). +const BALANCED_UNION_FROM: usize = 16; + /// Combine `shapes` (back to front, all in one coordinate space). `None` when nothing is left. pub fn combine(op: Op, shapes: &[PathData]) -> Option { let flo: Vec> = shapes.iter().map(to_flo).filter(|p| !p.is_empty()).collect(); let (first, rest) = flo.split_first()?; let union = |v: &[Vec]| -> Vec { + if v.len() > BALANCED_UNION_FROM { + // Pairs, then pairs of pairs: adding each shape to everything so far reprocesses the + // growing result every time (quadratic for many shapes). + let mut level: Vec> = v.to_vec(); + while level.len() > 1 { + level = level + .chunks(2) + .map(|c| match c { + [a, b] if a.is_empty() => b.clone(), + [a, b] if b.is_empty() => a.clone(), + [a, b] => path_add(a, b, ACCURACY), + _ => c.first().cloned().unwrap_or_default(), + }) + .collect(); + } + return level.pop().unwrap_or_default(); + } let mut acc: Vec = Vec::new(); for p in v { acc = if acc.is_empty() { p.clone() } else { path_add(&acc, p, ACCURACY) }; @@ -147,6 +167,19 @@ mod tests { p.subpaths.iter().map(|s| s.area()).sum::().abs() } + #[test] + fn a_union_of_many_shapes_adds_up() { + // 40 squares in a row, each overlapping the next by 5: width 40 * 10 + 5, height 10. + let shapes: Vec = (0..40).map(|i| shapes::rectangle(Rect::new(f64::from(i) * 5.0, 0.0, f64::from(i) * 5.0 + 10.0, 10.0))).collect(); + let u = combine(Op::Add, &shapes).unwrap(); + assert!((area(&u) - 205.0 * 10.0).abs() < 1.0, "{}", area(&u)); + // Far-apart squares stay separate. + let apart: Vec = + (0..40).map(|i| shapes::rectangle(Rect::new(f64::from(i) * 50.0, 0.0, f64::from(i) * 50.0 + 10.0, 10.0))).collect(); + let u = combine(Op::Add, &apart).unwrap(); + assert_eq!(u.subpaths.len(), 40); + } + #[test] fn boolean_ops_on_overlapping_squares() { let a = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)); diff --git a/crates/geom/src/stroke_style.rs b/crates/geom/src/stroke_style.rs index 26c201477..d3c25ecba 100644 --- a/crates/geom/src/stroke_style.rs +++ b/crates/geom/src/stroke_style.rs @@ -57,10 +57,18 @@ fn offset_subpath(bp: &BezPath, d: f64, tol: f64, out: &mut BezPath) { /// Bands (start, width) across a stroke, as fractions of the weight from its left edge. pub type Bands = [(f64, f64)]; +/// Most bands of a striped stroke that are drawn, and most path elements its fill may have: +/// every band strokes the whole path again, so both multiply the path's size. +pub const MAX_STRIPE_BANDS: usize = 64; +const MAX_STRIPE_ELEMENTS: usize = 2_000_000; + /// The filled area of a striped stroke of `weight` along `bp`. pub fn stripes(bp: &BezPath, weight: f64, bands: &Bands, tol: f64) -> BezPath { let mut out = BezPath::new(); - for &(start, width) in bands { + for &(start, width) in bands.iter().take(MAX_STRIPE_BANDS) { + if out.elements().len() > MAX_STRIPE_ELEMENTS { + break; + } if width <= 0.0 { continue; } @@ -139,6 +147,17 @@ pub fn hashed(bp: &BezPath, weight: f64, tol: f64) -> BezPath { #[cfg(test)] mod tests { use super::*; + + #[test] + fn stripes_draw_at_most_the_band_cap() { + let mut line = BezPath::new(); + line.move_to((0.0, 0.0)); + line.line_to((100.0, 0.0)); + let one = stripes(&line, 4.0, &[(0.0, 0.1)], 0.1).elements().len(); + let many = vec![(0.0, 0.1); 100_000]; + let all = stripes(&line, 4.0, &many, 0.1).elements().len(); + assert_eq!(all, one * MAX_STRIPE_BANDS); + } use kurbo::Shape; fn line() -> BezPath { From 55729a5128c5f1519b0c60ded8d5f6e44205e2c5 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Mon, 9 Nov 2026 02:45:42 +0100 Subject: [PATCH 0874/1349] Skip RTF header/footer left, right and first-page groups on import Found while testing crates/textimport/src/rtf.rs:43-63 (SKIP list) and :201 (`SKIP.contains(&word.as_str())`) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/textimport/src/rtf.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/crates/textimport/src/rtf.rs b/crates/textimport/src/rtf.rs index f750aa385..6660356aa 100644 --- a/crates/textimport/src/rtf.rs +++ b/crates/textimport/src/rtf.rs @@ -47,7 +47,13 @@ const SKIP: &[&str] = &[ "info", "pict", "header", + "headerl", + "headerr", + "headerf", "footer", + "footerl", + "footerr", + "footerf", "footnote", "listtable", "listoverridetable", @@ -310,6 +316,15 @@ fn cp1252(b: u8) -> char { mod tests { use super::*; + #[test] + fn header_and_footer_variants_are_skipped() { + for w in ["header", "headerl", "headerr", "headerf", "footer", "footerl", "footerr", "footerf"] { + let rtf = format!(r"{{\rtf1\ansi {{\{w} Page head\par}}Body text\par}}"); + let text = import(rtf.as_bytes()).unwrap().story.text; + assert_eq!(text.trim_end(), "Body text", "{w}"); + } + } + #[test] fn out_of_range_unicode_escape_is_dropped() { assert_eq!(import(br"{\rtf1 a\u4294967361?b}").unwrap().story.text, "ab"); From 79953b8ae303b6c5acd81d25c9fabfd9c0e4b7a0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 19:45:45 -0800 Subject: [PATCH 0875/1349] Updates: take craft-update from craft-libs main at 1b34eba41 --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c0df56599..3bc1e94a2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1138,7 +1138,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/dotCooCoo/craft-libs?rev=c7c84230631cbc01ee928f0a0e0d838b1ed612ae#c7c84230631cbc01ee928f0a0e0d838b1ed612ae" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "chrono", "dunce", diff --git a/Cargo.toml b/Cargo.toml index 47b925a23..6a07b01b1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,7 +18,7 @@ craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "92d392c # Separations, ink coverage and the ink manager; same revision as craft-pdf and the krilla patch. craft-prepress = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.1.0", features = ["flatten"] } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/dotCooCoo/craft-libs", version = "=0.1.0", rev = "c7c84230631cbc01ee928f0a0e0d838b1ed612ae", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } # internal designcraft-geom = { path = "crates/geom" } designcraft-color = { path = "crates/color" } From bb54c44ad937f00baba42e5ad12224314eeea074 Mon Sep 17 00:00:00 2001 From: kuseidos <49816124+kuseidos@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:05:22 -0600 Subject: [PATCH 0876/1349] Command API: refuse a page index past the end, and say how many pages went (#2460) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Command API: refuse a page index past the end, and say how many pages went layout.pages.delete answered ok for an index past the last page and deleted nothing for it, so a caller off by one removed a different range and read a success; on a 336-page book that is page 337 instead of 336. Both commands now check every index against the document and refuse it with the sentence the MCP export commands have used since #70, return how many pages they touched so a no-op and a success are told apart, and state in their params that the indices count from 0. * Pages: count the pages a delete will remove, not the indices it was given delete_pages refused [0, 0, 1, 2] on a four-page document as if it would leave none, because the guard measured the length of the list instead of the pages it names. Same family as the index check next to it: the count was of the wrong thing. A test in the engine pins it. * Pages: refuse a malformed page list instead of dropping what it cannot read Review finding: page_indices used filter_map, so a list holding a string, a fraction or nothing at all was silently shortened — the caller was told a page was handled when it never was, which is the same mistake the command now refuses one level down. Every entry must be a whole number, and pages must be a list. Tests cover all three shapes, and the new test functions carry docstrings so the coverage check has nothing to report. --- crates/doc/src/build.rs | 8 +- crates/engine/src/cmd/layout/registry.rs | 174 ++++++++++++++++++++--- 2 files changed, 157 insertions(+), 25 deletions(-) diff --git a/crates/doc/src/build.rs b/crates/doc/src/build.rs index 5915f9ba7..89e4b5ee7 100644 --- a/crates/doc/src/build.rs +++ b/crates/doc/src/build.rs @@ -581,12 +581,14 @@ impl Document { /// Delete absolute pages (items whose centre is on a deleted page are deleted too). pub fn delete_pages(&mut self, pages: &[usize]) -> Result<()> { - if pages.len() >= self.page_count() { - return Err(DocError::Invalid("a document needs at least one page".into())); - } let mut doomed: Vec<(usize, usize)> = pages.iter().filter_map(|p| self.page_loc(*p)).collect(); doomed.sort(); doomed.dedup(); + // The pages it will remove, not the indices it was given: asking for [0, 0, 1, 2] of four + // pages removes three of them and leaves one, which is allowed. + if doomed.len() >= self.page_count() { + return Err(DocError::Invalid("a document needs at least one page".into())); + } let mut remove_items: Vec = Vec::new(); for &(si, pi) in &doomed { let sp = &self.spreads[si]; diff --git a/crates/engine/src/cmd/layout/registry.rs b/crates/engine/src/cmd/layout/registry.rs index 9bccf2d96..2140d35d8 100644 --- a/crates/engine/src/cmd/layout/registry.rs +++ b/crates/engine/src/cmd/layout/registry.rs @@ -5,7 +5,7 @@ use super::parents::{ parent_label_taken, parent_name_param, parent_options, parent_page_size, parent_page_target, parent_prefix_param, parent_ref, parent_spread_index, }; use super::sections::{ChapterEdit, SectionEdit, chapter_numbering, start_number}; -use super::{CommandSpec, LAYER_COLORS, Layer, LayerId, Margins, SpreadId, Value, bad, cmd, has_doc, json, ok, str_param}; +use super::{CommandSpec, LAYER_COLORS, Layer, LayerId, Margins, Result, SpreadId, Value, bad, cmd, has_doc, json, ok, str_param}; pub fn specs() -> Vec { vec![ @@ -81,19 +81,25 @@ pub fn specs() -> Vec { }) } ), - cmd!("layout.pages.delete", "Delete Pages", ["Layout", "Pages"], None, "{pages: [index]}", has_doc, |s, p| { - let pages: Vec = p - .get("pages") - .and_then(Value::as_array) - .map(|a| a.iter().filter_map(Value::as_u64).map(|v| v as usize).collect()) - .unwrap_or_default(); - s.edit(|d, sel| { - d.delete_pages(&pages)?; - sel.items.retain(|i| d.item(*i).is_some()); - sel.text = sel.text.filter(|t| d.story(t.story).is_some()); - ok() - }) - }), + cmd!( + "layout.pages.delete", + "Delete Pages", + ["Layout", "Pages"], + None, + "{pages: [0-based page indices]} → {deleted: how many pages were removed}", + has_doc, + |s, p| { + const ID: &str = "layout.pages.delete"; + let pages = page_indices(ID, s.doc()?.doc.page_count(), p)?; + let deleted = distinct_pages(&pages); + s.edit(|d, sel| { + d.delete_pages(&pages)?; + sel.items.retain(|i| d.item(*i).is_some()); + sel.text = sel.text.filter(|t| d.story(t.story).is_some()); + Ok(json!({"deleted": deleted})) + }) + } + ), cmd!("layout.pages.move", "Move Pages…", ["Layout", "Pages"], None, "{from, to}", has_doc, |s, p| { let from = p.get("from").and_then(Value::as_u64).ok_or_else(|| bad("layout.pages.move", "missing from"))? as usize; let to = p.get("to").and_then(Value::as_u64).ok_or_else(|| bad("layout.pages.move", "missing to"))? as usize; @@ -165,18 +171,16 @@ pub fn specs() -> Vec { "Apply Parent to Pages…", ["Layout", "Pages"], None, - "{pages: [index], parent: id|\"A-Parent\"|\"A\"|null (null or \"[None]\" clears)}", + "{pages: [0-based page indices], parent: id|\"A-Parent\"|\"A\"|null (null or \"[None]\" clears)} → {applied: how many pages took the parent}", has_doc, |s, p| { - let pages: Vec = p - .get("pages") - .and_then(Value::as_array) - .map(|a| a.iter().filter_map(Value::as_u64).map(|v| v as usize).collect()) - .unwrap_or_default(); - let parent = parent_ref("layout.pages.applyParent", &s.doc()?.doc, p.get("parent"))?.unwrap_or(None); + const ID: &str = "layout.pages.applyParent"; + let pages = page_indices(ID, s.doc()?.doc.page_count(), p)?; + let applied = distinct_pages(&pages); + let parent = parent_ref(ID, &s.doc()?.doc, p.get("parent"))?.unwrap_or(None); s.edit(|d, _| { d.apply_parent(&pages, parent)?; - ok() + Ok(json!({"applied": applied})) }) } ), @@ -828,3 +832,129 @@ pub fn specs() -> Vec { }), ] } + +/// The page indices a `layout.pages.*` command was given, in the order it passed them. +/// +/// Both commands count pages from 0. An index past the last page used to be dropped in +/// silence, so a caller that was off by one deleted a different range and still read +/// `ok`; the sentence is the one the MCP export commands have used since #70. +fn page_indices(id: &str, count: usize, p: &Value) -> Result> { + // A list that is missing, is not a list, or holds something that is not a whole number is + // refused rather than filtered: dropping an entry silently is the same mistake this fixes, + // one level up — the caller would be told a page was handled when it never was. + let raw = p.get("pages").and_then(Value::as_array).ok_or_else(|| bad(id, "pages takes a list of page indices"))?; + let mut out = Vec::with_capacity(raw.len()); + for v in raw { + let n = v.as_u64().ok_or_else(|| bad(id, format!("pages takes whole numbers, and {v} is not one")))?; + let i = usize::try_from(n).unwrap_or(usize::MAX); + if i >= count { + return Err(bad(id, format!("no page {i} (the document has {count} pages, indices are 0-based)"))); + } + out.push(i); + } + Ok(out) +} + +/// How many pages a list of indices names, counting a repeated index once. +fn distinct_pages(pages: &[usize]) -> usize { + let mut v = pages.to_vec(); + v.sort_unstable(); + v.dedup(); + v.len() +} + +#[cfg(test)] +mod page_index_tests { + use serde_json::json; + + fn four_pages() -> crate::Session { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({"pages": 4})).unwrap(); + s + } + + fn pages_left(s: &crate::Session) -> usize { + s.doc().unwrap().doc.page_count() + } + + /// An index past the last page is an error that names it, and nothing is removed. + #[test] + fn a_page_index_past_the_end_is_refused_and_nothing_is_deleted() { + let mut s = four_pages(); + let err = s.execute("layout.pages.delete", &json!({"pages": [4]})).unwrap_err().to_string(); + assert!(err.contains("no page 4"), "the message names the index: {err}"); + assert!(err.contains("indices are 0-based"), "and the base: {err}"); + assert_eq!(pages_left(&s), 4, "nothing went"); + } + + /// The reply says how many pages went, and a page named twice is one page. + #[test] + fn deleting_says_how_many_pages_went() { + let mut s = four_pages(); + let r = s.execute("layout.pages.delete", &json!({"pages": [0, 1]})).unwrap(); + assert_eq!(r["deleted"], 2); + assert_eq!(pages_left(&s), 2); + // A page named twice is one page, not two. + let mut s = four_pages(); + let r = s.execute("layout.pages.delete", &json!({"pages": [1, 1]})).unwrap(); + assert_eq!(r["deleted"], 1); + assert_eq!(pages_left(&s), 3); + } + + /// Three pages named of four leave one, which is allowed even with a repeat. + #[test] + fn a_page_named_twice_does_not_count_as_two_against_the_last_one_left() { + // Four pages, three named (one of them twice): that leaves one and is allowed. + let mut s = four_pages(); + let r = s.execute("layout.pages.delete", &json!({"pages": [0, 0, 1, 2]})).unwrap(); + assert_eq!(r["deleted"], 3); + assert_eq!(pages_left(&s), 1); + } + + /// Applying a parent reports how many pages took it, and the pages really do. + #[test] + fn applying_a_parent_says_how_many_pages_took_it() { + let mut s = four_pages(); + s.execute("layout.parents.new", &json!({"prefix": "B"})).unwrap(); + let r = s.execute("layout.pages.applyParent", &json!({"pages": [1, 2], "parent": "B"})).unwrap(); + assert_eq!(r["applied"], 2); + let doc = s.doc().unwrap(); + for page in [1usize, 2] { + assert!(doc.doc.page(page).unwrap().parent.is_some(), "page {page} took the parent"); + } + } + + /// Refused before the edit starts, so no page changes parent. + #[test] + fn a_page_index_past_the_end_is_refused_by_a_parent() { + let mut s = four_pages(); + // Pages are born on the default parent A, so what must not change is which parent they have. + let b = s.execute("layout.parents.new", &json!({"prefix": "B"})).unwrap()["id"].as_u64().unwrap(); + let before: Vec<_> = (0..4).map(|i| s.doc().unwrap().doc.page(i).unwrap().parent.map(|p| p.0)).collect(); + let err = s.execute("layout.pages.applyParent", &json!({"pages": [4], "parent": "B"})).unwrap_err().to_string(); + assert!(err.contains("no page 4"), "{err}"); + let after: Vec<_> = (0..4).map(|i| s.doc().unwrap().doc.page(i).unwrap().parent.map(|p| p.0)).collect(); + assert_eq!(before, after, "no page changed parent"); + assert!(!after.contains(&Some(b)), "and none took B"); + } + + /// A malformed list is refused instead of quietly dropping the entries it cannot read. + #[test] + fn a_malformed_page_list_is_refused_instead_of_ignored() { + let mut s = four_pages(); + for list in [json!({"pages": "4"}), json!({"pages": [1, "2"]}), json!({})] { + let err = s.execute("layout.pages.delete", &list).unwrap_err().to_string(); + assert!(err.contains("pages takes"), "refused: {list} → {err}"); + } + assert_eq!(pages_left(&s), 4, "and nothing went"); + } + + /// Both commands' `params` doc states that the indices count from 0. + #[test] + fn both_commands_state_the_base_in_their_params() { + for id in ["layout.pages.delete", "layout.pages.applyParent"] { + let spec = crate::cmd::command_specs().iter().find(|s| s.id == id).unwrap(); + assert!(spec.params.contains("0-based"), "{id} says its base: {}", spec.params); + } + } +} From 147b3f475056967353606b90fa0dc8bb39de7f27 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 9 Nov 2026 06:30:13 -0500 Subject: [PATCH 0877/1349] Release 0.19.0 --- Cargo.lock | 42 +++++++++++++++++++++--------------------- Cargo.toml | 2 +- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3bc1e94a2..2cef88cfb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1306,7 +1306,7 @@ dependencies = [ [[package]] name = "designcraft" -version = "0.17.0" +version = "0.19.0" dependencies = [ "arboard", "craft-update", @@ -1331,7 +1331,7 @@ dependencies = [ [[package]] name = "designcraft-cli" -version = "0.17.0" +version = "0.19.0" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1348,7 +1348,7 @@ dependencies = [ [[package]] name = "designcraft-color" -version = "0.17.0" +version = "0.19.0" dependencies = [ "craft-cms", "kurbo", @@ -1360,7 +1360,7 @@ dependencies = [ [[package]] name = "designcraft-compose" -version = "0.17.0" +version = "0.19.0" dependencies = [ "designcraft-color", "designcraft-doc", @@ -1380,7 +1380,7 @@ dependencies = [ [[package]] name = "designcraft-doc" -version = "0.17.0" +version = "0.19.0" dependencies = [ "chrono", "designcraft-color", @@ -1393,7 +1393,7 @@ dependencies = [ [[package]] name = "designcraft-engine" -version = "0.17.0" +version = "0.19.0" dependencies = [ "caseless", "craft-atomic", @@ -1433,7 +1433,7 @@ dependencies = [ [[package]] name = "designcraft-epub" -version = "0.17.0" +version = "0.19.0" dependencies = [ "chrono", "designcraft-color", @@ -1443,7 +1443,7 @@ dependencies = [ [[package]] name = "designcraft-fonts" -version = "0.17.0" +version = "0.19.0" dependencies = [ "core-text", "harfrust 0.13.3", @@ -1456,7 +1456,7 @@ dependencies = [ [[package]] name = "designcraft-format" -version = "0.17.0" +version = "0.19.0" dependencies = [ "designcraft-doc", "designcraft-images", @@ -1468,7 +1468,7 @@ dependencies = [ [[package]] name = "designcraft-geom" -version = "0.17.0" +version = "0.19.0" dependencies = [ "flo_curves", "kurbo", @@ -1481,7 +1481,7 @@ dependencies = [ [[package]] name = "designcraft-idml" -version = "0.17.0" +version = "0.19.0" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1496,7 +1496,7 @@ dependencies = [ [[package]] name = "designcraft-images" -version = "0.17.0" +version = "0.19.0" dependencies = [ "craft-cms", "designcraft-color", @@ -1514,7 +1514,7 @@ dependencies = [ [[package]] name = "designcraft-mcp" -version = "0.17.0" +version = "0.19.0" dependencies = [ "designcraft-engine", "designcraft-geom", @@ -1527,7 +1527,7 @@ dependencies = [ [[package]] name = "designcraft-pdf" -version = "0.17.0" +version = "0.19.0" dependencies = [ "chrono", "craft-cms", @@ -1553,7 +1553,7 @@ dependencies = [ [[package]] name = "designcraft-pptx" -version = "0.17.0" +version = "0.19.0" dependencies = [ "chrono", "designcraft-color", @@ -1571,7 +1571,7 @@ dependencies = [ [[package]] name = "designcraft-render" -version = "0.17.0" +version = "0.19.0" dependencies = [ "craft-pdf", "designcraft-color", @@ -1590,7 +1590,7 @@ dependencies = [ [[package]] name = "designcraft-textimport" -version = "0.17.0" +version = "0.19.0" dependencies = [ "designcraft-doc", "quick-xml 0.41.0", @@ -1599,7 +1599,7 @@ dependencies = [ [[package]] name = "designcraft-tools" -version = "0.17.0" +version = "0.19.0" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1611,7 +1611,7 @@ dependencies = [ [[package]] name = "designcraft-ui-egui" -version = "0.17.0" +version = "0.19.0" dependencies = [ "craft-dialogs", "craft-keymap", @@ -1645,7 +1645,7 @@ dependencies = [ [[package]] name = "designcraft-web" -version = "0.17.0" +version = "0.19.0" dependencies = [ "designcraft-engine", "designcraft-format", @@ -7679,7 +7679,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.17.0" +version = "0.19.0" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index 6a07b01b1..5a4143f12 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/designcraft", "apps/designcraft-cli", "xtask"] [workspace.package] -version = "0.17.0" +version = "0.19.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From 57e68009da69245dc022d804308bbd34aa97f294 Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:53:59 +0000 Subject: [PATCH 0878/1349] Fix designCraft 0.18.0: arrowheads point the wrong way on curves whose (#2515) Fixes #2514. - crates/doc/src/arrow.rs - crates/doc/tests/autocraft_regression_2514.rs Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com> --- crates/doc/src/arrow.rs | 7 ++++- crates/doc/tests/autocraft_regression_2514.rs | 28 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 crates/doc/tests/autocraft_regression_2514.rs diff --git a/crates/doc/src/arrow.rs b/crates/doc/src/arrow.rs index e3f3387fe..432cd4b93 100644 --- a/crates/doc/src/arrow.rs +++ b/crates/doc/src/arrow.rs @@ -75,7 +75,12 @@ fn end_of(seg: &PathSeg, at_start: bool) -> (Point, Vec2) { let mut d = match seg { PathSeg::Line(l) => l.p1 - l.p0, PathSeg::Quad(q) => q.deriv().eval(t).to_vec2(), - PathSeg::Cubic(c) => c.deriv().eval(t).to_vec2(), + PathSeg::Cubic(c) => { + // A handle sitting on its anchor has no direction: the tangent then points at the next + // control point of the segment that differs from the end point. + let pts = if at_start { [c.p1 - c.p0, c.p2 - c.p0, c.p3 - c.p0] } else { [c.p3 - c.p2, c.p3 - c.p1, c.p3 - c.p0] }; + pts.into_iter().find(|v| v.hypot() >= 1e-9).unwrap_or(Vec2::ZERO) + } }; if d.hypot() < 1e-9 { d = seg.end() - seg.start(); diff --git a/crates/doc/tests/autocraft_regression_2514.rs b/crates/doc/tests/autocraft_regression_2514.rs new file mode 100644 index 000000000..addd40ef2 --- /dev/null +++ b/crates/doc/tests/autocraft_regression_2514.rs @@ -0,0 +1,28 @@ +use designcraft_doc::arrow::apply; +use designcraft_doc::geom::BezPath; +use designcraft_doc::geom::kurbo::Shape; +use designcraft_doc::{Arrowhead, Stroke}; + +#[test] +fn start_head_follows_tangent_when_start_handle_is_missing() { + let mut bp = BezPath::new(); + bp.move_to((0.0, 0.0)); + bp.curve_to((0.0, 0.0), (100.0, 0.0), (100.0, 100.0)); + let st = Stroke { weight: 1.0, start: Arrowhead::Bar, ..Stroke::default() }; + let (_, heads) = apply(&bp, &st, false).unwrap(); + // The curve leaves heading along +x, so the bar at the start stands upright. + let b = heads[0].path.bounding_box(); + assert!(b.height() > b.width() * 3.0, "{b:?}"); +} + +#[test] +fn end_head_follows_tangent_when_end_handle_is_missing() { + let mut bp = BezPath::new(); + bp.move_to((0.0, 0.0)); + bp.curve_to((100.0, 0.0), (100.0, 100.0), (100.0, 100.0)); + let st = Stroke { weight: 1.0, end: Arrowhead::Bar, ..Stroke::default() }; + let (_, heads) = apply(&bp, &st, false).unwrap(); + // The curve arrives heading along +y, so the bar at the end lies across, horizontally. + let b = heads[0].path.bounding_box(); + assert!(b.width() > b.height() * 3.0, "{b:?}"); +} From 32a1dbc7345fe14e010a36c691f1095562c387a9 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 9 Nov 2026 14:29:55 +0100 Subject: [PATCH 0879/1349] Place: a graphic dropped on a line gets its own frame and leaves the line alone (#2290) (#2521) * Place: a graphic dropped on a line gets its own frame and leaves the line alone (#2290) drop_frame took any unlocked item under the pointer whose content takes a graphic, so a file dropped on a line's stroke turned the line into a zero-height image frame. It now also requires the item's path to enclose an area, as the place cursor's click already does. * Place: the next file of a drop doesn't replace a graphic that got its own frame (#2290) A graphic dropped on a line, or on the page, gets a frame of its own at the pointer but left frame_free set, so the next file of the same drop found that new frame under the pointer and replaced the first graphic. Any graphic placed by the drop now clears the flag. --- crates/ui-egui/src/app/files.rs | 12 ++++++---- crates/ui-egui/src/canvas/input.rs | 7 +++--- crates/ui-egui/src/tests.rs | 37 +++++++++++++++++++++++++++++- 3 files changed, 48 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 3c90d8c59..069515394 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -194,8 +194,9 @@ impl DesignApp { } /// [`Self::open_dropped_at`] for one file of a drop. `frame_free` is whether the frame under the - /// pointer can still be filled: the first graphic of a drop takes it (and clears the flag), so - /// the files after it land at the pointer instead of replacing that graphic. + /// pointer can still be filled: the first graphic of a drop takes it, or a frame of its own at + /// the pointer when there is none, and clears the flag, so the files after it land at the + /// pointer instead of replacing that graphic. pub(crate) fn place_dropped(&mut self, path: &str, pointer: Option, frame_free: &mut bool) -> Result { if path.to_ascii_lowercase().ends_with(".ase") { return self.run("swatch.load", json!({"path": path})); @@ -210,7 +211,8 @@ impl DesignApp { let mut params = json!({"path": path}); // A graphic dropped on an empty or graphic frame fills it, as File > Place does. Text keeps // getting a frame of its own, so it never replaces the image in a graphic frame. - let frame = if *frame_free && !designcraft_textimport::is_text_file(path) { canvas::drop_frame(self, pointer) } else { None }; + let is_text = designcraft_textimport::is_text_file(path); + let frame = if *frame_free && !is_text { canvas::drop_frame(self, pointer) } else { None }; if let (Some(frame), Some(o)) = (frame, params.as_object_mut()) { o.insert("frame".into(), json!(frame.0)); } @@ -224,7 +226,9 @@ impl DesignApp { } } let placed = self.open_file("file.place", params); - if frame.is_some() && placed.is_ok() { + // A graphic placed in a frame of its own (dropped on a line or on the page) is under the + // pointer too, so the next file of the drop must not replace it (#2290). + if placed.is_ok() && !is_text { *frame_free = false; } placed diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 5b7f38d5f..590b0f8c6 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -171,15 +171,16 @@ fn item_at(app: &DesignApp, p: Point, zoom: f64) -> Option<(designcraft_doc::Ite /// The frame under a pointer over the canvas that takes a graphic (empty, holding a graphic, or /// holding only graphics pasted into it): a graphic dropped there fills it instead of becoming a -/// new object. `None` when the pointer isn't over the canvas or over such a frame, and for a -/// locked frame, which a drop never replaces. +/// new object. `None` when the pointer isn't over the canvas or over such a frame, for a locked +/// frame, which a drop never replaces, and for a line or any path that encloses no area, which +/// would become a zero-height image frame (#2290), as the place cursor skips them. pub fn drop_frame(app: &DesignApp, screen: Option) -> Option { let rect = app.canvas_rect?; let pos = screen.filter(|p| rect.contains(*p))?; let v = app.view()?; let (id, _) = item_at(app, Xf::new(rect, v).to_canvas(pos), v.zoom)?; let it = app.session.active()?.doc.item(id)?; - (!it.locked && it.takes_graphic()).then_some(id) + (!it.locked && it.path.encloses_area() && it.takes_graphic()).then_some(id) } /// Wheel, pinch and Alt/Ctrl/Cmd + wheel over the canvas: zoom at the pointer, else scroll. diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 5b3871bbf..0fcd2f3f6 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -856,9 +856,15 @@ fn dropping_an_ase_file_loads_its_swatches() { /// A document with one empty frame at (36, 36)-(136, 136): the app, the frame's id and a screen point inside it /// and one outside it. fn app_with_drop_frame() -> (DesignApp, u64, egui::Pos2, egui::Pos2) { + app_with_drop_item("frame.create", json!({"rect": [36, 36, 136, 136]})) +} + +/// A document with the one object `command` creates from `params`: the app, the object's id, the +/// screen point of page point (80, 80) and that of (300, 300), off the object. +fn app_with_drop_item(command: &str, params: serde_json::Value) -> (DesignApp, u64, egui::Pos2, egui::Pos2) { let mut app = DesignApp::new(Session::new(), Services::default()); app.run("file.new", json!({})).unwrap(); - let frame = app.run("frame.create", json!({"rect": [36, 36, 136, 136]})).unwrap()["id"].as_u64().unwrap(); + let frame = app.run(command, params).unwrap()["id"].as_u64().unwrap(); app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))); let _ = app.view_mut(); let (view, rect) = (app.view().unwrap(), app.canvas_rect.unwrap()); @@ -959,6 +965,35 @@ fn a_file_dropped_without_pointer_events_fills_the_frame_under_the_system_pointe } } +/// A line encloses no area, so a graphic dropped on it gets a frame of its own at the drop point +/// and the line stays a line, as with the place cursor (#2290). A second graphic of the same drop +/// gets a frame of its own too, instead of replacing the first in the frame the first one got. +#[test] +fn graphics_dropped_on_a_line_leave_the_line_alone() { + let (mut app, line, on_line, _) = app_with_drop_item("line.create", json!({"a": [36, 80], "b": [136, 80]})); + let id = designcraft_doc::ItemId(line); + let before = serde_json::to_value(app.session.doc().unwrap().doc.item(id).unwrap()).unwrap(); + assert!(canvas::drop_frame(&app, Some(on_line)).is_none(), "a line is no frame"); + let (first, second) = (dropped_png("drop-on-line-first"), dropped_png("drop-on-line-second")); + let mut frame_free = true; + let a = app.place_dropped(&first.to_string_lossy(), Some(on_line), &mut frame_free); + assert!(!frame_free, "the first graphic is under the pointer now"); + let b = app.place_dropped(&second.to_string_lossy(), Some(on_line), &mut frame_free); + let _ = (std::fs::remove_file(&first), std::fs::remove_file(&second)); + let a = designcraft_doc::ItemId(a.unwrap()["id"].as_u64().unwrap()); + let b = designcraft_doc::ItemId(b.unwrap()["id"].as_u64().unwrap()); + assert!(a != id && b != id && a != b, "each graphic has a new frame: {a:?} {b:?}"); + let d = &app.session.doc().unwrap().doc; + assert_eq!(d.spreads[0].items.len(), 3); + assert_eq!(serde_json::to_value(d.item(id).unwrap()).unwrap(), before, "the line is unchanged"); + for (placed, name) in [(a, "drop-on-line-first"), (b, "drop-on-line-second")] { + let it = d.item(placed).unwrap(); + let designcraft_doc::Content::Graphic(g) = &it.content else { panic!("{name} is in its frame") }; + assert!(d.assets[&g.asset].name.contains(name), "{name}"); + assert!(it.path.encloses_area() && it.bounds().height() > 1.0, "a real frame, not a zero-height one: {:?}", it.bounds()); + } +} + #[test] fn a_locked_frame_is_not_a_drop_target() { let (mut app, frame, inside, _) = app_with_drop_frame(); From 95abb2b03b6d510a72d687b2e5ee41ef3cbd7485 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Rese?= Date: Tue, 10 Nov 2026 09:50:31 -0300 Subject: [PATCH 0880/1349] pt-BR: translate 996 missing interface strings and the unit names (#1539) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * pt-BR: translate the 634 interface strings added since the catalog was completed Covers the strings the catalog lacked after #495: tool names, menu paths (Edit > Menus), Japanese typesetting dialogs (ruby, kinsoku, mojikumi, warichu, kenten), special characters, Load Styles, Text Frame auto-size, Data Merge, preflight, font replacement and About. Tools are "Ferramenta X", parent pages "página principal", stories "artigo"; menu paths reuse the existing menu names. IT, VA and Y: stay as they are, as in every other language. Co-Authored-By: Claude Opus 5.5 * pt-BR: one term per feature, the unit names, a catalog test and the docs Review fixes for the new rows: Gradient Feather, stroke styles and type on a path use the catalog's existing terms; warichu's Line Spacing no longer reads as Leading; em/en dash, hair space, nonbreaking space and hyphen and paragraph return take their Brazilian typographic names; the file and word counts read correctly for one. File > New's unit names, which reach tr at run time, are translated too. The new test checks every pt-BR row's placeholders, padding and ellipsis, and that each menu path is made of the menu names. Docs: pt-BR re-measured at 2,416 of 2,419 strings (61% before) in localization-parity.md, gaps.md (gap 21), target-app-parity.md and the ROADMAP languages table and progress log. Readiness is unchanged. Co-Authored-By: Claude Opus 5.5 * Docs: trace each localization count to its commit; list Russian The 1,724 baseline was counted at a127c6d5 (#355); recounting that commit by the same rule gives 1,723, with pt-BR at the same 1,057. The 2,419 strings are main at 438d7b6d. The 2,021 figure is gone: it was the same rule at the last commit of 2026-10-10, not another scale. Russian (ru, 1,705 of 2,419) joins the other shipped languages, which makes six beyond the twelve; ROADMAP's two "Also shipped" lines become one that includes it. Co-Authored-By: Claude Opus 5.5 * pt-BR: the 12 strings main added since; docs re-measured at 2e36dcf9 Merging main brought window and guide commands, the InDesign shortcut-set import and the credits' PRs column, which pt-BR didn't translate yet. Its button label and result message reach tr as literals no other catalog has, so they join the shared test's list of UI strings. Re-measured at main 2e36dcf9: pt-BR translates 2,431 of 2,434 strings (the Control panel's IT, VA and Y: stay English) and the unit names; Russian 1,709 of 2,434. The PR adds 645 strings and 7 unit names. Co-Authored-By: Claude Opus 5.5 * Docs: pt-BR at 2,574 of 2,941 strings by i18n-report; Russian listed Re-measured on main f3bcc886 with `cargo xtask i18n-report`: pt-BR translates 2,574 of 2,941 interface strings (1,933 before); the 367 it lacks are mostly strings main added since 2026-10-23. pt-BR to full is 4-6 h. localization-parity.md, gaps.md (gap 21), target-app-parity.md and the ROADMAP languages table and progress log say so, each with its revision row; the ROADMAP entry is dated today, as the review asked. Russian (1,855 of 2,941) joins the other shipped languages, eight beyond the twelve, and ROADMAP's two "Also shipped" lines become one. Co-Authored-By: Claude Opus 5.5 * pt-BR: drop two rows main removed; the test lists eight live labels `cargo xtask i18n-report` flagged ten pt-BR rows whose keys its interface list lacks. "/1000 em" and "Import InDesign Set…" are gone from the code, so their rows go. The other eight still reach tr (Auto-Sizing, Color Theme, Minimum Height/Width, No Line Breaks, Reference Point, the shortcut-import result and the unavailable-fonts message) and join the test's list of UI strings. The report now counts 2,939 strings; pt-BR translates 2,572 of them (88%), Russian 1,853. The docs say so; the PR adds 632 strings and the 7 unit names. Co-Authored-By: Claude Opus 5.5 * pt-BR: the 364 strings main added since 2026-10-23 Keyboard Shortcuts sets (craft-keymap's dialog, import messages and counts), panel docking, OpenType features, page presets, the Package summary and the command dialog's parameter names. "Atalho", "conjunto" and "escopo" for shortcut, set and scope; tab groups stay "grupo de guias" and inks "de escala"/"especial", as in the catalog. Key names stay as printed on keyboards. `cargo xtask i18n-report` now lists only the Control panel's IT, VA and Y: for pt-BR: 2,936 of 2,939 strings. The docs say so; pt-BR to full is 1-2 h (an in-app check and the older parent-page and story terms). Co-Authored-By: Claude Opus 5.5 * pt-BR review fixes: Affix in, Dir, End, Pathfinder and three clashes; doc scales - "Affix in" (where footnote prefix and suffix appear) is "Afixos em". - "Dir" is a folder in file.save, recovery save and links.copyTo and a direction in text.move: "Pasta/direção". - The End key is "Fim", as Home is "Início". - Pathfinder keeps its name ("Objeto/Pathfinder"), as "Pathfinder:" already did, instead of "Localizador de caminhos" beside "demarcador". - Pattern (stroke dashes) is "Padrão de traço", apart from Default ("Padrão"); Skipped is "Pulados", apart from "ignoradas"; Heading is "Intertítulo", apart from Title and Section headings. ROADMAP's "Also shipped" line now uses one scale (today's i18n-report of 2,939 strings); the pt-BR note names main ef6c3686, and Russian reads 1,855 of 2,939. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- ROADMAP.md | 6 +- crates/ui-egui/src/i18n/pt_br.rs | 1066 +++++++++++++++++++++++++++- crates/ui-egui/src/i18n/tests.rs | 10 + crates/ui-egui/src/new_document.rs | 2 +- docs/gaps.md | 5 +- docs/localization-parity.md | 18 +- docs/target-app-parity.md | 5 +- 7 files changed, 1088 insertions(+), 24 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 81e87eea3..73c4a0532 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -352,15 +352,14 @@ A string without a translation shows in English and fails no check; `cargo xtask | Hindi | hi | none | 0% | | Arabic | ar | partial (RTL UI and composition) | 85% | | French | fr | partial | 83% | -| Portuguese (Brazil) | pt-br | partial | 61% | +| Portuguese (Brazil) | pt-br | partial | ~100% | | Indonesian | id | none | 0% | | Japanese | ja | partial | 95% | | German | de | partial | 83% | | Korean | ko | none | 0% | | Vietnamese | vi | none | 0% | -Also shipped: Czech (99%), Italian (85%), Ukrainian (83%), Polish (99%). -Also shipped: Italian (85%), Ukrainian (83%), Georgian (100%), Swedish (99%). +Also shipped (2026-11-04 `i18n-report`, of 2,939): Czech (69%), Italian (68%), Ukrainian (65%), Polish (64%), Georgian (98%), Swedish (98%), Hungarian (65%), Russian (63%). ## Upcoming @@ -402,6 +401,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. - **2026-11-06** · Preflight warns about white or [Paper] set to overprint (#2401): a fill, stroke or stroke gap, or ruby and kenten, in [Paper] or a colour that lays down no ink (C=0 M=0 Y=0 K=0, a 0% tint; a spot ink, such as a white ink or a varnish, prints whatever colour stands in for it), is reported as `whiteOverprint`, since it disappears on press. Text itself has no overprint, so white text in a frame set to Overprint Fill still knocks out and prints, and is not reported. Preflight no longer says PDF export drops ruby and kenten overprint, which it writes. No readiness percentage change. +- **2026-11-04** · Interface Language › Português (Brasil) translates the whole interface: 996 strings the catalog lacked (tool names, window and guide commands, Keyboard Shortcuts sets, panel docking, Edit › Menus paths, the Japanese typesetting dialogs, special characters, Load Styles, Data Merge, Preflight, font replacement, the Package summary, OpenType features, page presets, About) and File › New's unit names, and a path is "demarcador" throughout. `cargo xtask i18n-report` counts 2,936 of 2,939 strings for pt-BR (1,933 before); only the Control panel's `IT`, `VA` and `Y:` captions stay English, as in every language. No readiness percentage change. - **2026-11-03** · `type.char` says when the font it applies isn't available (#2189): it returns `{"warnings": ["Missing font: Courier Prime (using Source Sans 3)"]}`, or `Missing font style: …` for a style the family doesn't have, in preflight's words. The font is still applied, as before, so Find Font and preflight list it. A script that asked for a font the machine doesn't have exported in the substitute with no word about it. No readiness percentage change. - **2026-11-02** · Packaged PDFs report their export warnings in the package result and Instructions.txt, and soft drop shadows and feathers in them are tested. Frame and text-range hyperlinks keep their source bounds when the frame is rasterized, including inside groups. No readiness percentage change. - **2026-11-01** · Parent page resizing (#1620): Properties, the Page Tool Control panel and on-page handles resize the selected parent page independently of document pages. Stable parent IDs, repeated resizing, anchors and liquid rules are preserved on the current command modules. Inline parent margin editing targets only the selected parent page and preserves opposite-page margins and document overrides; document commands retain their first-page default before the canvas is initialized. No readiness percentage change. diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 65cbf07c3..34bdad4da 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -103,7 +103,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Added swatch", "Amostra adicionada"), ("Eyedropper: drag it onto the page", "Conta-gotas: arraste-o para a página"), ("PDF Preset:", "Predefinição de PDF:"), - ("Packaged {count} files into {dir}", "{count} arquivos empacotados em {dir}"), + ("Packaged {count} files into {dir}", "{count} arquivo(s) empacotado(s) em {dir}"), ("Continue", "Continuar"), ("Printing Instructions", "Instruções de impressão"), ("Package", "Empacotar"), @@ -409,7 +409,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Library", "Biblioteca"), ("Text Wrap", "Quebra de texto"), ("Align", "Alinhar"), - ("Pathfinder", "Localizador de caminhos"), + ("Pathfinder", "Pathfinder"), ("Transform Again", "Transformar novamente"), ("Interactive", "Interativo"), ("Buttons and Forms", "Botões e formulários"), @@ -811,7 +811,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Minus Back", "Subtrair plano de trás"), ("Make Compound", "Criar composto"), ("Release", "Liberar"), - ("Paths", "Caminhos"), + ("Paths", "Demarcadores"), ("Align left edges", "Alinhar bordas esquerdas"), ("Align horizontal centers", "Alinhar centros horizontais"), ("Align right edges", "Alinhar bordas direitas"), @@ -1293,7 +1293,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Pages:", "Páginas:"), ("Part of the ArtCraft suite of open creative tools.", "Parte do conjunto ArtCraft de ferramentas criativas abertas."), ("Pasteboard Options", "Opções da área de transferência"), - ("Path", "Caminho"), + ("Path", "Demarcador"), ("Place the insertion point in a table, or create one.", "Coloque o ponto de inserção em uma tabela ou crie uma."), ("Plain Text", "Texto simples"), ("Plays in EPUB export; print and PDF show the poster.", "Reproduz na exportação EPUB; impressão e PDF mostram o pôster."), @@ -1625,7 +1625,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Character Formatting", "Formatação de caracteres"), ("Clear Conveyor", "Limpar transportador"), ("Clear Transformations", "Limpar transformações"), - ("Clipping Path…", "Traçado de recorte…"), + ("Clipping Path…", "Demarcador de recorte…"), ("Close Book", "Fechar livro"), ("Close Library", "Fechar biblioteca"), ("Collect", "Coletar"), @@ -1724,7 +1724,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("List Styles", "Listar estilos"), ("List Tools", "Listar ferramentas"), ("Load Place Cursor", "Carregar cursor de inserção"), - ("Make Compound Path", "Criar traçado composto"), + ("Make Compound Path", "Criar demarcador composto"), ("Map Styles to Tags", "Mapear estilos para tags"), ("Math Expression SVG", "SVG de expressão matemática"), ("Media Options", "Opções de mídia"), @@ -1783,7 +1783,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Recover Documents", "Recuperar documentos"), ("Recovery Data", "Dados de recuperação"), ("Reject All Changes", "Rejeitar todas as alterações"), - ("Release Compound Path", "Liberar traçado composto"), + ("Release Compound Path", "Liberar demarcador composto"), ("Remove Document", "Remover documento"), ("Report an Issue…", "Relatar um problema…"), ("Reset Shortcuts", "Redefinir atalhos"), @@ -1823,7 +1823,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Show/Hide Text Threads", "Mostrar/ocultar encadeamentos de texto"), ("Sort", "Ordenar"), ("Split Note", "Dividir nota"), - ("Split Path", "Dividir traçado"), + ("Split Path", "Dividir demarcador"), ("Step and Repeat…", "Passo e repetição…"), ("Stroke Styles", "Estilos de traço"), ("Style Source", "Origem do estilo"), @@ -1841,8 +1841,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Transform Values", "Valores de transformação"), ("Transparency Blend Space", "Espaço de mesclagem de transparência"), ("Transparency Flattener Presets", "Predefinições de achatamento de transparência"), - ("Type on a Path", "Texto em um traçado"), - ("Type on a Path Options…", "Opções de texto em um traçado…"), + ("Type on a Path", "Texto no demarcador"), + ("Type on a Path Options…", "Opções de texto no demarcador…"), ("Typical Display", "Exibição típica"), ("Update Link", "Atualizar link"), ("User Dictionary Words", "Palavras do dicionário do usuário"), @@ -1873,7 +1873,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Convert to Liquid Guide", "Converter em guia líquida"), ("Convert to Object", "Converter em objeto"), ("Create Line", "Criar linha"), - ("Create Path", "Criar traçado"), + ("Create Path", "Criar demarcador"), ("Decrease Point Size", "Diminuir tamanho em pontos"), ("Delete Article", "Excluir artigo"), ("Delete Bookmark", "Excluir marcador"), @@ -1943,7 +1943,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Apply Attributes (Eyedropper", "Aplicar atributos (conta-gotas"), ("Captions", "Legendas"), ("Change All (Object", "Alterar tudo (objeto"), - ("Clipping Path", "Traçado de recorte"), + ("Clipping Path", "Demarcador de recorte"), ("Convert Cell Type", "Converter tipo de célula"), ("Copy Link(s", "Copiar link(s"), ("DesignCraft", "DesignCraft"), @@ -1991,4 +1991,1046 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Insert field", "Inserir campo"), ("Pass csv, rows, or bytes from the control channel.", "Passe csv, linhas ou bytes pelo canal de controle."), ("Panels", "Painéis"), + // Strings added to the interface since the catalog was completed (2026-10-15). + (" Save ", " Salvar "), + (" Update ", " Atualizar "), + ("% of all commits", "% de todos os commits"), + ("(any)", "(qualquer)"), + ("(unchanged)", "(inalterado)"), + ("1 Parent Character", "1 caractere base"), + ("1 Ruby Character", "1 caractere ruby"), + ("1 Ruby Character Aki", "Aki de 1 caractere ruby"), + ("1-2-1 (JIS) Rule", "Regra 1-2-1 (JIS)"), + ("1-2-1 Aki", "Aki 1-2-1"), + ("1/2 Parent Character", "1/2 caractere base"), + ("1/2 Ruby Character", "1/2 caractere ruby"), + ("90° CCW", "90° anti-horário"), + ("90° CW", "90° horário"), + ("A, B, C, D...", "A, B, C, D..."), + ("About", "Sobre"), + ("Above/Right", "Acima/direita"), + ("Absorb Ideographic Space at Line End", "Absorver espaço ideográfico no fim da linha"), + ("Across the Line:", "Perpendicular à linha:"), + ("Activate Panel", "Ativar painel"), + ("Add Anchor Point Tool", "Ferramenta Adicionar ponto de ancoragem"), + ("Add Tab", "Adicionar tabulação"), + ("Adjust Rotation", "Ajustar rotação"), + ("Adjust Tsume", "Ajustar tsume"), + ("Adjust page elements to document changes", "Ajustar os elementos da página às alterações do documento"), + ("Adjustment When Ruby Is Longer Than Parent", "Ajuste quando o ruby é mais longo que a base"), + ("Align Left Edge", "Alinhar borda esquerda"), + ("Align Only First Line to Grid", "Alinhar somente a primeira linha à grade"), + ("Align To", "Alinhar a"), + ("All Classes", "Todas as classes"), + ("All pages", "Todas as páginas"), + ("Along the Line:", "Ao longo da linha:"), + ("Alpha Channel", "Canal alfa"), + ("Alternate layout", "Layout alternativo"), + ("Anchored Object Options", "Opções de objeto ancorado"), + ("Apply Numbering & Section Options", "Aplicar opções de numeração e de seção"), + ("Apply Text Attributes (Eyedropper)", "Aplicar atributos de texto (conta-gotas)"), + ("Apply To:", "Aplicar a:"), + ( + "Apply the changes; objects follow the new page size and margins", + "Aplicar as alterações; os objetos acompanham o novo tamanho de página e as margens", + ), + ("Apply to:", "Aplicar a:"), + ("ArtCraft App Page", "Página do aplicativo ArtCraft"), + ("ArtCraft Website", "Site do ArtCraft"), + ("Auto Align at Line Start/End", "Alinhar automaticamente no início/fim da linha"), + ("Auto Rename", "Renomear automaticamente"), + ("Auto Tate-Chu-Yoko", "Tate-chu-yoko automático"), + ("Auto Tate-chu-yoko Settings", "Configurações de tate-chu-yoko automático"), + ("Auto-Size", "Dimensionamento automático"), + ("Auto-Sizing", "Dimensionamento automático"), + ("Automatic Chapter Numbering", "Numeração automática de capítulos"), + ("Automatic Page Numbering", "Numeração automática de páginas"), + ("Below/Left", "Abaixo/esquerda"), + ("Between Entry and Number:", "Entre a entrada e o número:"), + ("Binary assets added", "Arquivos binários adicionados"), + ("Binary assets removed", "Arquivos binários removidos"), + ("Black Circle", "Círculo preto"), + ("Black Triangle", "Triângulo preto"), + ("Blank Document Presets", "Predefinições de documento em branco"), + ("Bleed:", "Sangria:"), + ("Book Name:", "Nome do livro:"), + ("Both Sides", "Ambos os lados"), + ("Both pages of the parent spread", "Ambas as páginas da página dupla principal"), + ("Both pages of the spread", "Ambas as páginas da página dupla"), + ("Bounding Box (All Layers)", "Caixa delimitadora (todas as camadas)"), + ("Bounding Box (Visible Layers Only)", "Caixa delimitadora (somente camadas visíveis)"), + ("Break Thread", "Romper encadeamento"), + ("Bullet Character", "Caractere de marcador"), + ("Bullseye", "Alvo"), + ("Bunri-Kinshi", "Bunri-kinshi"), + ("CMYK:", "CMYK:"), + ("Cancel Preview", "Cancelar visualização"), + ("Cell Number:", "Número do celular:"), + ("Centered", "Centralizado"), + ("Change Panel Layout", "Alterar layout do painel"), + ("Change Tab", "Alterar tabulação"), + ("Change fill to:", "Alterar preenchimento para:"), + ("Character Style", "Estilo de caractere"), + ("Character:", "Caractere:"), + ("Characters After Break:", "Caracteres depois da quebra:"), + ("Characters Before Break:", "Caracteres antes da quebra:"), + ("Characters:", "Caracteres:"), + ("Check Spelling", "Verificar ortografia"), + ("Chinese: Simplified", "Chinês: simplificado"), + ("Chinese: Traditional", "Chinês: tradicional"), + ("Clear All Tabs", "Limpar todas as tabulações"), + ("Clear Object Style Overrides", "Limpar substituições de estilo de objeto"), + ("Clear Rotation", "Limpar rotação"), + ("Clipping Path Options…", "Opções de demarcador de recorte…"), + ("Close Panel", "Fechar painel"), + ("Closed Path", "Demarcador fechado"), + ( + "Collect objects with the Content Collector (B); place them with the Content Placer.", + "Colete objetos com o Coletor de conteúdo (B); insira-os com o Posicionador de conteúdo.", + ), + ("Color Blindness – Deuteranopia", "Daltonismo – deuteranopia"), + ("Color Blindness – Protanopia", "Daltonismo – protanopia"), + ("Color Theme", "Tema de cores"), + ("Color Theme Tool", "Ferramenta Tema de cores"), + ("Color Theme…", "Tema de cores…"), + ("Color font", "Fonte colorida"), + ("Column Break", "Quebra de coluna"), + ("Column Gutter", "Medianiz da coluna"), + ("Commit Preview", "Confirmar visualização"), + ("Commits", "Commits"), + ("Company", "Empresa"), + ("Conditional Text", "Texto condicional"), + ("Content Collector Tool", "Ferramenta Coletor de conteúdo"), + ("Content Placer Tool", "Ferramenta Posicionador de conteúdo"), + ("Contributors", "Colaboradores"), + ("Convert Direction Point Tool", "Ferramenta Converter ponto de direção"), + ("Convert Rows", "Converter linhas"), + ("Copyright Symbol", "Símbolo de copyright"), + ("Corner Options", "Opções de canto"), + ("Corner Size", "Tamanho do canto"), + ("Couldn't write recovery data: {error}", "Não foi possível gravar os dados de recuperação: {error}"), + ("Create Guides", "Criar guias"), + ("Create Links When Placing Text Files", "Criar vínculos ao inserir arquivos de texto"), + ("Currently Rendered With", "Renderizado atualmente com"), + ("Dark", "Escuro"), + ("Data Fields", "Campos de dados"), + ("Data Merge Options", "Opções de mesclagem de dados"), + ("Decorative", "Decorativa"), + ("Default Rules", "Regras padrão"), + ("Define Cross-Reference Format", "Definir formato de referência cruzada"), + ("Define Lists", "Definir listas"), + ("Define Text Variable", "Definir variável de texto"), + ("Delete Anchor Point Tool", "Ferramenta Excluir ponto de ancoragem"), + ("Delete Character Style", "Excluir estilo de caractere"), + ("Delete Character Style…", "Excluir estilo de caractere…"), + ("Delete Document Preset", "Excluir predefinição de documento"), + ("Delete Paragraph Style…", "Excluir estilo de parágrafo…"), + ("Delete Preset", "Excluir predefinição"), + ("Delete Type from Path", "Excluir texto do demarcador"), + ("Delete the character style \"{name}\"?", "Excluir o estilo de caractere \"{name}\"?"), + ("Delete the paragraph style \"{name}\"?", "Excluir o estilo de parágrafo \"{name}\"?"), + ("DesignCraft Website", "Site do DesignCraft"), + ("DesignCraft on GitHub", "DesignCraft no GitHub"), + ("DesignCraft page", "Página do DesignCraft"), + ("Detect Edges", "Detectar bordas"), + ("Differs from this document", "Difere deste documento"), + ("Digits:", "Dígitos:"), + ("Direct Selection Tool", "Ferramenta Seleção direta"), + ("Discretionary Hyphen", "Hífen opcional"), + ("Display name", "Nome de exibição"), + ("Distance from Parent:", "Distância da base:"), + ("Distribute Rows Evenly", "Distribuir linhas uniformemente"), + ("Document CMYK", "CMYK do documento"), + ("Document Chapter Numbering", "Numeração de capítulos do documento"), + ("Document Endnote Options", "Opções de notas de fim do documento"), + ("Document Footnote Options", "Opções de notas de rodapé do documento"), + ("Document Name", "Nome do documento"), + ("Document RGB", "RGB do documento"), + ("Don't Save", "Não salvar"), + ("Double Circle", "Círculo duplo"), + ("Double Left Quotation Marks", "Aspas duplas de abertura"), + ("Double Right Quotation Marks", "Aspas duplas de fechamento"), + ("Drag Rows or Columns", "Arrastar linhas ou colunas"), + ("Drop Caps", "Capitulares"), + ("Drop Chars", "Caracteres capitulares"), + ("Drop Lines", "Linhas capitulares"), + ("Edit/Interface Language", "Editar/Idioma da interface"), + ("Edit/Spelling", "Editar/Ortografia"), + ("Edit/Transparency Blend Space", "Editar/Espaço de mesclagem de transparência"), + ("Edit/Transparency Flattener Presets", "Editar/Predefinições de achatamento de transparência"), + ("Ellipse Frame Tool", "Ferramenta Quadro elíptico"), + ("Ellipse Tool", "Ferramenta Elipse"), + ("Ellipsis", "Reticências"), + ("Em Box Bottom/Left", "Base/esquerda do quadratim"), + ("Em Box Center", "Centro do quadratim"), + ("Em Box Center (Down)", "Centro do quadratim (abaixo)"), + ("Em Box Top/Right", "Topo/direita do quadratim"), + ("Em Dash", "Travessão"), + ("Email Address:", "Endereço de e-mail:"), + ("En Dash", "Meia-risca"), + ("Entry Style:", "Estilo da entrada:"), + ("Equal Aki", "Aki igual"), + ( + "Equal fixed heights for the selected rows; cell text may become overset.", + "Alturas fixas iguais para as linhas selecionadas; o texto das células pode ficar excedente.", + ), + ("Erase Tool", "Ferramenta Apagar"), + ("Even Page Break", "Quebra para página par"), + ("Export EPUB", "Exportar EPUB"), + ("Export EPUB (Fixed Layout)", "Exportar EPUB (layout fixo)"), + ("Export EPUB (Reflowable)", "Exportar EPUB (reflowable)"), + ("Export HTML", "Exportar HTML"), + ("Export IDML", "Exportar IDML"), + ("Export PDF (Interactive)", "Exportar PDF (interativo)"), + ("Export Page as PNG", "Exportar página como PNG"), + ("Export PowerPoint…", "Exportar PowerPoint…"), + ("Export Text", "Exportar texto"), + ("Export XML", "Exportar XML"), + ( + "Export a PDF, IDML or package to share — no cloud account needed.", + "Exporte um PDF, IDML ou pacote para compartilhar — sem precisar de conta na nuvem.", + ), + ("Extract Color Theme", "Extrair tema de cores"), + ("Eyedropper Tool", "Ferramenta Conta-gotas"), + ("Figure Space", "Espaço de algarismo"), + ("File/Export", "Arquivo/Exportar"), + ("Filters:", "Filtros:"), + ("Find fill:", "Localizar preenchimento:"), + ("First commit", "Primeiro commit"), + ("Fisheye", "Olho de peixe"), + ("Fit to Width", "Ajustar à largura"), + ("Flush Space", "Espaço de alinhamento"), + ("Force", "Forçar"), + ("Forced Line Break", "Quebra de linha forçada"), + ("Formatting Affects Text", "A formatação afeta o texto"), + ("Found", "Encontrado"), + ("Frame", "Quadro"), + ("Frame Break", "Quebra de quadro"), + ("Free Transform Tool", "Ferramenta Transformação livre"), + ("Full Justify", "Justificado total"), + ("GREP", "GREP"), + ("Gap Tool", "Ferramenta Espaço"), + ("Generate Index", "Gerar índice remissivo"), + ("Generate Live Caption", "Gerar legenda dinâmica"), + ("Georgian", "Georgiano"), + ("Get Cell Stroke", "Obter traçado da célula"), + ("Get Tabs", "Obter tabulações"), + ("Global Light", "Luz global"), + ("Grab bag", "Lista corrida"), + ("Gradient Feather Tool", "Ferramenta Esmaecimento em gradiente"), + ("Gradient Swatch Tool", "Ferramenta Amostra de gradiente"), + ("Graphic", "Gráfico"), + ("Grid Alignment:", "Alinhamento à grade:"), + ("Grid Settings", "Configurações de grade"), + ("Group Ruby", "Ruby de grupo"), + ("Group with", "Agrupar com"), + ("Gyoudori:", "Gyoudori:"), + ("Hair Space", "Espaço capilar"), + ("Hand Tool", "Ferramenta Mão"), + ("Hanging Type:", "Pontuação pendente:"), + ("Hard Kinsoku", "Kinsoku rígido"), + ("Hide Styles", "Ocultar estilos"), + ("High Contrast", "Alto contraste"), + ("High Resolution", "Alta resolução"), + ("I, II, III, IV...", "I, II, III, IV..."), + ("ICF Bottom", "Base do ICF"), + ("ICF Top", "Topo do ICF"), + ("Import Warnings", "Avisos de importação"), + ("Import XML", "Importar XML"), + ("Import cancelled: the originating document has closed", "Importação cancelada: o documento de origem foi fechado"), + ("Include Paragraph Styles:", "Incluir estilos de parágrafo:"), + ("Include Prefix when Numbering Pages", "Incluir prefixo ao numerar páginas"), + ("Include Roman Characters", "Incluir caracteres latinos"), + ("Indent to Here", "Recuar até aqui"), + ("Ink Limit 300%", "Limite de tinta 300%"), + ("Insert Anchored Object", "Inserir objeto ancorado"), + ("Insert Cross-Reference", "Inserir referência cruzada"), + ("Insert Field", "Inserir campo"), + ("Insert Math Expression", "Inserir expressão matemática"), + ("Internet Standard RGB (sRGB)", "RGB padrão da Internet (sRGB)"), + ("Invalid panel layout; restored the default dock", "Layout de painéis inválido; o encaixe padrão foi restaurado"), + ("Japanese Composition Settings", "Configurações de composição japonesa"), + ("Join the ArtCraft Discord", "Entrar no Discord do ArtCraft"), + ("Kenten Color", "Cor do kenten"), + ("Kenten Settings", "Configurações de kenten"), + ("Kenten Type:", "Tipo de kenten:"), + ("Kerning/Tracking Step", "Incremento de kerning/espaçamento"), + ("Kerning/Tracking:", "Kerning/espaçamento:"), + ("Key Object", "Objeto-chave"), + ("Kinsoku Set:", "Conjunto kinsoku:"), + ("Kinsoku Type:", "Tipo de kinsoku:"), + ("Korean Kinsoku", "Kinsoku coreano"), + ("Large Sample Text Size", "Tamanho de amostra grande"), + ("Last commit", "Último commit"), + ("Layout/Index", "Layout/Índice remissivo"), + ("Layout/Pages", "Layout/Páginas"), + ("Leading Model:", "Modelo de entrelinha:"), + ("Left/Right Position:", "Posição esquerda/direita:"), + ("Left/Top", "Esquerda/topo"), + ("Legacy Macintosh RGB", "RGB Macintosh antigo"), + ("Light", "Claro"), + ("Line Break Options", "Opções de quebra de linha"), + ("Line Spacing:", "Espaçamento entre linhas:"), + ("Line Tool", "Ferramenta Linha"), + ("Line delta", "Diferença de linhas"), + ("Lines +/−", "Linhas +/−"), + ("Lines added", "Linhas adicionadas"), + ("Lines deleted", "Linhas excluídas"), + ("Lines:", "Linhas:"), + ("List Composite Fonts", "Listar fontes compostas"), + ("List Styles in File", "Listar estilos do arquivo"), + ("Load All Text Styles…", "Carregar todos os estilos de texto…"), + ("Load Character Styles…", "Carregar estilos de caractere…"), + ("Load DTD", "Carregar DTD"), + ("Load Paragraph Styles…", "Carregar estilos de parágrafo…"), + ("Load Styles", "Carregar estilos"), + ("Load Styles…", "Carregar estilos…"), + ("Load Swatches", "Carregar amostras"), + ("Loading fonts…", "Carregando fontes…"), + ("Low Resolution", "Baixa resolução"), + ("Magnification:", "Ampliação:"), + ("Margins:", "Margens:"), + ("Measure Tool", "Ferramenta Medida"), + ("Medium Dark", "Médio-escuro"), + ("Medium Light", "Médio-claro"), + ("Medium Resolution", "Resolução média"), + ("Medium Sample Text Size", "Tamanho de amostra médio"), + ("Menus", "Menus"), + ("Merged PRs", "PRs mesclados"), + ("Message:", "Mensagem:"), + ("Minimum Height", "Altura mínima"), + ("Minimum Scale:", "Escala mínima:"), + ("Minimum Width", "Largura mínima"), + ("Models", "Modelos"), + ("Mojikumi Set:", "Conjunto mojikumi:"), + ("Monitor RGB", "RGB do monitor"), + ("Monospaced", "Monoespaçada"), + ("Move Pages", "Mover páginas"), + ("Move Panel", "Mover painel"), + ("Move Tab", "Mover tabulação"), + ("N/A", "N/D"), + ("Name (A–Z)", "Nome (A–Z)"), + ("New Cell Style", "Novo estilo de célula"), + ("New Condition", "Nova condição"), + ("New Hyperlink", "Novo hiperlink"), + ("New Hyperlink Destination", "Novo destino de hiperlink"), + ("New Page Reference", "Nova referência de página"), + ("New Stroke Style", "Novo estilo de traço"), + ("New Table Style", "Novo estilo de tabela"), + ("Next Page Number", "Número da próxima página"), + ("No Adjustment", "Sem ajuste"), + ("No Line Breaks", "Sem quebras de linha"), + ("No contributor data was built into this copy.", "Nenhum dado de colaboradores foi incluído nesta cópia."), + ("No fonts match", "Nenhuma fonte corresponde"), + ("No matches", "Nenhuma correspondência"), + ("No model credits were built into this copy.", "Nenhum crédito de modelos foi incluído nesta cópia."), + ("Nonbreaking Hyphen", "Hífen inseparável"), + ("Nonbreaking Space", "Espaço inseparável"), + ("None (keep transparency)", "Nenhum (manter transparência)"), + ("Note Tool", "Ferramenta Nota"), + ("Numbering & Section Options", "Opções de numeração e de seção"), + ("Object Style", "Estilo de objeto"), + ("Object Style Options…", "Opções de estilo de objeto…"), + ("Object/Anchored Object", "Objeto/Objeto ancorado"), + ("Object/Arrange", "Objeto/Organizar"), + ("Object/Captions", "Objeto/Legendas"), + ("Object/Clipping Path", "Objeto/Demarcador de recorte"), + ("Object/Content", "Objeto/Conteúdo"), + ("Object/Convert Shape", "Objeto/Converter forma"), + ("Object/Effects", "Objeto/Efeitos"), + ("Object/Fitting", "Objeto/Ajuste"), + ("Object/Pathfinder", "Objeto/Pathfinder"), + ("Object/Paths", "Objeto/Demarcadores"), + ("Object/Select", "Objeto/Selecionar"), + ("Object/Transform", "Objeto/Transformar"), + ("Object/Transform Again", "Objeto/Transformar novamente"), + ("Odd Page Break", "Quebra para página ímpar"), + ("Offset from Parent", "Deslocamento em relação à base"), + ("OpenType font", "Fonte OpenType"), + ("Optical Margin Alignment", "Alinhamento óptico de margem"), + ("Organization:", "Organização:"), + ("Other Styles:", "Outros estilos:"), + ("PDF import cancelled: the originating document has closed", "Importação de PDF cancelada: o documento de origem foi fechado"), + ("Page Break", "Quebra de página"), + ("Page Number:", "Número da página:"), + ("Page Options", "Opções de página"), + ("Page Size:", "Tamanho da página:"), + ("Page Tool", "Ferramenta Página"), + ("Paragraph Return", "Fim de parágrafo"), + ("Paragraph Style", "Estilo de parágrafo"), + ("Paragraph Symbol", "Símbolo de parágrafo"), + ("Parent Character Spacing:", "Espaçamento dos caracteres base:"), + ("Parent's Font", "Fonte da base"), + ("Pen Tool", "Ferramenta Caneta"), + ("Pencil Tool", "Ferramenta Lápis"), + ("Per-Character Ruby", "Ruby por caractere"), + ("Picas", "Paicas"), + ("Points", "Pontos"), + ("Inches", "Polegadas"), + ("Millimeters", "Milímetros"), + ("Centimeters", "Centímetros"), + ("Ciceros", "Cíceros"), + ("Agates", "Ágatas"), + ("Pixels", "Pixels"), + ("Pin Bar Position", "Fixar posição da barra"), + ("Place with Import Options", "Inserir com opções de importação"), + ("Polygon Frame Tool", "Ferramenta Quadro poligonal"), + ("Polygon Tool", "Ferramenta Polígono"), + ("Preflight", "Preflight"), + ("Preflight Panel…", "Painel Preflight…"), + ("Presentation", "Apresentação"), + ("Preset Details", "Detalhes da predefinição"), + ("Preset Name", "Nome da predefinição"), + ("Press keys…", "Pressione as teclas…"), + ("Preview Change", "Visualizar alteração"), + ("Preview Record", "Visualizar registro"), + ("Previous Page Number", "Número da página anterior"), + ("Print Booklet", "Imprimir folheto"), + ("Prioritize Adjustment Amount", "Priorizar a quantidade de ajuste"), + ("Punctuation Space", "Espaço de pontuação"), + ("Push In First", "Primeiro para dentro"), + ("Push Out First", "Primeiro para fora"), + ("Push Out Only", "Somente para fora"), + ("Quarter Space", "Espaço de um quarto"), + ("Quick Apply", "Aplicação rápida"), + ("RGB:", "RGB:"), + ("Range:", "Intervalo:"), + ("Real name", "Nome real"), + ("Recent", "Recentes"), + ("Recent Files", "Arquivos recentes"), + ("Rectangle Frame Tool", "Ferramenta Quadro retangular"), + ("Rectangle Tool", "Ferramenta Retângulo"), + ("Redefine Character Style", "Redefinir estilo de caractere"), + ("Redefine Document Style", "Redefinir estilo do documento"), + ("Redefine Paragraph Style", "Redefinir estilo de parágrafo"), + ("Reference Point", "Ponto de referência"), + ("Registered Trademark Symbol", "Símbolo de marca registrada"), + ("Relink", "Vincular novamente"), + ("Relink to Folder", "Vincular novamente à pasta"), + ("Relinked {count}", "Vinculados novamente: {count}"), + ("Reload Fonts", "Recarregar fontes"), + ("Remove Data Source", "Remover fonte de dados"), + ("Remove Existing Ruler Guides", "Remover guias de régua existentes"), + ("Remove Field", "Remover campo"), + ("Remove Frame from Thread", "Remover quadro do encadeamento"), + ("Remove »", "Remover »"), + ("Rensuuji", "Rensuuji"), + ("Reorder Objects", "Reordenar objetos"), + ("Replace All", "Substituir tudo"), + ( + "Replace All updates this font throughout text and styles. Done keeps remaining fallback fonts.", + "Substituir tudo atualiza esta fonte em todo o texto e estilos. Concluir mantém as fontes substitutas restantes.", + ), + ("Replace Existing Table of Contents", "Substituir sumário existente"), + ("Replace with:", "Substituir por:"), + ("Report an Issue", "Relatar um problema"), + ("Report an issue", "Relatar um problema"), + ("Reset Bar Position", "Redefinir posição da barra"), + ("Resize Row or Column", "Redimensionar linha ou coluna"), + ("Resize panel window", "Redimensionar janela do painel"), + ("Resize panels", "Redimensionar painéis"), + ("Reverse the order", "Inverter a ordem"), + ("Right/Bottom", "Direita/base"), + ("Roman Baseline", "Linha de base latina"), + ("Roman Word Break", "Quebra de palavras latinas"), + ("Rotate Roman Characters in Vertical Text", "Girar caracteres latinos no texto vertical"), + ("Rotate Tool", "Ferramenta Girar"), + ("Ruby Color", "Cor do ruby"), + ("Ruby Font and Size", "Fonte e tamanho do ruby"), + ("Ruby Overhang:", "Projeção do ruby:"), + ("Ruby Placement and Spacing", "Posição e espaçamento do ruby"), + ("Ruby Type:", "Tipo de ruby:"), + ("Ruler Zero Point", "Ponto zero da régua"), + ("Same as Previous Document in the Book", "Igual ao documento anterior do livro"), + ("Sample", "Amostra"), + ("Sans Serif", "Sem serifa"), + ("Save As", "Salvar como"), + ("Save Document Preset", "Salvar predefinição de documento"), + ("Save Document Preset As:", "Salvar predefinição de documento como:"), + ("Save Preset", "Salvar predefinição"), + ("Save Swatches for Exchange", "Salvar amostras para intercâmbio"), + ("Save a Copy", "Salvar uma cópia"), + ("Saved", "Salvas"), + ("Saved Presets", "Predefinições salvas"), + ("Scale Tool", "Ferramenta Escala"), + ("Scale for Descenders", "Escalar para descendentes"), + ("Scissors Tool", "Ferramenta Tesoura"), + ("Script", "Manuscrita"), + ("Scripts", "Scripts"), + ("Section Marker", "Marcador de seção"), + ("Section Marker:", "Marcador de seção:"), + ("Section Prefix:", "Prefixo da seção:"), + ("Section Symbol", "Símbolo de seção"), + ("Select Page", "Selecionar página"), + ("Select Paragraph", "Selecionar parágrafo"), + ("Select Sentence", "Selecionar frase"), + ("Select Story", "Selecionar artigo"), + ("Select Text Unit", "Selecionar unidade de texto"), + ( + "Select a placed video or sound (File › Place a .mp4, .mov, .mp3, .wav …).", + "Selecione um vídeo ou som inserido (Arquivo › Inserir um .mp4, .mov, .mp3, .wav …).", + ), + ("Select an object to color its fill or stroke.", "Selecione um objeto para colorir seu preenchimento ou traçado."), + ("Selected Text", "Texto selecionado"), + ("Selection Tool", "Ferramenta Seleção"), + ("Sent {count} page(s) to {printer}", "{count} página(s) enviada(s) para {printer}"), + ("Sentence case", "Primeira letra da frase em maiúscula"), + ("Serif", "Com serifa"), + ("Sesame Dot", "Ponto de gergelim"), + ("Set Composite Font", "Definir fonte composta"), + ("Set OpenType Features", "Definir recursos OpenType"), + ("Shatai", "Shatai"), + ("Shear Tool", "Ferramenta Distorcer"), + ("Show Recently Added", "Mostrar adicionadas recentemente"), + ("Show Similar Fonts", "Mostrar fontes semelhantes"), + ("Show Styles", "Mostrar estilos"), + ("Show the Typography panel", "Mostrar o painel Tipografia"), + ("Show/Hide Document Grid", "Mostrar/ocultar grade do documento"), + ("Shrink Ruby Width Automatically", "Reduzir automaticamente a largura do ruby"), + ("Similar to {family}", "Semelhantes a {family}"), + ("Simplified Chinese Kinsoku", "Kinsoku de chinês simplificado"), + ("Simulate Paper Color", "Simular cor do papel"), + ("Single Left Quotation Mark", "Aspa simples de abertura"), + ("Single Right Quotation Mark", "Aspa simples de fechamento"), + ("Sixth Space", "Espaço de um sexto"), + ("Slab Serif", "Serifa quadrada"), + ("Slug:", "Área de informações:"), + ("Small Black Circle", "Círculo preto pequeno"), + ("Small Sample Text Size", "Tamanho de amostra pequeno"), + ("Small White Circle", "Círculo branco pequeno"), + ("Smart Guide Options", "Opções de guias inteligentes"), + ("Smooth Tool", "Ferramenta Suavizar"), + ("Soft Kinsoku", "Kinsoku flexível"), + ("Sort Entries in Alphabetical Order", "Classificar entradas em ordem alfabética"), + ("Start #", "Nº inicial"), + ("Start Chapter Numbering at:", "Iniciar numeração de capítulos em:"), + ("Start Page Numbering at:", "Iniciar numeração de páginas em:"), + ("Start Section", "Iniciar seção"), + ("Step and Repeat", "Passo e repetição"), + ("Stop Preview", "Parar visualização"), + ("Story Column Direction", "Direção das colunas do artigo"), + ("Story Editor — {count} words", "Editor de artigo — {count} palavra(s)"), + ("Story {story} ← story {parent}", "Artigo {story} ← artigo {parent}"), + ("Straight Double Quotation Marks", "Aspas duplas retas"), + ("Straight Single Quotation Mark (Apostrophe)", "Aspa simples reta (apóstrofo)"), + ("Stroke Behind Fill", "Traçado atrás do preenchimento"), + ("Stroke Weight", "Peso do traçado"), + ("Styles in Table of Contents", "Estilos no sumário"), + ("Stylistic Set", "Conjunto estilístico"), + ("Subject:", "Assunto:"), + ("Subscript:", "Subscrito:"), + ("Superscript:", "Sobrescrito:"), + ("Swap Text Fill and Stroke", "Alternar preenchimento e traçado do texto"), + ("Symbol", "Símbolo"), + ("Table of Contents", "Sumário"), + ("Table/Convert Cell Type", "Tabela/Converter tipo de célula"), + ("Table/Delete", "Tabela/Excluir"), + ("Table/Insert", "Tabela/Inserir"), + ("Table/Select", "Tabela/Selecionar"), + ("Tate-chu-yoko Digits:", "Dígitos de tate-chu-yoko:"), + ("Tate-chu-yoko Settings", "Configurações de tate-chu-yoko"), + ("Text Anchor", "Âncora de texto"), + ("Text Color", "Cor do texto"), + ("Text:", "Texto:"), + ("The selected fonts have no OpenType features.", "As fontes selecionadas não têm recursos OpenType."), + ("Thin Space", "Espaço fino"), + ("Third Space", "Espaço de um terço"), + ( + "This document uses unavailable fonts. Choose replacements, or select Done to continue with fallback fonts.", + "Este documento usa fontes indisponíveis. Escolha outras fontes ou selecione Concluir para continuar com as fontes substitutas.", + ), + ("This page", "Esta página"), + ("This page is", "Esta página é"), + ( + "This story was edited in the layout: you'll be asked before those edits are replaced", + "Este artigo foi editado no layout: você será consultado antes que essas edições sejam substituídas", + ), + ("This style is in use. Text using it will be reassigned to:", "Este estilo está em uso. O texto que o usa será reatribuído a:"), + ("Thread Text Frames", "Encadear quadros de texto"), + ("Title Case", "Iniciais Maiúsculas"), + ("Title:", "Título:"), + ("To Body", "Para o corpo"), + ("To Footer", "Para o rodapé"), + ("To Header", "Para o cabeçalho"), + ("Trademark Symbol", "Símbolo de marca comercial"), + ("Traditional Chinese Kinsoku", "Kinsoku de chinês tradicional"), + ("Transform Again Individually", "Transformar novamente individualmente"), + ("Transform Sequence Again", "Transformar sequência novamente"), + ("Transform Sequence Again Individually", "Transformar sequência novamente individualmente"), + ("TrueType font", "Fonte TrueType"), + ("Type Tool", "Ferramenta Texto"), + ( + "Type a word with ~ at each allowed break (ex~am~ple); without ~ the word is never hyphenated.", + "Digite uma palavra com ~ em cada quebra permitida (ex~em~plo); sem ~ a palavra nunca é hifenizada.", + ), + ("Type on a Path Options", "Opções de texto no demarcador"), + ("Type on a Path Tool", "Ferramenta Texto no demarcador"), + ("Type/Bulleted and Numbered Lists", "Tipo/Listas com marcadores e numeradas"), + ("Type/Change Case", "Tipo/Alterar maiúsculas/minúsculas"), + ("Type/Hyperlinks & Cross-References", "Tipo/Hiperlinks e referências cruzadas"), + ("Type/Insert Break Character", "Tipo/Inserir caractere de quebra"), + ("Type/Insert Special Character/Hyphens and Dashes", "Tipo/Inserir caractere especial/Hifens e travessões"), + ("Type/Insert Special Character/Markers", "Tipo/Inserir caractere especial/Marcadores"), + ("Type/Insert Special Character/Other", "Tipo/Inserir caractere especial/Outros"), + ("Type/Insert Special Character/Quotation Marks", "Tipo/Inserir caractere especial/Aspas"), + ("Type/Insert Special Character/Symbols", "Tipo/Inserir caractere especial/Símbolos"), + ("Type/Insert White Space", "Tipo/Inserir espaço"), + ("Type/Proof Setup", "Tipo/Configuração de prova"), + ("Type/Rotate Spread", "Tipo/Girar spread"), + ("Type/Separations Preview", "Tipo/Visualização de separações"), + ("Type/Story Direction", "Tipo/Direção do texto"), + ("Type/Text Variables", "Tipo/Variáveis de texto"), + ("Type/Track Changes", "Tipo/Controlar alterações"), + ("Type/Type on a Path", "Tipo/Texto no demarcador"), + ("URL:", "URL:"), + ("Unassigned", "Não atribuído"), + ("Unlimited", "Ilimitado"), + ("Unsaved Changes", "Alterações não salvas"), + ("Up/Down Position:", "Posição acima/abaixo:"), + ("Update Data Source", "Atualizar fonte de dados"), + ("Use Document Style Definition", "Usar a definição de estilo do documento"), + ("Use OpenType Pro Ruby Glyphs", "Usar glifos ruby do OpenType Pro"), + ("Use Paragraph Gyoudori", "Usar gyoudori do parágrafo"), + ("Username", "Nome de usuário"), + ("Validate from Root Element", "Validar a partir do elemento raiz"), + ("Variable font", "Fonte variável"), + ("Vertical Type Tool", "Ferramenta Texto vertical"), + ("Vertical Type on a Path Tool", "Ferramenta Texto vertical no demarcador"), + ("View/Display Performance", "Exibir/Desempenho de exibição"), + ("View/Extras", "Exibir/Extras"), + ("View/Grids & Guides", "Exibir/Grades e guias"), + ("View/Proof Setup", "Exibir/Configuração de prova"), + ("View/Rotate Spread", "Exibir/Girar spread"), + ("View/Screen Mode", "Exibir/Modo de tela"), + ("View/Separations Preview", "Exibir/Visualização de separações"), + ("View/Structure", "Exibir/Estrutura"), + ("Warichu", "Warichu"), + ("Warichu Settings", "Configurações de warichu"), + ("Warichu Size:", "Tamanho do warichu:"), + ("White Circle", "Círculo branco"), + ("White Sesame Dot", "Ponto de gergelim branco"), + ("White Triangle", "Triângulo branco"), + ("Window/Arrange", "Janela/Organizar"), + ("Window/Interactive", "Janela/Interativo"), + ("Window/Interface Color Theme", "Janela/Tema de cores da interface"), + ("Window/Output", "Janela/Saída"), + ("Window/Panels", "Janela/Painéis"), + ("Window/Type & Tables", "Janela/Texto e tabelas"), + ("Window/Utilities", "Janela/Utilitários"), + ("Working CMYK", "CMYK de trabalho"), + ("Your Recent Items", "Seus itens recentes"), + ("Zoom Tool", "Ferramenta Zoom"), + ("[No Language]", "[Nenhum idioma]"), + ("a, b, c, d...", "a, b, c, d..."), + ("dropcap", "capitular"), + ("i, ii, iii, iv...", "i, ii, iii, iv..."), + ("image editing", "edição de imagens"), + ("layer", "camada"), + ("layers", "camadas"), + ("lowercase", "minúsculas"), + ("motion graphics and visual effects", "motion graphics e efeitos visuais"), + ("photo library and raw development", "biblioteca de fotos e revelação raw"), + ("reading, organizing and protecting PDFs", "leitura, organização e proteção de PDFs"), + ("the default printer", "a impressora padrão"), + ("vector illustration", "ilustração vetorial"), + ("video editing, color and sound", "edição de vídeo, cor e som"), + ("{contributors} contributors · {commits} commits", "{contributors} colaboradores · {commits} commits"), + ("{count} conflict(s): {names}", "{count} conflito(s): {names}"), + ("{count} match(es)", "{count} correspondência(s)"), + ("{count} replacement(s) made", "{count} substituição(ões) feita(s)"), + ("{label}: {name} (double-click: Color Picker)", "{label}: {name} (clique duplo: Seletor de cores)"), + ( + "{name}: import cancelled while a dialog is open; choose the file again", + "{name}: importação cancelada enquanto uma caixa de diálogo estava aberta; escolha o arquivo novamente", + ), + ("{name}: {count} step(s) done", "{name}: {count} etapa(s) concluída(s)"), + ("« Add", "« Adicionar"), + ( + "“{}” has been edited in this layout. Updating replaces those edits with the text from the file.", + "“{}” foi editado neste layout. A atualização substitui essas edições pelo texto do arquivo.", + ), + ("“{}” has changes that are not saved. Save them before closing?", "“{}” tem alterações não salvas. Salvá-las antes de fechar?"), + ("Close Window", "Fechar janela"), + ("Deselect Guides", "Desmarcar guias"), + ("Import InDesign Shortcut Set", "Importar conjunto de atalhos do InDesign"), + ( + "Imported {count} shortcuts from “{set}”; {unmatched} items not matched, {unreadable} unreadable.", + "{count} atalho(s) importado(s) de “{set}”; {unmatched} item(ns) sem correspondência, {unreadable} ilegível(is).", + ), + ("Maximize/Restore Window", "Maximizar/restaurar janela"), + ("Minimize Window", "Minimizar janela"), + ("Move Guides", "Mover guias"), + ("Move Window", "Mover janela"), + ("PRs", "PRs"), + ("Resize Window", "Redimensionar janela"), + ("Select Guide", "Selecionar guia"), + // Strings main added from 2026-10-23 to 2026-11-04 (Keyboard Shortcuts sets, panel docking, + // OpenType features, page presets, the Package summary, command parameter names). + ("(cycles)", "(alterna)"), + ("(modified)", "(modificado)"), + ("+Bin", "+Bin"), + ("+LOC", "+LOC"), + ("180°", "180°"), + ("A command can have at most {n} shortcuts", "Um comando pode ter no máximo {n} atalhos"), + ("A set with this name exists", "Já existe um conjunto com este nome"), + ("Action", "Ação"), + ("Add a shortcut to {label}", "Adicionar um atalho a {label}"), + ("Adjust layout", "Ajustar layout"), + ("Advance seconds", "Segundos para avançar"), + ("Affix in", "Afixos em"), + ("All Commands", "Todos os comandos"), + ("All Inks", "Todas as tintas"), + ("Allow", "Permitir"), + ("Also used by {label}", "Também usado por {label}"), + ("Alt", "Alt"), + ("Anchor", "Âncora"), + ("Application", "Aplicativo"), + ("Approximated", "Aproximado"), + ("Artifact", "Artefato"), + ("Asset", "Recurso"), + ("Assets", "Recursos"), + ("Assign", "Atribuir"), + ("Assign to Selected", "Atribuir ao selecionado"), + ("Assign {chord} to {label}", "Atribuir {chord} a {label}"), + ("At end", "No final"), + ("Attrs", "Atributos"), + ("Author", "Autor"), + ("Auto fit", "Ajuste automático"), + ("Auto size", "Dimensionamento automático"), + ("Auto size reference", "Referência do dimensionamento automático"), + ("Auto-Collapse Iconic Panels", "Recolher automaticamente painéis em ícones"), + ("Axis", "Eixo"), + ("Bands", "Faixas"), + ("Based on:", "Baseado em:"), + ("Bookmarks panel", "Painel Indicadores"), + ("Built-in sets cannot be changed", "Conjuntos integrados não podem ser alterados"), + ("Cancel Import", "Cancelar importação"), + ("Cancel the new shortcut", "Cancelar o novo atalho"), + ("Caps Lock", "Caps Lock"), + ("Case", "Caixa"), + ("Changed", "Alterado"), + ("Check for Updates…", "Verificar atualizações…"), + ("Choose a command…", "Escolher um comando…"), + ("Click a key to see its shortcuts", "Clique em uma tecla para ver seus atalhos"), + ("Close Other Panels in Group", "Fechar outros painéis do grupo"), + ("Close panel window", "Fechar janela do painel"), + ("Colors and Inks: {process} process, {spot} spot", "Cores e tintas: {process} de escala, {spot} especiais"), + ("Column gutter", "Medianiz da coluna"), + ("Column width", "Largura da coluna"), + ("Columns kind", "Tipo de colunas"), + ("Command", "Comando"), + ("Command for {item}", "Comando para {item}"), + ("Commands", "Comandos"), + ("Conflicts", "Conflitos"), + ("Context:", "Contexto:"), + ("Continue across stories", "Continuar entre artigos"), + ("Copies", "Cópias"), + ("Copy Report", "Copiar relatório"), + ("Corners", "Cantos"), + ("Cover image", "Imagem de capa"), + ("Ctrl", "Ctrl"), + ("Current shortcuts", "Atalhos atuais"), + ("Current shortcuts:", "Atalhos atuais:"), + ("Currently assigned to:", "Atribuído atualmente a:"), + ("Default: {chord}", "Padrão: {chord}"), + ("Definition", "Definição"), + ("Delete Points", "Excluir pontos"), + ("Delete Surrounding Text", "Excluir texto ao redor"), + ("Delete the set “{set}”?", "Excluir o conjunto “{set}”?"), + ("Detail pane size", "Tamanho do painel de detalhes"), + ("Dir", "Pasta/direção"), + ("Dry run", "Simulação"), + ("EPUB Split Document", "Dividir documento EPUB"), + ("Embed fonts", "Embutir fontes"), + ("Embedded images: {embedded}", "Imagens embutidas: {embedded}"), + ("End", "Fim"), + ("Expand", "Expandir"), + ("Expand Panels", "Expandir painéis"), + ("Export…", "Exportar…"), + ("Extension", "Extensão"), + ("Facing pages", "Páginas frente a frente"), + ("Family", "Família"), + ("File Info", "Informações do arquivo"), + ("File Info…", "Informações do arquivo…"), + ("Filter:", "Filtro:"), + ("First baseline", "Primeira linha de base"), + ("First baseline min", "Mín. da primeira linha de base"), + ("Fit to", "Ajustar a"), + ("Fixed Keys", "Teclas fixas"), + ("Fixed layout", "Layout fixo"), + ("Flatten", "Achatar"), + ("Float Tab Group", "Flutuar grupo de guias"), + ("Font size", "Tamanho da fonte"), + ("Fonts: {used} in use, {missing} unavailable", "Fontes: {used} em uso, {missing} indisponíveis"), + ("Format", "Formato"), + ("From", "De"), + ("Full screen", "Tela cheia"), + ("Go to Conflict", "Ir para o conflito"), + ("Grep", "GREP"), + ("Group Tab Group with", "Agrupar grupo de guias com"), + ("Heading", "Intertítulo"), + ("Heading style", "Estilo de intertítulo"), + ("Hidden", "Oculto"), + ("Historical Forms", "Formas históricas"), + ("Horizontal Kana", "Kana horizontal"), + ("Identifier", "Identificador"), + ("Idml", "IDML"), + ("Ids", "IDs"), + ("Import", "Importar"), + ("Import as New Set", "Importar como novo conjunto"), + ("Import “{set}”", "Importar “{set}”"), + ("Imported", "Importado"), + ("Imported as “{set}”", "Importado como “{set}”"), + ("Import…", "Importar…"), + ("Include inside edges", "Incluir bordas internas"), + ("Include prefix", "Incluir prefixo"), + ("Instructions", "Instruções"), + ("Intent", "Finalidade"), + ("Justification Alternates", "Alternativas de justificação"), + ("Keep Both", "Manter ambos"), + ("Keep within column", "Manter dentro da coluna"), + ("Key: {key}", "Tecla: {key}"), + ("Keyboard", "Teclado"), + ("Keyboard Shortcuts (JSON)", "Atalhos de teclado (JSON)"), + ("Keyboard: US", "Teclado: EUA"), + ("Keyboard: US (macOS)", "Teclado: EUA (macOS)"), + ("Kind", "Tipo"), + ("Label", "Rótulo"), + ("Latex", "LaTeX"), + ("Layout page", "Página de layout"), + ("Legal", "Legal"), + ("Letter", "Carta"), + ("Letter - Half", "Carta - metade"), + ("Line breaks", "Quebras de linha"), + ( + "Links and Images: {found} linked, {modified} changed, {missing} not found", + "Links e imagens: {found} vinculados, {modified} alterados, {missing} não encontrados", + ), + ("Load cursor", "Cursor carregado"), + ("Localized Forms", "Formas localizadas"), + ("Lock Workspace", "Bloquear área de trabalho"), + ("Mark Positioning", "Posicionamento de marcas"), + ("Marker", "Marcador"), + ("Marks", "Marcas"), + ("Matched without change", "Correspondido sem alteração"), + ("Maximize Frame", "Maximizar painel"), + ("Message", "Mensagem"), + ("Minimum height", "Altura mínima"), + ("Minimum width", "Largura mínima"), + ("Missing only", "Somente ausentes"), + ("Mobile 1080 × 1920", "Celular 1080 × 1920"), + ("Mobile 390 × 844", "Celular 390 × 844"), + ("Mode", "Modo"), + ("Modifier on", "Modificador em"), + ("More", "Mais"), + ("Move Panel to New Window", "Mover painel para nova janela"), + ("Move panel column", "Mover coluna de painéis"), + ("Move panel window", "Mover janela do painel"), + ("Move tab group", "Mover grupo de guias"), + ("New Set…", "Novo conjunto…"), + ("New shortcut:", "Novo atalho:"), + ("New shortcut: {chord}", "Novo atalho: {chord}"), + ("Not assigned", "Não atribuído"), + ("Not changed", "Não alterado"), + ("Not matched", "Sem correspondência"), + ("Nothing uses this key", "Nada usa esta tecla"), + ("Now used by {label}", "Agora usado por {label}"), + ("Number", "Número"), + ("Object point", "Ponto do objeto"), + ("Object/Convert Point", "Objeto/Converter ponto"), + ("Optical Margin Size", "Tamanho da margem óptica"), + ("Option", "Option"), + ("Org", "Origem"), + ("PDF/X-1a:2003", "PDF/X-1a:2003"), + ("Page break before", "Quebra de página antes"), + ("Page layout", "Layout da página"), + ("Panel or context", "Painel ou contexto"), + ("Para style", "Estilo de parágrafo"), + ("Paragraphs", "Parágrafos"), + ("Parent", "Página principal"), + ("Parent Page Size", "Tamanho da página principal"), + ("Pattern", "Padrão de traço"), + ("Pdf", "PDF"), + ("Pdf crop", "Corte do PDF"), + ("Pdf page", "Página do PDF"), + ("Phone", "Telefone"), + ("Pos", "Pos."), + ("Postcard", "Cartão-postal"), + ("Prefix", "Prefixo"), + ("Primary text frame", "Quadro de texto principal"), + ("Printer", "Impressora"), + ("Proportional Metrics", "Métricas proporcionais"), + ("Rasterize", "Rasterizar"), + ("Rect", "Retângulo"), + ("Redefine styles", "Redefinir estilos"), + ("Ref", "Ref."), + ("Ref char style", "Estilo de caractere da ref."), + ("Ref position", "Posição da ref."), + ("Remove existing", "Remover existentes"), + ("Remove {chord} from {label}", "Remover {chord} de {label}"), + ("Rename…", "Renomear…"), + ("Reset All", "Redefinir tudo"), + ("Reset All…", "Redefinir tudo…"), + ("Restart", "Reiniciar"), + ("Restore Frame Size", "Restaurar tamanho do painel"), + ("Restore every default shortcut in this set?", "Restaurar todos os atalhos padrão deste conjunto?"), + ("Restore the default for {label}", "Restaurar o padrão de {label}"), + ("Revert Set", "Reverter conjunto"), + ("Roman Italics", "Itálico romano"), + ("Row gutter", "Medianiz entre linhas"), + ("Rule", "Linha"), + ("Run in", "Em sequência"), + ("Save changes to “{set}”?", "Salvar as alterações em “{set}”?"), + ("Scope", "Escopo"), + ("Search by key", "Pesquisar por tecla"), + ("Section headings", "Títulos de seção"), + ("Select Parent Page", "Selecionar página principal"), + ("Select a command first", "Selecione um comando primeiro"), + ("Select a command to see and change its shortcuts", "Selecione um comando para ver e alterar seus atalhos"), + ("Separator", "Separador"), + ("Set name:", "Nome do conjunto:"), + ("Set:", "Conjunto:"), + ("Shape", "Forma"), + ("Shift", "Shift"), + ("Shortcut", "Atalho"), + ("Shortcut Sets", "Conjuntos de atalhos"), + ("Show:", "Mostrar:"), + ("Skipped", "Pulados"), + ("Space", "Espaço"), + ("Space after", "Espaço depois"), + ("Space before", "Espaço antes"), + ("Space between", "Espaço entre"), + ("Span columns", "Abranger colunas"), + ("Start", "Início"), + ("Start at", "Começar em"), + ("Start number", "Número inicial"), + ("Start page", "Página inicial"), + ("Story Options", "Opções de artigo"), + ("Stylistic Alternates", "Alternativas estilísticas"), + ("Subject", "Assunto"), + ("Subpath", "Subdemarcador"), + ("Suffix", "Sufixo"), + ("Suggestions", "Sugestões"), + ("Suggestions ({n})", "Sugestões ({n})"), + ("Summarize…", "Resumir…"), + ("Super", "Super"), + ("Tablet 1024 × 1366", "Tablet 1024 × 1366"), + ("Tabloid", "Tabloide"), + ("Tagged", "Com tags"), + ("Take It", "Usar este"), + ("Take It and Go to Conflict", "Usar este e ir para o conflito"), + ("Taken from other commands", "Retirados de outros comandos"), + ("Target", "Destino"), + ("The file is too large", "O arquivo é grande demais"), + ("The name is empty, too long or has control characters", "O nome está vazio, é longo demais ou contém caracteres de controle"), + ("The scope {scope} is unknown", "O escopo {scope} é desconhecido"), + ("The set was not found", "O conjunto não foi encontrado"), + ("There are too many sets", "Há conjuntos demais"), + ("This command is unknown", "Este comando é desconhecido"), + ("This file is from a newer version (format {n})", "Este arquivo é de uma versão mais recente (formato {n})"), + ("This is not a craft-keymap file", "Este não é um arquivo craft-keymap"), + ("This is not a shortcut set file", "Este não é um arquivo de conjunto de atalhos"), + ("Threshold", "Limiar"), + ("Title", "Título"), + ("To family", "Para a família"), + ("To spread", "Para a página dupla"), + ("To style", "Para o estilo"), + ("Toc title", "Título do sumário"), + ("Toggle Text and Cell Selection", "Alternar seleção de texto e de célula"), + ("Tolerance", "Tolerância"), + ("Too many shortcuts are assigned", "Há atalhos demais atribuídos"), + ("Tools", "Ferramentas"), + ("Topics", "Tópicos"), + ("Transparency Flattener", "Achatamento de transparência"), + ("Type…", "Tipo…"), + ("Unreadable", "Ilegível"), + ("Url", "URL"), + ("Use", "Usar"), + ("Use Default", "Usar padrão"), + ("Use minimum height", "Usar altura mínima"), + ("Use minimum width", "Usar largura mínima"), + ("Value", "Valor"), + ("Visible", "Visível"), + ("Web 1024 × 768", "Web 1024 × 768"), + ("Web 1366 × 768", "Web 1366 × 768"), + ("Web 1920 × 1080", "Web 1920 × 1080"), + ("Will change", "Será alterado"), + ("Win", "Win"), + ("With Shortcut", "Com atalho"), + ("Word", "Palavra"), + ("X offset", "Deslocamento X"), + ("X relative", "X relativo a"), + ("Y offset", "Deslocamento Y"), + ("empty shortcut", "atalho vazio"), + ("in a context that is not imported", "em um contexto que não é importado"), + ("key sequences are not supported", "sequências de teclas não são suportadas"), + ("line {n}", "linha {n}"), + ("modifier {key} given twice", "modificador {key} informado duas vezes"), + ("more than one command fits", "mais de um comando corresponde"), + ("no command has this name", "nenhum comando tem este nome"), + ("numeric keypad key read as main key", "tecla do teclado numérico lida como tecla principal"), + ("only a command of the other kind fits (tool or menu command)", "só corresponde um comando do outro tipo (ferramenta ou comando de menu)"), + ("press keys", "pressione as teclas"), + ("reserved by the system", "reservado pelo sistema"), + ("taken by a later entry", "ocupado por uma entrada posterior"), + ("taken by {label}", "ocupado por {label}"), + ("the scope is unknown", "o escopo é desconhecido"), + ("the scope name is not valid", "o nome do escopo não é válido"), + ("the set's shortcuts could not be added", "os atalhos do conjunto não puderam ser adicionados"), + ("the shortcut has no key", "o atalho não tem tecla"), + ("the shortcut is too long", "o atalho é longo demais"), + ("the shortcuts could not be removed", "os atalhos não puderam ser removidos"), + ("unknown key {key}", "tecla desconhecida {key}"), + ("unknown modifier {key}", "modificador desconhecido {key}"), + ("unsupported modifier {key}", "modificador não suportado {key}"), + ("{chord} (Default)", "{chord} (padrão)"), + ("{chord} (press again for a double press)", "{chord} (pressione de novo para um toque duplo)"), + ("{chord} ({scope})", "{chord} ({scope})"), + ("{chord} is reserved by the system", "{chord} é reservado pelo sistema"), + ("{chord} was removed from {label}", "{chord} foi removido de {label}"), + ("{chord}: {label}", "{chord}: {label}"), + ("{key}: listed more than once", "{key}: listado mais de uma vez"), + ("{key}: no command has this name", "{key}: nenhum comando tem este nome"), + ("{key}: part of the entry was dropped", "{key}: parte da entrada foi descartada"), + ("{key}: the scope in “{text}” is unknown", "{key}: o escopo em “{text}” é desconhecido"), + ("{key}: {text} is reserved by the system", "{key}: {text} é reservado pelo sistema"), + ("{key}: “{text}” is not a shortcut ({error})", "{key}: “{text}” não é um atalho ({error})"), + ("{label} (Changed)", "{label} (alterado)"), + ("{label} (cycles)", "{label} (alterna)"), + ("{label} ({scope})", "{label} ({scope})"), + ("{label} ({scope}, both work)", "{label} ({scope}, ambos funcionam)"), + ("{label} keeps its shortcuts (matched by a panel menu name)", "{label} mantém seus atalhos (correspondido pelo nome de um menu de painel)"), + ("{label}: press keys", "{label}: pressione as teclas"), + ("{label}: {chord}", "{label}: {chord}"), + ("{label}: {chord} (Now used by {holder})", "{label}: {chord} (agora usado por {holder})"), + ("{menu} Menu", "Menu {menu}"), + ("{n} command changed", "{n} comando alterado"), + ("{n} command will change", "{n} comando será alterado"), + ("{n} commands changed", "{n} comandos alterados"), + ("{n} commands will change", "{n} comandos serão alterados"), + ("{n} entries cut at a limit", "{n} entradas cortadas em um limite"), + ("{n} entries were ignored: too many commands", "{n} entradas foram ignoradas: comandos demais"), + ("{n} entry cut at a limit", "{n} entrada cortada em um limite"), + ("{n} entry was ignored: too many commands", "{n} entrada foi ignorada: comandos demais"), + ("{n} item could not be read", "{n} item não pôde ser lido"), + ("{n} item not matched", "{n} item sem correspondência"), + ("{n} item without a shortcut", "{n} item sem atalho"), + ("{n} items could not be read", "{n} itens não puderam ser lidos"), + ("{n} items not matched", "{n} itens sem correspondência"), + ("{n} items without a shortcut", "{n} itens sem atalho"), + ("{n} key read approximately", "{n} tecla lida aproximadamente"), + ("{n} keys read approximately", "{n} teclas lidas aproximadamente"), + ("{n} saved shortcut could not be used", "{n} atalho salvo não pôde ser usado"), + ("{n} saved shortcuts could not be used", "{n} atalhos salvos não puderam ser usados"), + ("{n} shortcut also works in another scope", "{n} atalho também funciona em outro escopo"), + ("{n} shortcut is assigned more than once", "{n} atalho está atribuído mais de uma vez"), + ("{n} shortcuts also work in another scope", "{n} atalhos também funcionam em outro escopo"), + ("{n} shortcuts are assigned more than once", "{n} atalhos estão atribuídos mais de uma vez"), + ("{panel} Panel", "Painel {panel}"), + ("{title} ({n})", "{title} ({n})"), + ("{title}: {set}", "{title}: {set}"), + ("ΔLOC", "ΔLOC"), + ("−Bin", "−Bin"), + ("−LOC", "−LOC"), + ("⚠ {chord} is used by {label}", "⚠ {chord} é usado por {label}"), ]; diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index b676a0c5f..32aecd9e7 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -466,8 +466,18 @@ fn interface_strings() -> HashSet<&'static str> { keys.extend(crate::credits::SortKey::ALL.iter().flat_map(|key| [key.label().0, key.label().1])); // Docking chrome labels reach `tr` through craft-ui's localizer. keys.extend(crate::panel_docking::DOCK_LABELS.iter().map(|(_, english)| *english)); + // File › New's Units list passes each unit's name to `tr`. + keys.extend(crate::new_document::NEW_DOCUMENT_UNITS.map(|unit| unit.label())); // UI labels passed to `tr` that no other catalog has yet. keys.extend([ + "Auto-Sizing", + "Color Theme", + "Imported {count} shortcuts from “{set}”; {unmatched} items not matched, {unreadable} unreadable.", + "Minimum Height", + "Minimum Width", + "No Line Breaks", + "Reference Point", + "This document uses unavailable fonts. Choose replacements, or select Done to continue with fallback fonts.", "180°", "Create Links When Placing Text Files", "Delete Character Style…", diff --git a/crates/ui-egui/src/new_document.rs b/crates/ui-egui/src/new_document.rs index 0acdb36f4..195d9cb76 100644 --- a/crates/ui-egui/src/new_document.rs +++ b/crates/ui-egui/src/new_document.rs @@ -15,7 +15,7 @@ use crate::dialogs::Dialog; use crate::theme::{Tokens, semibold}; /// The Units list, as InDesign's New Document window has it. -const NEW_DOCUMENT_UNITS: [Unit; 8] = +pub(crate) const NEW_DOCUMENT_UNITS: [Unit; 8] = [Unit::Points, Unit::Picas, Unit::Inches, Unit::Millimeters, Unit::Centimeters, Unit::Ciceros, Unit::Agates, Unit::Pixels]; /// Tab key and English label. const TABS: [(&str, &str); 5] = [("recent", "Recent"), ("saved", "Saved"), ("print", "Print"), ("web", "Web"), ("mobile", "Mobile")]; diff --git a/docs/gaps.md b/docs/gaps.md index d74de3b04..addb0b679 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where DesignCraft falls short of InDesign -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (placed graphic layer-option preservation and explicit rendering warnings; gap 16 shrunk: File › File Info; gap 16: Convert Variable to Text; gap 28 added: placed-PDF font repair remains after visible unembedded font detection, #909; gap 26 shrunk: autoflow fills the following pages before it adds pages at the end; gap 6 shrunk: Type › Reload Fonts reads fonts installed, edited or removed while running (#328); gap 3: Package links are relative, #340; gap 27 closed: the loaded text cursor threads into a frame inside a group (#1075); .indd and .indt open through indd-utils; gap 0 shrunk: text threads by hand; threading gaps added; Optical kerning from outlines (#181); gap 6: macOS lists fonts that font services and managers activate; shared print spooler; image clipping paths from IDML; Tabs panel listed as present (#343); book chapter update safety; gap 16: Based on Parent leftovers; bounded control click/drag input; swatches on placed greyscale and bitmap images) · **Target:** Adobe InDesign 2026 (21.6) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (gap 21 shrunk: pt-BR translates the whole interface; placed graphic layer-option preservation and explicit rendering warnings; gap 16 shrunk: File › File Info; gap 16: Convert Variable to Text; gap 28 added: placed-PDF font repair remains after visible unembedded font detection, #909; gap 26 shrunk: autoflow fills the following pages before it adds pages at the end; gap 6 shrunk: Type › Reload Fonts reads fonts installed, edited or removed while running (#328); gap 3: Package links are relative, #340; gap 27 closed: the loaded text cursor threads into a frame inside a group (#1075); .indd and .indt open through indd-utils; gap 0 shrunk: text threads by hand; threading gaps added; Optical kerning from outlines (#181); gap 6: macOS lists fonts that font services and managers activate; shared print spooler; image clipping paths from IDML; Tabs panel listed as present (#343); book chapter update safety; gap 16: Based on Parent leftovers; bounded control click/drag input; swatches on placed greyscale and bitmap images) · **Target:** Adobe InDesign 2026 (21.6) Every known shortfall against InDesign 2026, one entry each, ranked by how much it stops an InDesign professional from doing real work. This is the work list: agents pick from the top. @@ -247,7 +247,7 @@ Kind: **F** feature · **U** UI/UX · **T** typography · **FF** file format · ### 21. Localization breadth (L) - **Missing:** Hindi, Indonesian, Korean, Vietnamese interfaces; ~17% of strings in the 83–85% - languages; 39% of pt-BR; native-speaker review for all. **Estimate:** 120–180 h. + languages; native-speaker review for all. **Estimate:** 120–180 h. **Doc:** [localization-parity.md](localization-parity.md) ### 22. InDesign scripting compatibility (E) @@ -278,6 +278,7 @@ Cue. These are excluded from every percentage. | Date | Change | Summary | |---|---|---| +| 2026-11-04 | trivial | Gap 21 shrunk: pt-BR translates 2,936 of 2,939 strings, all but three Control panel captions (61% before) | | 2026-10-22 | minor | Gap 26 shrunk: autoflow threads a frame per column on the pages that follow the story's last frame, then adds pages at the end of the document | | 2026-10-19 | minor | Gap 28 added for remaining placed-PDF font embedding, substitution or outlining; visible unembedded font detection now ships in PDF/X-4 export and `validate-pdf`, with invisible text exempt and operation- or depth-limited checks reported incomplete (#909) | | 2026-10-16 | minor | Gap 27 closed: the loaded text cursor threads into a text frame inside a group (#1075) | diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 0e77995d4..b1b55d2fa 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-04 · **Change:** minor (Esperanto text language; Hungarian interface catalog, bundled-font coverage and flyout regression checks; Swedish interface) · **Target:** Adobe InDesign 2026 (21.6) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-04 · **Change:** minor (pt-BR catalog filled; Russian listed; Esperanto text language; Hungarian interface catalog, bundled-font coverage and flyout regression checks; Swedish interface) · **Target:** Adobe InDesign 2026 (21.6) Per-language status of the DesignCraft interface and of document typesetting in each script. Script-specific typesetting detail: [cjk.md](cjk.md), [cjk-typography.md](cjk-typography.md), @@ -39,7 +39,7 @@ come as Middle East editions with an English or French interface and right-to-le | Hindi | hi | ✗ | 0 (0%) | none | Devanagari shaped by harfrust in documents but untested; no Hindi hyphenation or spelling | no | none | 20–30 | | Arabic | ar | Middle East edition (English/French UI) | 1,459 (85%) | menus, panels, most dialogs; no help | RTL UI text (`rtl.rs`: bidi + shaping); Arabic composition, kashida, digits, RTL stories and tables ✓ (arabic-typography.md); list bullets and multi-column RTL open (#100) | no | partial | 15–25 | | French | fr | ✓ | 1,438 (83%) | menus, panels, most dialogs; no help | Latin ✓; French hyphenation ✓ (hyph-fr) | no | partial | 6–10 | -| Portuguese (Brazil) | pt-br | ✓ (pt) | 1,057 (61%) | menus, panels, some dialogs; no help | Latin ✓; Portuguese hyphenation ✓ | no | partial | 8–12 | +| Portuguese (Brazil) | pt-br | ✓ (pt) | 2,936 of 2,939 (~100%, 2026-11-04 missing-translations report) | whole interface but the Control panel's `IT`, `VA` and `Y:` captions; no help | Latin ✓; Portuguese hyphenation ✓ | no | partial | 1–2 | | Indonesian | id | ✗ | 0 (0%) | none | Latin ✓ | no | none | 12–18 | | Japanese | ja | ✓ | 1,644 (95%) | whole interface (#272), vertical-type commands; no help | vertical text, kinsoku, aki, ruby, warichu ✓ (partial depth, cjk.md); canvas IME ✓, not checked by hand (#322); Japanese UI and Mincho fonts from craft-fonts | no | partial | 6–10 (+ IME checks, shared with zh) | | German | de | ✓ | 1,438 (83%) | menus, panels, most dialogs; no help | Latin ✓; German 2006 hyphenation ✓ (hyph-de-1996, MIT) | no | partial | 6–10 | @@ -75,11 +75,20 @@ right-click flyouts in both Tools-panel layouts. Narrow-window coverage exercise scrolling, complete label/shortcut accessibility and selecting a scrolled row at 180 and 240 points; the existing wide-window checks keep their assertions. +Brazilian Portuguese (2026-11-04): `cargo xtask i18n-report` on main `ef6c3686` with this catalog +counts 2,939 interface strings; pt-BR translates 2,936 of them (up from 1,933). Like every other +language it leaves the Control panel's `IT`, `VA` and `Y:` captions in English. Tools are named "Ferramenta …", parent pages "página principal", stories "artigo" and +paths "demarcador" ("traçado" is Stroke; Pathfinder keeps its name). The 996 new strings were AI-drafted and approved by +the contributor; they are not yet checked in the running app, and a native-speaker review is +pending. Older rows still use "página-pai" and "página mestra" for parent pages and "Matéria" +for a story. + ## Other shipped languages | Language | Code | UI strings translated | Status | |---|---|---|---| | Hungarian | hu | 1,906 entries + 4 context captions (2026-11-01); initial catalog native-reviewed | partial | +| Russian | ru | 1,855 of 2,939 (63%, 2026-11-04 missing-translations report), count captions category-first | partial | | Czech | cs | 1,722 (99%), plural categories handled | partial | | Italian | it | 1,464 (85%) | partial | | Ukrainian | uk | 1,432 (83%), plural categories handled | partial | @@ -87,7 +96,7 @@ scrolling, complete label/shortcut accessibility and selecting a scrolled row at | Georgian | ka | 1,724 (~100%: every catalog key plus the command labels the others lack), count captions as `noun: n` | partial (reviewed by a native speaker) | | Swedish | sv | 2,857 of 2,891 (99%, 2026-11-01 missing-translations report): menus, panels, dialogs and messages; singular for a count of one; AI-drafted with Claude Code from the English source, spot-checked by a native speaker (not every string) | partial | -DesignCraft ships **6** interface languages beyond the twelve; InDesign ships 17 beyond its +DesignCraft ships **8** interface languages beyond the twelve; InDesign ships 17 beyond its eight of the twelve (cs, da, el, en_GB, fi, hu, it, nb, nl, pl, ro, ru, sq, sv, tr, uk, zh_TW). ## Document languages @@ -106,7 +115,7 @@ German variants have no automatic hyphenation; their German shaping and quotes a | Work | Opus 5.5 h | |---|---| | Fill the 83–85% catalogs (de, fr, es, zh, ar, it, uk; ~290 strings each) | 25–40 | -| pt-BR to full | 8–12 | +| pt-BR to full: check it in the running app; one term each for parent page and story | 1–2 | | New: Hindi, Indonesian, Korean, Vietnamese (1,724 strings, plural rules, tests) | 50–75 | | Canvas IME (zh, ja, ko): checks by hand with system IMEs, and fixes | 10–20 | | CJK UI font in every release build; Devanagari and Vietnamese rendering tests | 10–15 | @@ -118,6 +127,7 @@ German variants have no automatic hyphenation; their German shaping and quotes a | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | pt-BR catalog filled (996 strings and the unit names; path is "demarcador"): 2,936 of 2,939 strings by `i18n-report`, pt-BR to full 8–12 → 1–2 h; Russian (1,855) listed, eight languages beyond the twelve | | 2026-11-01 | minor | Initial Hungarian interface: 1,906 entries, four context captions, native review, bundled-font glyph coverage and wide/narrow flyout regressions | | 2026-10-11 | minor | Localized Japanese print, import and table controls; checked Japanese and English renders | | 2026-10-15 | minor | Swedish (`sv`) interface added | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cb57677a2..5f6b28243 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # DesignCraft parity with Adobe InDesign -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (Text Frame Options layout, Preview and Paragraph Spacing Limit; Swatches rows show InDesign's type columns; Keyboard Shortcuts on craft-keymap's shared dialog, with shortcut sets; Convert Variable to Text; list buttons with the default hanging indent; custom anchored objects honour Relative to Spine; PDF/X-4 visible unembedded font detection, #909; autoflow fills the following pages first; File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; image clipping paths from IDML; anchored objects wrap text; Tabs panel listed as present (#343); spring-loaded Zoom navigation; recovery checkpoint retention; cancelable macOS Dock Quit; Based on Parent; object styles carry effects; colour management on craft-cms, Coated FOGRA39 default CMYK; swatches on placed greyscale and bitmap images) · **Target:** Adobe InDesign 2026 (21.6.0.57, macOS) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (pt-BR interface ~100%, Localization unchanged at 45%; Text Frame Options layout, Preview and Paragraph Spacing Limit; Swatches rows show InDesign's type columns; Keyboard Shortcuts on craft-keymap's shared dialog, with shortcut sets; Convert Variable to Text; list buttons with the default hanging indent; custom anchored objects honour Relative to Spine; PDF/X-4 visible unembedded font detection, #909; autoflow fills the following pages first; File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; image clipping paths from IDML; anchored objects wrap text; Tabs panel listed as present (#343); spring-loaded Zoom navigation; recovery checkpoint retention; cancelable macOS Dock Quit; Based on Parent; object styles carry effects; colour management on craft-cms, Coated FOGRA39 default CMYK; swatches on placed greyscale and bitmap images) · **Target:** Adobe InDesign 2026 (21.6.0.57, macOS) The authoritative assessment of how close DesignCraft is to Adobe InDesign. [ROADMAP.md](../ROADMAP.md) summarizes it; [gaps.md](gaps.md) lists every known shortfall one at a time; the feature-by-feature @@ -64,7 +64,7 @@ they receive, setting type exactly, and basic editing that never fails. | UI/UX fidelity | 15% | 45% | 120–180 | Measured InDesign 2026 look; but users report object copy/paste (#351, #348, #185, #164), right-click menus (#238, #187, #160), out-port threading (#352, #194, #165) failing | [ui-parity.md](ui-parity.md) | | Stability | 10% | 45% | 60–100 | Never-crash rules and last-resort guards; startup failures on some GPUs and machines (#334, #273, #220, #192, #167, #166); no CI runs the tests on pull requests | [gaps.md](gaps.md) | | Performance | 5% | 65% | 40–80 | 300k characters compose in ~38 ms warm; typing repaints in < 1 ms (damage regions); no incremental composition; nothing benchmarked against InDesign; no large real documents | [gaps.md](gaps.md) | -| Localization | 3% | 45% | 120–180 | 9 translations beyond English; Japanese 95%, most others 83–85%, pt-BR 61%; Hindi, Indonesian, Korean, Vietnamese none | [localization-parity.md](localization-parity.md) | +| Localization | 3% | 45% | 120–180 | 15 translations beyond English; Japanese 95%, most others 83–85% (2026-10-10), pt-BR ~100% (2026-11-04); Hindi, Indonesian, Korean, Vietnamese none | [localization-parity.md](localization-parity.md) | | Platforms | 3% | 55% | 40–80 | macOS is where it's tested; Windows and Linux users hit basic failures; web and FreeBSD builds exist | [hardware-parity.md](hardware-parity.md) | | Hardware | 2% | 45% | 20–40 | Canvas rasterizes on the CPU (vello_cpu, multithreaded); GPU only presents; printing uses shared CUPS/Windows PDF spoolers (no PostScript; physical output needs validation) | [hardware-parity.md](hardware-parity.md) | | Ecosystem (scripting, plug-ins) | 2% | 15% | 150–250 | Own command/script/MCP API is strong; no ExtendScript/UXP DOM, so InDesign scripts don't run; no plug-ins | [gaps.md](gaps.md) | @@ -473,6 +473,7 @@ Task notes that headed ROADMAP.md: | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | Localization evidence: 15 translations beyond English, pt-BR ~100%; readiness and hours unchanged | | 2026-10-19 | minor | Output assessment records visible unembedded font detection in PDF/X-4 export and `validate-pdf`, the invisible-text exemption, incomplete-check reporting at the operation and nesting-depth limits, and remaining placed-PDF font repair (#909); readiness and hours unchanged | | 2026-10-13 | minor | `.indd` and `.indt` open through storytold/indd-utils; INDD remaining work 10–30 h (real-file corpus); readiness unchanged until it is measured | | 2026-10-12 | minor | Text threads by hand; stage note and distance to alpha follow the gate (5–7 h, #165); percentages unchanged | From 9da88149be2e093721b2659765f682a7aa839a4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Rese?= Date: Tue, 10 Nov 2026 13:39:39 -0300 Subject: [PATCH 0881/1349] Fix Links panel stalls on network paths (#1444) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fix Links panel stalls on network paths * Fix Links review findings * Fix Links worker gating and wasm build A link check blocked on another document's unreachable share no longer holds back the document now shown: after 200 ms a fresh worker takes over (at most four alive at once) and the stale result is dropped. relinked_asset used the native-only fingerprint_from, breaking the wasm build; it now uses fingerprint_of. The EPS relink and IDML link reach tests build Windows paths correctly. Co-Authored-By: Claude Opus 5.5 * Fix Links worker repaint and graphic read retry Switching documents before the 200 ms takeover now schedules a repaint for it: a blocked worker never asks for one, so without other input the panel kept waiting. A failed graphic read is no longer cached as missing, so the next check reads again. The legacy EPS fixture clears its source fingerprint, as documents from before fingerprints have none, so the test no longer depends on running within two seconds. Co-Authored-By: Claude Opus 5.5 * Keep touched links OK and poll Links within seconds Only a new size now marks a graphic Modified from its fingerprint. A file with the same size but a new time (saved again, copied, restored or checked out) is compared byte for byte, once per new time, and stays OK when unchanged. External changes are polled every two seconds instead of every five minutes. The next check waits at least as long as the last one took (up to five minutes), so a slow share stays idle half the time. Co-Authored-By: Claude Opus 5.5 * Wake Links when a worker slot frees; translate check strings A worker thread asks for a repaint when it ends, so a document waiting at the four-worker limit gets a worker as soon as a superseded one returns from its blocked call, without other input. Rows from a check keep a weak reference to their document. The key names it by address, which a later document can't reuse while the allocation is kept. The Links panel's new strings ("Checking", "Checking links…", "Link status is unavailable.") use the UI's ellipsis and are translated in every interface language. The comments on Session::text_link_checks and on the byte comparison in links::status describe what they do now. Co-Authored-By: Claude Opus 5.5 * Links: rows from the document, statuses from a check that can stop The panel lists links from the document on the UI thread (no file is looked at) and fills in the statuses a worker check last found, kept per document. An edit shows at once, and a check of an earlier edit still supplies statuses instead of being discarded. - A check of another document is told to stop and ends before its next file; only one blocked in a file system call is replaced, so blocked workers no longer hold their slots for a whole document. - Checks are timed on the worker, and what they remember passes to the worker that replaces them. - A fingerprint is kept only for a file whose time was settled when it was read, as for linked text. A file found unchanged by its bytes gets its current size and time stored with the document (remember_link_files), without marking a saved document as changed. - Asset::set_link keeps link and fingerprint together; copies made by Package and Copy Links To carry none. - The Session holds one LinkListChecks. Update Link lists files only when a linked story was edited in the layout. - The unused "Checking links..." caption is removed. Co-Authored-By: Claude Fable 5.2 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- ROADMAP.md | 1 + crates/doc/src/assets.rs | 10 +- crates/doc/src/lib.rs | 7 + crates/engine/src/cmd.rs | 1 + crates/engine/src/cmd/datamerge.rs | 6 +- crates/engine/src/cmd/file/place.rs | 54 +- crates/engine/src/cmd/interchange.rs | 41 +- crates/engine/src/cmd/links.rs | 224 ++++- crates/engine/src/cmd/links/tests.rs | 262 +++++ crates/engine/src/cmd/package.rs | 8 +- crates/engine/src/cmd/package/tests.rs | 13 +- crates/engine/src/lib.rs | 14 +- .../engine/tests/support/optional_content.rs | 1 + crates/epub/tests/it/grouped_reading_order.rs | 1 + crates/render/tests/it/colorize.rs | 1 + crates/tools/src/tests.rs | 1 + crates/ui-egui/src/app.rs | 2 + crates/ui-egui/src/i18n/ar.rs | 2 + crates/ui-egui/src/i18n/cs.rs | 2 + crates/ui-egui/src/i18n/de.rs | 2 + crates/ui-egui/src/i18n/hu.rs | 2 + crates/ui-egui/src/i18n/it.rs | 2 + crates/ui-egui/src/i18n/ja.rs | 2 + crates/ui-egui/src/i18n/ka.rs | 2 + crates/ui-egui/src/i18n/pl.rs | 2 + crates/ui-egui/src/i18n/pt_br.rs | 2 + crates/ui-egui/src/i18n/ru.rs | 2 + crates/ui-egui/src/i18n/sv.rs | 2 + crates/ui-egui/src/i18n/table.rs | 11 + crates/ui-egui/src/i18n/tests.rs | 17 + crates/ui-egui/src/i18n/uk.rs | 2 + crates/ui-egui/src/lib.rs | 6 + crates/ui-egui/src/links_worker.rs | 942 ++++++++++++++++++ crates/ui-egui/src/panels/properties/links.rs | 73 +- crates/ui-egui/src/panels/properties/tests.rs | 16 + 35 files changed, 1648 insertions(+), 88 deletions(-) create mode 100644 crates/ui-egui/src/links_worker.rs diff --git a/ROADMAP.md b/ROADMAP.md index 73c4a0532..e2cd24a93 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -485,6 +485,7 @@ Newest first. - **2026-10-22** · macOS menu bar: the menus keep working after the interface language or Show CJK Features changes (a rebuilt menu bar lost every click, Quit included), and its key equivalents are the shortcuts in effect, so a shortcut moved in the Keyboard Shortcuts editor leaves its old menu item. No readiness percentage change. - **2026-10-20** · MCP: every tool states all four behaviour hints (read-only, destructive, idempotent, open-world), input schemas are closed, and a misspelt key inside a `batch` step, a `pointer` event or `mods` is refused (`-32602`) like a top-level one instead of being ignored; a JSON script step with a key other than `command`/`params` is an error. A panic outside a command is a tool error instead of ending the server. No readiness percentage change. - **2026-10-22** · Paragraph rules: Rule Above's offset is measured from the first line's baseline to the rule's bottom edge, as in InDesign. Rules sat one ascent too high and crossed the previous paragraph's text (reported from an imported INDD document). No readiness percentage change. +- **2026-10-20** · The Links panel lists a document's links at once and takes their statuses from a check of the local and network files on a background worker, showing the last ones found meanwhile. It keeps the size and time of a graphic's file with the document, so an unchanged link needs no read even on the first check after opening (a file with a new time but the same size is compared once and then remembered, so a copied or restored folder stays OK). External changes are polled every two seconds, or as long as the last check took on a slow share; a document edit shows at once, and a selection change (Go To) starts no check. No readiness percentage change. - **2026-10-21** · Ruler guides are selected like objects (#1282): a click with the Selection tools selects a guide (also where it crosses an object), Shift-click adds or removes one, a new guide from the rulers is selected, a marquee that touches no object selects the guides it crosses, and Edit › Select All Guides (⌥⌘G, `guide.selectAll`) selects every unlocked guide on the spread. Selected guides draw thicker in their layer's color, drag together (all of them shown moving), nudge with the arrow keys and go with Delete, each as one undo step (`guide.select`, `guide.deselect`, `guide.moveBy`, `guide.delete {}`). With one guide selected the Control bar's X (vertical guide) or Y (horizontal guide) field and Properties › Transform show where it is, as the rulers measure, and typing a value moves it there. No readiness percentage change. - **2026-10-21** · Properties for points selected with Direct Selection, as InDesign's: the title is "Anchor Point(s)", and the panel shows Transform, Appearance, Convert Points (Plain, Corner, Smooth, Symmetrical) and the Delete Point(s) quick action (`path.deletePoints`, one undo step). Found in Zero2Graphic's *How to Page Layout design in Adobe InDesign 2022 CC*. No readiness percentage change. - **2026-10-20** · Direct Selection selects anchor points: a marquee selects the points inside it on every path it reaches, a click selects one point and Shift+click adds or removes one, selected points show solid, and dragging one (Shift: at 45° steps) or pressing the arrow keys moves them all in one step (`selection.set {anchors}`, `path.moveAnchors {points}`). No readiness percentage change. diff --git a/crates/doc/src/assets.rs b/crates/doc/src/assets.rs index 6ddd52b1e..0d100cee7 100644 --- a/crates/doc/src/assets.rs +++ b/crates/doc/src/assets.rs @@ -9,7 +9,7 @@ use std::hash::BuildHasher; use std::sync::Arc; use crate::story::Story; -use crate::{Asset, AssetId, Content, Document, Item}; +use crate::{Asset, AssetId, Content, Document, Fingerprint, Item}; /// Nesting limit for groups, anchored objects, table cells and notes. A document nested deeper /// is treated as using every asset, so nothing it references is merged away or pruned. @@ -82,6 +82,14 @@ impl Document { } impl Asset { + /// Link the asset to another file, or to none (embedded). The size and time kept with a link + /// ([`Asset::link_fingerprint`]) never outlive it: `loaded` is the new file's when `data` was + /// read from it, and `None` when it wasn't (a copy of the bytes, a file found again by name). + pub fn set_link(&mut self, link: Option, loaded: Option) { + self.link_fingerprint = loaded.filter(|_| link.is_some()); + self.link = link; + } + /// Whether `other` holds the same file: the same type, PDF page and crop, link and bytes. Files at /// different paths stay apart even with identical bytes, since each can be updated or /// relinked on its own. Assets without bytes (a link that couldn't be read) are the same only diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index b569610bc..8d1f99456 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -567,6 +567,13 @@ pub struct Asset { /// Original location on disk (Links panel), if linked. #[serde(default, skip_serializing_if = "Option::is_none")] pub link: Option, + /// The size and modification time the linked file had when `data` was read from it, or when + /// it was last found to hold `data`: link status compares these first instead of reading a + /// large file from a network share again. They are the file's only together with `link` and + /// `data`: a new link goes through [`Asset::set_link`], and whoever replaces `data` sets or + /// clears them. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub link_fingerprint: Option, #[serde(skip)] pub data: Arc>, /// Pixel size for raster images. diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index ed77b3319..03b6082db 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -33,6 +33,7 @@ mod layout; pub mod library; mod linked; mod links; +pub use links::{LinkListChecks, list_document_links, preview_document_links, remember_link_files}; mod liquid; mod lists; mod load_styles; diff --git a/crates/engine/src/cmd/datamerge.rs b/crates/engine/src/cmd/datamerge.rs index 5b42e6c1e..fb8d572cb 100644 --- a/crates/engine/src/cmd/datamerge.rs +++ b/crates/engine/src/cmd/datamerge.rs @@ -19,13 +19,11 @@ use serde_json::{Value, json}; use super::{CommandSpec, bad, cmd, has_doc, id_param, ok, str_param}; use crate::{DocState, Result, Session}; use fill::{FillReport, ImageCache, Maps, MissingImage, Sources, copy_item, fill_row, identity_map}; -use parse::{ - Table, TileInput, extension, fingerprint_of, relative_between, select_records, status_of, table_from_bytes, table_from_grid, table_from_objects, - tile, -}; +use parse::{Table, TileInput, extension, relative_between, select_records, status_of, table_from_bytes, table_from_grid, table_from_objects, tile}; #[cfg(not(target_arch = "wasm32"))] pub(crate) use parse::fingerprint_from; +pub(crate) use parse::fingerprint_of; pub(crate) fn fingerprint_from_path(path: &str) -> Option { fingerprint_of(Path::new(path)) diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index c6a581d5d..a30cb2321 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -90,7 +90,17 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { _ => PdfCrop::Crop, }; let mime = designcraft_render::image_mime(&bytes).to_string(); - let mut asset = Asset { page: pdf_page, name, mime, link, data: Arc::new(bytes), pixels: Some((pw, ph)), pdf_crop, ..Default::default() }; + let mut asset = Asset { + page: pdf_page, + name, + mime, + link, + link_fingerprint: crate::cmd::links::loaded_fingerprint(before, &bytes), + data: Arc::new(bytes), + pixels: Some((pw, ph)), + pdf_crop, + ..Default::default() + }; // The graphic's natural size: the box in points (the whole page when the box can't be found, // and then the document says so). let (bw, bh) = match crop_pdf(&mut asset) { @@ -198,16 +208,25 @@ pub(crate) fn crop_pdf(a: &mut Asset) -> Option<(f64, f64)> { } pub(crate) fn read_source(p: &Value) -> Result<(Vec, String, Option)> { + read_linked_source(p).map(|(bytes, name, link, _)| (bytes, name, link)) +} + +/// [`read_source`], with the size and time to keep with a linked file's bytes +/// ([`crate::cmd::links::loaded_fingerprint`]): the file's from before it is read, not those of a +/// later version that replaces it while a network or syncing source is being loaded. +fn read_linked_source(p: &Value) -> Result<(Vec, String, Option, Option)> { if let Some(b) = str_param(p, "base64") { - return Ok((base64_decode(b), str_param(p, "name").unwrap_or("image").to_string(), None)); + return Ok((base64_decode(b), str_param(p, "name").unwrap_or("image").to_string(), None, None)); } let path = str_param(p, "path").ok_or_else(|| bad("place", "missing `path` or `base64`"))?; + let before = crate::cmd::datamerge::fingerprint_from_path(path); #[cfg(not(target_arch = "wasm32"))] let b = crate::io::read_file(path).map_err(EngineError::Other)?; #[cfg(target_arch = "wasm32")] let b: Vec = vec![]; let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.into()); - Ok((b, name, Some(path.to_string()))) + let loaded = crate::cmd::links::loaded_fingerprint(before, &b); + Ok((b, name, Some(path.to_string()), loaded)) } fn eps_size(bytes: &[u8], command: &str) -> Result> { @@ -236,11 +255,11 @@ pub(crate) fn validate_placement(size: (f64, f64), frame: Rect, xf: Affine, comm } pub(super) fn place_load(s: &mut Session, p: &Value) -> Result { - let (bytes, name, link) = read_source(p)?; + let (bytes, name, link, link_fingerprint) = read_linked_source(p)?; let (pw, ph) = designcraft_render::image_size(&bytes).ok_or_else(|| bad("place.load", "unsupported or corrupt image"))?; let natural = eps_size(&bytes, "place.load")?.or_else(|| designcraft_render::natural_size(&bytes, 0)).unwrap_or((pw as f64, ph as f64)); let mime = designcraft_render::image_mime(&bytes).to_string(); - let asset = Asset { name, mime, link, data: Arc::new(bytes), pixels: Some((pw, ph)), ..Default::default() }; + let asset = Asset { name, mime, link, link_fingerprint, data: Arc::new(bytes), pixels: Some((pw, ph)), ..Default::default() }; load_cursor(s, asset, natural) } @@ -378,7 +397,7 @@ fn place_layout_page(s: &mut Session, p: &Value, name: &str, bytes: &[u8]) -> Re #[cfg(all(test, not(target_arch = "wasm32")))] pub(super) mod image_place_tests { - use designcraft_doc::{Content, ItemId}; + use designcraft_doc::{AssetId, Content, ItemId}; use designcraft_geom::Rect; use serde_json::{Value, json}; @@ -449,6 +468,29 @@ pub(super) mod image_place_tests { assert!(matches!(session.doc().unwrap().doc.item(ItemId(frame)).unwrap().content, Content::Graphic(_))); } + #[test] + fn place_load_remembers_the_fingerprint_captured_for_its_link() { + let image = image_file().unwrap(); + let mut session = Session::new(); + session.execute("file.new", &json!({})).unwrap(); + let load = |session: &mut Session| { + let loaded = session.execute("place.load", &json!({"path": image.path()})).unwrap(); + session.doc().unwrap().doc.assets[&AssetId(loaded["asset"].as_u64().unwrap())].clone() + }; + + // Written just now: another write in the same second would keep its time, so the time + // can't vouch for the bytes later and isn't kept. + let asset = load(&mut session); + assert_eq!(asset.link_fingerprint, None); + assert_eq!(asset.link.as_deref(), image.path().to_str()); + + // A file that has been as it is for a while is remembered by its size and time. + image.as_file().set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60)).unwrap(); + let expected = crate::cmd::datamerge::fingerprint_from(&std::fs::metadata(image.path()).unwrap()); + session.execute("file.new", &json!({})).unwrap(); + assert_eq!(load(&mut session).link_fingerprint, Some(expected)); + } + #[test] fn individual_placement_parameters_bypass_selected_frames() { let image = image_file().unwrap(); diff --git a/crates/engine/src/cmd/interchange.rs b/crates/engine/src/cmd/interchange.rs index 335773ee5..47b36b776 100644 --- a/crates/engine/src/cmd/interchange.rs +++ b/crates/engine/src/cmd/interchange.rs @@ -90,7 +90,7 @@ fn with_pdf_layer_variants(doc: &Document, embed: bool) -> Result Option> { #[cfg(not(target_arch = "wasm32"))] { - read_packaged_link(link, package).map(|(_, data)| data) + read_packaged_link(link, package).map(|(_, data, _)| data) } #[cfg(target_arch = "wasm32")] { @@ -174,8 +174,8 @@ fn import_report_with_previews( let read = |link: &str| -> Option> { #[cfg(not(target_arch = "wasm32"))] { - let (path, data) = read_packaged_link(link, package)?; - resolved.borrow_mut().insert(link.to_string(), path); + let (path, data, fingerprint) = read_packaged_link(link, package)?; + resolved.borrow_mut().insert(link.to_string(), (path, fingerprint)); Some(data) } #[cfg(target_arch = "wasm32")] @@ -191,9 +191,9 @@ fn import_report_with_previews( let document = { let mut document = document; for asset in document.assets.values_mut() { - if let Some(path) = asset.link.as_ref().and_then(|link| resolved.borrow().get(link).cloned()) { + if let Some((path, fingerprint)) = asset.link.as_ref().and_then(|link| resolved.borrow().get(link).cloned()) { // Relocated packages must also use the new path for preflight and link updates. - std::sync::Arc::make_mut(asset).link = Some(path); + std::sync::Arc::make_mut(asset).set_link(Some(path), fingerprint); } } resolve_packaged_links(&mut document, package); @@ -357,29 +357,41 @@ pub(crate) fn resolve_packaged_links(document: &mut Document, package: Option<&s // A link relative to the document (what File › Package writes, `Links/logo.png`) is // held as the file it names, as every other link is, so preflight and updates find it. if std::path::Path::new(link).is_relative() { - std::sync::Arc::make_mut(asset).link = Some(path.to_string_lossy().into_owned()); + // The same file under its full name: what is kept of it stays. + let loaded = asset.link_fingerprint; + std::sync::Arc::make_mut(asset).set_link(Some(path.to_string_lossy().into_owned()), loaded); } continue; } let Some(path) = packaged_link_candidates(link, Some(package)).into_iter().find(|p| crate::io::is_file(p)) else { continue }; - std::sync::Arc::make_mut(asset).link = Some(path.to_string_lossy().into_owned()); + // Another file than the link named, found again by name: the bytes weren't read from it. + std::sync::Arc::make_mut(asset).set_link(Some(path.to_string_lossy().into_owned()), None); } } /// The first candidate for `link` ([`packaged_link_candidates`]) that is a regular file no larger -/// than [`MAX_LINKED_FILE_BYTES`] holding an image or a graphic, with its path. +/// than [`MAX_LINKED_FILE_BYTES`] holding an image or a graphic, with its path and the size and +/// time to keep with its bytes ([`super::links::loaded_fingerprint`]). #[cfg(not(target_arch = "wasm32"))] -fn read_packaged_link(link: &str, package: Option<&std::path::Path>) -> Option<(String, Vec)> { +fn read_packaged_link(link: &str, package: Option<&std::path::Path>) -> Option<(String, Vec, Option)> { for path in packaged_link_candidates(link, package) { - if !crate::io::is_file(&path) || !crate::io::metadata(&path).is_ok_and(|m| m.len() <= MAX_LINKED_FILE_BYTES) { + if !crate::io::is_file(&path) { continue; } + // The version about to be read: one that replaces it during the read (a syncing or + // network file) has other metadata, and the next Links check compares the bytes. + let Ok(metadata) = crate::io::metadata(&path) else { continue }; + if metadata.len() > MAX_LINKED_FILE_BYTES { + continue; + } + let before = super::datamerge::fingerprint_from(&metadata); // At most one byte over the limit, in case the file grew since. let Ok(bytes) = crate::io::read_capped(&path, MAX_LINKED_FILE_BYTES) else { continue }; if bytes.len() as u64 > MAX_LINKED_FILE_BYTES || !is_graphic(&bytes) { continue; } - return Some((path.to_string_lossy().into_owned(), bytes)); + let loaded = super::links::loaded_fingerprint(Some(before), &bytes); + return Some((path.to_string_lossy().into_owned(), bytes, loaded)); } None } @@ -520,6 +532,9 @@ mod tests { std::fs::create_dir_all(path.parent().unwrap()).unwrap(); let (idml, png) = linked_idml("C:\\original-computer\\project\\Links\\illustrations\\logo.png", false).unwrap(); std::fs::write(&path, &png).unwrap(); + // Not written just now: its size and time can vouch for the imported bytes. + let earlier = std::time::SystemTime::now() - std::time::Duration::from_secs(60); + std::fs::File::options().write(true).open(&path).unwrap().set_modified(earlier).unwrap(); std::fs::write(dir.join("logo.png"), b"a different file with the same basename").unwrap(); let doc = import(&idml, Some(&dir.join("x.idml"))).unwrap(); @@ -527,6 +542,8 @@ mod tests { assert_eq!(*asset.data, png, "the packaged graphic must render even when its author-machine path no longer exists"); let resolved = std::path::absolute(&path).unwrap(); assert_eq!(asset.link.as_deref(), resolved.to_str(), "remember the resolved link so update and preflight use the packaged file"); + let expected = super::super::datamerge::fingerprint_from(&std::fs::metadata(&path).unwrap()); + assert_eq!(asset.link_fingerprint, Some(expected), "remember the same version of the file whose bytes were imported"); assert_eq!(super::super::links::status_cached(asset, None, &mut Default::default()), "ok"); std::fs::remove_dir_all(dir).unwrap(); } diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index ec7bf6ba8..22e31cf64 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -13,6 +13,7 @@ use std::path::Path; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use designcraft_compose::Cache; use designcraft_doc::{AssetId, Content, Document, Fingerprint, Item, ItemId, Selection, Story, StoryId, TextFileLink}; @@ -26,11 +27,9 @@ pub fn specs() -> Vec { vec![ cmd!(query "links.list", "Links", [], None, "{} → [{asset, name, path, status: ok|modified|missing|embedded, refused?: why a missing link isn't followed (a path on another computer, a device), pixels, pdfCrop (placed PDFs: the box shown), uses: [{id, page, ppi}]}], then linked text files: [{story, name, path, status (also tooLarge: unchanged size, too big to check), edited (the story was changed in the layout), uses: [{id, page}]}]", has_doc, |s, _| { // Taken out for the call so the document needn't be cloned on every poll. - let mut checks = std::mem::take(&mut s.text_link_checks); - let mut images = std::mem::take(&mut s.image_link_checks); - let links = s.doc().map(|d| list(&d.doc, &s.cache, d.path.as_deref().map(Path::new), &mut checks, &mut images)); - s.text_link_checks = checks; - s.image_link_checks = images; + let mut checks = std::mem::take(&mut s.link_checks); + let links = s.doc().map(|d| list(&d.doc, &s.cache, d.path.as_deref().map(Path::new), Some(&mut checks), None).unwrap_or_default()); + s.link_checks = checks; Ok(Value::Array(links?)) }), cmd!( @@ -77,7 +76,7 @@ pub fn specs() -> Vec { let aid = asset_param(p, "links.embed")?; s.edit(|d, _| { let a = d.assets.get_mut(&aid).ok_or_else(|| bad("links.embed", "no such graphic"))?; - Arc::make_mut(a).link = None; + Arc::make_mut(a).set_link(None, None); Ok(Value::Null) }) } @@ -163,51 +162,81 @@ pub fn link_missing(a: &designcraft_doc::Asset, document: Option<&Path>) -> bool /// describe other bytes. pub(crate) type ImageChecks = std::collections::HashMap<(AssetId, usize, std::path::PathBuf), (Fingerprint, bool)>; +/// The size and time to keep with `bytes` just read from a linked file, `before` being the +/// file's from before the read. Kept only when they can vouch for the bytes later: the size is +/// the bytes' (the file didn't change while it was read) and the time is [`settled`] (another +/// write in the same second, a file still being synced, would keep it). A linked text file's time +/// is kept on the same terms. +pub(crate) fn loaded_fingerprint(before: Option, bytes: &[u8]) -> Option { + before.filter(|f| f.size == bytes.len() as u64 && settled(f)) +} + +/// Is the linked file still the one the asset's bytes were loaded from, going by the size and +/// time kept then ([`designcraft_doc::Asset::link_fingerprint`], [`loaded_fingerprint`])? Nothing +/// is read when it is, also on the first check after a document is opened, which matters on a +/// network share. A fingerprint of another size than the bytes isn't theirs and doesn't count; a +/// new time or no fingerprint leave it to the byte comparison. +#[cfg(not(target_arch = "wasm32"))] +fn loaded_unchanged(a: &designcraft_doc::Asset, now: Fingerprint) -> bool { + a.link_fingerprint.is_some_and(|loaded| loaded.size == a.data.len() as u64 && loaded == now && settled(&now)) +} + /// Link status of a placed graphic (`ok`, `modified`, `missing`, `embedded`), reading the file -/// only when its size is the asset's and its time isn't the one remembered from the last read -/// (`checks`): the Links panel polls twice a second, and a document -/// of press-size images would otherwise be read whole on every poll. A file changed in the last -/// two seconds is never remembered (see [`settled`]). +/// only when its size is the asset's and its time is neither the one the bytes were loaded at +/// ([`loaded_unchanged`]) nor the one remembered from the last read (`checks`): the Links panel +/// polls, and a document of press-size images would otherwise be read whole on every poll. A file +/// changed in the last two seconds is never remembered (see [`settled`]). pub(crate) fn status_cached(a: &designcraft_doc::Asset, document: Option<&Path>, checks: &mut ImageChecks) -> &'static str { - let Some(link) = &a.link else { return "embedded" }; + image_status(a, document, checks).0 +} + +/// [`status_cached`], and the file's size and time when a read found the asset's bytes in it +/// although the fingerprint kept with the asset says nothing or something else: what +/// [`remember_link_files`] keeps, so the file isn't read again in another session. +fn image_status(a: &designcraft_doc::Asset, document: Option<&Path>, checks: &mut ImageChecks) -> (&'static str, Option) { + let Some(link) = &a.link else { return ("embedded", None) }; // Nothing was read from the file (a package's link that wasn't followed): missing, as in // Preflight. if a.data.is_empty() { - return "missing"; + return ("missing", None); } #[cfg(not(target_arch = "wasm32"))] { - let Ok(path) = crate::io::document_path(link, document) else { return "missing" }; + let Ok(path) = crate::io::document_path(link, document) else { return ("missing", None) }; if !crate::io::is_file(&path) { - return "missing"; + return ("missing", None); } let now = match crate::io::metadata(&path) { - Err(_) => return "missing", + Err(_) => return ("missing", None), Ok(m) => super::datamerge::fingerprint_from(&m), }; + if loaded_unchanged(a, now) { + return ("ok", None); + } if now.size != a.data.len() as u64 { - return "modified"; + return ("modified", None); } let key = (a.id, Arc::as_ptr(&a.data) as usize, path.clone()); if let Some((at, same)) = checks.get(&key) && *at == now { - return if *same { "ok" } else { "modified" }; + return if *same { ("ok", Some(now)) } else { ("modified", None) }; } let same = match crate::io::read_capped(&path, a.data.len() as u64) { Ok(b) => b == *a.data, - Err(_) => return "missing", + Err(_) => return ("missing", None), }; // The time from before the read: a change during it is seen next time. - if settled(&now) { + let settled = settled(&now); + if settled { checks.insert(key, (now, same)); } - if same { "ok" } else { "modified" } + if same { ("ok", settled.then_some(now)) } else { ("modified", None) } } #[cfg(target_arch = "wasm32")] { let _ = (link, document, checks); - "ok" + ("ok", None) } } @@ -342,19 +371,130 @@ fn shown<'a>(d: &'a Document, cache: &Cache, aid: AssetId) -> Vec> { out } -/// `links.list`: every used placed graphic, then every linked text file, each with its status -/// (`images` and `checks` remember what was read this session, so a poll reads nothing unchanged). -fn list(d: &Document, cache: &Cache, document: Option<&Path>, checks: &mut TextChecks, images: &mut ImageChecks) -> Vec { - let texts = d.stories.values().filter_map(|st| { - let l = st.file_link.as_ref()?; +/// What a check of a document's links remembers between runs: the linked text files and images +/// already compared with the document ([`TextChecks`], [`ImageChecks`]), so a poll reads nothing +/// unchanged. The [`Session`] keeps one for `links.list`; a caller that lists a document's links +/// itself ([`list_document_links`]) keeps its own. +#[derive(Default)] +pub struct LinkListChecks { + text: TextChecks, + images: ImageChecks, + /// Linked images the latest list read and found to hold the document's bytes, with the file's + /// size and time then ([`LinkListChecks::take_verified`]). + verified: Vec<(AssetId, Fingerprint)>, +} + +impl LinkListChecks { + /// The linked images the latest list found unchanged by comparing bytes, because the size + /// and time kept with them said nothing or something else: [`remember_link_files`] keeps the + /// file's current ones with them. + pub fn take_verified(&mut self) -> Vec<(AssetId, Fingerprint)> { + std::mem::take(&mut self.verified) + } + + /// Add what `other` remembers (the checks of another worker thread). + pub fn absorb(&mut self, other: LinkListChecks) { + self.text.extend(other.text); + self.images.extend(other.images); + } + + /// How many files are remembered. + pub fn len(&self) -> usize { + self.text.len() + self.images.len() + } + + /// Is nothing remembered yet? + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +/// The rows of `links.list` without looking at a linked file: `checking` stands where a file +/// would be read or asked for its size and time. A native UI shows these at once and fills in +/// what [`list_document_links`] finds on a worker thread, where a share that doesn't answer +/// can't stall it. +pub fn preview_document_links(d: &Document, cache: &Cache, document: Option<&Path>) -> Vec { + list(d, cache, document, None, None).unwrap_or_default() +} + +/// The rows of `links.list` for a document outside a [`Session`], so a native UI can check the +/// linked files on a worker thread. `checks` is what the worker remembers between calls. Another +/// thread sets `stop` to end the check before its next file (the one being asked may be on a +/// share that doesn't answer, and hundreds more may follow it): nothing is returned then. +pub fn list_document_links( + d: &Document, + cache: &Cache, + document: Option<&Path>, + checks: &mut LinkListChecks, + stop: &AtomicBool, +) -> Option> { + list(d, cache, document, Some(checks), Some(stop)) +} + +/// Keep, with each linked image in `files`, the size and time its file had when a check read it +/// and found the document's bytes in it ([`LinkListChecks::take_verified`]). Later checks, and +/// the first one of another session, then don't read it: copying, restoring or checking out a +/// project folder gives every file a new time. `doc` is the document the check ran on: nothing +/// is kept when the active document isn't that one any more (other bytes may be linked by now), +/// or during a gesture. Nothing placed changes, so a saved document stays saved; the times go +/// into its file with the next save. → how many were kept +pub fn remember_link_files(s: &mut Session, doc: &Arc, files: &[(AssetId, Fingerprint)]) -> usize { + let Ok(st) = s.doc_mut() else { return 0 }; + if !Arc::ptr_eq(&st.doc, doc) || st.interaction.is_some() { + return 0; + } + let stale = |a: &designcraft_doc::Asset, f: &Fingerprint| a.link.is_some() && a.data.len() as u64 == f.size && a.link_fingerprint != Some(*f); + let fresh: Vec<(AssetId, Fingerprint)> = files.iter().filter(|(id, f)| st.doc.assets.get(id).is_some_and(|a| stale(a, f))).copied().collect(); + if fresh.is_empty() { + return 0; + } + let saved = !st.is_dirty(); + let d = Arc::make_mut(&mut st.doc); + for (id, f) in &fresh { + if let Some(a) = d.assets.get_mut(id) { + Arc::make_mut(a).link_fingerprint = Some(*f); + } + } + if saved { + st.saved_doc = Arc::clone(&st.doc); + } + fresh.len() +} + +/// `links.list`: every used placed graphic, then every linked text file, each with its status. +/// `files` is what was read this session (a poll reads nothing unchanged); without it no file is +/// looked at and a status that needs one is `checking` ([`preview_document_links`]). `None` when +/// `stop` was set before the last link was reached. +fn list(d: &Document, cache: &Cache, document: Option<&Path>, files: Option<&mut LinkListChecks>, stop: Option<&AtomicBool>) -> Option> { + let stopped = || stop.is_some_and(|stop| stop.load(Ordering::Relaxed)); + let (mut checks, mut images, mut verified) = match files { + Some(files) => { + files.verified.clear(); + (Some(&mut files.text), Some(&mut files.images), Some(&mut files.verified)) + } + None => (None, None, None), + }; + let texts = d.stories.values().filter_map(|st| Some((st, st.file_link.as_ref()?))).map(|(st, l)| { + if stopped() { + return None; + } let uses: Vec = st.frames.iter().map(|id| json!({"id": id.0, "page": d.page_of_item(*id).map(|p| d.page_name(p))})).collect(); - Some(json!({"story": st.id.0, "name": file_name(&l.path), "path": l.path, "status": text_status(l, checks, document), "refused": refused(&l.path, document).map(|r| r.to_string()), "edited": story_hash(st) != l.story_hash, "uses": uses})) + let why = refused(&l.path, document).map(|r| r.to_string()); + let status = match checks.as_deref_mut() { + Some(checks) => text_status(l, checks, document), + None if why.is_some() => "missing", + None => "checking", + }; + Some(json!({"story": st.id.0, "name": file_name(&l.path), "path": l.path, "status": status, "refused": why, "edited": story_hash(st) != l.story_hash, "uses": uses})) }); let used = d.used_assets(); d.assets .values() .filter(|a| used.contains(&a.id)) .map(|a| { + if stopped() { + return None; + } let uses: Vec = shown(d, cache, a.id) .into_iter() .map(|u| { @@ -377,7 +517,19 @@ fn list(d: &Document, cache: &Cache, document: Option<&Path>, checks: &mut TextC .collect(); let pdf_crop = (a.mime == "application/pdf").then(|| a.pdf_crop.name()); let why = a.link.as_deref().and_then(|l| refused(l, document)).map(|r| r.to_string()); - json!({"asset": a.id.0, "name": a.name, "path": a.link, "status": status_cached(a, document, images), "refused": why, "pixels": a.pixels, "pdfCrop": pdf_crop, "uses": uses}) + let status = match images.as_deref_mut() { + Some(images) => { + let (status, file) = image_status(a, document, images); + if let (Some(verified), Some(file)) = (verified.as_deref_mut(), file) { + verified.push((a.id, file)); + } + status + } + None if a.link.is_none() => "embedded", + None if a.data.is_empty() || why.is_some() => "missing", + None => "checking", + }; + Some(json!({"asset": a.id.0, "name": a.name, "path": a.link, "status": status, "refused": why, "pixels": a.pixels, "pdfCrop": pdf_crop, "uses": uses})) }) .chain(texts) .collect() @@ -456,7 +608,10 @@ fn reload(path: impl AsRef) -> Result<(Vec, (u32, u32))> { /// Relink passes the file the user chose as both. Update passes the path the stored link resolved /// to and the stored link itself, so refreshing a link never rewrites what the document holds. fn relinked_asset(a: &designcraft_doc::Asset, read: &Path, link: &str) -> Result> { + // The size and time from before the read: a change during it is seen by the next check. + let before = super::datamerge::fingerprint_of(read); let (bytes, px) = reload(read)?; + let loaded = loaded_fingerprint(before, &bytes); let page = if designcraft_render::is_pdf(&bytes) { a.page } else { 0 }; let px = if page > 0 { designcraft_render::pdf_page_size(&bytes, page as usize) @@ -471,7 +626,7 @@ fn relinked_asset(a: &designcraft_doc::Asset, read: &Path, link: &str) -> Result a.pixels = Some(px); a.page = page; a.name = Path::new(link).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| link.to_string()); - a.link = Some(link.to_string()); + a.set_link(Some(link.to_string()), loaded); // A placed PDF keeps its crop choice; its box is found on the new file. super::file::crop_pdf(&mut a); Ok(Arc::new(a)) @@ -497,7 +652,7 @@ fn relink(s: &mut Session, p: &Value) -> Result { d.assets.insert(aid, fresh); Ok(json!({"name": name})) }); - s.image_link_checks.clear(); + s.link_checks.images.clear(); r } @@ -518,7 +673,7 @@ fn relink_folder(s: &mut Session, p: &Value) -> Result { } let missing_only = p.get("missingOnly").and_then(Value::as_bool).unwrap_or(dir.is_some() && ext.is_none()); let only: Option> = p.get("assets").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect()); - let mut images = std::mem::take(&mut s.image_link_checks); + let mut images = std::mem::take(&mut s.link_checks.images); let st = s.doc()?; let (d, document) = (&st.doc, st.path.as_deref().map(Path::new)); let mut todo: Vec<(AssetId, std::path::PathBuf)> = Vec::new(); @@ -573,7 +728,7 @@ fn relink_folder(s: &mut Session, p: &Value) -> Result { })?; images.clear(); } - s.image_link_checks = images; + s.link_checks.images = images; Ok(json!({"relinked": n, "notFound": not_found})) } @@ -584,8 +739,7 @@ fn update(s: &mut Session, p: &Value) -> Result { (st.doc.clone(), st.path.clone()) }; let document = document.as_deref().map(Path::new); - let checks = &mut s.text_link_checks; - let images = &mut s.image_link_checks; + let LinkListChecks { text: checks, images, .. } = &mut s.link_checks; let (only_asset, only_story) = (p.get("asset").and_then(Value::as_u64), story_param(p)); let all = only_asset.is_none() && only_story.is_none(); // A link craft-docpath refuses is missing, so it is never read or refreshed. @@ -626,7 +780,7 @@ fn update(s: &mut Session, p: &Value) -> Result { } Ok(json!({"updated": n, "warnings": warnings})) }); - s.image_link_checks.clear(); + s.link_checks.images.clear(); r } diff --git a/crates/engine/src/cmd/links/tests.rs b/crates/engine/src/cmd/links/tests.rs index c3391b333..733891dbf 100644 --- a/crates/engine/src/cmd/links/tests.rs +++ b/crates/engine/src/cmd/links/tests.rs @@ -76,6 +76,268 @@ fn unchanged_linked_images_are_not_read_again() { let _ = std::fs::remove_dir_all(&dir); } +/// A file's time `secs` ago (a file changed in the last two seconds is always read). +#[cfg(not(target_arch = "wasm32"))] +fn set_age(path: &Path, secs: u64) { + let f = std::fs::File::options().write(true).open(path).unwrap(); + f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(secs)).unwrap(); +} + +/// The size and time an image was loaded at are kept with it, so a file that still has them is +/// not read at all, also on the first check after a document is opened (nothing is remembered +/// yet then, and reading every link of a document on a network share takes minutes). The bytes +/// here differ from the file's on purpose: a status that read the file would say modified. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_linked_image_at_its_loaded_size_and_time_is_not_read() { + let dir = std::env::temp_dir().join(format!("dc-image-link-loaded-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("photo.bin"); + std::fs::write(&path, b"file").unwrap(); + set_age(&path, 60); + let loaded = crate::cmd::datamerge::fingerprint_of(&path).unwrap(); + let asset = |link_fingerprint| designcraft_doc::Asset { + id: AssetId(1), + link: Some(path.to_string_lossy().into_owned()), + link_fingerprint, + data: Arc::new(b"data".to_vec()), + ..Default::default() + }; + let status = |a: &designcraft_doc::Asset| status_cached(a, None, &mut ImageChecks::default()); + + assert_eq!(status(&asset(Some(loaded))), "ok", "the size and time it was loaded at: not read"); + // No fingerprint (a document from before they were kept) or another time: compared. + assert_eq!(status(&asset(None)), "modified"); + assert_eq!(status(&asset(Some(Fingerprint { mtime: loaded.mtime - 60, ..loaded }))), "modified", "a new time alone is compared"); + // Bytes replaced without their fingerprint: it is of another size, so it isn't theirs. + let swapped = designcraft_doc::Asset { data: Arc::new(b"other bytes".to_vec()), ..asset(Some(loaded)) }; + assert_eq!(status(&swapped), "modified"); + // A time too recent to trust: another write in the same second would keep it. + set_age(&path, 0); + let recent = crate::cmd::datamerge::fingerprint_of(&path).unwrap(); + assert_eq!(status(&asset(Some(recent))), "modified"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A file saved again unchanged, or copied, restored from a backup or checked out again, has a +/// new time and the same bytes: it stays OK (only a new size is conclusive), read once per new +/// time. The fingerprint is saved with the document, so every link of a copied project folder +/// would otherwise show Modified. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_graphic_rewritten_with_the_same_bytes_stays_ok() { + let dir = std::env::temp_dir().join(format!("dc-link-touched-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("logo.png"); + let image = png(2, 2); + let rewrite = |bytes: &[u8], age: u64| { + std::fs::write(&path, bytes).unwrap(); + set_age(&path, age); + }; + rewrite(&image, 300); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let aid = AssetId(s.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap()["asset"].as_u64().unwrap()); + rewrite(&image, 60); + let a = s.doc().unwrap().doc.assets[&aid].clone(); + assert!(a.link_fingerprint.is_some()); + assert_ne!(a.link_fingerprint, crate::cmd::datamerge::fingerprint_of(&path), "the file has another time than when it was placed"); + let mut checks = ImageChecks::default(); + assert_eq!(status_cached(&a, None, &mut checks), "ok"); + assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "ok"); + + // One byte changed, same size, at a time not seen before: compared again. + let mut changed = image.clone(); + if let Some(last) = changed.last_mut() { + *last ^= 0xff; + } + rewrite(&changed, 120); + assert_eq!(status_cached(&a, None, &mut checks), "modified"); + assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "modified"); + // Update remembers the file it read, so the next check needs no read. + assert_eq!(s.execute("links.update", &json!({})).unwrap()["updated"], 1); + let a = s.doc().unwrap().doc.assets[&aid].clone(); + assert_eq!(a.link_fingerprint, crate::cmd::datamerge::fingerprint_of(&path)); + assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "ok"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The rows a UI shows while the files are checked on a worker thread come from the document +/// alone: no file is looked at, not even for its size, so a share that doesn't answer can't +/// hold them back. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn preview_rows_look_at_no_file() { + let dir = std::env::temp_dir().join(format!("dc-link-preview-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let (linked, embedded, gone) = (dir.join("linked.png"), dir.join("embedded.png"), dir.join("gone.png")); + for (path, width) in [(&linked, 10), (&embedded, 11), (&gone, 12)] { + std::fs::write(path, png(width, 10)).unwrap(); + set_age(path, 60); + } + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let place = |s: &mut Session, path: &Path, x: u32| { + AssetId(s.execute("file.place", &json!({"path": path.to_string_lossy(), "x": x, "y": 72})).unwrap()["asset"].as_u64().unwrap()) + }; + let ids = [place(&mut s, &linked, 72), place(&mut s, &embedded, 144), place(&mut s, &gone, 216)]; + s.execute("links.embed", &json!({"asset": ids[1].0})).unwrap(); + std::fs::remove_file(&gone).unwrap(); + let st = s.doc().unwrap(); + assert!(st.doc.assets[&ids[0]].link_fingerprint.is_some(), "a placed file is remembered by its size and time"); + assert!(st.doc.assets[&ids[1]].link_fingerprint.is_none(), "embed forgets the file"); + let statuses = |rows: &[Value]| -> Vec { + ids.iter().map(|id| rows.iter().find(|r| r["asset"] == id.0).unwrap()["status"].as_str().unwrap().to_string()).collect() + }; + + let (preview, seen) = crate::io::touched(|| preview_document_links(&st.doc, &s.cache, None)); + assert!(seen.is_empty(), "the preview looked at {seen:?}"); + assert_eq!(statuses(&preview), ["checking", "embedded", "checking"]); + + // The check fills them in, with the rest of each row as in the preview. + let checked = list_document_links(&st.doc, &s.cache, None, &mut LinkListChecks::default(), &AtomicBool::new(false)).unwrap(); + assert_eq!(statuses(&checked), ["ok", "embedded", "missing"]); + let without_status = |rows: &[Value]| -> Vec { + rows.iter() + .cloned() + .map(|mut row| { + if let Some(row) = row.as_object_mut() { + row.remove("status"); + } + row + }) + .collect() + }; + assert_eq!(without_status(&preview), without_status(&checked)); + assert_eq!(Value::Array(checked), s.execute("links.list", &json!({})).unwrap(), "the same rows as links.list"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The size and time kept with bytes read from a linked file vouch for them later only if the +/// file wasn't being written then: a file changed in the same second, or still being synced, +/// keeps its time and size, and a status trusting them would say OK for other bytes. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_file_written_just_now_is_not_vouched_for_by_its_time() { + let dir = std::env::temp_dir().join(format!("dc-link-settled-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("photo.png"); + let image = png(3, 3); + std::fs::write(&path, &image).unwrap(); + let now = crate::cmd::datamerge::fingerprint_of(&path).unwrap(); + assert_eq!(loaded_fingerprint(Some(now), &image), None, "written in the last two seconds"); + set_age(&path, 60); + let settled = crate::cmd::datamerge::fingerprint_of(&path).unwrap(); + assert_eq!(loaded_fingerprint(Some(settled), &image), Some(settled)); + assert_eq!(loaded_fingerprint(Some(settled), &image[1..]), None, "the file changed while it was read"); + assert_eq!(loaded_fingerprint(None, &image), None); + + // Placed while it is that recent, then replaced by other bytes of the same size at the same + // time: the status reads the file instead of trusting the time. + std::fs::write(&path, &image).unwrap(); + let written = std::fs::metadata(&path).unwrap().modified().unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let aid = AssetId(s.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap()["asset"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.assets[&aid].link_fingerprint, None); + let mut other = image.clone(); + if let Some(last) = other.last_mut() { + *last ^= 0xff; + } + std::fs::write(&path, &other).unwrap(); + std::fs::File::options().write(true).open(&path).unwrap().set_modified(written).unwrap(); + assert_eq!(s.execute("links.list", &json!({})).unwrap()[0]["status"], "modified"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A check on a worker thread is told to stop when its document is no longer the one shown: it +/// ends before the next file instead of asking a share that doesn't answer about hundreds more. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_stopped_check_looks_at_no_further_file() { + let dir = std::env::temp_dir().join(format!("dc-link-stop-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + for (name, x) in [("a.png", 72), ("b.png", 144)] { + let path = dir.join(name); + std::fs::write(&path, png(x, 10)).unwrap(); + s.execute("file.place", &json!({"path": path.to_string_lossy(), "x": x, "y": 72})).unwrap(); + } + let st = s.doc().unwrap(); + let mut checks = LinkListChecks::default(); + + let stop = AtomicBool::new(true); + let (rows, seen) = crate::io::touched(|| list_document_links(&st.doc, &s.cache, None, &mut checks, &stop)); + assert_eq!(rows, None); + assert!(seen.is_empty(), "a stopped check looked at {seen:?}"); + + stop.store(false, Ordering::Relaxed); + assert_eq!(list_document_links(&st.doc, &s.cache, None, &mut checks, &stop).map(|rows| rows.len()), Some(2)); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A copied or restored project folder gives every linked file a new time. The check then +/// compares the bytes, and what it found is kept with the document, so neither later checks nor +/// the next session read the file again. The document isn't marked as changed by that. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_file_found_unchanged_by_its_bytes_is_remembered_with_the_document() { + let dir = std::env::temp_dir().join(format!("dc-link-remember-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("photo.png"); + std::fs::write(&path, png(4, 4)).unwrap(); + set_age(&path, 300); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let aid = AssetId(s.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap()["asset"].as_u64().unwrap()); + s.execute("file.saveAs", &json!({"path": dir.join("doc.designcraft").to_string_lossy()})).unwrap(); + assert!(!s.doc().unwrap().is_dirty()); + set_age(&path, 60); + let file = crate::cmd::datamerge::fingerprint_of(&path).unwrap(); + let check = |s: &Session, checks: &mut LinkListChecks| { + let st = s.doc().unwrap(); + let rows = list_document_links(&st.doc, &s.cache, st.path.as_deref().map(Path::new), checks, &AtomicBool::new(false)).unwrap(); + (rows[0]["status"].as_str().unwrap().to_string(), checks.take_verified()) + }; + + // Read once and found unchanged; found again from what the check remembers. + let mut checks = LinkListChecks::default(); + assert_eq!(check(&s, &mut checks), ("ok".to_string(), vec![(aid, file)])); + assert_eq!(checks.len(), 1); + assert_eq!(check(&s, &mut checks), ("ok".to_string(), vec![(aid, file)])); + + // Not for another document state, another size, or a graphic that isn't linked. + let checked = s.doc().unwrap().doc.clone(); + let other = Arc::new((*checked).clone()); + assert_eq!(remember_link_files(&mut s, &other, &[(aid, file)]), 0); + assert_eq!(remember_link_files(&mut s, &checked, &[(aid, Fingerprint { size: file.size + 1, ..file })]), 0); + assert_eq!(remember_link_files(&mut s, &checked, &[(AssetId(u64::MAX), file)]), 0); + assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &checked), "nothing kept, nothing changed"); + + assert_eq!(remember_link_files(&mut s, &checked, &[(aid, file)]), 1); + let st = s.doc().unwrap(); + assert_eq!(st.doc.assets[&aid].link_fingerprint, Some(file)); + assert!(!st.is_dirty(), "a saved document stays saved"); + let kept = s.doc().unwrap().doc.clone(); + assert_eq!(remember_link_files(&mut s, &kept, &[(aid, file)]), 0, "already kept"); + // The next check, with nothing remembered (another session), reads nothing and has nothing new. + assert_eq!(check(&s, &mut LinkListChecks::default()), ("ok".to_string(), vec![])); + + // What one worker remembers goes to the next. + let mut pooled = LinkListChecks::default(); + assert!(pooled.is_empty()); + pooled.absorb(checks); + assert_eq!(pooled.len(), 1); + let _ = std::fs::remove_dir_all(&dir); +} + /// A linked file's size is the document's choice, so a link is read under a cap (#1596). #[cfg(not(target_arch = "wasm32"))] #[test] diff --git a/crates/engine/src/cmd/package.rs b/crates/engine/src/cmd/package.rs index 85b06a92d..8d706a2b3 100644 --- a/crates/engine/src/cmd/package.rs +++ b/crates/engine/src/cmd/package.rs @@ -310,10 +310,14 @@ fn write_links(d: &Document, root: &OutputRoot, dir: &Path, only: Option<&[Asset let path = dir.join(&name); root.write(&path, a.data.as_slice())?; let mut na = (**a).clone(); - na.link = Some(match relative_to { + let link = match relative_to { Some(folder) => format!("{folder}/{name}"), None => path.to_string_lossy().to_string(), - }); + }; + // The copy is the linked file now, and the original's size and time say nothing of it. + // Its own are too recent to vouch for it yet: the first check compares the bytes and + // keeps them (`remember_link_files`). + na.set_link(Some(link), None); out.assets.insert(id, Arc::new(na)); written.push(path); } diff --git a/crates/engine/src/cmd/package/tests.rs b/crates/engine/src/cmd/package/tests.rs index 0ffc7979b..1848d5b5d 100644 --- a/crates/engine/src/cmd/package/tests.rs +++ b/crates/engine/src/cmd/package/tests.rs @@ -303,9 +303,14 @@ fn package_writes_document_links_and_report() { std::fs::create_dir_all(&dir).unwrap(); let svg = dir.join("logo.svg"); std::fs::write(&svg, r##""##).unwrap(); + // An older file than the copies made of it below. + let earlier = std::time::SystemTime::now() - std::time::Duration::from_secs(60); + std::fs::File::options().write(true).open(&svg).unwrap().set_modified(earlier).unwrap(); + let fingerprint = |path: &std::path::Path| crate::cmd::datamerge::fingerprint_of(path); let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); s.execute("file.place", &json!({"path": svg.to_string_lossy(), "x": 100, "y": 100})).unwrap(); + assert_eq!(s.doc().unwrap().doc.assets.values().next().unwrap().link_fingerprint, fingerprint(&svg)); s.execute("frame.create", &json!({"rect": [72, 300, 400, 400], "content": "text", "text": "Hello"})).unwrap(); let out = dir.join("Pkg"); let r = s.execute("file.package", &json!({"dir": out.to_string_lossy(), "pdf": true, "instructions": "Print on matte."})).unwrap(); @@ -323,10 +328,16 @@ fn package_writes_document_links_and_report() { let packed = super::super::from_bytes(&std::fs::read(doc_file).unwrap()).unwrap(); let link = packed.assets.values().next().unwrap().link.clone().unwrap(); assert!(link.contains("Links"), "{link}"); + // The link is the copy now: the original file's size and time don't go with it (the copy's + // own are too recent to vouch for it; the first check compares the bytes and keeps them). + assert!(fingerprint(&out.join("Links").join("logo.svg")).is_some()); + assert_eq!(packed.assets.values().next().unwrap().link_fingerprint, None); // Copy Links To relinks the open document. let r = s.execute("links.copyTo", &json!({"dir": dir.join("Copies").to_string_lossy()})).unwrap(); assert_eq!(r["copied"], 1); - assert!(s.doc().unwrap().doc.assets.values().next().unwrap().link.as_deref().unwrap().contains("Copies")); + let relinked = s.doc().unwrap().doc.assets.values().next().unwrap().clone(); + assert!(relinked.link.as_deref().unwrap().contains("Copies")); + assert_eq!(relinked.link_fingerprint, None); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1c585aa4f..18072e27d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -435,13 +435,10 @@ pub struct Session { /// New Document's Preview: the preview document's uid and the uid of the document that was /// active before it (see [`Session::preview_new_document`]). pub(crate) new_document_preview: Option<(u64, Option)>, - /// Linked text files checked by the Links panel: path → the size and modification time the - /// file had and the hash of its contents then, so a file touched but not changed is read once. - pub(crate) text_link_checks: std::collections::HashMap, - /// Linked images checked against their files this session (`links.list` polls twice a second): - /// a file of the recorded size and time isn't read again. - pub(crate) image_link_checks: - std::collections::HashMap<(designcraft_doc::AssetId, usize, std::path::PathBuf), (designcraft_doc::Fingerprint, bool)>, + /// Linked text files and images checked against their files this session (`links.list` is + /// polled): a file of the recorded size and time isn't read again, and one touched but not + /// changed is read once. + pub(crate) link_checks: cmd::LinkListChecks, } impl Default for Session { @@ -473,8 +470,7 @@ impl Session { clipboard_origin: 0.0, recovery_dir: None, text_clipboard: None, - text_link_checks: Default::default(), - image_link_checks: Default::default(), + link_checks: Default::default(), ui_requests: vec![], loaded: None, transforms: Default::default(), diff --git a/crates/engine/tests/support/optional_content.rs b/crates/engine/tests/support/optional_content.rs index b3acb3511..2b506b5f4 100644 --- a/crates/engine/tests/support/optional_content.rs +++ b/crates/engine/tests/support/optional_content.rs @@ -95,6 +95,7 @@ pub fn document(bytes: Vec, hidden_sets: &[&[&str]]) -> Document { mime: "application/pdf".into(), data: Arc::new(bytes), link: None, + link_fingerprint: None, pixels: None, page: 0, pdf_crop: Default::default(), diff --git a/crates/epub/tests/it/grouped_reading_order.rs b/crates/epub/tests/it/grouped_reading_order.rs index 42811f61d..c4689cf20 100644 --- a/crates/epub/tests/it/grouped_reading_order.rs +++ b/crates/epub/tests/it/grouped_reading_order.rs @@ -90,6 +90,7 @@ fn nested_and_item_rotations_are_combined_before_measuring_graphics() { name: "Grouped image".into(), mime: "image/svg+xml".into(), link: None, + link_fingerprint: None, data: Arc::new(br#""#.to_vec()), pixels: None, page: 0, diff --git a/crates/render/tests/it/colorize.rs b/crates/render/tests/it/colorize.rs index a99cc8435..b88854e8e 100644 --- a/crates/render/tests/it/colorize.rs +++ b/crates/render/tests/it/colorize.rs @@ -40,6 +40,7 @@ fn shown(file: Vec, fill: Fill) -> Vec<[u8; 4]> { name: "a".into(), mime: "image/png".into(), link: None, + link_fingerprint: None, data: Arc::new(file), pixels: Some((3, 1)), pdf_crop: Default::default(), diff --git a/crates/tools/src/tests.rs b/crates/tools/src/tests.rs index 0131885ae..40a494679 100644 --- a/crates/tools/src/tests.rs +++ b/crates/tools/src/tests.rs @@ -1771,6 +1771,7 @@ fn eyedropper_samples_a_placed_image_and_matches_other_objects() { name: "photo.png".into(), mime: "image/png".into(), link: None, + link_fingerprint: None, data: std::sync::Arc::new(vec![]), pixels: Some((100, 100)), page: 0, diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index b2b433b71..88bd48c58 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -53,6 +53,8 @@ impl DesignApp { views: HashMap::new(), page_history: HashMap::new(), canvas: CanvasCache::new(), + #[cfg(not(target_arch = "wasm32"))] + links_worker: crate::links_worker::State::default(), canvas_rect: None, split: false, second_window: false, diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 7c7d31e88..adf22f4fb 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1057,6 +1057,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Set", "مجموعة"), ("unused", "غير مستخدم"), ("⚠ Missing", "⚠ مفقود"), + ("Checking", "جارٍ التحقق"), + ("Link status is unavailable.", "حالة الروابط غير متاحة."), ("▲ Modified", "▲ معدّل"), ("(Text Color)", "(لون النص)"), ("{count} glyphs — click to insert at the text cursor", "عدد المحارف: {count} — انقر للإدراج عند مؤشر النص"), diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index b648aef56..5310e8d12 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -1499,6 +1499,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Set", "Sada"), ("unused", "nepoužito"), ("⚠ Missing", "⚠ Chybí"), + ("Checking", "Kontroluje se"), + ("Link status is unavailable.", "Stav propojení není k dispozici."), ("▲ Modified", "▲ Změněno"), ("(Text Color)", "(Barva textu)"), ("{count} glyphs — click to insert at the text cursor", "Glyfy: {count} — kliknutím vložíte na pozici textového kurzoru"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 894af427a..2e9920126 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1501,6 +1501,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Set", "Festlegen"), ("unused", "nicht verwendet"), ("⚠ Missing", "⚠ Fehlt"), + ("Checking", "Wird geprüft"), + ("Link status is unavailable.", "Der Verknüpfungsstatus ist nicht verfügbar."), ("▲ Modified", "▲ Geändert"), ("(Text Color)", "(Textfarbe)"), ("{count} glyphs — click to insert at the text cursor", "{count} Glyphen – zum Einfügen an der Einfügemarke klicken"), diff --git a/crates/ui-egui/src/i18n/hu.rs b/crates/ui-egui/src/i18n/hu.rs index b8d2942c2..ab30bce8d 100644 --- a/crates/ui-egui/src/i18n/hu.rs +++ b/crates/ui-egui/src/i18n/hu.rs @@ -1939,6 +1939,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("⌥-click clears overrides", "⌥-kattintás törli a felülírásokat"), ("▲ Modified", "▲ Módosítva"), ("⚠ Missing", "⚠ Hiányzik"), + ("Checking", "Ellenőrzés"), + ("Link status is unavailable.", "A csatolások állapota nem érhető el."), ("⚠ out of date", "⚠ elavult"), ("Selection Tool", "Kijelölő eszköz"), ("Direct Selection Tool", "Közvetlen kijelölő eszköz"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 28d58bf1a..131875d46 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1679,6 +1679,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Set", "Imposta"), ("unused", "non utilizzato"), ("⚠ Missing", "⚠ Mancante"), + ("Checking", "Verifica in corso"), + ("Link status is unavailable.", "Lo stato dei collegamenti non è disponibile."), ("▲ Modified", "▲ Modificato"), ("(Text Color)", "(Colore testo)"), ("{count} glyphs — click to insert at the text cursor", "{count} glifi — fai clic per inserire nella posizione del cursore di testo"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 2164f1309..ae2dd653f 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1702,6 +1702,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Set", "セット"), ("unused", "未使用"), ("⚠ Missing", "⚠ リンク切れ"), + ("Checking", "確認中"), + ("Link status is unavailable.", "リンクの状態を取得できません。"), ("▲ Modified", "▲ 変更済み"), ("(Text Color)", "(テキストカラー)"), ("{count} glyphs — click to insert at the text cursor", "{count}グリフ — クリックでテキストカーソル位置に挿入"), diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index 949e8e12c..1ba9a61a9 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -1594,6 +1594,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Set", "დაყენება"), ("unused", "გამოუყენებელი"), ("⚠ Missing", "⚠ აკლია"), + ("Checking", "მოწმდება"), + ("Link status is unavailable.", "ბმულის სტატუსი მიუწვდომელია."), ("▲ Modified", "▲ შეცვლილია"), ("(Text Color)", "(ტექსტის ფერი)"), ("{count} glyphs — click to insert at the text cursor", "გლიფი: {count} — დაწკაპეთ ტექსტის კურსორთან ჩასასმელად"), diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index 16d8e7d3a..7aac5d74b 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -1534,6 +1534,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Set", "Ustaw"), ("unused", "nieużywane"), ("⚠ Missing", "⚠ Brak"), + ("Checking", "Sprawdzanie"), + ("Link status is unavailable.", "Stan łączy jest niedostępny."), ("▲ Modified", "▲ Zmodyfikowane"), ("(Text Color)", "(Kolor tekstu)"), ("{count} glyphs — click to insert at the text cursor", "Glify: {count} — kliknij, aby wstawić przy kursorze tekstowym"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 34bdad4da..147947dbd 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1061,6 +1061,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Set", "Definir"), ("unused", "não utilizado"), ("⚠ Missing", "⚠ Ausente"), + ("Checking", "Verificando"), + ("Link status is unavailable.", "O status dos links não está disponível."), ("▲ Modified", "▲ Modificado"), ("(Text Color)", "(Cor do texto)"), ("{count} glyphs — click to insert at the text cursor", "{count} glifos — clique para inserir no cursor do texto"), diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index e0173ba11..178cc9bc3 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -1490,6 +1490,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Set", "Задать"), ("unused", "не используется"), ("⚠ Missing", "⚠ Отсутствует"), + ("Checking", "Проверка"), + ("Link status is unavailable.", "Состояние связей недоступно."), ("▲ Modified", "▲ Изменено"), ("(Text Color)", "(Цвет текста)"), ("{count} glyphs — click to insert at the text cursor", "Глифов: {count} — щелкните, чтобы вставить в позиции текстового курсора"), diff --git a/crates/ui-egui/src/i18n/sv.rs b/crates/ui-egui/src/i18n/sv.rs index d2371732b..766ba32da 100644 --- a/crates/ui-egui/src/i18n/sv.rs +++ b/crates/ui-egui/src/i18n/sv.rs @@ -852,6 +852,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Set", "Ange"), ("unused", "oanvänd"), ("⚠ Missing", "⚠ Saknas"), + ("Checking", "Kontrollerar"), + ("Link status is unavailable.", "Länkstatus är inte tillgänglig."), ("▲ Modified", "▲ Ändrad"), ("(Text Color)", "(Textfärg)"), ("{count} glyphs — click to insert at the text cursor", "{count} glyfer – klicka för att infoga vid textmarkören"), diff --git a/crates/ui-egui/src/i18n/table.rs b/crates/ui-egui/src/i18n/table.rs index 13e0a1bd0..ebde2b629 100644 --- a/crates/ui-egui/src/i18n/table.rs +++ b/crates/ui-egui/src/i18n/table.rs @@ -4148,6 +4148,17 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[ ("Set", ["Set", "Jeu", "Set", "Set", "样式集"]), ("unused", ["unused", "inutilisé", "unused", "unused", "未使用"]), ("⚠ Missing", ["⚠ Missing", "⚠ Manquant", "⚠ Missing", "⚠ Missing", "⚠ 缺失"]), + ("Checking", ["Wird geprüft", "Vérification", "Comprobando", "確認中", "正在检查"]), + ( + "Link status is unavailable.", + [ + "Der Verknüpfungsstatus ist nicht verfügbar.", + "L'état des liens n'est pas disponible.", + "El estado de los vínculos no está disponible.", + "リンクの状態を取得できません。", + "链接状态不可用。", + ], + ), ("▲ Modified", ["▲ Modified", "▲ Modifié", "▲ Modified", "▲ Modified", "▲ 已修改"]), ("(Text Color)", ["(Text Color)", "(Couleur du texte)", "(Text Color)", "(Text Color)", "(文本颜色)"]), ( diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 32aecd9e7..f873e5b8a 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -249,6 +249,23 @@ fn arrangement_accessible_name_is_localized_in_every_interface_language() { } } +/// The Links panel's captions for a status its background check hasn't found yet, and for when +/// the check can't run. +#[test] +fn links_panel_check_captions_are_localized_in_every_interface_language() { + for (code, name) in LANGUAGES { + for key in ["Checking", "Link status is unavailable."] { + let label = tr(code, key); + if code.is_empty() { + assert_eq!(label, key, "{name}"); + } else { + assert_ne!(label, key, "{name} still shows the English caption"); + assert!(!label.trim().is_empty(), "{name}: {key}"); + } + } + } +} + /// Checks language-specific context precedence and fallback to the plain translation. #[test] fn context_captions_come_from_their_context_or_the_plain_translation() { diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 6bdb6135f..4b2853eae 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -1676,6 +1676,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Set", "Установити"), ("unused", "не використовується"), ("⚠ Missing", "⚠ Немає"), + ("Checking", "Перевірка"), + ("Link status is unavailable.", "Стан зв’язків недоступний."), ("▲ Modified", "▲ Змінено"), ("(Text Color)", "(Колір тексту)"), ("{count} glyphs — click to insert at the text cursor", "Гліфів: {count} — клацніть, щоб вставити в позиції текстового курсора"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6775c7755..40bdfbcb3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -28,6 +28,8 @@ pub mod export_batch_dialog; pub mod i18n; pub mod icons; pub mod keys; +#[cfg(not(target_arch = "wasm32"))] +mod links_worker; pub mod menus; mod modal_drag; mod new_document; @@ -152,6 +154,10 @@ pub struct DesignApp { pub(crate) page_history: HashMap, /// The canvas cache and rect of the pane in `pane` (the other pane's are in `other_pane`). pub canvas: CanvasCache, + /// Native link checks run separately because an unavailable network share may block for an + /// operating-system timeout. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) links_worker: links_worker::State, pub canvas_rect: Option, /// Window › Arrange › Split Window: two views of the document side by side. pub split: bool, diff --git a/crates/ui-egui/src/links_worker.rs b/crates/ui-egui/src/links_worker.rs new file mode 100644 index 000000000..6e207d969 --- /dev/null +++ b/crates/ui-egui/src/links_worker.rs @@ -0,0 +1,942 @@ +//! Native background link checks for the Links panel. +//! +//! Whether a linked file is still there and unchanged is asked of the file system, and a network +//! share that doesn't answer keeps the caller waiting for an operating-system timeout. The +//! panel's rows therefore come from the document alone, on the UI thread, and their statuses +//! from a check on a worker thread: the statuses last found stay until newer ones arrive, so an +//! unavailable share can't stop the application from repainting or accepting input. + +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, PoisonError, Weak}; +use std::time::{Duration, Instant}; +use std::{hash::Hash, hash::Hasher}; + +use designcraft_compose::Cache; +use designcraft_doc::{AssetId, Document, Fingerprint}; +use designcraft_engine::cmd::LinkListChecks; +use serde_json::Value; + +// A document edit is checked at once. External changes (a file restored or edited elsewhere) are +// polled: an unchanged link costs one metadata call, but on a slow share with hundreds of links a +// check can itself take seconds, so the next one waits at least as long as the last took and the +// worker is idle at least half the time. +const REFRESH_MIN: Duration = Duration::from_secs(2); +const REFRESH_MAX: Duration = Duration::from_secs(5 * 60); +// A check for another document than the one shown is told to stop. One still running this long +// after is blocked in a file system call: the document shown gets a fresh worker instead of +// waiting behind it, and the blocked one ends when its call returns. +const SUPERSEDE_AFTER: Duration = Duration::from_millis(200); +// Workers alive at once, counting replaced ones still blocked in a file system call. Switching +// documents while a share is down can't pile up threads beyond this. +const MAX_WORKERS: usize = 4; +// A worker that couldn't be started, or that ended on its own (a panic under the link check), +// is replaced after this long: one failure doesn't leave the panel without statuses for the +// rest of the session, and a failure that repeats isn't retried on every frame. +const RETRY_AFTER: Duration = Duration::from_secs(30); +// Documents whose statuses are kept: going back to one shows them at once. +const MAX_DOCUMENTS: usize = 8; + +/// A document as a check sees it: which one, which state of it, and where it is saved (relative +/// links resolve against that). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) struct Key { + pub(crate) uid: u64, + document: usize, + path: u64, +} + +impl Key { + pub(crate) fn new(uid: u64, document: &Arc, path: Option<&str>) -> Self { + let mut path_hash = std::collections::hash_map::DefaultHasher::new(); + path.hash(&mut path_hash); + Self { uid, document: Arc::as_ptr(document) as usize, path: path_hash.finish() } + } +} + +#[derive(Clone)] +pub(crate) struct Snapshot { + pub(crate) key: Key, + pub(crate) doc: Arc, + pub(crate) cache: Arc, + pub(crate) document: Option, +} + +pub(crate) struct Rows { + /// The document's links as it is now, each with the status last found for it (`checking` + /// until one is). + pub(crate) values: Arc>, + /// No check can run for now (the worker couldn't be started, or ended): statuses may be old. + pub(crate) unavailable: bool, + /// Linked images a check just read and found unchanged, for + /// [`designcraft_engine::cmd::remember_link_files`]: only when the check was of the document + /// as it is now. + pub(crate) verified: Vec<(AssetId, Fingerprint)>, +} + +struct Job { + token: u64, + snapshot: Snapshot, + /// Set by the UI thread to end the check before its next file. + stop: Arc, +} + +struct Done { + token: u64, + key: Key, + /// Keeps the checked document's allocation, so no later document can reuse the address in + /// `key` and pass for it once this one is dropped. + pin: Weak, + /// The checked rows; `None` when the check was stopped. + rows: Option>, + verified: Vec<(AssetId, Fingerprint)>, + /// How long the check took and when it ended, on the worker's clock: the result may wait to + /// be read (the panel can be hidden meanwhile). + took: Duration, + finished: Instant, +} + +enum Poll { + Done(Done), + Empty, + Disconnected, +} + +type Runner = Box Option> + Send>; + +/// What the checks remember (files already compared), handed from job to job and from a replaced +/// worker to the next. Locked only between jobs, never while a file is asked for. +type Pool = Arc>; + +/// Counts a worker thread as alive until it ends, however it ends. Its end frees a slot below +/// [`MAX_WORKERS`], so the UI is woken to replace a worker it was waiting behind. +struct Alive { + live: Arc, + ctx: egui::Context, +} + +impl Drop for Alive { + fn drop(&mut self) { + self.live.fetch_sub(1, Ordering::Relaxed); + self.ctx.request_repaint(); + } +} + +struct Worker { + tx: std::sync::mpsc::Sender, + rx: std::sync::mpsc::Receiver, +} + +impl Worker { + fn spawn(ctx: egui::Context, live: Arc, pool: Pool) -> Option { + Self::spawn_with( + ctx, + live, + pool, + Box::new(|snapshot, checks, stop| { + designcraft_engine::cmd::list_document_links(&snapshot.doc, &snapshot.cache, snapshot.document.as_deref(), checks, stop) + }), + ) + } + + fn spawn_with(ctx: egui::Context, live: Arc, pool: Pool, mut run: Runner) -> Option { + let (tx, jobs) = std::sync::mpsc::channel::(); + let (done_tx, rx) = std::sync::mpsc::channel::(); + live.fetch_add(1, Ordering::Relaxed); + let alive = Alive { live, ctx: ctx.clone() }; + std::thread::Builder::new() + .name("designcraft-links".into()) + .spawn(move || { + let _alive = alive; + while let Ok(Job { token, snapshot, stop }) = jobs.recv() { + let (key, pin, started) = (snapshot.key, Arc::downgrade(&snapshot.doc), Instant::now()); + let mut checks = std::mem::take(&mut *pool.lock().unwrap_or_else(PoisonError::into_inner)); + let rows = run(&snapshot, &mut checks, &stop); + let verified = checks.take_verified(); + pool.lock().unwrap_or_else(PoisonError::into_inner).absorb(checks); + // Before the result is sent: whoever receives it finds the document no longer + // held here (an edited document isn't kept alive by its check). + drop(snapshot); + let done = Done { token, key, pin, rows, verified, took: started.elapsed(), finished: Instant::now() }; + if done_tx.send(done).is_err() { + break; + } + ctx.request_repaint(); + } + }) + .ok()?; + Some(Self { tx, rx }) + } + + fn submit(&self, job: Job) -> bool { + self.tx.send(job).is_ok() + } + + fn poll(&self) -> Poll { + let mut latest = None; + loop { + match self.rx.try_recv() { + Ok(done) => latest = Some(done), + Err(std::sync::mpsc::TryRecvError::Empty) => return latest.map_or(Poll::Empty, Poll::Done), + Err(std::sync::mpsc::TryRecvError::Disconnected) => return latest.map_or(Poll::Disconnected, Poll::Done), + } + } + } +} + +/// How long a check that took `took` stays current. +fn refresh_after(took: Duration) -> Duration { + took.clamp(REFRESH_MIN, REFRESH_MAX) +} + +/// The document's rows with, where a status waits for the files, the one the last check found +/// for the same link (the same graphic or story, at the same path). +fn with_statuses(document: &[Value], checked: Option<&[Value]>) -> Vec { + let Some(checked) = checked else { return document.to_vec() }; + let link = |row: &Value| (row["asset"].as_u64(), row["story"].as_u64(), row["path"].as_str().map(str::to_owned)); + let found: HashMap<_, &Value> = checked.iter().map(|row| (link(row), &row["status"])).collect(); + document + .iter() + .map(|row| { + let mut row = row.clone(); + if row["status"] == "checking" + && let Some(status) = found.get(&link(&row)) + && let Some(fields) = row.as_object_mut() + { + fields.insert("status".into(), (*status).clone()); + } + row + }) + .collect() +} + +/// The latest check of a document. +struct Checked { + key: Key, + /// As in [`Done`]: `key` names this document only while its allocation is kept. + _pin: Weak, + rows: Vec, + finished: Instant, + /// When its files are asked again. + due: Instant, +} + +/// The rows of the document shown, from the document alone. +struct Structure { + key: Key, + _pin: Weak, + rows: Vec, +} + +struct InFlight { + token: u64, + key: Key, + stop: Arc, + /// When the check was told to stop. + stopping: Option, +} + +#[cfg(test)] +type Spawn = Box, Pool) -> Option + Send + Sync>; + +/// What tests put in place of the worker's check and of the document's rows. +#[cfg(test)] +struct Hooks { + spawn: Spawn, + preview: Box Vec + Send + Sync>, +} + +#[derive(Default)] +pub(crate) struct State { + worker: Option, + /// When to try again after the worker couldn't be started or was found ended. + retry_at: Option, + next_token: u64, + in_flight: Option, + /// The latest check of each document shown lately, by uid. + checked: HashMap, + structure: Option, + /// `structure` with the statuses of the check that ended at the given time (none: `None`): + /// what the panel draws. + shown: Option<(Option, Arc>)>, + live: Arc, + pool: Pool, + #[cfg(test)] + hooks: Option, +} + +impl State { + pub(crate) fn rows(&mut self, ctx: &egui::Context, snapshot: Snapshot) -> Rows { + let key = snapshot.key; + let mut verified = Vec::new(); + match self.worker.as_ref().map(Worker::poll) { + Some(Poll::Done(done)) => { + if self.in_flight.as_ref().is_some_and(|job| job.token == done.token) { + self.in_flight = None; + } + // A check of an earlier state of the document still says how its files are: its + // statuses are shown while the next check runs. What it read vouches only for + // the bytes it compared, so that is passed on for this very state alone. + if let Some(rows) = done.rows { + if done.key == key { + verified = done.verified; + } + self.keep(Checked { + key: done.key, + _pin: done.pin, + rows, + finished: done.finished, + due: done.finished + refresh_after(done.took), + }); + } + } + Some(Poll::Disconnected) => { + self.worker = None; + self.retry_at = Some(Instant::now() + RETRY_AFTER); + self.in_flight = None; + } + Some(Poll::Empty) | None => {} + } + + // A check of another document than the one shown ends before its next file. If a file + // system call keeps it (a share that doesn't answer), it is left to finish on its own, + // its result dropped with its channel, and the document shown gets a fresh worker. + if let Some(job) = self.in_flight.as_mut().filter(|job| job.key.uid != key.uid) { + if job.stopping.is_none() { + job.stop.store(true, Ordering::Relaxed); + job.stopping = Some(Instant::now()); + } + let waited = job.stopping.map_or(Duration::ZERO, |at| at.elapsed()); + if waited < SUPERSEDE_AFTER { + // A blocked worker never asks for a repaint, so come back when it can be replaced. + ctx.request_repaint_after(SUPERSEDE_AFTER.saturating_sub(waited)); + } else if self.live.load(Ordering::Relaxed) < MAX_WORKERS { + self.worker = None; + self.in_flight = None; + } + } + if self.retry_at.is_some_and(|at| Instant::now() >= at) { + self.retry_at = None; + } + if self.worker.is_none() && self.retry_at.is_none() { + self.worker = self.spawn(ctx); + if self.worker.is_none() { + self.retry_at = Some(Instant::now() + RETRY_AFTER); + } + } + + let due = self.checked.get(&key.uid).is_none_or(|checked| checked.key != key || Instant::now() >= checked.due); + if due && self.in_flight.is_none() && self.retry_at.is_none() { + self.next_token = self.next_token.wrapping_add(1); + let (token, stop) = (self.next_token, Arc::new(AtomicBool::new(false))); + if self.worker.as_ref().is_some_and(|worker| worker.submit(Job { token, snapshot: snapshot.clone(), stop: Arc::clone(&stop) })) { + self.in_flight = Some(InFlight { token, key, stop, stopping: None }); + } else { + self.worker = None; + self.retry_at = Some(Instant::now() + RETRY_AFTER); + } + } + + let values = self.shown(&snapshot); + if let Some(at) = self.retry_at { + // Nothing else wakes the panel for the next try. + ctx.request_repaint_after(at.saturating_duration_since(Instant::now())); + } else if self.in_flight.is_none() + && let Some(checked) = self.checked.get(&key.uid).filter(|checked| checked.key == key) + { + ctx.request_repaint_after(checked.due.saturating_duration_since(Instant::now())); + } + Rows { values, unavailable: self.retry_at.is_some(), verified } + } + + fn spawn(&self, ctx: &egui::Context) -> Option { + let (live, pool) = (Arc::clone(&self.live), Arc::clone(&self.pool)); + #[cfg(test)] + if let Some(hooks) = &self.hooks { + return (hooks.spawn)(ctx.clone(), live, pool); + } + Worker::spawn(ctx.clone(), live, pool) + } + + /// The document's rows, looking at no file: an edit shows at once, whatever the worker is + /// waiting for. + fn preview(&self, snapshot: &Snapshot) -> Vec { + #[cfg(test)] + if let Some(hooks) = &self.hooks { + return (hooks.preview)(snapshot); + } + designcraft_engine::cmd::preview_document_links(&snapshot.doc, &snapshot.cache, snapshot.document.as_deref()) + } + + /// The rows to draw: built again only when the document or its latest check changes. + fn shown(&mut self, snapshot: &Snapshot) -> Arc> { + let key = snapshot.key; + if self.structure.as_ref().is_none_or(|structure| structure.key != key) { + let rows = self.preview(snapshot); + self.structure = Some(Structure { key, _pin: Arc::downgrade(&snapshot.doc), rows }); + self.shown = None; + } + let checked = self.checked.get(&key.uid); + let checked_at = checked.map(|checked| checked.finished); + if let Some((at, rows)) = &self.shown + && *at == checked_at + { + return Arc::clone(rows); + } + let document = self.structure.as_ref().map_or(&[][..], |structure| &structure.rows); + let rows = Arc::new(with_statuses(document, checked.map(|checked| checked.rows.as_slice()))); + self.shown = Some((checked_at, Arc::clone(&rows))); + rows + } + + fn keep(&mut self, checked: Checked) { + self.checked.insert(checked.key.uid, checked); + if self.checked.len() > MAX_DOCUMENTS + && let Some(oldest) = self.checked.iter().min_by_key(|(_, checked)| checked.finished).map(|(uid, _)| *uid) + { + self.checked.remove(&oldest); + } + } + + #[cfg(test)] + pub(crate) fn checking(&self) -> bool { + self.in_flight.is_some() + } +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + fn snapshot(key: Key) -> Snapshot { + Snapshot { key, doc: Arc::new(Document::new(&Default::default())), cache: Arc::new(Cache::new()), document: None } + } + + fn key(uid: u64, document: usize) -> Key { + Key { uid, document, path: 0 } + } + + fn row(asset: u64, status: &str) -> Value { + json!({"asset": asset, "name": format!("{asset}.png"), "path": format!("/links/{asset}.png"), "status": status}) + } + + fn statuses(rows: &Rows) -> Vec { + rows.values.iter().map(|row| row["status"].as_str().unwrap_or_default().to_string()).collect() + } + + /// Something a test's check waits for: opened by the test, or after two seconds so a failing + /// test can't hang. + #[derive(Clone, Default)] + struct Gate(Arc<(Mutex, std::sync::Condvar)>); + + impl Gate { + fn new() -> Self { + let gate = Self::default(); + let timeout = gate.clone(); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_secs(2)); + timeout.open(); + }); + gate + } + + fn open(&self) { + *self.0.0.lock().unwrap() = true; + self.0.1.notify_all(); + } + + fn wait(&self) { + let mut open = self.0.0.lock().unwrap(); + while !*open { + open = self.0.1.wait(open).unwrap(); + } + } + } + + /// A state whose document rows are `preview` and whose workers check with `run`; and how many + /// workers it has started. + fn state( + preview: impl Fn(&Snapshot) -> Vec + Send + Sync + 'static, + run: impl Fn(&Snapshot, &AtomicBool) -> Option> + Send + Sync + 'static, + ) -> (State, Arc) { + let (run, started) = (Arc::new(run), Arc::new(AtomicUsize::new(0))); + let count = Arc::clone(&started); + let spawn: Spawn = Box::new(move |ctx, live, pool| { + count.fetch_add(1, Ordering::Relaxed); + let run = Arc::clone(&run); + Worker::spawn_with(ctx, live, pool, Box::new(move |snapshot, _, stop| run(snapshot, stop))) + }); + (State { hooks: Some(Hooks { spawn, preview: Box::new(preview) }), ..Default::default() }, started) + } + + /// Ask for the rows as the panel does, frame after frame, until no check is in flight. + fn settle(state: &mut State, ctx: &egui::Context, key: Key) -> Rows { + let mut rows = state.rows(ctx, snapshot(key)); + for _ in 0..1000 { + if !state.checking() { + break; + } + std::thread::sleep(Duration::from_millis(2)); + rows = state.rows(ctx, snapshot(key)); + } + rows + } + + /// A worker the test answers for: the jobs sent to it, and where its results go. + fn by_hand(state: &mut State) -> (std::sync::mpsc::Receiver, std::sync::mpsc::Sender) { + let (tx, jobs) = std::sync::mpsc::channel::(); + let (done_tx, rx) = std::sync::mpsc::channel::(); + state.worker = Some(Worker { tx, rx }); + (jobs, done_tx) + } + + fn done(token: u64, key: Key, rows: Vec) -> Done { + Done { token, key, pin: Weak::new(), rows: Some(rows), verified: Vec::new(), took: Duration::ZERO, finished: Instant::now() } + } + + #[test] + fn the_rows_are_there_while_the_check_is_blocked() { + let ctx = egui::Context::default(); + let gate = Gate::new(); + let blocked = gate.clone(); + let (mut state, _) = state( + |_| vec![row(1, "checking")], + move |_, _| { + blocked.wait(); + Some(vec![row(1, "ok")]) + }, + ); + + let before = Instant::now(); + let rows = state.rows(&ctx, snapshot(key(1, 1))); + let elapsed = before.elapsed(); + + assert!(elapsed < Duration::from_millis(500), "the UI call waited {elapsed:?}"); + assert_eq!(statuses(&rows), ["checking"], "the document's rows, before any file answered"); + assert!(state.checking()); + gate.open(); + assert_eq!(statuses(&settle(&mut state, &ctx, key(1, 1))), ["ok"]); + } + + #[test] + fn an_edit_shows_at_once_with_the_statuses_last_found() { + let ctx = egui::Context::default(); + let gate = Gate::new(); + let blocked = gate.clone(); + // The edit (document 2) places a second graphic; its check doesn't answer for a while. + let (mut state, _) = state( + |snapshot| if snapshot.key.document == 1 { vec![row(1, "checking")] } else { vec![row(1, "checking"), row(2, "checking")] }, + move |snapshot, _| { + if snapshot.key.document == 1 { + return Some(vec![row(1, "modified")]); + } + blocked.wait(); + Some(vec![row(1, "ok"), row(2, "ok")]) + }, + ); + assert_eq!(statuses(&settle(&mut state, &ctx, key(1, 1))), ["modified"]); + + let rows = state.rows(&ctx, snapshot(key(1, 2))); + + assert_eq!(statuses(&rows), ["modified", "checking"], "the new graphic is listed, the other keeps its status"); + assert!(state.checking()); + gate.open(); + assert_eq!(statuses(&settle(&mut state, &ctx, key(1, 2))), ["ok", "ok"]); + } + + #[test] + fn a_check_of_an_earlier_edit_still_fills_in_statuses() { + let ctx = egui::Context::default(); + let (first, second) = (Gate::new(), Gate::new()); + let (wait_first, wait_second) = (first.clone(), second.clone()); + let (mut state, _) = state( + |_| vec![row(1, "checking")], + move |snapshot, _| { + if snapshot.key.document == 1 { + wait_first.wait(); + return Some(vec![row(1, "missing")]); + } + wait_second.wait(); + Some(vec![row(1, "ok")]) + }, + ); + // The document is edited while its check runs: the check isn't thrown away, or typing + // faster than a slow share answers would leave the statuses as they were for good. + state.rows(&ctx, snapshot(key(1, 1))); + assert_eq!(statuses(&state.rows(&ctx, snapshot(key(1, 2)))), ["checking"]); + first.open(); + let mut rows = state.rows(&ctx, snapshot(key(1, 2))); + for _ in 0..1000 { + if statuses(&rows) != ["checking"] { + break; + } + std::thread::sleep(Duration::from_millis(2)); + rows = state.rows(&ctx, snapshot(key(1, 2))); + } + + assert_eq!(statuses(&rows), ["missing"], "what the earlier check found is shown"); + assert!(state.checking(), "and the document as it is now is checked next"); + second.open(); + assert_eq!(statuses(&settle(&mut state, &ctx, key(1, 2))), ["ok"]); + } + + #[test] + fn a_check_is_timed_by_the_worker_not_by_when_its_result_is_read() { + let ctx = egui::Context::default(); + let (mut state, _) = state(|_| vec![row(1, "checking")], |_, _| None); + let (_jobs, results) = by_hand(&mut state); + state.rows(&ctx, snapshot(key(1, 1))); + // The panel may be hidden while a check ends: what counts is when it ended, there. + let (finished, took) = (Instant::now(), Duration::from_secs(4)); + results.send(Done { took, finished, ..done(1, key(1, 1), vec![row(1, "ok")]) }).unwrap(); + + let rows = state.rows(&ctx, snapshot(key(1, 1))); + + assert_eq!(statuses(&rows), ["ok"]); + let checked = &state.checked[&1]; + assert_eq!((checked.finished, checked.due), (finished, finished + took)); + } + + #[test] + fn external_changes_are_polled_within_seconds_and_slow_checks_space_out() { + assert_eq!(refresh_after(Duration::from_millis(30)), REFRESH_MIN, "a quick check is repeated after two seconds"); + assert_eq!(refresh_after(Duration::from_secs(4)), Duration::from_secs(4), "a slow share is idle as long as it was busy"); + assert_eq!(refresh_after(Duration::from_secs(3600)), REFRESH_MAX); + } + + #[test] + fn the_files_are_asked_again_when_a_check_is_due() { + let ctx = egui::Context::default(); + let (mut state, _) = state(|_| vec![row(1, "checking")], |_, _| Some(vec![row(1, "ok")])); + assert_eq!(statuses(&settle(&mut state, &ctx, key(1, 1))), ["ok"]); + state.rows(&ctx, snapshot(key(1, 1))); + assert!(!state.checking(), "a check just made is current"); + + state.checked.get_mut(&1).unwrap().due = Instant::now(); + state.rows(&ctx, snapshot(key(1, 1))); + + assert!(state.checking(), "an external change shows within the interval"); + } + + #[test] + fn a_check_of_another_document_is_stopped_and_its_worker_goes_on() { + let ctx = egui::Context::default(); + // Document 1's check has many files to go; like the engine's, it looks at the stop flag + // between them. + let (mut state, started) = state( + |snapshot| vec![row(snapshot.key.uid, "checking")], + |snapshot, stop| { + if snapshot.key.uid == 1 { + while !stop.load(Ordering::Relaxed) { + std::thread::sleep(Duration::from_millis(1)); + } + return None; + } + Some(vec![row(2, "ok")]) + }, + ); + state.rows(&ctx, snapshot(key(1, 1))); + + let rows = settle(&mut state, &ctx, key(2, 1)); + + assert_eq!(statuses(&rows), ["ok"]); + assert_eq!(started.load(Ordering::Relaxed), 1, "no thread is left behind for a check that can be stopped"); + } + + #[test] + fn a_blocked_check_of_another_document_does_not_gate_the_one_shown() { + let ctx = egui::Context::default(); + let gate = Gate::new(); + let blocked = gate.clone(); + // Document 1's links are on a share that doesn't answer. + let (mut state, started) = state( + |snapshot| vec![row(snapshot.key.uid, "checking")], + move |snapshot, _| { + if snapshot.key.uid == 1 { + blocked.wait(); + } + Some(vec![row(snapshot.key.uid, "ok")]) + }, + ); + state.rows(&ctx, snapshot(key(1, 1))); + state.rows(&ctx, snapshot(key(2, 1))); + std::thread::sleep(SUPERSEDE_AFTER); + + let rows = settle(&mut state, &ctx, key(2, 1)); + gate.open(); + + assert_eq!(statuses(&rows), ["ok"], "document 2 waited behind document 1's blocked check"); + assert_eq!(started.load(Ordering::Relaxed), 2); + } + + #[test] + fn a_switch_before_the_takeover_is_due_schedules_a_repaint_for_it() { + let ctx = egui::Context::default(); + let delays = Arc::new(Mutex::new(Vec::new())); + let seen = Arc::clone(&delays); + ctx.set_request_repaint_callback(move |info| seen.lock().unwrap().push(info.delay)); + let gate = Gate::new(); + let blocked = gate.clone(); + let (mut state, started) = state( + |_| Vec::new(), + move |_, _| { + blocked.wait(); + None + }, + ); + state.rows(&ctx, snapshot(key(1, 1))); + delays.lock().unwrap().clear(); + + state.rows(&ctx, snapshot(key(2, 1))); + + assert!(state.in_flight.as_ref().is_some_and(|job| job.key.uid == 1 && job.stop.load(Ordering::Relaxed)), "told to stop, not replaced yet"); + assert_eq!(started.load(Ordering::Relaxed), 1); + let delays = delays.lock().unwrap(); + assert!(delays.iter().any(|delay| *delay <= SUPERSEDE_AFTER), "no repaint scheduled for the takeover: {delays:?}"); + gate.open(); + } + + #[test] + fn a_replaced_worker_that_ends_wakes_the_document_waiting_at_the_limit() { + let ctx = egui::Context::default(); + let repaints = Arc::new(AtomicUsize::new(0)); + let seen = Arc::clone(&repaints); + ctx.set_request_repaint_callback(move |_| { + seen.fetch_add(1, Ordering::Relaxed); + }); + // Documents 1 and 2 are on shares that don't answer until released. + let (first, second) = (Gate::new(), Gate::new()); + let (wait_first, wait_second) = (first.clone(), second.clone()); + let (mut state, started) = state( + |snapshot| vec![row(snapshot.key.uid, "checking")], + move |snapshot, _| { + match snapshot.key.uid { + 1 => wait_first.wait(), + 2 => wait_second.wait(), + _ => {} + } + Some(vec![row(snapshot.key.uid, "ok")]) + }, + ); + // Two slots left: document 1's worker, then document 2's, which replaces it. + state.live = Arc::new(AtomicUsize::new(MAX_WORKERS - 2)); + let show = |state: &mut State, uid: u64| { + state.rows(&ctx, snapshot(key(uid, 1))); + std::thread::sleep(SUPERSEDE_AFTER); + state.rows(&ctx, snapshot(key(uid, 1))) + }; + show(&mut state, 1); + show(&mut state, 2); + show(&mut state, 3); + assert!(state.in_flight.as_ref().is_some_and(|job| job.key.uid == 2), "document 3 waits at the limit"); + assert_eq!((state.live.load(Ordering::Relaxed), started.load(Ordering::Relaxed)), (MAX_WORKERS, 2)); + + repaints.store(0, Ordering::Relaxed); + first.open(); + let woken = (0..1000).any(|_| { + std::thread::sleep(Duration::from_millis(2)); + repaints.load(Ordering::Relaxed) > 0 && state.live.load(Ordering::Relaxed) < MAX_WORKERS + }); + let rows = settle(&mut state, &ctx, key(3, 1)); + second.open(); + + assert!(woken, "the ended worker freed its slot and asked for a repaint"); + assert_eq!(statuses(&rows), ["ok"], "document 3 got a worker once a slot was free"); + assert_eq!(started.load(Ordering::Relaxed), 3); + } + + #[test] + fn replaced_workers_are_bounded() { + let ctx = egui::Context::default(); + let (mut state, started) = state(|_| Vec::new(), |_, _| None); + let (_jobs, _results) = by_hand(&mut state); + state.live = Arc::new(AtomicUsize::new(MAX_WORKERS)); + state.in_flight = Some(InFlight { token: 7, key: key(1, 1), stop: Arc::default(), stopping: Some(Instant::now()) }); + std::thread::sleep(SUPERSEDE_AFTER); + + state.rows(&ctx, snapshot(key(2, 1))); + + assert_eq!(state.in_flight.as_ref().map(|job| job.token), Some(7), "at the limit the document shown waits instead"); + assert_eq!(started.load(Ordering::Relaxed), 0); + } + + #[test] + fn a_worker_that_fails_is_replaced_after_a_while() { + let ctx = egui::Context::default(); + let delays = Arc::new(Mutex::new(Vec::new())); + let seen = Arc::clone(&delays); + ctx.set_request_repaint_callback(move |info| seen.lock().unwrap().push(info.delay)); + let (mut state, started) = state(|_| vec![row(1, "checking")], |_, _| Some(vec![row(1, "ok")])); + // The first worker can't be started; the next ones can. + let hooks = state.hooks.take().unwrap(); + let (attempts, spawn) = (Arc::new(AtomicUsize::new(0)), hooks.spawn); + let count = Arc::clone(&attempts); + let spawn: Spawn = Box::new(move |ctx, live, pool| if count.fetch_add(1, Ordering::Relaxed) == 0 { None } else { spawn(ctx, live, pool) }); + state.hooks = Some(Hooks { spawn, preview: hooks.preview }); + + let rows = settle(&mut state, &ctx, key(1, 1)); + assert!(rows.unavailable); + assert_eq!(statuses(&rows), ["checking"], "the document's rows are still listed"); + assert!(state.rows(&ctx, snapshot(key(1, 1))).unavailable, "not tried again on the next frame"); + assert_eq!(attempts.load(Ordering::Relaxed), 1); + let retry = |delay: &Duration| *delay > RETRY_AFTER / 2 && *delay <= RETRY_AFTER; + assert!(delays.lock().unwrap().iter().any(retry), "no repaint scheduled for the next try"); + + state.retry_at = Some(Instant::now()); + let rows = settle(&mut state, &ctx, key(1, 1)); + assert!(!rows.unavailable); + assert_eq!(statuses(&rows), ["ok"]); + + // The same for a worker found ended: its channels are closed. + let (jobs, results) = by_hand(&mut state); + drop((jobs, results)); + let rows = state.rows(&ctx, snapshot(key(1, 1))); + assert!(rows.unavailable); + assert_eq!(statuses(&rows), ["ok"], "the statuses last found stay"); + state.retry_at = Some(Instant::now()); + state.checked.clear(); + let rows = settle(&mut state, &ctx, key(1, 1)); + assert!(!rows.unavailable); + assert_eq!(statuses(&rows), ["ok"]); + assert_eq!((attempts.load(Ordering::Relaxed), started.load(Ordering::Relaxed)), (3, 2)); + } + + #[test] + fn statuses_are_kept_for_each_document_lately_shown() { + let ctx = egui::Context::default(); + let (mut state, _) = state(|snapshot| vec![row(snapshot.key.uid, "checking")], |snapshot, _| Some(vec![row(snapshot.key.uid, "ok")])); + settle(&mut state, &ctx, key(1, 1)); + settle(&mut state, &ctx, key(2, 1)); + + let rows = state.rows(&ctx, snapshot(key(1, 1))); + + assert_eq!(statuses(&rows), ["ok"], "going back to a document shows its statuses at once"); + assert!(!state.checking(), "and a check still current isn't made again"); + for uid in 3..=(MAX_DOCUMENTS as u64 + 2) { + settle(&mut state, &ctx, key(uid, 1)); + } + assert_eq!(state.checked.len(), MAX_DOCUMENTS); + assert!(!state.checked.contains_key(&1), "the document checked longest ago goes first"); + } + + #[test] + fn files_found_unchanged_are_passed_on_only_for_the_document_as_it_was_checked() { + let ctx = egui::Context::default(); + let (mut state, _) = state(|_| vec![row(1, "checking")], |_, _| None); + let (_jobs, results) = by_hand(&mut state); + let found = vec![(AssetId(1), Fingerprint { size: 4, mtime: 9 })]; + state.rows(&ctx, snapshot(key(1, 1))); + results.send(Done { verified: found.clone(), ..done(1, key(1, 1), vec![row(1, "ok")]) }).unwrap(); + assert_eq!(state.rows(&ctx, snapshot(key(1, 1))).verified, found); + assert_eq!(state.rows(&ctx, snapshot(key(1, 1))).verified, [], "once"); + + // Edited since the check started: other bytes may be linked now. + state.rows(&ctx, snapshot(key(1, 2))); + results.send(Done { verified: found, ..done(2, key(1, 2), vec![row(1, "modified")]) }).unwrap(); + let rows = state.rows(&ctx, snapshot(key(1, 3))); + assert_eq!(rows.verified, []); + assert_eq!(statuses(&rows), ["modified"], "its statuses are still shown"); + } + + #[test] + fn what_a_check_remembers_goes_to_the_worker_that_replaces_it() { + let dir = std::env::temp_dir().join(format!("dc-links-worker-pool-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("photo.png"); + std::fs::write(&path, designcraft_render::Rendered { width: 2, height: 2, pixels: vec![200; 16] }.to_png()).unwrap(); + let age = |secs: u64| { + let file = std::fs::File::options().write(true).open(&path).unwrap(); + file.set_modified(std::time::SystemTime::now() - Duration::from_secs(secs)).unwrap(); + }; + // Placed, then given a new time (a restored folder): the check has to compare its bytes. + age(300); + let mut session = designcraft_engine::Session::new(); + session.execute("file.new", &json!({})).unwrap(); + session.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap(); + age(60); + let doc = Arc::clone(&session.doc().unwrap().doc); + let real = Snapshot { key: Key::new(1, &doc, None), doc, cache: Arc::clone(&session.cache), document: None }; + // Each worker says how much it was handed before checking. + let (handed_tx, handed) = std::sync::mpsc::channel(); + let handed_tx = Mutex::new(handed_tx); + let spawn: Spawn = Box::new(move |ctx, live, pool| { + let handed = handed_tx.lock().unwrap().clone(); + Worker::spawn_with( + ctx, + live, + pool, + Box::new(move |snapshot, checks, stop| { + let _ = handed.send(checks.len()); + designcraft_engine::cmd::list_document_links(&snapshot.doc, &snapshot.cache, None, checks, stop) + }), + ) + }); + let ctx = egui::Context::default(); + let mut state = State { hooks: Some(Hooks { spawn, preview: Box::new(|_| Vec::new()) }), ..Default::default() }; + let check = |state: &mut State| { + state.rows(&ctx, real.clone()); + for _ in 0..1000 { + if !state.checking() { + break; + } + std::thread::sleep(Duration::from_millis(2)); + state.rows(&ctx, real.clone()); + } + }; + + check(&mut state); + // A replaced worker: as when a check of another document was blocked. + state.worker = None; + state.checked.clear(); + check(&mut state); + + assert_eq!(handed.try_iter().collect::>(), [0, 1], "the second worker starts from what the first compared"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_check_keeps_its_documents_address_from_being_reused() { + let ctx = egui::Context::default(); + let (mut state, _) = state(|_| Vec::new(), |_, _| Some(Vec::new())); + let doc = Arc::new(Document::new(&Default::default())); + let key = Key::new(1, &doc, None); + let snapshot = || Snapshot { key, doc: Arc::clone(&doc), cache: Arc::new(Cache::new()), document: None }; + state.rows(&ctx, snapshot()); + for _ in 0..1000 { + if !state.checking() { + break; + } + std::thread::sleep(Duration::from_millis(2)); + state.rows(&ctx, snapshot()); + } + assert!(!state.checking(), "the check finished"); + let address = Arc::as_ptr(&doc); + + // Edits replace the document; the old one is dropped once nothing else holds it. + drop(doc); + + // A weak reference keeps the allocation, so no later document can be given the address + // in `key` while this check is kept. The worker let go of the document before it + // answered, so nothing else holds it. + let pin = state.checked.get(&1).map(|checked| &checked._pin); + assert!(pin.is_some_and(|pin| pin.as_ptr() == address && pin.strong_count() == 0), "the check doesn't hold its document's allocation"); + } + + #[test] + fn statuses_go_to_the_same_link_only() { + let document = + [row(1, "checking"), json!({"story": 1, "path": "/links/1.png", "status": "checking"}), row(2, "embedded"), row(3, "checking")]; + // Graphic 3 was relinked since: what was found is of another file. + let checked = [row(1, "modified"), json!({"asset": 3, "path": "/elsewhere/3.png", "status": "ok"}), row(2, "ok")]; + + let rows = with_statuses(&document, Some(&checked)); + + let status: Vec<_> = rows.iter().map(|row| row["status"].as_str().unwrap()).collect(); + assert_eq!(status, ["modified", "checking", "embedded", "checking"]); + assert_eq!(with_statuses(&document, None), document); + } +} diff --git a/crates/ui-egui/src/panels/properties/links.rs b/crates/ui-egui/src/panels/properties/links.rs index 8d13fe06d..5ee02ea79 100644 --- a/crates/ui-egui/src/panels/properties/links.rs +++ b/crates/ui-egui/src/panels/properties/links.rs @@ -35,19 +35,47 @@ pub fn links_panel(app: &mut DesignApp, ui: &mut egui::Ui) { } let Some(st) = app.session.active() else { return }; let t = Tokens::get(ui.ctx()); - // The list checks files on disk: refresh it at most twice a second. - let key = egui::Id::unique("links_panel"); - let now = ui.input(|i| i.time); - let rev = (st.uid, st.revision); - let cached: Option<(f64, (u64, u64), Vec)> = ui.data(|d| d.get_temp(key)); - let rows = match cached { - Some((at, r, rows)) if r == rev && now - at < 0.5 => rows, - _ => { - let rows = app.session.execute("links.list", &json!({})).ok().and_then(|v| v.as_array().cloned()).unwrap_or_default(); - ui.data_mut(|d| d.insert_temp(key, (now, rev, rows.clone()))); - rows + // Whether a linked file is still there and unchanged is asked of the file system, and a + // network path may take an operating-system timeout to answer: native builds list the links + // from the document and take their statuses from a check on a background worker. + #[cfg(not(target_arch = "wasm32"))] + let refresh = { + let doc = std::sync::Arc::clone(&st.doc); + let snapshot = crate::links_worker::Snapshot { + key: crate::links_worker::Key::new(st.uid, &doc, st.path.as_deref()), + doc: std::sync::Arc::clone(&doc), + cache: std::sync::Arc::clone(&app.session.cache), + document: st.path.as_ref().map(std::path::PathBuf::from), + }; + let refresh = app.links_worker.rows(ui.ctx(), snapshot); + // A file the check read and found unchanged isn't read again, in this session or the next. + if !refresh.verified.is_empty() { + designcraft_engine::cmd::remember_link_files(&mut app.session, &doc, &refresh.verified); + } + refresh + }; + #[cfg(not(target_arch = "wasm32"))] + let rows = &refresh.values; + // Web builds have no filesystem to wait for: the list is refreshed at most twice a second. + #[cfg(target_arch = "wasm32")] + let rows = { + let key = egui::Id::unique("links_panel"); + let now = ui.input(|i| i.time); + let rev = (st.uid, st.revision); + let cached: Option<(f64, (u64, u64), Vec)> = ui.data(|d| d.get_temp(key)); + match cached { + Some((at, r, rows)) if r == rev && now - at < 0.5 => rows, + _ => { + let rows = app.session.execute("links.list", &json!({})).ok().and_then(|v| v.as_array().cloned()).unwrap_or_default(); + ui.data_mut(|d| d.insert_temp(key, (now, rev, rows.clone()))); + rows + } } }; + #[cfg(not(target_arch = "wasm32"))] + if refresh.unavailable && !rows.is_empty() { + crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Link status is unavailable.")).color(t.text_dim).size(11.0)); + } if rows.is_empty() { crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "No placed graphics.")).color(t.text_dim)); return; @@ -61,7 +89,7 @@ pub fn links_panel(app: &mut DesignApp, ui: &mut egui::Ui) { crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Status")).color(t.text_dim).size(11.0)); crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Page · PPI")).color(t.text_dim).size(11.0)); ui.end_row(); - for r in &rows { + for r in rows.iter() { // Asset and story ids come from one counter: a row is chosen by either. let aid = r["asset"].as_u64().or_else(|| r["story"].as_u64()).unwrap_or(0); let name = r["name"].as_str().unwrap_or(""); @@ -90,6 +118,7 @@ pub fn links_panel(app: &mut DesignApp, ui: &mut egui::Ui) { "missing" => ("\u{26A0} Missing", egui::Color32::from_rgb(0xe5, 0x4b, 0x4b)), "modified" => ("\u{25B2} Modified", egui::Color32::from_rgb(0xe8, 0xb3, 0x2c)), "embedded" => ("Embedded", t.text_dim), + "checking" => ("Checking", t.text_dim), "tooLarge" => ("Too large to check", egui::Color32::from_rgb(0xe8, 0xb3, 0x2c)), _ => ("OK", t.text_dim), }; @@ -203,14 +232,22 @@ pub fn links_panel(app: &mut DesignApp, ui: &mut egui::Ui) { /// first when a linked text story edited in the layout would lose those edits, as InDesign's /// Links panel does. The `links.update` command itself doesn't ask (as in InDesign scripting). pub fn update_links(app: &mut DesignApp, target: Value) { - let rows = app.session.execute("links.list", &json!({})).ok().and_then(|v| v.as_array().cloned()).unwrap_or_default(); let one = target.get("story").and_then(Value::as_u64); let all = one.is_none() && target.get("asset").is_none(); - let edited: Vec<&str> = rows - .iter() - .filter(|r| (all || (one.is_some() && r["story"].as_u64() == one)) && r["edited"] == true && r["status"] == "modified") - .filter_map(|r| r["name"].as_str()) - .collect(); + let wanted = |r: &Value| (all || (one.is_some() && r["story"].as_u64() == one)) && r["edited"] == true; + // Which linked stories were edited in the layout is in the document. Only when one was are + // the files asked whether it changed too: `links.list` asks every linked file, on this + // thread, and a share that doesn't answer would hold up every other update. + let any_edited = app.session.active().is_some_and(|st| { + let document = st.path.as_deref().map(std::path::Path::new); + designcraft_engine::cmd::preview_document_links(&st.doc, &app.session.cache, document).iter().any(wanted) + }); + let rows = if any_edited { + app.session.execute("links.list", &json!({})).ok().and_then(|v| v.as_array().cloned()).unwrap_or_default() + } else { + Vec::new() + }; + let edited: Vec<&str> = rows.iter().filter(|r| wanted(r) && r["status"] == "modified").filter_map(|r| r["name"].as_str()).collect(); if edited.is_empty() { let _ = run_update_links(app, target); } else { diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index cdbc9002d..1e7c40c8a 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -81,9 +81,24 @@ fn links_harness(app: DesignApp, width: f32) -> Harness<'static, DesignApp> { ); h.input_mut().max_texture_side = Some(8192); h.run_steps(3); + settle_links(&mut h); h } +/// The link statuses come from a background check: step until it has finished and its rows are +/// drawn. +fn settle_links(h: &mut Harness<'static, DesignApp>) { + for _ in 0..500 { + h.run_steps(1); + if !h.state().links_worker.checking() { + h.run_steps(1); + return; + } + std::thread::sleep(std::time::Duration::from_millis(2)); + } + panic!("the background link check did not finish"); +} + /// With the caret in text, the Stroke panel offers the text's stroke options, not an empty panel. /// The first and last line indents take negative values, as InDesign's (and the Paragraph /// panel's) do; the left and right indents and the spacing don't. @@ -165,6 +180,7 @@ fn links_panel_distinguishes_same_named_sources_and_keeps_link_actions() { assert_eq!(h.state().session.active().unwrap().selection.items, vec![items[1]]); h.get_by_label("Embed").click(); h.run_steps(3); + settle_links(&mut h); assert!(h.state().session.active().unwrap().doc.assets[&assets[1]].link.is_none()); assert_eq!(h.state().session.active().unwrap().doc.assets[&assets[0]].link.as_deref(), Some(first)); assert!(h.query_by_label(second).is_none(), "an embedded graphic no longer shows a source path"); From e8f162ea9f3f9ece9db9c45b4bfad2ef5519165d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 15:50:54 +0000 Subject: [PATCH 0882/1349] fix(engine): end runaway loops in variable deletion, data-merge markers and nested scripts --- crates/engine/src/cmd/datamerge/fill.rs | 34 +++++++++++-- crates/engine/src/cmd/variables.rs | 13 +++-- crates/engine/src/cmd/variables/tests.rs | 16 ++++++ crates/engine/src/lib.rs | 6 +++ crates/engine/src/script.rs | 62 +++++++++++++++++++++++- 5 files changed, 121 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/datamerge/fill.rs b/crates/engine/src/cmd/datamerge/fill.rs index ae0b4e6b4..a7b4a0ba6 100644 --- a/crates/engine/src/cmd/datamerge/fill.rs +++ b/crates/engine/src/cmd/datamerge/fill.rs @@ -334,13 +334,18 @@ fn typed_reps( fn find_markers(text: &str) -> Vec<(usize, usize, String)> { let mut out = Vec::new(); let mut i = 0; + // The next `>>` at or after the `<<` being looked at: found once, kept until passed, so the + // text is scanned once however many `<<` it holds (not again from every one of them). + let mut close: Option = Some(0); while i < text.len() { - if text[i..].starts_with("<<") - && let Some(rel) = text[i + 2..].find(">>") - { - let name = &text[i + 2..i + 2 + rel]; + if text[i..].starts_with("<<") { + if close.is_some_and(|c| c < i + 2) { + close = text[i + 2..].find(">>").map(|rel| i + 2 + rel); + } + let Some(c) = close else { break }; + let name = &text[i + 2..c]; if !name.is_empty() && !name.contains(['<', '>', '\n']) { - let end = i + 2 + rel + 2; + let end = c + 2; out.push((i, end, name.to_string())); i = end; continue; @@ -570,6 +575,25 @@ fn cell_of<'a>(fields: &[DataField], row: &'a [String], name: &str) -> &'a str { fields.iter().position(|f| f.name == name).and_then(|i| row.get(i)).map(String::as_str).unwrap_or("") } +#[cfg(test)] +mod marker_tests { + use super::find_markers; + + #[test] + fn markers_are_found_in_one_pass() { + let found = find_markers; + assert_eq!(found("a <> b <>"), [(2, 10, "Name".to_string()), (13, 18, "x".to_string())]); + assert_eq!(found("<<>> <> <>"), [(13, 19, "ok".to_string())]); + assert_eq!(found("<<<>"), [(2, 7, "a".to_string())]); + // Many `<<` with no `>>` to close them: linear, not a search from each of them. + let open = "<<".repeat(200_000); + let t = std::time::Instant::now(); + assert!(found(&open).is_empty()); + assert!(found(&format!("{open}>>")).is_empty(), "a name made of `<` isn't one"); + assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed()); + } +} + #[cfg(test)] mod link_tests { use super::*; diff --git a/crates/engine/src/cmd/variables.rs b/crates/engine/src/cmd/variables.rs index e2bf23e9a..1bbe39849 100644 --- a/crates/engine/src/cmd/variables.rs +++ b/crates/engine/src/cmd/variables.rs @@ -361,16 +361,21 @@ fn unvar(st: &mut designcraft_doc::Story, i: usize, n: usize, value: &str, depth return; } if st.text.chars().any(|c| designcraft_doc::vars::var_index(c).is_some_and(|k| k >= i)) { + // The instances as they are now, replaced last first so earlier positions stay valid: + // text put in isn't searched again (a value holding the marker would never end). + let instances = |text: &str, target: &str| { + let mut at: Vec = text.match_indices(target).map(|(pos, _)| pos).collect(); + at.reverse(); + at + }; let target = var_char(i).unwrap_or(' ').to_string(); - let mut occurrences: Vec = st.text.match_indices(&target).map(|(pos, _)| pos).collect(); - occurrences.reverse(); - for pos in occurrences { + for pos in instances(&st.text, &target) { st.replace(pos..pos + target.len(), value); on_replace(pos, target.len()); } for k in i + 1..n { let (from, to) = (var_char(k).unwrap_or(' ').to_string(), var_char(k - 1).unwrap_or(' ').to_string()); - while let Some(pos) = st.text.find(&from) { + for pos in instances(&st.text, &from) { st.replace(pos..pos + from.len(), &to); } } diff --git a/crates/engine/src/cmd/variables/tests.rs b/crates/engine/src/cmd/variables/tests.rs index 6a2291ccb..e89573bb5 100644 --- a/crates/engine/src/cmd/variables/tests.rs +++ b/crates/engine/src/cmd/variables/tests.rs @@ -290,6 +290,22 @@ fn delete_variable_reaches_table_cells() { assert_eq!(t.cells[0].text.text, format!("Alpha|{}", var_char(nb).unwrap())); } +/// A custom variable whose text holds its own instance marker: deleting it puts that text in +/// once per instance and ends (the text put in isn't searched for instances again). +#[test] +fn delete_variable_whose_value_holds_its_marker_ends() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("variables.define", &json!({"name": "A", "type": "custom", "text": "a"})).unwrap(); + let a = s.doc().unwrap().doc.variable("A").unwrap(); + let marker = var_char(a).unwrap(); + s.execute("variables.define", &json!({"name": "A", "type": "custom", "text": format!("<{marker}>")})).unwrap(); + s.execute("frame.create", &json!({"rect": [72, 72, 400, 300], "content": "text", "text": format!("x{marker}y{marker}z")})).unwrap(); + s.execute("variables.delete", &json!({"name": "A"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.stories.values().next().unwrap().text, format!("x<{marker}>y<{marker}>z")); +} + /// Deleting a variable flattens its instances in footnotes and endnotes too and moves the /// instances of later variables down. #[test] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1bec28c75..f87371531 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -392,6 +392,10 @@ pub struct Session { active: Option, /// An undoable command is running: the commands it runs are part of its undo step. in_undo_step: bool, + /// Scripts running one inside another, and the steps the outermost may still run + /// ([`script::MAX_SCRIPT_DEPTH`], [`script::MAX_SCRIPT_STEPS`]). + pub(crate) script_depth: usize, + pub(crate) script_steps: usize, pub prefs: Prefs, pub cache: Arc, pub(crate) tool: Box, @@ -461,6 +465,8 @@ impl Session { docs: vec![], active: None, in_undo_step: false, + script_depth: 0, + script_steps: 0, prefs: Prefs::default(), cache: Arc::new(Cache::new()), tool: designcraft_tools::create("selection"), diff --git a/crates/engine/src/script.rs b/crates/engine/src/script.rs index 2f8394f34..25c548d04 100644 --- a/crates/engine/src/script.rs +++ b/crates/engine/src/script.rs @@ -110,6 +110,10 @@ fn is_reference(r: &str) -> bool { head_ok && parts.all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')) } +/// Longest string a `${…}` interpolation may build: a step that pastes an earlier result into a +/// story, then interpolates that story into the next, could otherwise double its size each step. +pub const MAX_INTERPOLATED_BYTES: usize = 16 << 20; + /// Replace references in `params` with values from earlier `results`. pub fn resolve(params: &Value, results: &[Value]) -> Result { Ok(match params { @@ -134,6 +138,10 @@ pub fn resolve(params: &Value, results: &[Value]) -> Result { Value::String(t) => out.push_str(&t), other => out.push_str(&other.to_string()), } + if out.len() > MAX_INTERPOLATED_BYTES { + return Err(format!("the interpolated text of {} is longer than {MAX_INTERPOLATED_BYTES} bytes", s.get(..40).unwrap_or(s)) + .replace('\n', " ")); + } rest = &inner[end + 1..]; } else { out.push('$'); @@ -182,10 +190,33 @@ pub fn run(steps: &[Step], mut exec: impl FnMut(&str, Value) -> Result Report { - run(steps, |c, p| self.execute(c, &p).map_err(|e| e.to_string())) + if self.script_depth >= MAX_SCRIPT_DEPTH { + let command = steps.first().map(|s| s.command.clone()).unwrap_or_default(); + return Report { + results: vec![], + failed: Some((0, command, format!("scripts nest deeper than {MAX_SCRIPT_DEPTH} (a script running a script…)"))), + }; + } + if self.script_depth == 0 { + self.script_steps = MAX_SCRIPT_STEPS; + } + self.script_depth += 1; + let report = run(steps, |c, p| { + self.script_steps = + self.script_steps.checked_sub(1).ok_or_else(|| format!("the script and the scripts it runs exceed {MAX_SCRIPT_STEPS} steps"))?; + self.execute(c, &p).map_err(|e| e.to_string()) + }); + self.script_depth -= 1; + report } } @@ -275,6 +306,35 @@ mod tests { assert_eq!(r.results[3]["text"], "a\u{a0}v\u{a0}Praze"); } + /// A script that runs scripts stops at the depth limit, and the steps of all of them count + /// against one budget; the session goes on afterwards. + #[test] + fn nested_scripts_are_bounded() { + let mut s = crate::Session::new(); + let steps = parse("file.new\ndocument.inspect\ndocument.inspect").unwrap(); + s.script_depth = MAX_SCRIPT_DEPTH; + let e = s.run_script(&steps).failed.expect("must fail").2; + assert!(e.contains("nest deeper"), "{e}"); + s.script_depth = 1; + s.script_steps = 2; + let r = s.run_script(&steps); + assert_eq!(r.results.len(), 2); + assert!(r.failed.as_ref().is_some_and(|f| f.2.contains("exceed")), "{r:?}"); + s.script_depth = 0; + let r = s.run_script(&steps); + assert!(r.failed.is_none(), "{r:?}"); + assert_eq!(s.script_depth, 0); + } + + #[test] + fn interpolation_is_capped() { + let big = "x".repeat(MAX_INTERPOLATED_BYTES / 2 + 1); + let results = vec![json!({"text": big})]; + assert!(resolve(&json!("${0.text}"), &results).is_ok()); + let e = resolve(&json!("${0.text}${0.text}"), &results).unwrap_err(); + assert!(e.contains("longer than"), "{e}"); + } + #[test] fn runs_on_a_session_with_references() { let mut s = crate::Session::new(); From d0683224caf2a32b0f038f98754891a021f4085c Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Tue, 3 Nov 2026 19:32:55 +0000 Subject: [PATCH 0883/1349] Apply review fixes - crates/engine/src/cmd/variables.rs - crates/engine/src/cmd/variables/tests.rs - crates/engine/src/script.rs --- crates/engine/src/cmd/variables.rs | 3 ++- crates/engine/src/cmd/variables/tests.rs | 5 +++-- crates/engine/src/script.rs | 4 ++++ 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/variables.rs b/crates/engine/src/cmd/variables.rs index 1bbe39849..b9319325e 100644 --- a/crates/engine/src/cmd/variables.rs +++ b/crates/engine/src/cmd/variables.rs @@ -369,8 +369,9 @@ fn unvar(st: &mut designcraft_doc::Story, i: usize, n: usize, value: &str, depth at }; let target = var_char(i).unwrap_or(' ').to_string(); + let value = match var_char(i) { Some(c) => value.replace(c, ""), None => value.to_string() }; for pos in instances(&st.text, &target) { - st.replace(pos..pos + target.len(), value); + st.replace(pos..pos + target.len(), &value); on_replace(pos, target.len()); } for k in i + 1..n { diff --git a/crates/engine/src/cmd/variables/tests.rs b/crates/engine/src/cmd/variables/tests.rs index e89573bb5..beb775424 100644 --- a/crates/engine/src/cmd/variables/tests.rs +++ b/crates/engine/src/cmd/variables/tests.rs @@ -291,7 +291,8 @@ fn delete_variable_reaches_table_cells() { } /// A custom variable whose text holds its own instance marker: deleting it puts that text in -/// once per instance and ends (the text put in isn't searched for instances again). +/// once per instance, without the value's own marker, and ends (the text put in isn't searched +/// for instances again). #[test] fn delete_variable_whose_value_holds_its_marker_ends() { let mut s = Session::new(); @@ -303,7 +304,7 @@ fn delete_variable_whose_value_holds_its_marker_ends() { s.execute("frame.create", &json!({"rect": [72, 72, 400, 300], "content": "text", "text": format!("x{marker}y{marker}z")})).unwrap(); s.execute("variables.delete", &json!({"name": "A"})).unwrap(); let d = &s.doc().unwrap().doc; - assert_eq!(d.stories.values().next().unwrap().text, format!("x<{marker}>y<{marker}>z")); + assert_eq!(d.stories.values().next().unwrap().text, "x<>y<>z"); } /// Deleting a variable flattens its instances in footnotes and endnotes too and moves the diff --git a/crates/engine/src/script.rs b/crates/engine/src/script.rs index 25c548d04..e3646476d 100644 --- a/crates/engine/src/script.rs +++ b/crates/engine/src/script.rs @@ -149,6 +149,10 @@ pub fn resolve(params: &Value, results: &[Value]) -> Result { } } out.push_str(rest); + if out.len() > MAX_INTERPOLATED_BYTES { + return Err(format!("the interpolated text of {} is longer than {MAX_INTERPOLATED_BYTES} bytes", s.get(..40).unwrap_or(s)) + .replace('\n', " ")); + } Value::String(out) } Value::Array(a) => Value::Array(a.iter().map(|v| resolve(v, results)).collect::>()?), From 95acc4d47edb87c4f61297a6b90689361d911b9c Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Tue, 3 Nov 2026 19:38:39 +0000 Subject: [PATCH 0884/1349] Apply review fixes - crates/engine/src/cmd/variables.rs --- crates/engine/src/cmd/variables.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/variables.rs b/crates/engine/src/cmd/variables.rs index b9319325e..b1c5ff59b 100644 --- a/crates/engine/src/cmd/variables.rs +++ b/crates/engine/src/cmd/variables.rs @@ -369,7 +369,7 @@ fn unvar(st: &mut designcraft_doc::Story, i: usize, n: usize, value: &str, depth at }; let target = var_char(i).unwrap_or(' ').to_string(); - let value = match var_char(i) { Some(c) => value.replace(c, ""), None => value.to_string() }; + let value = var_char(i).map_or_else(|| value.to_string(), |c| value.replace(c, "")); for pos in instances(&st.text, &target) { st.replace(pos..pos + target.len(), &value); on_replace(pos, target.len()); From ef82d650db8c8685e6686b4626e3e2487e32aaeb Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:15:30 +0000 Subject: [PATCH 0885/1349] Fix failing CI check - crates/engine/src/script.rs --- crates/engine/src/script.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script.rs b/crates/engine/src/script.rs index e3646476d..de2589d9f 100644 --- a/crates/engine/src/script.rs +++ b/crates/engine/src/script.rs @@ -150,8 +150,9 @@ pub fn resolve(params: &Value, results: &[Value]) -> Result { } out.push_str(rest); if out.len() > MAX_INTERPOLATED_BYTES { - return Err(format!("the interpolated text of {} is longer than {MAX_INTERPOLATED_BYTES} bytes", s.get(..40).unwrap_or(s)) - .replace('\n', " ")); + return Err( + format!("the interpolated text of {} is longer than {MAX_INTERPOLATED_BYTES} bytes", s.get(..40).unwrap_or(s)).replace('\n', " ") + ); } Value::String(out) } From c85f7425a412a41db04e3c9cd1807faa1dfb6d67 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 4 Nov 2026 04:35:43 +0000 Subject: [PATCH 0886/1349] address review: build unvar value only when an instance exists; check interpolation length before copying; bound the limit-error preview --- crates/engine/src/cmd/variables.rs | 11 ++++--- crates/engine/src/script.rs | 51 ++++++++++++++++++------------ 2 files changed, 38 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/variables.rs b/crates/engine/src/cmd/variables.rs index b1c5ff59b..28fd6d37a 100644 --- a/crates/engine/src/cmd/variables.rs +++ b/crates/engine/src/cmd/variables.rs @@ -369,10 +369,13 @@ fn unvar(st: &mut designcraft_doc::Story, i: usize, n: usize, value: &str, depth at }; let target = var_char(i).unwrap_or(' ').to_string(); - let value = var_char(i).map_or_else(|| value.to_string(), |c| value.replace(c, "")); - for pos in instances(&st.text, &target) { - st.replace(pos..pos + target.len(), &value); - on_replace(pos, target.len()); + let at = instances(&st.text, &target); + if !at.is_empty() { + let value = var_char(i).map_or_else(|| value.to_string(), |c| value.replace(c, "")); + for pos in at { + st.replace(pos..pos + target.len(), &value); + on_replace(pos, target.len()); + } } for k in i + 1..n { let (from, to) = (var_char(k).unwrap_or(' ').to_string(), var_char(k - 1).unwrap_or(' ').to_string()); diff --git a/crates/engine/src/script.rs b/crates/engine/src/script.rs index de2589d9f..52efddf78 100644 --- a/crates/engine/src/script.rs +++ b/crates/engine/src/script.rs @@ -75,8 +75,8 @@ fn step_of(v: &Value) -> Result { Ok(Step { command, params }) } -/// The value a reference (`N.path`, `last.path`) points at. -fn lookup(r: &str, results: &[Value]) -> Result { +/// The value a reference (`N.path`, `last.path`) points at, borrowed from `results`. +fn lookup<'a>(r: &str, results: &'a [Value]) -> Result<&'a Value, String> { let mut parts = r.split('.'); let head = parts.next().unwrap_or(""); let idx = if head == "last" { @@ -84,14 +84,14 @@ fn lookup(r: &str, results: &[Value]) -> Result { } else { head.parse::().map_err(|_| format!("bad reference `${r}`"))? }; - let mut v = results.get(idx).ok_or_else(|| format!("`${r}`: step {idx} hasn't run (only {} have)", results.len()))?.clone(); + let mut v = results.get(idx).ok_or_else(|| format!("`${r}`: step {idx} hasn't run (only {} have)", results.len()))?; for p in parts { - v = match (&v, p.parse::()) { - (Value::Array(a), Ok(i)) => a.get(i).cloned(), - (Value::Object(o), _) => o.get(p).cloned(), + v = match (v, p.parse::()) { + (Value::Array(a), Ok(i)) => a.get(i), + (Value::Object(o), _) => o.get(p), _ => None, } - .ok_or_else(|| format!("`${r}`: no `{p}` in {}", short(&v)))?; + .ok_or_else(|| format!("`${r}`: no `{p}` in {}", short(v)))?; } Ok(v) } @@ -114,12 +114,18 @@ fn is_reference(r: &str) -> bool { /// story, then interpolates that story into the next, could otherwise double its size each step. pub const MAX_INTERPOLATED_BYTES: usize = 16 << 20; +fn too_long(s: &str) -> String { + // Cut at a char boundary: a preview of a long Unicode input mustn't copy all of it. + let preview = &s[..s.floor_char_boundary(40)]; + format!("the interpolated text of {preview} is longer than {MAX_INTERPOLATED_BYTES} bytes").replace('\n', " ") +} + /// Replace references in `params` with values from earlier `results`. pub fn resolve(params: &Value, results: &[Value]) -> Result { Ok(match params { Value::String(s) => { if let Some(r) = s.strip_prefix('$').filter(|r| is_reference(r)) { - return lookup(r, results); + return lookup(r, results).cloned(); } if !s.contains("${") && !s.contains("$$") { return Ok(params.clone()); @@ -134,26 +140,25 @@ pub fn resolve(params: &Value, results: &[Value]) -> Result { rest = tail; } else if let Some(inner) = after.strip_prefix('{') { let end = inner.find('}').ok_or_else(|| format!("unclosed `${{` in {s:?}"))?; - match lookup(&inner[..end], results)? { - Value::String(t) => out.push_str(&t), - other => out.push_str(&other.to_string()), - } - if out.len() > MAX_INTERPOLATED_BYTES { - return Err(format!("the interpolated text of {} is longer than {MAX_INTERPOLATED_BYTES} bytes", s.get(..40).unwrap_or(s)) - .replace('\n', " ")); + // The length is checked before the value is copied in. + let piece = match lookup(&inner[..end], results)? { + Value::String(t) => std::borrow::Cow::Borrowed(t.as_str()), + other => std::borrow::Cow::Owned(other.to_string()), + }; + if out.len().saturating_add(piece.len()) > MAX_INTERPOLATED_BYTES { + return Err(too_long(s)); } + out.push_str(&piece); rest = &inner[end + 1..]; } else { out.push('$'); rest = after; } } - out.push_str(rest); - if out.len() > MAX_INTERPOLATED_BYTES { - return Err( - format!("the interpolated text of {} is longer than {MAX_INTERPOLATED_BYTES} bytes", s.get(..40).unwrap_or(s)).replace('\n', " ") - ); + if out.len().saturating_add(rest.len()) > MAX_INTERPOLATED_BYTES { + return Err(too_long(s)); } + out.push_str(rest); Value::String(out) } Value::Array(a) => Value::Array(a.iter().map(|v| resolve(v, results)).collect::>()?), @@ -227,6 +232,12 @@ impl crate::Session { #[cfg(test)] mod tests { + #[test] + fn the_limit_error_previews_a_multibyte_input_in_bounds() { + let e = super::too_long(&"€".repeat(1000)); + assert!(e.len() < 150, "{e}"); + } + use super::*; #[test] From b18506e3b5c8991b4ce5562a08e436ae455f05fc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 19:31:41 -0800 Subject: [PATCH 0887/1349] Anchored text frames: place a frame anchored inside another anchored frame placed::locate only looked for an anchored frame in host frames that sit on a spread. When the host frame was itself anchored, the inner frame got no placement and composed where it is stored, on no page. The host frame is now placed through its own host first, up to MAX_DEPTH hosts out. --- crates/compose/src/placed.rs | 40 +++++++++++++++++++++++--------- crates/compose/src/tests.rs | 44 ++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 11 deletions(-) diff --git a/crates/compose/src/placed.rs b/crates/compose/src/placed.rs index 33e4ff73c..0207f3af4 100644 --- a/crates/compose/src/placed.rs +++ b/crates/compose/src/placed.rs @@ -36,24 +36,42 @@ pub(crate) fn placements(doc: &Document, sid: StoryId, host: &mut dyn FnMut(Stor continue; } let items = anchored.get_or_insert_with(|| doc.anchored_items()); - // A frame anchored in its own story would need its own composition to place it. - let Some(owner) = items.iter().find_map(|(owner, it)| (it.id == fid).then_some(*owner)).filter(|o| *o != sid) else { continue }; - let composed = hosts.entry(owner).or_insert_with(|| host(owner)); - if let Some(p) = locate(doc, composed, fid) { + if let Some(p) = locate(doc, items, sid, fid, &mut hosts, host, 0) { out.push((fid, p)); } } out } -/// Where `cs` (a host story's composition) places item `fid`: in its frames' anchored objects, -/// footnotes and table cells. -fn locate(doc: &Document, cs: &ComposedStory, fid: ItemId) -> Option { +/// Where the host story of `fid`, an anchored frame of story `sid`, places it: in its frames' +/// anchored objects, footnotes and table cells. A host frame that is itself anchored is placed +/// the same way first, up to [`MAX_DEPTH`] hosts out. `items` is [`Document::anchored_items`]. +fn locate( + doc: &Document, + items: &[(StoryId, &Item)], + sid: StoryId, + fid: ItemId, + hosts: &mut HashMap>, + host: &mut dyn FnMut(StoryId) -> Arc, + depth: usize, +) -> Option { + if depth > MAX_DEPTH { + return None; + } + // A frame anchored in its own story would need its own composition to place it. + let owner = items.iter().find_map(|(owner, it)| (it.id == fid).then_some(*owner)).filter(|o| *o != sid)?; + let cs = hosts.entry(owner).or_insert_with(|| host(owner)).clone(); cs.frames.iter().find_map(|ft| { - let loc = doc.find(ft.frame)?; - let frame = doc.item_at(&loc)?; - let xf = in_frame(ft, doc.parent_xf(&loc) * doc.text_xf(frame), fid, 0)?; - Some(Placement { spread: loc.spread, xf }) + if let Some(loc) = doc.find(ft.frame) { + let frame = doc.item_at(&loc)?; + let xf = in_frame(ft, doc.parent_xf(&loc) * doc.text_xf(frame), fid, 0)?; + return Some(Placement { spread: loc.spread, xf }); + } + // The host frame is anchored too: find `fid` in it before placing the frame. + let local = in_frame(ft, Affine::IDENTITY, fid, 0)?; + let frame = items.iter().find_map(|(_, it)| (it.id == ft.frame).then_some(*it))?; + let outer = locate(doc, items, owner, ft.frame, hosts, host, depth + 1)?; + Some(Placement { spread: outer.spread, xf: outer.xf * doc.text_xf(frame) * local }) }) } diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index f15f1e33d..e56095312 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -8566,6 +8566,50 @@ fn anchored_frames_in_one_host_compose_it_once() { assert_eq!(Cache::new().get(&d, nsid, None).frames.len(), compose_story(&d, nsid, &ComposeOptions::default()).frames.len()); } +/// A text frame anchored in a text frame that is itself anchored in a frame on page 1 is placed +/// through both hosts: on page 1, at the inner object's spot in the outer anchored frame. +#[test] +fn a_frame_anchored_in_an_anchored_frame_is_placed_through_both_hosts() { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let lid = d.default_layer(); + let body = "One.\nTwo.\nThree."; + let (bf, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 400.0, 400.0), lid, body, ParaFormat::default()).unwrap(); + let frame = |d: &mut Document, text: &str, w: f64, h: f64| { + let (fid, fsid) = (ItemId(d.alloc()), StoryId(d.alloc())); + let mut story = Story::with_text(fsid, text, ParaFormat::default()); + story.frames.push(fid); + d.stories.insert(fsid, Arc::new(story)); + let mut it = + designcraft_doc::Item::new(fid, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, w, h))); + it.content = Content::Text(designcraft_doc::TextFrame { story: fsid, options: Default::default() }); + (it, fsid) + }; + let (outer, osid) = frame(&mut d, "Outer text", 200.0, 100.0); + let (inner, isid) = frame(&mut d, "Inner", 80.0, 30.0); + let (outer_id, inner_id) = (outer.id, inner.id); + d.story_mut(osid).unwrap().insert_object("Outer ".len(), designcraft_doc::AnchoredObject::new(inner, Default::default())); + d.story_mut(sid).unwrap().insert_object(body.find("Two").unwrap(), designcraft_doc::AnchoredObject::new(outer, Default::default())); + + let placed = placed::placements(&d, isid, &mut |h| Arc::new(compose_story(&d, h, &ComposeOptions::default()))); + assert_eq!(placed.len(), 1, "{placed:?}"); + let (id, p) = placed[0]; + assert_eq!((id, p.spread), (inner_id, SpreadRef::Doc(0))); + // The body frame's object, then the outer frame's object, each at its composed origin. + let host = compose_story(&d, sid, &ComposeOptions::default()); + let o1 = &host.frame(bf).unwrap().objects[0]; + let mid = compose_story(&d, osid, &ComposeOptions::default()); + let o2 = &mid.frame(outer_id).unwrap().objects[0]; + let want = d.item(bf).unwrap().xf + * Affine::translate(o1.origin.to_vec2()) + * d.anchored_item(outer_id).unwrap().xf + * Affine::translate(o2.origin.to_vec2()); + let (got, want) = (p.xf.as_coeffs(), want.as_coeffs()); + assert!(got.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{got:?} != {want:?}"); + assert_eq!(frame_specs_placed(&d, isid, &placed)[0].page, Some(0)); + // The cache places it the same way. + assert_eq!(Cache::new().get(&d, isid, None).frames.len(), 1); +} + /// A marginal note (an anchored text frame, Only Align First Line to Grid, 9/10) hangs 15 pt /// above its anchor's baseline on a right-hand page. It composes against the document grid where /// it is placed: its first line moves down onto the grid line, the second follows 10 pt below, From edd2f24bb06aa0d31fac050718e21abdeda87c43 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 05:11:14 +0000 Subject: [PATCH 0888/1349] address review: cap whole-reference strings and the resolved parameters of a step; range adjustment uses the inserted length --- crates/engine/src/cmd/variables.rs | 14 +++--- crates/engine/src/cmd/variables/tests.rs | 9 +++- crates/engine/src/script.rs | 56 ++++++++++++++++++++++-- 3 files changed, 68 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/variables.rs b/crates/engine/src/cmd/variables.rs index 28fd6d37a..87479c214 100644 --- a/crates/engine/src/cmd/variables.rs +++ b/crates/engine/src/cmd/variables.rs @@ -53,9 +53,9 @@ pub fn specs() -> Vec { } let st = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; let mut replacements = Vec::new(); - unvar(st, i, n, &value, 0, &mut |pos, len| replacements.push((pos, len))); - for (pos, tlen) in replacements { - d.adjust_text_ranges(sid, pos..pos + tlen, value.len()); + unvar(st, i, n, &value, 0, &mut |pos, len, ins| replacements.push((pos, len, ins))); + for (pos, tlen, ins) in replacements { + d.adjust_text_ranges(sid, pos..pos + tlen, ins); } } d.text_variables.remove(i); @@ -356,7 +356,7 @@ fn needs_unvar(st: &designcraft_doc::Story, i: usize, depth: usize) -> bool { /// `i + 1..n` down by one, including table cells and foot/endnotes nested in the story. Only /// touches (and unshares) the parts that hold such instances; a story whose nested text changed /// gets a new revision. -fn unvar(st: &mut designcraft_doc::Story, i: usize, n: usize, value: &str, depth: usize, on_replace: &mut dyn FnMut(usize, usize)) { +fn unvar(st: &mut designcraft_doc::Story, i: usize, n: usize, value: &str, depth: usize, on_replace: &mut dyn FnMut(usize, usize, usize)) { if depth > MAX_DEPTH { return; } @@ -374,7 +374,7 @@ fn unvar(st: &mut designcraft_doc::Story, i: usize, n: usize, value: &str, depth let value = var_char(i).map_or_else(|| value.to_string(), |c| value.replace(c, "")); for pos in at { st.replace(pos..pos + target.len(), &value); - on_replace(pos, target.len()); + on_replace(pos, target.len(), value.len()); } } for k in i + 1..n { @@ -391,14 +391,14 @@ fn unvar(st: &mut designcraft_doc::Story, i: usize, n: usize, value: &str, depth } for c in &mut std::sync::Arc::make_mut(t).cells { if needs_unvar(&c.text, i, depth + 1) { - unvar(&mut c.text, i, n, value, depth + 1, &mut |_, _| {}); + unvar(&mut c.text, i, n, value, depth + 1, &mut |_, _, _| {}); } } nested = true; } for note in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { if needs_unvar(¬e.text, i, depth + 1) { - unvar(&mut std::sync::Arc::make_mut(note).text, i, n, value, depth + 1, &mut |_, _| {}); + unvar(&mut std::sync::Arc::make_mut(note).text, i, n, value, depth + 1, &mut |_, _, _| {}); nested = true; } } diff --git a/crates/engine/src/cmd/variables/tests.rs b/crates/engine/src/cmd/variables/tests.rs index beb775424..726f8d6a8 100644 --- a/crates/engine/src/cmd/variables/tests.rs +++ b/crates/engine/src/cmd/variables/tests.rs @@ -301,10 +301,17 @@ fn delete_variable_whose_value_holds_its_marker_ends() { let a = s.doc().unwrap().doc.variable("A").unwrap(); let marker = var_char(a).unwrap(); s.execute("variables.define", &json!({"name": "A", "type": "custom", "text": format!("<{marker}>")})).unwrap(); - s.execute("frame.create", &json!({"rect": [72, 72, 400, 300], "content": "text", "text": format!("x{marker}y{marker}z")})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 300], "content": "text", "text": format!("x{marker}y{marker}z")})).unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story; + // A link on the last "z": its range follows the text put in (without the marker). + let z = format!("x{marker}y{marker}").len(); + s.execute("text.select", &json!({"story": sid.0, "anchor": z, "focus": z + 1})).unwrap(); + s.execute("hyperlink.create", &json!({"url": "https://example.org"})).unwrap(); s.execute("variables.delete", &json!({"name": "A"})).unwrap(); let d = &s.doc().unwrap().doc; assert_eq!(d.stories.values().next().unwrap().text, "x<>y<>z"); + let designcraft_doc::HyperlinkSource::Text { start, end, .. } = &d.hyperlinks[0].source else { panic!("a text link") }; + assert_eq!((*start, *end), (6, 7)); } /// Deleting a variable flattens its instances in footnotes and endnotes too and moves the diff --git a/crates/engine/src/script.rs b/crates/engine/src/script.rs index 52efddf78..1ccd6f29c 100644 --- a/crates/engine/src/script.rs +++ b/crates/engine/src/script.rs @@ -120,14 +120,49 @@ fn too_long(s: &str) -> String { format!("the interpolated text of {preview} is longer than {MAX_INTERPOLATED_BYTES} bytes").replace('\n', " ") } +/// Longest string a whole reference (`$last.text`) may copy in. A story is far smaller; the cap +/// stops a loop of "read the story, paste it back" from doubling it until memory runs out. +pub const MAX_REFERENCED_BYTES: usize = 64 << 20; + +/// Most bytes of strings one step's parameters may hold once its references are resolved: the +/// limits above apply to each string, this one to a whole parameter tree (an array of 256 +/// references to a large string would pass each of them). +pub const MAX_STEP_PARAM_BYTES: usize = 256 << 20; + +/// Roughly how many bytes cloning `v` allocates (its strings, plus a word per node). +fn weight(v: &Value) -> usize { + match v { + Value::String(s) => s.len(), + Value::Array(a) => a.iter().fold(8, |n, x| n.saturating_add(weight(x))), + Value::Object(o) => o.iter().fold(8, |n, (k, x)| n.saturating_add(k.len()).saturating_add(weight(x))), + _ => 8, + } +} + +fn charge(budget: &mut usize, bytes: usize) -> Result<(), String> { + *budget = + budget.checked_sub(bytes).ok_or_else(|| format!("the parameters of a step are longer than {MAX_STEP_PARAM_BYTES} bytes once resolved"))?; + Ok(()) +} + /// Replace references in `params` with values from earlier `results`. pub fn resolve(params: &Value, results: &[Value]) -> Result { + resolve_in(params, results, MAX_REFERENCED_BYTES, &mut { MAX_STEP_PARAM_BYTES }) +} + +fn resolve_in(params: &Value, results: &[Value], max_ref: usize, budget: &mut usize) -> Result { Ok(match params { Value::String(s) => { if let Some(r) = s.strip_prefix('$').filter(|r| is_reference(r)) { - return lookup(r, results).cloned(); + let v = lookup(r, results)?; + if matches!(v, Value::String(t) if t.len() > max_ref) { + return Err(format!("`${r}` is longer than {max_ref} bytes")); + } + charge(budget, weight(v))?; + return Ok(v.clone()); } if !s.contains("${") && !s.contains("$$") { + charge(budget, s.len())?; return Ok(params.clone()); } let mut out = String::new(); @@ -159,10 +194,13 @@ pub fn resolve(params: &Value, results: &[Value]) -> Result { return Err(too_long(s)); } out.push_str(rest); + charge(budget, out.len())?; Value::String(out) } - Value::Array(a) => Value::Array(a.iter().map(|v| resolve(v, results)).collect::>()?), - Value::Object(o) => Value::Object(o.iter().map(|(k, v)| Ok((k.clone(), resolve(v, results)?))).collect::>()?), + Value::Array(a) => Value::Array(a.iter().map(|v| resolve_in(v, results, max_ref, budget)).collect::>()?), + Value::Object(o) => { + Value::Object(o.iter().map(|(k, v)| Ok((k.clone(), resolve_in(v, results, max_ref, budget)?))).collect::>()?) + } v => v.clone(), }) } @@ -240,6 +278,18 @@ mod tests { use super::*; + /// A whole reference to a long string is refused, and the strings of one step's parameters + /// share a budget (small limits here: the real ones would mean allocating them). + #[test] + fn whole_references_and_the_parameter_tree_are_bounded() { + let results = vec![json!({"text": "x".repeat(100)})]; + assert!(resolve_in(&json!("$0.text"), &results, 100, &mut 1000).is_ok()); + assert!(resolve_in(&json!("$0.text"), &results, 99, &mut 1000).unwrap_err().contains("longer than 99")); + let many = json!(["$0.text", "$0.text", "${0.text}"]); + assert!(resolve_in(&many, &results, 100, &mut 300).is_ok()); + assert!(resolve_in(&many, &results, 100, &mut 299).unwrap_err().contains("once resolved")); + } + #[test] fn leading_blank_lines_keep_line_numbers() { let e = parse("\n\n# c\nfile.new\nframe.create {bad").unwrap_err(); From 65bac1f1fafc8999e67663e22b02e4078e16cd4c Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:40:22 +0100 Subject: [PATCH 0889/1349] Release: DesignCraft v0.20.0 (#2603) --- Cargo.lock | 42 +++++++++++++++++++++--------------------- Cargo.toml | 2 +- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3bc1e94a2..5505fc5f3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1306,7 +1306,7 @@ dependencies = [ [[package]] name = "designcraft" -version = "0.17.0" +version = "0.20.0" dependencies = [ "arboard", "craft-update", @@ -1331,7 +1331,7 @@ dependencies = [ [[package]] name = "designcraft-cli" -version = "0.17.0" +version = "0.20.0" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1348,7 +1348,7 @@ dependencies = [ [[package]] name = "designcraft-color" -version = "0.17.0" +version = "0.20.0" dependencies = [ "craft-cms", "kurbo", @@ -1360,7 +1360,7 @@ dependencies = [ [[package]] name = "designcraft-compose" -version = "0.17.0" +version = "0.20.0" dependencies = [ "designcraft-color", "designcraft-doc", @@ -1380,7 +1380,7 @@ dependencies = [ [[package]] name = "designcraft-doc" -version = "0.17.0" +version = "0.20.0" dependencies = [ "chrono", "designcraft-color", @@ -1393,7 +1393,7 @@ dependencies = [ [[package]] name = "designcraft-engine" -version = "0.17.0" +version = "0.20.0" dependencies = [ "caseless", "craft-atomic", @@ -1433,7 +1433,7 @@ dependencies = [ [[package]] name = "designcraft-epub" -version = "0.17.0" +version = "0.20.0" dependencies = [ "chrono", "designcraft-color", @@ -1443,7 +1443,7 @@ dependencies = [ [[package]] name = "designcraft-fonts" -version = "0.17.0" +version = "0.20.0" dependencies = [ "core-text", "harfrust 0.13.3", @@ -1456,7 +1456,7 @@ dependencies = [ [[package]] name = "designcraft-format" -version = "0.17.0" +version = "0.20.0" dependencies = [ "designcraft-doc", "designcraft-images", @@ -1468,7 +1468,7 @@ dependencies = [ [[package]] name = "designcraft-geom" -version = "0.17.0" +version = "0.20.0" dependencies = [ "flo_curves", "kurbo", @@ -1481,7 +1481,7 @@ dependencies = [ [[package]] name = "designcraft-idml" -version = "0.17.0" +version = "0.20.0" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1496,7 +1496,7 @@ dependencies = [ [[package]] name = "designcraft-images" -version = "0.17.0" +version = "0.20.0" dependencies = [ "craft-cms", "designcraft-color", @@ -1514,7 +1514,7 @@ dependencies = [ [[package]] name = "designcraft-mcp" -version = "0.17.0" +version = "0.20.0" dependencies = [ "designcraft-engine", "designcraft-geom", @@ -1527,7 +1527,7 @@ dependencies = [ [[package]] name = "designcraft-pdf" -version = "0.17.0" +version = "0.20.0" dependencies = [ "chrono", "craft-cms", @@ -1553,7 +1553,7 @@ dependencies = [ [[package]] name = "designcraft-pptx" -version = "0.17.0" +version = "0.20.0" dependencies = [ "chrono", "designcraft-color", @@ -1571,7 +1571,7 @@ dependencies = [ [[package]] name = "designcraft-render" -version = "0.17.0" +version = "0.20.0" dependencies = [ "craft-pdf", "designcraft-color", @@ -1590,7 +1590,7 @@ dependencies = [ [[package]] name = "designcraft-textimport" -version = "0.17.0" +version = "0.20.0" dependencies = [ "designcraft-doc", "quick-xml 0.41.0", @@ -1599,7 +1599,7 @@ dependencies = [ [[package]] name = "designcraft-tools" -version = "0.17.0" +version = "0.20.0" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1611,7 +1611,7 @@ dependencies = [ [[package]] name = "designcraft-ui-egui" -version = "0.17.0" +version = "0.20.0" dependencies = [ "craft-dialogs", "craft-keymap", @@ -1645,7 +1645,7 @@ dependencies = [ [[package]] name = "designcraft-web" -version = "0.17.0" +version = "0.20.0" dependencies = [ "designcraft-engine", "designcraft-format", @@ -7679,7 +7679,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.17.0" +version = "0.20.0" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index 6a07b01b1..ee27e5fbd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/designcraft", "apps/designcraft-cli", "xtask"] [workspace.package] -version = "0.17.0" +version = "0.20.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From 4698331d1594a1c7b7083e036034149ae44c2517 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 12:10:37 -0500 Subject: [PATCH 0890/1349] ci: run Harden-Runner on every job (#2621) Adds step-security/harden-runner (audit, pinned to v2.22.4 like craft-common-actions) as the first step of each job that did not have it, so every workflow in the org's public repos reports its egress to StepSecurity. Audit, not block: block-mode allow lists come from each job's observed traffic. --- .github/workflows/packaging-lint.yml | 4 ++++ .github/workflows/release.yml | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index ea61d8430..1771a35fe 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -27,6 +27,10 @@ jobs: name: Windows installation policy (no app build) runs-on: windows-latest steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 722f30145..aa9693e28 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -30,6 +30,10 @@ jobs: permissions: contents: read steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false From 5df1707f0e3106376ddde28dbc5390e04f7ee465 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 12:43:55 -0500 Subject: [PATCH 0891/1349] Updates: take craft-update from craft-libs main at 6e03f65bf --- Cargo.lock | 3 ++- Cargo.toml | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5505fc5f3..1f33db562 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1138,7 +1138,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "chrono", "dunce", @@ -1148,6 +1148,7 @@ dependencies = [ "image", "log", "plist", + "rustix 1.1.5", "semver", "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index ee27e5fbd..fb5f5a826 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,7 +18,7 @@ craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "92d392c # Separations, ink coverage and the ink manager; same revision as craft-pdf and the krilla patch. craft-prepress = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.1.0", features = ["flatten"] } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } # internal designcraft-geom = { path = "crates/geom" } designcraft-color = { path = "crates/color" } From 19815eba4a739bced64956f247fb2fe989c50a8f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 14:24:07 -0500 Subject: [PATCH 0892/1349] Fix Flatpak permissions for update checks and self-updates (#2626) * fix(flatpak): allow release checks and self-update helpers * test: keep Flatpak permission parsing within strict Clippy rules --- crates/ui-egui/tests/flatpak_updates.rs | 27 +++++++++++++++++++ .../ai.storyteller.designcraft.bundle.yml | 2 ++ .../flatpak/ai.storyteller.designcraft.yml | 2 ++ 3 files changed, 31 insertions(+) create mode 100644 crates/ui-egui/tests/flatpak_updates.rs diff --git a/crates/ui-egui/tests/flatpak_updates.rs b/crates/ui-egui/tests/flatpak_updates.rs new file mode 100644 index 000000000..01d835f42 --- /dev/null +++ b/crates/ui-egui/tests/flatpak_updates.rs @@ -0,0 +1,27 @@ +//! Release and source Flatpaks must allow release checks and host update helpers. +fn finish_args(manifest: &str) -> Vec<&str> { + manifest + .split("finish-args:") + .nth(1) + .unwrap_or_default() + .lines() + .take_while(|line| line.is_empty() || line.starts_with(' ') || line.starts_with('#')) + .filter_map(|line| line.trim().strip_prefix("- ")) + .map(|arg| arg.trim_matches(['\'', '"'])) + .collect() +} + +#[test] +fn flatpak_update_permissions() { + let manifests = [ + include_str!("../../../packaging/linux/flatpak/ai.storyteller.designcraft.bundle.yml"), + include_str!("../../../packaging/linux/flatpak/ai.storyteller.designcraft.yml"), + ]; + let args = manifests.map(finish_args); + assert_eq!(args[0], args[1], "source and release permissions must agree"); + for permissions in args { + for required in ["--share=network", "--talk-name=org.freedesktop.Flatpak"] { + assert!(permissions.contains(&required), "missing update permission: {required}"); + } + } +} diff --git a/packaging/linux/flatpak/ai.storyteller.designcraft.bundle.yml b/packaging/linux/flatpak/ai.storyteller.designcraft.bundle.yml index 750400657..eac2602c6 100644 --- a/packaging/linux/flatpak/ai.storyteller.designcraft.bundle.yml +++ b/packaging/linux/flatpak/ai.storyteller.designcraft.bundle.yml @@ -17,6 +17,8 @@ runtime-version: '25.08' sdk: org.freedesktop.Sdk command: designcraft finish-args: + # The shared updater inspects and updates this installation via flatpak-spawn --host. + - --talk-name=org.freedesktop.Flatpak - --filesystem=xdg-data/ArtCraft/versions:ro # Display: Wayland first; X11 only when no Wayland compositor is running. - --socket=wayland diff --git a/packaging/linux/flatpak/ai.storyteller.designcraft.yml b/packaging/linux/flatpak/ai.storyteller.designcraft.yml index fd56910ce..4cbee1c12 100644 --- a/packaging/linux/flatpak/ai.storyteller.designcraft.yml +++ b/packaging/linux/flatpak/ai.storyteller.designcraft.yml @@ -18,6 +18,8 @@ sdk-extensions: - org.freedesktop.Sdk.Extension.rust-stable command: designcraft finish-args: + # The shared updater inspects and updates this installation via flatpak-spawn --host. + - --talk-name=org.freedesktop.Flatpak - --filesystem=xdg-data/ArtCraft/versions:ro # Display: Wayland first; X11 only when no Wayland compositor is running. - --socket=wayland From 741ccbbabb7bde2a60c1f40d2f32b2b2a71477dd Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 14:27:23 -0500 Subject: [PATCH 0893/1349] Release 0.20.1: repair Flatpak update checks and self-updates (#2627) * Release 0.20.1: fix Flatpak update permissions * test: avoid unchecked option parsing in Flatpak regression --- Cargo.lock | 42 +++++++++---------- Cargo.toml | 2 +- crates/ui-egui/tests/flatpak_updates.rs | 27 ++++++++++++ .../ai.storyteller.designcraft.bundle.yml | 2 + .../flatpak/ai.storyteller.designcraft.yml | 2 + 5 files changed, 53 insertions(+), 22 deletions(-) create mode 100644 crates/ui-egui/tests/flatpak_updates.rs diff --git a/Cargo.lock b/Cargo.lock index 5505fc5f3..48cd5dd5f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1306,7 +1306,7 @@ dependencies = [ [[package]] name = "designcraft" -version = "0.20.0" +version = "0.20.1" dependencies = [ "arboard", "craft-update", @@ -1331,7 +1331,7 @@ dependencies = [ [[package]] name = "designcraft-cli" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1348,7 +1348,7 @@ dependencies = [ [[package]] name = "designcraft-color" -version = "0.20.0" +version = "0.20.1" dependencies = [ "craft-cms", "kurbo", @@ -1360,7 +1360,7 @@ dependencies = [ [[package]] name = "designcraft-compose" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-color", "designcraft-doc", @@ -1380,7 +1380,7 @@ dependencies = [ [[package]] name = "designcraft-doc" -version = "0.20.0" +version = "0.20.1" dependencies = [ "chrono", "designcraft-color", @@ -1393,7 +1393,7 @@ dependencies = [ [[package]] name = "designcraft-engine" -version = "0.20.0" +version = "0.20.1" dependencies = [ "caseless", "craft-atomic", @@ -1433,7 +1433,7 @@ dependencies = [ [[package]] name = "designcraft-epub" -version = "0.20.0" +version = "0.20.1" dependencies = [ "chrono", "designcraft-color", @@ -1443,7 +1443,7 @@ dependencies = [ [[package]] name = "designcraft-fonts" -version = "0.20.0" +version = "0.20.1" dependencies = [ "core-text", "harfrust 0.13.3", @@ -1456,7 +1456,7 @@ dependencies = [ [[package]] name = "designcraft-format" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-doc", "designcraft-images", @@ -1468,7 +1468,7 @@ dependencies = [ [[package]] name = "designcraft-geom" -version = "0.20.0" +version = "0.20.1" dependencies = [ "flo_curves", "kurbo", @@ -1481,7 +1481,7 @@ dependencies = [ [[package]] name = "designcraft-idml" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1496,7 +1496,7 @@ dependencies = [ [[package]] name = "designcraft-images" -version = "0.20.0" +version = "0.20.1" dependencies = [ "craft-cms", "designcraft-color", @@ -1514,7 +1514,7 @@ dependencies = [ [[package]] name = "designcraft-mcp" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-engine", "designcraft-geom", @@ -1527,7 +1527,7 @@ dependencies = [ [[package]] name = "designcraft-pdf" -version = "0.20.0" +version = "0.20.1" dependencies = [ "chrono", "craft-cms", @@ -1553,7 +1553,7 @@ dependencies = [ [[package]] name = "designcraft-pptx" -version = "0.20.0" +version = "0.20.1" dependencies = [ "chrono", "designcraft-color", @@ -1571,7 +1571,7 @@ dependencies = [ [[package]] name = "designcraft-render" -version = "0.20.0" +version = "0.20.1" dependencies = [ "craft-pdf", "designcraft-color", @@ -1590,7 +1590,7 @@ dependencies = [ [[package]] name = "designcraft-textimport" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-doc", "quick-xml 0.41.0", @@ -1599,7 +1599,7 @@ dependencies = [ [[package]] name = "designcraft-tools" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1611,7 +1611,7 @@ dependencies = [ [[package]] name = "designcraft-ui-egui" -version = "0.20.0" +version = "0.20.1" dependencies = [ "craft-dialogs", "craft-keymap", @@ -1645,7 +1645,7 @@ dependencies = [ [[package]] name = "designcraft-web" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-engine", "designcraft-format", @@ -7679,7 +7679,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.20.0" +version = "0.20.1" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index ee27e5fbd..496998bcb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/designcraft", "apps/designcraft-cli", "xtask"] [workspace.package] -version = "0.20.0" +version = "0.20.1" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" diff --git a/crates/ui-egui/tests/flatpak_updates.rs b/crates/ui-egui/tests/flatpak_updates.rs new file mode 100644 index 000000000..01d835f42 --- /dev/null +++ b/crates/ui-egui/tests/flatpak_updates.rs @@ -0,0 +1,27 @@ +//! Release and source Flatpaks must allow release checks and host update helpers. +fn finish_args(manifest: &str) -> Vec<&str> { + manifest + .split("finish-args:") + .nth(1) + .unwrap_or_default() + .lines() + .take_while(|line| line.is_empty() || line.starts_with(' ') || line.starts_with('#')) + .filter_map(|line| line.trim().strip_prefix("- ")) + .map(|arg| arg.trim_matches(['\'', '"'])) + .collect() +} + +#[test] +fn flatpak_update_permissions() { + let manifests = [ + include_str!("../../../packaging/linux/flatpak/ai.storyteller.designcraft.bundle.yml"), + include_str!("../../../packaging/linux/flatpak/ai.storyteller.designcraft.yml"), + ]; + let args = manifests.map(finish_args); + assert_eq!(args[0], args[1], "source and release permissions must agree"); + for permissions in args { + for required in ["--share=network", "--talk-name=org.freedesktop.Flatpak"] { + assert!(permissions.contains(&required), "missing update permission: {required}"); + } + } +} diff --git a/packaging/linux/flatpak/ai.storyteller.designcraft.bundle.yml b/packaging/linux/flatpak/ai.storyteller.designcraft.bundle.yml index 750400657..eac2602c6 100644 --- a/packaging/linux/flatpak/ai.storyteller.designcraft.bundle.yml +++ b/packaging/linux/flatpak/ai.storyteller.designcraft.bundle.yml @@ -17,6 +17,8 @@ runtime-version: '25.08' sdk: org.freedesktop.Sdk command: designcraft finish-args: + # The shared updater inspects and updates this installation via flatpak-spawn --host. + - --talk-name=org.freedesktop.Flatpak - --filesystem=xdg-data/ArtCraft/versions:ro # Display: Wayland first; X11 only when no Wayland compositor is running. - --socket=wayland diff --git a/packaging/linux/flatpak/ai.storyteller.designcraft.yml b/packaging/linux/flatpak/ai.storyteller.designcraft.yml index fd56910ce..4cbee1c12 100644 --- a/packaging/linux/flatpak/ai.storyteller.designcraft.yml +++ b/packaging/linux/flatpak/ai.storyteller.designcraft.yml @@ -18,6 +18,8 @@ sdk-extensions: - org.freedesktop.Sdk.Extension.rust-stable command: designcraft finish-args: + # The shared updater inspects and updates this installation via flatpak-spawn --host. + - --talk-name=org.freedesktop.Flatpak - --filesystem=xdg-data/ArtCraft/versions:ro # Display: Wayland first; X11 only when no Wayland compositor is running. - --socket=wayland From 00d3b31ccf288ff8cd010bba6ad3ba0aa1304b5c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 14:55:49 -0500 Subject: [PATCH 0894/1349] chore: bump version to 0.20.1 for the Flatpak update fix (#2629) --- Cargo.lock | 42 +++++++++++++++++++++--------------------- Cargo.toml | 2 +- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1f33db562..9760f61ff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1307,7 +1307,7 @@ dependencies = [ [[package]] name = "designcraft" -version = "0.20.0" +version = "0.20.1" dependencies = [ "arboard", "craft-update", @@ -1332,7 +1332,7 @@ dependencies = [ [[package]] name = "designcraft-cli" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1349,7 +1349,7 @@ dependencies = [ [[package]] name = "designcraft-color" -version = "0.20.0" +version = "0.20.1" dependencies = [ "craft-cms", "kurbo", @@ -1361,7 +1361,7 @@ dependencies = [ [[package]] name = "designcraft-compose" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-color", "designcraft-doc", @@ -1381,7 +1381,7 @@ dependencies = [ [[package]] name = "designcraft-doc" -version = "0.20.0" +version = "0.20.1" dependencies = [ "chrono", "designcraft-color", @@ -1394,7 +1394,7 @@ dependencies = [ [[package]] name = "designcraft-engine" -version = "0.20.0" +version = "0.20.1" dependencies = [ "caseless", "craft-atomic", @@ -1434,7 +1434,7 @@ dependencies = [ [[package]] name = "designcraft-epub" -version = "0.20.0" +version = "0.20.1" dependencies = [ "chrono", "designcraft-color", @@ -1444,7 +1444,7 @@ dependencies = [ [[package]] name = "designcraft-fonts" -version = "0.20.0" +version = "0.20.1" dependencies = [ "core-text", "harfrust 0.13.3", @@ -1457,7 +1457,7 @@ dependencies = [ [[package]] name = "designcraft-format" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-doc", "designcraft-images", @@ -1469,7 +1469,7 @@ dependencies = [ [[package]] name = "designcraft-geom" -version = "0.20.0" +version = "0.20.1" dependencies = [ "flo_curves", "kurbo", @@ -1482,7 +1482,7 @@ dependencies = [ [[package]] name = "designcraft-idml" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1497,7 +1497,7 @@ dependencies = [ [[package]] name = "designcraft-images" -version = "0.20.0" +version = "0.20.1" dependencies = [ "craft-cms", "designcraft-color", @@ -1515,7 +1515,7 @@ dependencies = [ [[package]] name = "designcraft-mcp" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-engine", "designcraft-geom", @@ -1528,7 +1528,7 @@ dependencies = [ [[package]] name = "designcraft-pdf" -version = "0.20.0" +version = "0.20.1" dependencies = [ "chrono", "craft-cms", @@ -1554,7 +1554,7 @@ dependencies = [ [[package]] name = "designcraft-pptx" -version = "0.20.0" +version = "0.20.1" dependencies = [ "chrono", "designcraft-color", @@ -1572,7 +1572,7 @@ dependencies = [ [[package]] name = "designcraft-render" -version = "0.20.0" +version = "0.20.1" dependencies = [ "craft-pdf", "designcraft-color", @@ -1591,7 +1591,7 @@ dependencies = [ [[package]] name = "designcraft-textimport" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-doc", "quick-xml 0.41.0", @@ -1600,7 +1600,7 @@ dependencies = [ [[package]] name = "designcraft-tools" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1612,7 +1612,7 @@ dependencies = [ [[package]] name = "designcraft-ui-egui" -version = "0.20.0" +version = "0.20.1" dependencies = [ "craft-dialogs", "craft-keymap", @@ -1646,7 +1646,7 @@ dependencies = [ [[package]] name = "designcraft-web" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-engine", "designcraft-format", @@ -7680,7 +7680,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.20.0" +version = "0.20.1" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index fb5f5a826..dcf2c7235 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/designcraft", "apps/designcraft-cli", "xtask"] [workspace.package] -version = "0.20.0" +version = "0.20.1" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From 513f77b88e701e45d4fbb7ee1685814dbad5ac91 Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Wed, 11 Nov 2026 11:56:37 -0800 Subject: [PATCH 0895/1349] Tables: commands given a table id run with nothing in a table selected (#2607) * Tables: commands given a table id run with nothing in a table selected Table commands whose params list `story?` and `table?` (table.insertRow, table.deleteColumn, table.options, the Convert Rows commands and the others) were refused with "place the insertion point in a table" when the call named the table but the selection was not in one. A call that passes `table` now acts on that table whatever is selected. A table that is not in the document, or not in the given `story`, is refused, and a `story` that is not a non-negative integer is an error. The menus are unchanged: with nothing in a table selected, the table items stay disabled, and calls that name no table are still refused. * Tables: a bad story is refused whether or not a table is selected A call that names a table with a story that is not a non-negative integer (a string, a negative number, a fraction or null) was refused only when nothing in a table was selected. With a table selected, the command ignored the story and acted on the named table. Both paths now read story with one helper and refuse it the same way. * Tables: an edit to a named table keeps a caret in footnote text With the caret in footnote text, a table command that names a table runs, and the edit cleared the caret's footnote address, so the next typing went into the story. clamp_selection now leaves footnote addresses alone, as in_cell does. --- crates/engine/src/cmd.rs | 18 +++++ crates/engine/src/cmd/table.rs | 2 +- crates/engine/src/cmd/table/target.rs | 6 +- crates/engine/src/lib.rs | 15 +++- crates/engine/src/tests/table.rs | 101 ++++++++++++++++++++++++++ docs/mcp.md | 8 ++ 6 files changed, 146 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 03b6082db..dc1acaf15 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -331,6 +331,24 @@ pub(crate) fn named_targets(spec: &CommandSpec, p: &Value) -> Option id_param(p, "id").map(|i| vec![i]) } +/// The table a call names with `table`, for a command whose params document an optional `table`. +/// `None` when the call names no table. [`table_story`] reads the `story` that goes with it. +pub(crate) fn named_table(spec: &CommandSpec, p: &Value) -> Option { + if !spec.params.split(|c: char| !c.is_ascii_alphanumeric() && c != '?').any(|w| w == "table?") { + return None; + } + p.get("table").and_then(Value::as_u64) +} + +/// The `story` a table command's call names alongside `table`, or `None` when the call has no +/// `story`. A `story` that is present but not a non-negative integer, `null` included, is an error. +pub(crate) fn table_story(p: &Value, cmd: &str) -> Result> { + match p.get("story") { + None => Ok(None), + Some(v) => v.as_u64().map(Some).ok_or_else(|| bad(cmd, "`story` must be a non-negative integer")), + } +} + /// Targets: `ids` / `id` params or the selection. pub(crate) fn targets(s: &Session, p: &Value) -> Result> { if let Some(ids) = ids_param(p, "ids") { diff --git a/crates/engine/src/cmd/table.rs b/crates/engine/src/cmd/table.rs index d3743df9e..7674d1c70 100644 --- a/crates/engine/src/cmd/table.rs +++ b/crates/engine/src/cmd/table.rs @@ -14,7 +14,7 @@ use designcraft_doc::{ }; use serde_json::{Value, json}; -use super::{CommandSpec, bad, cmd, f64_or, has_doc, has_text, ok, str_param}; +use super::{CommandSpec, bad, cmd, f64_or, has_doc, has_text, ok, str_param, table_story}; use crate::{Result, Session}; mod cell; diff --git a/crates/engine/src/cmd/table/target.rs b/crates/engine/src/cmd/table/target.rs index 2e1784560..629493e9b 100644 --- a/crates/engine/src/cmd/table/target.rs +++ b/crates/engine/src/cmd/table/target.rs @@ -1,6 +1,6 @@ use super::{ CellAddr, CellRange, Document, Result, Selection, Session, StoryId, Table, TableSel, TextSel, Value, bad, compose, floor_char_boundary, has_doc, - str_param, + str_param, table_story, }; // ---------- enablement and targeting ---------- @@ -58,8 +58,8 @@ pub(super) fn target(s: &Session, p: &Value, cmd: &str) -> Result { let st = s.doc()?; let doc = &st.doc; let explicit_table = p.get("table").and_then(Value::as_u64); - let explicit_story = p.get("story").and_then(Value::as_u64).map(StoryId); let (story, table, range) = if let Some(tid) = explicit_table { + let explicit_story = table_story(p, cmd)?.map(StoryId); let sid = explicit_story.or_else(|| find_table(doc, tid)).ok_or_else(|| bad(cmd, format!("no table {tid}")))?; (sid, tid, None) } else if let Some(c) = st.selection.cells { @@ -116,8 +116,10 @@ pub(super) fn clamp_selection(d: &Document, sel: &mut Selection) { None => sel.cells = None, } } + // Footnote text is addressed as a cell too, but isn't in a table. if let Some(t) = sel.text && let Some(c) = t.cell + && c.footnote_id().is_none() { let story = d.story(t.story); match story.and_then(|x| x.tables.get(&c.table)) { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index f87371531..3d43a80e0 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -680,9 +680,22 @@ impl Session { Ok(r) } - /// Fails with `Disabled` unless the command is enabled or names objects it can act on. + /// Fails with `Disabled` unless the command is enabled or names objects or a table it can act on. fn check_enabled(&self, spec: &CommandSpec, id: &str, params: &Value) -> Result<()> { if let Err(e) = (spec.enabled)(self) { + // A table command that takes `story` and `table` acts on the table the call names, so + // the selection doesn't matter: with nothing selected, the caret outside a table, or + // selected rows the command can't act on, `{"table": 3}` still runs. + if let Some(table) = cmd::named_table(spec, params) + && cmd::has_doc(self).is_ok() + { + let story = cmd::table_story(params, id)?; + let st = self.doc()?; + if !st.doc.stories.iter().any(|(sid, x)| story.is_none_or(|n| sid.0 == n) && x.tables.contains_key(&table)) { + return Err(EngineError::Disabled(id.into(), format!("no table {table}"))); + } + return Ok(()); + } // A command that takes `ids` acts on the objects the call names, so the selection // doesn't matter: with a text caret, nothing selected, or a selection the command // can't act on, `{"ids": [5]}` still runs. diff --git a/crates/engine/src/tests/table.rs b/crates/engine/src/tests/table.rs index 77bcb9bfd..3941778f2 100644 --- a/crates/engine/src/tests/table.rs +++ b/crates/engine/src/tests/table.rs @@ -493,6 +493,107 @@ fn rows_columns_merge_and_options() { assert_eq!(st.doc.story(sid).unwrap().text, "Intro"); } +/// A table command given `story` and `table` acts on that table with nothing selected, the caret +/// outside the table, or a selection it can't act on, and a table that isn't there is refused. +#[test] +fn table_commands_run_on_a_named_table_without_a_table_selection() { + let (mut s, sid, _) = session_with_frame(); + let tid = s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap(); + let size = |s: &mut Session| { + let t = s.execute("table.get", &json!({"story": sid, "table": tid})).unwrap(); + (t["rows"].as_array().unwrap().len(), t["columns"].as_array().unwrap().len()) + }; + assert_eq!(size(&mut s), (2, 2)); + s.execute("edit.deselectAll", &json!({})).unwrap(); + s.execute("table.insertRow", &json!({"story": sid, "table": tid, "where": "below"})).unwrap(); + assert_eq!(size(&mut s), (3, 2)); + s.execute("table.insertColumnRight", &json!({"table": tid})).unwrap(); + assert_eq!(size(&mut s), (3, 3)); + s.execute("table.convertRowsToHeader", &json!({"story": sid, "table": tid, "rows": [0, 0]})).unwrap(); + assert_eq!(s.execute("table.get", &json!({"table": tid})).unwrap()["headerRows"], 1); + // A selected header row can't become a header, but the named rows can. + s.execute("table.select", &json!({"table": tid, "rows": [0, 0], "what": "row"})).unwrap(); + assert!(!crate::cmd::find_command("table.convertRowsToHeader").unwrap().info(&s).enabled); + s.execute("table.convertRowsToHeader", &json!({"table": tid, "rows": [1, 1]})).unwrap(); + assert_eq!(s.execute("table.get", &json!({"table": tid})).unwrap()["headerRows"], 2); + // The caret in the story's text, outside the table. + s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap(); + s.execute("table.deleteRow", &json!({"story": sid, "table": tid, "rows": [2, 2]})).unwrap(); + assert_eq!(size(&mut s), (2, 3)); + check(&s); + s.execute("edit.deselectAll", &json!({})).unwrap(); + let disabled = |r: Result| match r { + Err(crate::EngineError::Disabled(_, why)) => why, + other => panic!("expected Disabled, got {other:?}"), + }; + assert_eq!(disabled(s.execute("table.insertRow", &json!({"table": tid + 100}))), format!("no table {}", tid + 100)); + assert_eq!(disabled(s.execute("table.insertRow", &json!({"story": sid + 100, "table": tid}))), format!("no table {tid}")); + for story in [json!("x"), json!(-1), json!(null)] { + let r = s.execute("table.insertRow", &json!({"story": story, "table": tid})); + assert!(matches!(r, Err(crate::EngineError::BadParams { .. })), "{r:?}"); + } + assert_eq!(size(&mut s), (2, 3)); +} + +/// A `story` that is not a non-negative integer is refused the same way whether or not a table is +/// selected, and the table is left unchanged. +#[test] +fn a_bad_story_is_refused_with_or_without_a_table_selection() { + let (mut s, _, _) = session_with_frame(); + let tid = s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap(); + let rows = |s: &mut Session| s.execute("table.get", &json!({"table": tid})).unwrap()["rows"].as_array().unwrap().len(); + for select in [json!({"table": tid, "rows": [0, 0], "what": "row"}), json!(null)] { + if select.is_null() { + s.execute("edit.deselectAll", &json!({})).unwrap(); + } else { + s.execute("table.select", &select).unwrap(); + } + for story in [json!("x"), json!(-1), json!(1.5), json!(null)] { + let r = s.execute("table.insertRow", &json!({"story": story, "table": tid})); + assert!(matches!(r, Err(crate::EngineError::BadParams { .. })), "{select} {story}: {r:?}"); + } + assert_eq!(rows(&mut s), 2, "{select}"); + } +} + +/// An edit to a named table leaves a caret in footnote text where it was. +#[test] +fn a_named_table_edit_keeps_a_footnote_caret() { + let (mut s, sid, _) = session_with_frame(); + let tid = s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap(); + s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap(); + s.execute("footnote.insert", &json!({"text": "Note"})).unwrap(); + let before = s.doc().unwrap().selection.clone(); + assert!(before.text.and_then(|t| t.cell).and_then(|c| c.footnote_id()).is_some(), "the caret is in the footnote"); + s.execute("table.insertRow", &json!({"table": tid})).unwrap(); + assert_eq!(s.execute("table.get", &json!({"table": tid})).unwrap()["rows"].as_array().unwrap().len(), 3); + assert_eq!(s.doc().unwrap().selection, before); + check(&s); +} + +/// With nothing selected, the table commands stay disabled for menus and for calls that name no +/// table. +#[test] +fn table_commands_stay_disabled_with_nothing_selected() { + let (mut s, _, _) = session_with_frame(); + s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap(); + let in_table = ["table.insertRow", "table.deleteColumn", "table.merge", "table.options", "table.selectTable", "style.table.apply"]; + let in_cell = ["table.convertRowsToHeader", "table.nextCell"]; + let info = |s: &Session, id: &str| crate::cmd::find_command(id).unwrap().info(s); + for id in in_table.iter().chain(&in_cell) { + assert!(info(&s, id).enabled, "{id} is enabled with the caret in a cell"); + } + s.execute("edit.deselectAll", &json!({})).unwrap(); + for (ids, reason) in [(&in_table[..], "place the insertion point in a table"), (&in_cell[..], "not in a table cell")] { + for id in ids { + let i = info(&s, id); + assert!(!i.enabled, "{id}"); + assert_eq!(i.disabled_reason.as_deref(), Some(reason), "{id}"); + assert!(matches!(s.execute(id, &json!({})), Err(crate::EngineError::Disabled(..))), "{id}"); + } + } +} + /// `table.insert` styles the table in the same step; a style that isn't there, or isn't a name, /// leaves the story alone. Its dimensions stop at the documented limits. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 61e59df4d..f7e0b8187 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -206,6 +206,14 @@ is an error that gives the story length in bytes, and the story is left unchange that has a `cell` (`{table, row, col}`) is in that table cell's text, and its `start` / `end` count from the start of the cell. +## Tables without a selection + +A table command acts on the selected cells or on the table that holds the insertion point. A command whose params list +`story?` and `table?` also runs when nothing in a table is selected, or the selection is one it can't act on, if the +call passes `table` (the id that `table.insert` and `table.get` return) and, optionally, `story`. A `table` that is not +in the document, or not in the given `story`, is an error, and so is a `story` that is not a non-negative integer. The +Table menu items stay disabled while nothing in a table is selected. + ## Text and image fitting Hyphenation is on by default for new text (`hyphenate: true`). To turn it off, select the text or a text frame, From 94c6798577c554c9c9ea51cc43b7043cf0d67cf6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 16:15:39 -0500 Subject: [PATCH 0896/1349] swatches panel: group membership and row lookups by name map (#2262) --- crates/ui-egui/src/panels/swatches.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index 680391e03..265b45759 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -28,11 +28,16 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { let fill_cur = target.map(|(fill, _, stroke, _)| if app.ui.stroke_front { stroke } else { fill }); // Unnamed colours (mixed in the Color panel) aren't listed until Add to Swatches; swatches in // colour groups are listed under their folder. - let grouped: Vec<&str> = doc.color_groups.iter().flat_map(|g| g.swatches.iter().map(String::as_str)).collect(); + let grouped: std::collections::HashSet<&str> = doc.color_groups.iter().flat_map(|g| g.swatches.iter().map(String::as_str)).collect(); + // Swatches by name (the first of a repeated name), so a row's lookup isn't a search of the list. + let mut by_name: std::collections::HashMap<&str, &designcraft_color::swatch::Swatch> = std::collections::HashMap::new(); + for w in &doc.swatches { + by_name.entry(w.name.as_str()).or_insert(w); + } // A gradient dragged from the Gradient panel's thumbnail is dropped on the list, colour // groups included. let (_, dropped) = ui.dnd_drop_zone::(egui::Frame::NONE, |ui| { - for sw in doc.swatches.iter().filter(|w| !w.hidden && !grouped.contains(&w.name.as_str())) { + for sw in doc.swatches.iter().filter(|w| !w.hidden && !grouped.contains(w.name.as_str())) { swatch_row(app, ui, &doc, sw, 0.0, fill_cur.as_deref()); } for g in &doc.color_groups { @@ -74,7 +79,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { }); if open { for n in &g.swatches { - if let Some(sw) = doc.swatches.iter().find(|w| w.name == *n) { + if let Some(sw) = by_name.get(n.as_str()).copied() { swatch_row(app, ui, &doc, sw, 16.0, fill_cur.as_deref()); } } From ed3f45a57a6007d9099d85995903fe5749713e75 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 16:16:04 -0500 Subject: [PATCH 0897/1349] render: cap the blend-area growth rounds, one name per optional-content layer (#2257) --- crates/render/src/blendspace.rs | 12 +++++++++++- crates/render/src/pdf_layers.rs | 5 +++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/render/src/blendspace.rs b/crates/render/src/blendspace.rs index 73855cea9..449410c59 100644 --- a/crates/render/src/blendspace.rs +++ b/crates/render/src/blendspace.rs @@ -28,6 +28,9 @@ pub(crate) struct CachedView { stats: crate::FrameStats, threads: u16, } +/// Rounds [`transparent_area`](Renderer::transparent_area) grows the blend area by joining touching objects. +const MAX_AREA_ROUNDS: usize = 64; + impl CachedView { pub(crate) const MAX_BYTES: usize = 64 << 20; #[allow(clippy::too_many_arguments)] @@ -326,13 +329,20 @@ impl Renderer { // Objects the area touches join it whole, so none is drawn partly through the ink passes // and partly through the ordinary drawing (their colour conversions differ slightly). let Some(mut area) = area else { return Some(Rect::ZERO) }; - for _ in 0..items.len() { + // A chain of overlapping objects joins one more per round (a pass over every item each), so the + // rounds are capped; past that the area is everything, a larger area the passes blend exactly. + let mut settled = false; + for _ in 0..MAX_AREA_ROUNDS.min(items.len()) { let grown = items.iter().filter(|(r, _)| r.intersect(area).area() > 0.0).fold(area, |a, (r, _)| a.union(*r)); if grown == area { + settled = true; break; } area = grown; } + if !settled && items.len() > MAX_AREA_ROUNDS { + area = items.iter().fold(area, |a, (r, _)| a.union(*r)); + } Some(f.view.transform_rect_bbox(area)) } diff --git a/crates/render/src/pdf_layers.rs b/crates/render/src/pdf_layers.rs index 3b323a505..bf3a7509d 100644 --- a/crates/render/src/pdf_layers.rs +++ b/crates/render/src/pdf_layers.rs @@ -22,6 +22,11 @@ fn ocgs(pdf: &Pdf) -> Vec<(ObjRef, String, bool)> { let (on, off) = (ids_in(b"ON"), ids_in(b"OFF")); list.raw_iter() .filter_map(|o| o.as_obj_ref()) + // A layer listed again is one layer: it gets one name, not one per entry. + .filter({ + let mut seen = std::collections::HashSet::new(); + move |r| seen.insert(*r) + }) .filter_map(|r| { let d = xref.get::>(ObjectIdentifier::from(r))?; let name = d From bcbc3ed4243a373e53184d0c6d2628d3bf429eaf Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 16:16:29 -0500 Subject: [PATCH 0898/1349] Story: appending text no longer scans every run and the whole prefix (#2245) * doc: appending to a story extends the last run, no scans * Apply review fixes - crates/doc/src/story.rs --------- Co-authored-by: aiongg <67543387+aiongg@users.noreply.github.com> --- crates/doc/src/story.rs | 39 +++++++++++++++++++++++++++++++++++---- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/story.rs b/crates/doc/src/story.rs index bbdbc6409..5628021b9 100644 --- a/crates/doc/src/story.rs +++ b/crates/doc/src/story.rs @@ -341,6 +341,11 @@ impl Story { /// Character format at byte `pos` (the run containing it; at a boundary, the preceding run — /// the format new typing takes). pub fn char_format_at(&self, pos: usize) -> &CharFormat { + if pos == self.text.len() + && let Some(r) = self.chars.iter().rev().find(|r| r.len > 0) + { + return &r.format; + } let mut start = 0; for r in &self.chars { let end = start + r.len; @@ -430,7 +435,9 @@ impl Story { self.marks_inserted(pos, text); } // Paragraph formats: each new '\n' splits the current paragraph; the new paragraphs copy it. - let pi = self.para_at(pos); + // An append (an import building a story piece by piece) is in the last paragraph: no prefix count. + let at_end = pos == self.text.len(); + let pi = if at_end { self.paras.len().saturating_sub(1) } else { self.para_at(pos) }; let newlines = text.bytes().filter(|b| *b == b'\n').count(); if newlines > 0 && let Some(f) = self.paras.get(pi).cloned() @@ -439,9 +446,15 @@ impl Story { self.paras.splice(pi + 1..pi + 1, std::iter::repeat_n(f, newlines)); } self.text.insert_str(pos, text); - // Character runs. - self.splice_runs(pos, 0, text.len(), fmt); - self.normalize(); + // Character runs. Appending extends or pushes at the end: no scan, and the runs stay normalized. + match self.chars.last_mut() { + Some(last) if at_end && last.len > 0 && last.format == fmt => last.len += text.len(), + Some(last) if at_end && last.len > 0 => self.chars.push(CharRun { len: text.len(), format: fmt }), + _ => { + self.splice_runs(pos, 0, text.len(), fmt); + self.normalize(); + } + } self.rev = self.rev.wrapping_add(1); } @@ -868,4 +881,22 @@ last"); } } } + + /// Appending pieces in alternating formats keeps one run per piece and merges equal neighbours. + #[test] + fn appended_pieces_keep_their_runs() { + let bold = CharFormat { style: "B".into(), ..Default::default() }; + let mut s = Story::new(StoryId(1)); + for i in 0..3000 { + let f = if i % 2 == 0 { CharFormat::default() } else { bold.clone() }; + let at = s.len(); + s.insert_with(at, if i % 7 == 0 { "a\n" } else { "b" }, f); + } + assert_eq!(s.chars.len(), 3000); + assert_eq!(s.chars.iter().map(|r| r.len).sum::(), s.text.len()); + assert_eq!(s.paras.len(), s.text.matches('\n').count() + 1); + let at = s.len(); + s.insert_with(at, "c", bold); + assert_eq!(s.chars.len(), 3000); + } } From 589f5ff8a37bdffa04231438ed6a815d22dafba1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 16:16:54 -0500 Subject: [PATCH 0899/1349] Engine: Erase and Smooth search each distinct drag sample once (#2272) * engine: Erase/Smooth look at each distinct drag sample once, thinned past 4096 * Apply review fixes - crates/engine/src/cmd/anchors.rs * address review: decide whether a drag touched the path on every distinct sample, then thin --------- Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com> --- crates/engine/src/cmd/anchors.rs | 73 +++++++++++++++++++++++++++----- 1 file changed, 63 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/anchors.rs b/crates/engine/src/cmd/anchors.rs index 4ccbeec7e..0968fb588 100644 --- a/crates/engine/src/cmd/anchors.rs +++ b/crates/engine/src/cmd/anchors.rs @@ -291,33 +291,61 @@ fn convert_points(s: &mut Session, p: &Value) -> Result { }) } +/// Most samples of a drag that Erase / Smooth look at. +const MAX_DRAG_SAMPLES: usize = 4096; + /// Erase / Smooth: the stretch of one subpath touched by the drag. fn erase_or_smooth(s: &mut Session, p: &Value, smooth: bool) -> Result { let cmd = if smooth { "path.smooth" } else { "path.erase" }; let id = super::id_param(p, "id").ok_or_else(|| bad(cmd, "missing id"))?; let tol = p.get("tolerance").and_then(Value::as_f64).unwrap_or(4.0); - let pts: Vec = p + let mut pts: Vec = p .get("points") .and_then(Value::as_array) .map(|a| a.iter().filter_map(|v| Some(Point::new(v.get(0)?.as_f64()?, v.get(1)?.as_f64()?))).collect()) .unwrap_or_default(); + // Each sample is a search of every segment: repeated samples add nothing, and a drag has no use + // for more than MAX_DRAG_SAMPLES (evenly thinned, the first and last kept). Whether the drag + // touched the path is decided on every distinct sample, though: see below. + let mut seen = std::collections::HashSet::new(); + pts.retain(|q| seen.insert((q.x.to_bits(), q.y.to_bits()))); + let thinned: Vec = if pts.len() > MAX_DRAG_SAMPLES { + let (n, last) = (pts.len(), pts.last().copied()); + (0..MAX_DRAG_SAMPLES).filter_map(|i| pts.get((i as u64 * n as u64 / MAX_DRAG_SAMPLES as u64) as usize).copied()).chain(last).collect() + } else { + Vec::new() + }; s.edit(|d, sel| { path_editable(d, id, cmd)?; let inv = to_inner(d, id).ok_or(designcraft_doc::DocError::NoItem(id))?; let scale = inv.determinant().abs().sqrt().max(1e-9); let it = d.item_mut(id).ok_or(designcraft_doc::DocError::NoItem(id))?; // Where the drag touched the path, per subpath. - let mut hits: Vec<(usize, usize, f64)> = Vec::new(); - for q in &pts { - if let Some((si, seg, t, _, dist)) = it.path.nearest(inv * *q) - && dist <= tol * scale - { - hits.push((si, seg, t)); + let hits_of = |set: &[Point]| -> Vec<(usize, usize, f64)> { + let mut hits = Vec::new(); + for q in set { + if let Some((si, seg, t, _, dist)) = it.path.nearest(inv * *q) + && dist <= tol * scale + { + hits.push((si, seg, t)); + } + } + hits + }; + // A long drag is searched thinned; only when that finds nothing are all its samples, so a + // touch the thinning skipped over still counts and a long drag is never refused for it. + let mut hits = hits_of(if thinned.is_empty() { &pts } else { &thinned }); + if hits.is_empty() && !thinned.is_empty() { + hits = hits_of(&pts); + } + // The subpath with the most hits (the last of equals), counted in one pass. + let mut counts = vec![0usize; it.path.subpaths.len()]; + for h in &hits { + if let Some(n) = counts.get_mut(h.0) { + *n += 1; } } - let Some(si) = - (0..it.path.subpaths.len()).max_by_key(|i| hits.iter().filter(|h| h.0 == *i).count()).filter(|i| hits.iter().any(|h| h.0 == *i)) - else { + let Some((si, _)) = counts.iter().copied().enumerate().filter(|(_, n)| *n > 0).max_by_key(|(_, n)| *n) else { return Err(bad(cmd, "the drag didn't touch the path")); }; let on: Vec<(usize, f64)> = hits.iter().filter(|h| h.0 == si).map(|h| (h.1, h.2)).collect(); @@ -663,6 +691,31 @@ mod tests { assert!(s.execute("path.erase", &json!({"id": id, "points": [[100, 600]]})).is_err()); } + /// A touch only thinning would skip still counts: a long drag is not refused as missing the path. + #[test] + fn a_touch_the_thinning_skips_still_counts() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let pts: Vec = (0..=20).map(|i| json!({"p": [100.0 + i as f64 * 20.0, 300.0]})).collect(); + let id = s.execute("path.create", &json!({"anchors": pts})).unwrap()["id"].as_u64().unwrap(); + // 6,000 distinct samples far from the path but one, at an index thinning to 4,096 drops. + let drag: Vec = (0..6_000).map(|i| if i == 3 { json!([200.0, 300.0]) } else { json!([200.0 + f64::from(i) * 0.01, 900.0]) }).collect(); + assert!(s.execute("path.erase", &json!({"id": id, "points": drag})).is_ok()); + } + + /// A drag of many repeated and many distinct samples is thinned and still erases where it went. + #[test] + fn a_drag_with_many_samples_still_erases() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let pts: Vec = (0..=20).map(|i| json!({"p": [100.0 + i as f64 * 20.0, if i % 2 == 0 { 300.0 } else { 306.0 }]})).collect(); + let id = s.execute("path.create", &json!({"anchors": pts})).unwrap()["id"].as_u64().unwrap(); + // 60,000 samples along the middle of the path, each point repeated. + let drag: Vec = (0..60_000).map(|i| json!([200.0 + f64::from(i % 6000) * 0.025, 303.0])).collect(); + let r = s.execute("path.erase", &json!({"id": id, "points": drag})).unwrap(); + assert_eq!(r["subpaths"], 2, "a gap in the middle"); + } + /// The Direct Selection's selected points stay the same points when the path changes under /// them: a point added before them, one of them deleted, the path reversed. #[test] From 79d7a912f1f86dfa23179bd24e42936a91a9f65b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 16:17:18 -0500 Subject: [PATCH 0900/1349] Strokes: cap the points a wavy or hashed stroke places along a path (#2188) * Strokes: cap the points a wavy or hashed stroke places along a path * address review: zero-length quadratic contributes no length in stroke samples * Fix failing CI check - crates/geom/src/stroke_style.rs * Fix failing CI check - crates/geom/src/stroke_style.rs --------- Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com> --- crates/geom/src/stroke_style.rs | 73 +++++++++++++++++++++++++++++---- 1 file changed, 66 insertions(+), 7 deletions(-) diff --git a/crates/geom/src/stroke_style.rs b/crates/geom/src/stroke_style.rs index d3c25ecba..42a92a0bb 100644 --- a/crates/geom/src/stroke_style.rs +++ b/crates/geom/src/stroke_style.rs @@ -83,22 +83,55 @@ pub fn stripes(bp: &BezPath, weight: f64, bands: &Bands, tol: f64) -> BezPath { out } +/// Most points [`samples`] places along one path. A wavy or hashed stroke places one every +/// few points of length, so a long path from a document (a segment thousands of kilometres +/// long) would otherwise take millions; past this the points spread out to fit the budget. +pub const MAX_STROKE_SAMPLES: usize = 100_000; + +/// Points along `bp` every `step` of arc length, with the unit tangent there, all subpaths in turn. +fn samples(bp: &BezPath, step: f64) -> Vec<(Point, Vec2)> { + sample_subpaths(bp, step).into_iter().flatten().collect() +} + /// Points along each subpath of `bp` every `step` of arc length, with the unit tangent there. -fn samples(bp: &BezPath, step: f64) -> Vec> { - subpaths(bp).iter().map(|sub| subpath_samples(sub, step)).collect() +/// When that would take more than [`MAX_STROKE_SAMPLES`] points, the step widens so the path +/// still gets them evenly; a path whose length isn't finite gets none. +fn sample_subpaths(bp: &BezPath, step: f64) -> Vec> { + let subs = subpaths(bp); + // kurbo's arclen of an all-equal quadratic is NaN; it has no length, so skip it. + let total: f64 = subs + .iter() + .flat_map(|s| s.segments()) + .map(|seg| match seg { + PathSeg::Quad(q) if q.p0 == q.p1 && q.p1 == q.p2 => 0.0, + _ => seg.arclen(1e-3), + }) + .sum(); + if !total.is_finite() || !step.is_finite() || step <= 0.0 { + return Vec::new(); + } + let step = step.max(total / MAX_STROKE_SAMPLES as f64); + subs.iter().map(|sub| subpath_samples(sub, step)).collect() } /// Points along one subpath every `step` of arc length, with the unit tangent there. fn subpath_samples(bp: &BezPath, step: f64) -> Vec<(Point, Vec2)> { + // kurbo's arclen of an all-equal quadratic is NaN; it has no length, so skip it. + let lens: Vec = bp + .segments() + .map(|seg| match seg { + PathSeg::Quad(q) if q.p0 == q.p1 && q.p1 == q.p2 => 0.0, + _ => seg.arclen(1e-3), + }) + .collect(); let mut out = Vec::new(); let mut carry = 0.0; - for seg in bp.segments() { - let len = seg.arclen(1e-3); + for (seg, &len) in bp.segments().zip(&lens) { if len < 1e-9 { continue; } let mut s = carry; - while s <= len { + while s <= len && out.len() < MAX_STROKE_SAMPLES { let t = seg.inv_arclen(s, 1e-3); let d = match seg { PathSeg::Line(l) => l.p1 - l.p0, @@ -120,7 +153,7 @@ fn subpath_samples(bp: &BezPath, step: f64) -> Vec<(Point, Vec2)> { pub fn wavy(bp: &BezPath, weight: f64, tol: f64) -> BezPath { let wavelength = (weight * 4.0).max(2.0); let mut line = BezPath::new(); - for pts in samples(bp, wavelength / 16.0) { + for pts in sample_subpaths(bp, wavelength / 16.0) { for (i, (p, t)) in pts.iter().enumerate() { let normal = Vec2::new(-t.y, t.x); let phase = i as f64 / 16.0 * std::f64::consts::TAU; @@ -135,7 +168,7 @@ pub fn wavy(bp: &BezPath, weight: f64, tol: f64) -> BezPath { /// A straight-hash stroke: short ticks across the path, as wide as the weight. pub fn hashed(bp: &BezPath, weight: f64, tol: f64) -> BezPath { let mut ticks = BezPath::new(); - for (p, t) in samples(bp, (weight * 0.6).max(1.0)).into_iter().flatten() { + for (p, t) in samples(bp, (weight * 0.6).max(1.0)) { let normal = Vec2::new(-t.y, t.x) * (weight / 2.0); ticks.move_to(p - normal); ticks.line_to(p + normal); @@ -193,6 +226,32 @@ mod tests { assert!((off.bounding_box().y0 + 3.0).abs() < 1e-6, "left of travel is −y"); } + /// A path kilometres long gets at most the sample budget, not one point per few points of + /// length; a path of infinite length gets none. + #[test] + fn long_paths_stay_within_the_sample_budget() { + let mut long = BezPath::new(); + long.move_to((0.0, 0.0)); + long.line_to((1e12, 0.0)); + long.line_to((1e12, 1e12)); + assert!(samples(&long, 1.0).len() <= MAX_STROKE_SAMPLES); + let h = hashed(&long, 1.0, 0.01).bounding_box(); + assert!(h.width() > 1e11, "{h:?}"); + assert!(!wavy(&long, 1.0, 0.01).is_empty()); + let mut huge = BezPath::new(); + huge.move_to((-f64::MAX, 0.0)); + huge.line_to((f64::MAX, 0.0)); + assert!(samples(&huge, 1.0).is_empty()); + assert_eq!(samples(&line(), 10.0).len(), 11, "short paths sample as before"); + } + + #[test] + fn a_zero_length_quadratic_keeps_the_line_before_it() { + let mut bp = line(); + bp.quad_to((100.0, 0.0), (100.0, 0.0)); + assert_eq!(samples(&bp, 10.0).len(), 11); + } + #[test] fn wavy_and_hash_cover_the_weight() { let w = wavy(&line(), 9.0, 0.01).bounding_box(); From c684db5428f1f521824ee5f3533eef14f5af7d0f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 16:17:42 -0500 Subject: [PATCH 0901/1349] Tools: selection bounds in one walk, bounded smart spacing and parent snapping (#2260) * tools: selection bounds in one walk, caps on smart-spacing boxes and parent occurrences * Apply review fixes - crates/tools/src/lib.rs * address review: iterative selection walk; stop collecting spacing boxes at the cap --------- Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com> --- crates/tools/src/lib.rs | 50 ++++++++++++++++++++++++++++++++++++---- crates/tools/src/snap.rs | 26 +++++++++++++++++---- 2 files changed, 67 insertions(+), 9 deletions(-) diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 73afc4d5d..d4a11b582 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -314,11 +314,54 @@ impl ToolContext<'_> { self.doc.item(id) } + /// The selected items with the transform from their own space to the canvas, found in one walk + /// of the document (a search per item made a big selection quadratic). Same first match per + /// id as `Document::find`, in selection order. + fn selected_with_canvas_xf(&self) -> Vec<(&Item, Affine)> { + let mut want: std::collections::HashSet = self.selection.items.iter().copied().collect(); + let mut found: std::collections::HashMap = std::collections::HashMap::new(); + // Pre-order with an explicit stack: a deep group tree must not exhaust the call stack. + fn walk<'a>( + items: &'a [std::sync::Arc], + want: &mut std::collections::HashSet, + found: &mut std::collections::HashMap, + ) { + let mut stack = vec![(items.iter(), Affine::IDENTITY)]; + while let Some((kids, xf)) = stack.last_mut() { + if want.is_empty() { + return; + } + let Some(it) = kids.next() else { + stack.pop(); + continue; + }; + let xf = *xf; + if want.remove(&it.id) { + found.insert(it.id, (it, xf)); + } + stack.push((it.children().iter(), xf * it.xf)); + } + } + for r in self.doc.spread_refs() { + if want.is_empty() { + break; + } + if let Some(sp) = self.doc.spread(r) { + let mut here = std::collections::HashMap::new(); + walk(&sp.items, &mut want, &mut here); + if !here.is_empty() { + let canvas = self.layout.xf(r); + found.extend(here.into_iter().map(|(id, (it, xf))| (id, (it, canvas * xf)))); + } + } + } + self.selection.items.iter().filter_map(|id| found.get(id).copied()).collect() + } + /// Canvas bounds of the selected items' paths. Handles and resize use this geometric box. pub fn selection_bounds(&self) -> Option { let mut r: Option = None; - for id in &self.selection.items { - let (Some(it), Some(xf)) = (self.doc.item(*id), self.item_canvas_xf(*id)) else { continue }; + for (it, xf) in self.selected_with_canvas_xf() { let b = xf.transform_rect_bbox(it.bounds()); r = Some(r.map_or(b, |r| r.union(b))); } @@ -328,8 +371,7 @@ impl ToolContext<'_> { /// Canvas union of the selection's visible bounds. A group uses the alignment box. pub fn selection_visible_bounds(&self) -> Option { let mut acc: Option = None; - for id in &self.selection.items { - let (Some(it), Some(xf)) = (self.doc.item(*id), self.item_canvas_xf(*id)) else { continue }; + for (it, xf) in self.selected_with_canvas_xf() { let Some(local) = crate::snap::moving_bounds(it) else { continue }; let b = xf.transform_rect_bbox(local); if !(b.x0.is_finite() && b.y0.is_finite() && b.x1.is_finite() && b.y1.is_finite()) { diff --git a/crates/tools/src/snap.rs b/crates/tools/src/snap.rs index c76a0bd82..97b94a64b 100644 --- a/crates/tools/src/snap.rs +++ b/crates/tools/src/snap.rs @@ -525,7 +525,8 @@ fn pass_spacing(cx: &ToolContext, req: &SnapRequest<'_>, axis: Axis, tol: f64) - return None; } let mover = interval_on(req.rect, axis)?; - let boxes = spacing_intervals(cx, req, axis, &mover); + // Every box is compared with every other (quadratic on each pointer move): none past the cap. + let boxes = spacing_intervals(cx, req, axis, &mover)?; let stationary = stationary_gaps(&boxes); let low = nearest_side(&mover, &boxes, None, true); let high = nearest_side(&mover, &boxes, None, false); @@ -561,20 +562,27 @@ fn pass_spacing(cx: &ToolContext, req: &SnapRequest<'_>, axis: Axis, tol: f64) - /// Top-level visible boxes that overlap `mover` on the other axis. /// -/// The moving rect is not one of them. Parents are not walked. -fn spacing_intervals(cx: &ToolContext, req: &SnapRequest<'_>, axis: Axis, mover: &Interval) -> Vec { +/// The moving rect is not one of them. Parents are not walked. `None` as soon as there would be +/// more than [`MAX_SPACING_BOXES`], before any more are collected. +fn spacing_intervals(cx: &ToolContext, req: &SnapRequest<'_>, axis: Axis, mover: &Interval) -> Option> { let mut out = Vec::new(); - let Some(sp) = cx.doc.spread(req.spread) else { return out }; + let Some(sp) = cx.doc.spread(req.spread) else { return Some(out) }; for item in &sp.items { let Some(rect) = item_target_rect(cx.selection, req, item) else { continue }; let Some(span) = interval_on(rect, axis) else { continue }; if ranges_overlap(mover.perp_lo, mover.perp_hi, span.perp_lo, span.perp_hi) { + if out.len() == MAX_SPACING_BOXES { + return None; + } out.push(span); } } - out + Some(out) } +/// Most boxes on the mover's band that smart spacing compares; a spread with more has no spacing guides. +const MAX_SPACING_BOXES: usize = 2048; + struct Interval { lo: f64, hi: f64, @@ -1213,6 +1221,8 @@ fn offer_parent_items(best: &mut Option, cx: &ToolContext, req: &SnapReque fn shown_parent_items(doc: &Document, spread: SpreadRef) -> Vec<(&Item, f64)> { let Some(sp) = doc.spread(spread) else { return Vec::new() }; let mut out = Vec::new(); + // Pages times parent items can be many times what the file stores: no more than this are listed. + let room = MAX_PARENT_OCCURRENCES; for (pi, page) in sp.pages.iter().enumerate() { if !page.show_parent_items { continue; @@ -1233,6 +1243,9 @@ fn shown_parent_items(doc: &Document, spread: SpreadRef) -> Vec<(&Item, f64)> { if parent.pages.len() > 1 && parent.page_at_x(item.bounds().center().x) != Some(ppage) { continue; } + if out.len() >= room { + return out; + } out.push((item.as_ref(), dx)); } } @@ -1240,6 +1253,9 @@ fn shown_parent_items(doc: &Document, spread: SpreadRef) -> Vec<(&Item, f64)> { out } +/// Parent item occurrences snapping considers on one spread. +const MAX_PARENT_OCCURRENCES: usize = 100_000; + fn shift_x(r: Rect, dx: f64) -> Rect { Rect::new(r.x0 + dx, r.y0, r.x1 + dx, r.y1) } From eba5b9f8456f37c366f42396dddca520599a492c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 16:18:07 -0500 Subject: [PATCH 0902/1349] datamerge: all further pages in one insertion, page lookups by start index (#2279) --- crates/engine/src/cmd/datamerge.rs | 67 +++++++++++++++++++----- crates/engine/src/cmd/datamerge/tests.rs | 24 +++++++++ 2 files changed, 77 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/datamerge.rs b/crates/engine/src/cmd/datamerge.rs index fb8d572cb..7cb332fd3 100644 --- a/crates/engine/src/cmd/datamerge.rs +++ b/crates/engine/src/cmd/datamerge.rs @@ -274,37 +274,74 @@ fn merge_cmd(s: &mut Session, p: &Value) -> Result { })) } +/// Pages a merge may make in all, checked before any is built. +const MAX_MERGED_PAGES: usize = 1_000_000; + fn copy_records(dst: &mut Document, src: &Document, table: &Table, selected: &[usize], sources: &Sources, sink: &mut Sink) -> Result<()> { if let Some(&idx) = selected.first() { let maps = identity_map(dst); fill_at(dst, table, idx, sources, &maps, sink); } - for &idx in selected.iter().skip(1) { - let maps = append_copy(dst, src)?; + let rest = selected.len().saturating_sub(1); + if rest == 0 { + return Ok(()); + } + // The pages of every further record in one insertion (one repagination, not one per record), + // then each copy goes onto its own. + let n = src.page_count().max(1); + let first_new = dst.page_count(); + let total = n + .checked_mul(rest) + .filter(|t| t.saturating_add(first_new) <= MAX_MERGED_PAGES) + .ok_or_else(|| bad("data.merge", format!("the merge would make more than {MAX_MERGED_PAGES} pages")))?; + let parent = src.page(0).and_then(|p| p.parent); + dst.insert_pages(Some(first_new.saturating_sub(1)), total, parent)?; + let dst_starts = spread_starts(dst); + let src_starts = spread_starts(src); + for (k, &idx) in selected.iter().skip(1).enumerate() { + let maps = append_copy(dst, src, first_new + k * n, &dst_starts, &src_starts)?; fill_at(dst, table, idx, sources, &maps, sink); } Ok(()) } -fn append_copy(dst: &mut Document, src: &Document) -> Result { - let start = dst.page_count(); +/// Absolute index of each spread's first page: page lookups by search rather than by walking the spreads. +fn spread_starts(d: &Document) -> Vec { + let mut n = 0; + d.spreads + .iter() + .map(|s| { + let at = n; + n += s.pages.len(); + at + }) + .collect() +} + +/// (spread, page in spread) of absolute page `abs`, as [`Document::page_loc`] says, given `starts`. +fn loc_of(d: &Document, starts: &[usize], abs: usize) -> Option<(usize, usize)> { + let si = starts.partition_point(|&s| s <= abs).checked_sub(1)?; + let pi = abs - starts.get(si)?; + (pi < d.spreads.get(si)?.pages.len()).then_some((si, pi)) +} + +/// Copy `src`'s pages and items onto the pages of `dst` from absolute page `start`. +fn append_copy(dst: &mut Document, src: &Document, start: usize, dst_starts: &[usize], src_starts: &[usize]) -> Result { let n = src.page_count().max(1); - let parent = src.page(0).and_then(|p| p.parent); - dst.insert_pages(Some(start.saturating_sub(1)), n, parent)?; for i in 0..n { if let Some(pg) = src.page(i).cloned() { - assign_page(dst, start.saturating_add(i), &pg); + assign_page(dst, loc_of(dst, dst_starts, start.saturating_add(i)), &pg); } } let mut maps = Maps::default(); for (spi, sp) in src.spreads.iter().enumerate() { for it in &sp.items { let pi = sp.page_at_x(it.bounds().center().x).unwrap_or(0); - let abs = src.first_page_of_spread(spi).saturating_add(pi); + let abs = src_starts.get(spi).copied().unwrap_or(0).saturating_add(pi); let dest_abs = start.saturating_add(abs); - let Some((dsi, _)) = dst.page_loc(dest_abs) else { continue }; + let Some((dsi, dpi)) = loc_of(dst, dst_starts, dest_abs) else { continue }; let src_x = src.page(abs).map(|p| p.x).unwrap_or(0.0); - let dst_x = dst.page(dest_abs).map(|p| p.x).unwrap_or(0.0); + let dst_x = dst.spreads.get(dsi).and_then(|s| s.pages.get(dpi)).map(|p| p.x).unwrap_or(0.0); copy_item(dst, src, it, SpreadRef::Doc(dsi), Vec2::new(dst_x - src_x, 0.0), &mut maps)?; } } @@ -333,11 +370,13 @@ fn tile_records(dst: &mut Document, src: &Document, table: &Table, selected: &[u let template = src.page(0).cloned(); dst.insert_pages(Some(0), plan.pages.saturating_sub(1), parent)?; if let Some(pg) = template { + let starts = spread_starts(dst); for i in 1..plan.pages { - assign_page(dst, i, &pg); + assign_page(dst, loc_of(dst, &starts, i), &pg); } } } + let starts = spread_starts(dst); for hit in plan.hits { let Some(&idx) = selected.get(hit.index) else { continue }; if hit.index == 0 && hit.page == 0 && hit.col == 0 && hit.row == 0 { @@ -345,7 +384,7 @@ fn tile_records(dst: &mut Document, src: &Document, table: &Table, selected: &[u fill_at(dst, table, idx, sources, &maps, sink); continue; } - let Some((dsi, _)) = dst.page_loc(hit.page) else { continue }; + let Some((dsi, _)) = loc_of(dst, &starts, hit.page) else { continue }; let mut maps = Maps::default(); for id in &ids { let Some(it) = src.item(*id) else { continue }; @@ -406,8 +445,8 @@ fn block_of(doc: &Document) -> (Rect, Vec) { (block.unwrap_or(Rect::ZERO), ids) } -fn assign_page(dst: &mut Document, abs: usize, from: &Page) { - let Some((si, pi)) = dst.page_loc(abs) else { return }; +fn assign_page(dst: &mut Document, loc: Option<(usize, usize)>, from: &Page) { + let Some((si, pi)) = loc else { return }; let Some(sp) = dst.spreads.get_mut(si) else { return }; let sp = Arc::make_mut(sp); let Some(p) = sp.pages.get_mut(pi) else { return }; diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index c58628551..4793aac17 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -854,6 +854,30 @@ fn tiling_rows_first_bottom_inset_and_refusals() { assert_eq!(s.documents().len(), before); } +/// A two-page template merged for three records: six pages made in one insertion, each record's +/// frame on its own pages, in record order. +#[test] +fn a_two_page_template_merges_onto_consecutive_pages() { + let mut s = Session::new(); + new_doc(&mut s, 2); + text_frame(&mut s, [72.0, 72.0, 172.0, 172.0], "<>", None); + select_csv(&mut s, "Name\nA\nB\nC\n"); + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["pages"], 6); + let d = &s.documents()[s.active_index().unwrap()].doc; + assert_eq!(d.page_count(), 6); + let mut at: Vec<(usize, String)> = Vec::new(); + for st in d.stories.values() { + let f = d.item(*st.frames.first().unwrap()).unwrap(); + let sp = d.spreads.iter().position(|sp| sp.items.iter().any(|i| i.id == f.id)).unwrap(); + let page = d.first_page_of_spread(sp) + d.spreads[sp].page_at_x(f.bounds().center().x).unwrap_or(0); + at.push((page, st.text.clone())); + } + at.sort(); + assert_eq!(at, vec![(0, "A".to_string()), (2, "B".to_string()), (4, "C".to_string())]); + d.check().unwrap(); +} + /// An IME delete-surrounding while a record is previewed edits the template, not the filled /// record, and its undo step restores the template. #[test] From 34f24a4d2af567ee4d9e17153d20dc3f73991967 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 16:18:31 -0500 Subject: [PATCH 0903/1349] Gradients: expand midpoint stops in linear time (#2214) * fix(color): sample gradients by binary search when expanding midpoints * Apply review fixes - crates/color/src/gradient.rs * Apply review fixes - crates/color/src/gradient.rs * Fix failing CI check - crates/color/src/gradient.rs --------- Co-authored-by: aiongg <67543387+aiongg@users.noreply.github.com> --- crates/color/src/gradient.rs | 108 +++++++++++++++++++++++++++++------ 1 file changed, 92 insertions(+), 16 deletions(-) diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index 29f710627..be3ce9543 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -72,23 +72,45 @@ impl Default for Gradient { impl Gradient { /// Colour and opacity at `t` (honours midpoints). pub fn sample(&self, t: f32) -> (Color, f32) { + self.sample_in(None, t) + } + + /// For each window `(stops[k], stops[k + 1])`, the largest end offset of windows `0..=k`: the + /// first window whose end reaches `t` is the first `k` where this does, so a binary search + /// finds it (stops in any order). + fn window_ends(&self) -> Vec { + let mut end = f32::NAN; + self.stops + .iter() + .skip(1) + .map(|s| { + end = end.max(s.offset); + end + }) + .collect() + } + + /// [`Self::sample`], with [`Self::window_ends`] given when it was worked out once (else a scan). + fn sample_in(&self, ends: Option<&[f32]>, t: f32) -> (Color, f32) { let stops = &self.stops; - if stops.is_empty() { + let Some(first) = stops.first() else { return (Color::BLACK, 1.0); + }; + if t <= first.offset { + return (first.color, first.opacity); } - if t <= stops[0].offset { - return (stops[0].color, stops[0].opacity); - } - for w in stops.windows(2) { - let (a, b) = (&w[0], &w[1]); - if t <= b.offset { - let span = (b.offset - a.offset).max(1e-6); - let u = (t - a.offset) / span; - // Map through the midpoint: u=mid → 0.5. - let m = a.midpoint.clamp(0.01, 0.99); - let v = if u < m { 0.5 * u / m } else { 0.5 + 0.5 * (u - m) / (1.0 - m) }; - return (a.color.lerp(&b.color, v), a.opacity + (b.opacity - a.opacity) * v); - } + // The first window whose end offset is at or past `t` (none for a NaN `t`). + let k = match ends { + None => stops.windows(2).position(|w| t <= w[1].offset).unwrap_or(stops.len()), + Some(ends) => ends.partition_point(|e| matches!(e.partial_cmp(&t), None | Some(std::cmp::Ordering::Less))), + }; + if let (Some(a), Some(b)) = (stops.get(k), stops.get(k + 1)) { + let span = (b.offset - a.offset).max(1e-6); + let u = (t - a.offset) / span; + // Map through the midpoint: u=mid → 0.5. + let m = a.midpoint.clamp(0.01, 0.99); + let v = if u < m { 0.5 * u / m } else { 0.5 + 0.5 * (u - m) / (1.0 - m) }; + return (a.color.lerp(&b.color, v), a.opacity + (b.opacity - a.opacity) * v); } match stops.last() { Some(l) => (l.color, l.opacity), @@ -97,6 +119,7 @@ impl Gradient { } /// Stops expanded so that midpoints are represented as explicit stops (for renderers without midpoints). pub fn expanded_stops(&self) -> Vec<(f32, Color, f32)> { + let ends = self.window_ends(); let mut out = Vec::new(); for (i, s) in self.stops.iter().enumerate() { out.push((s.offset, s.color, s.opacity)); @@ -105,7 +128,7 @@ impl Gradient { && (mid - 0.5).abs() > 1e-3 { let t = s.offset + (n.offset - s.offset) * mid; - let (c, o) = self.sample(t); + let (c, o) = self.sample_in(Some(&ends), t); out.push((t, c, o)); } } @@ -116,6 +139,7 @@ impl Gradient { pub fn display_stops(&self) -> Vec<(f32, Color, f32)> { const STEPS: usize = 16; let stops = self.expanded_stops(); + let ends = self.window_ends(); let mut out: Vec<(f32, Color, f32)> = Vec::with_capacity(stops.len() * STEPS); for (i, s) in stops.iter().enumerate() { out.push(*s); @@ -125,7 +149,7 @@ impl Gradient { } for j in 1..STEPS { let t = s.0 + (n.0 - s.0) * j as f32 / STEPS as f32; - let (c, a) = self.sample(t); + let (c, a) = self.sample_in(Some(&ends), t); out.push((t, c, a)); } } @@ -216,6 +240,58 @@ impl GradientPaint { #[cfg(test)] mod tests { + /// The sampler as it was: the first window whose end reaches `t`, by a scan. + fn sample_by_scan(g: &super::Gradient, t: f32) -> (super::Color, f32) { + let stops = &g.stops; + if stops.is_empty() { + return (super::Color::BLACK, 1.0); + } + if t <= stops[0].offset { + return (stops[0].color, stops[0].opacity); + } + for w in stops.windows(2) { + let (a, b) = (&w[0], &w[1]); + if t <= b.offset { + let span = (b.offset - a.offset).max(1e-6); + let u = (t - a.offset) / span; + let m = a.midpoint.clamp(0.01, 0.99); + let v = if u < m { 0.5 * u / m } else { 0.5 + 0.5 * (u - m) / (1.0 - m) }; + return (a.color.lerp(&b.color, v), a.opacity + (b.opacity - a.opacity) * v); + } + } + stops.last().map_or((super::Color::BLACK, 1.0), |l| (l.color, l.opacity)) + } + + /// The search finds the window the scan found, for stops in order, out of order, repeated + /// and NaN; and many stops expand in linear time. + #[test] + fn sampling_by_search_matches_the_scan() { + use super::{Color, Gradient, GradientKind, GradientStop}; + let offsets = [0.0, 0.3, 0.2, 0.2, f32::NAN, 0.9, 0.5, 1.0, 0.95]; + let stops: Vec = offsets + .iter() + .enumerate() + .map(|(i, &o)| GradientStop { midpoint: 0.3, ..GradientStop::new(o, Color::rgb8((i * 25) as u8, 0, 255 - (i * 25) as u8)) }) + .collect(); + for n in 0..=stops.len() { + let g = Gradient { kind: GradientKind::Linear, stops: stops[..n].to_vec() }; + for t in [-1.0, 0.0, 0.1, 0.2, 0.25, 0.3, 0.6, 0.9, 0.93, 1.0, 2.0, f32::NAN, f32::INFINITY] { + // Compared as printed: a NaN offset gives NaN components on both sides. + let a = format!("{:?}", g.sample_in(Some(&g.window_ends()), t)); + let b = format!("{:?}", sample_by_scan(&g, t)); + assert_eq!(format!("{:?}", g.sample(t)), b, "{n} stops at {t} (scan)"); + assert_eq!(a, b, "{n} stops at {t}"); + } + } + let many = Gradient { + kind: GradientKind::Linear, + stops: (0..100_000).map(|i| GradientStop { midpoint: 0.3, ..GradientStop::new(i as f32 / 100_000.0, Color::BLACK) }).collect(), + }; + let t = std::time::Instant::now(); + assert_eq!(many.expanded_stops().len(), 199_999); + assert!(t.elapsed() < std::time::Duration::from_secs(2), "{:?}", t.elapsed()); + } + use super::*; #[test] From cfd99ba9b5ba09218cdcb04079787f709532e6b9 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 16:18:55 -0500 Subject: [PATCH 0904/1349] Automation roots: compare paths exactly; recovery reads only regular entry files (#2205) * fix(engine): exact root containment and regular-file recovery entries * Apply review fixes - crates/engine/src/recovery.rs --------- Co-authored-by: aiongg <67543387+aiongg@users.noreply.github.com> --- crates/engine/src/file_access.rs | 34 ++++++++++---------- crates/engine/src/recovery.rs | 49 +++++++++++++++++++++++++++-- crates/engine/src/recovery/tests.rs | 31 ++++++++++++++++++ 3 files changed, 93 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 81a6761bd..69edeaca1 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -10,8 +10,9 @@ //! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so //! is a link that leads nowhere). //! - The result must lie inside one of the roots of its kind, compared by whole components -//! (`/work2` isn't inside `/work`), without regard to case on Windows. Two roots don't make their -//! common parent one. +//! (`/work2` isn't inside `/work`), in the case the file system stores (so a case-variant name +//! reaches the same folder on an ordinary Windows volume, and a distinct sibling in a +//! case-sensitive one stays outside). Two roots don't make their common parent one. //! - Read and write access are separate: a root given alone grants only its own kind of access. //! //! Roots are in force on a thread inside [`confine`], and in the whole process after @@ -255,24 +256,13 @@ fn resolve(path: &Path) -> Result { } } -/// Is `path` (resolved) `root` or inside it, component by component (without regard to case on -/// Windows, whose file systems ignore it)? +/// Is `path` (resolved) `root` or inside it, component by component? Both are canonical, so each +/// component carries the case the file system stores: a path that differs only in case names the +/// same folder on an ordinary Windows volume (and resolves to the same components), and a distinct +/// sibling in a case-sensitive folder (which must not pass as the root). fn inside(path: &Path, root: &Path) -> bool { let mut path = path.components(); - root.components().all(|r| path.next().is_some_and(|p| same_component(p, r))) -} - -fn same_component(a: Component, b: Component) -> bool { - if a == b { - return true; - } - if !cfg!(windows) { - return false; - } - match (a.as_os_str().to_str(), b.as_os_str().to_str()) { - (Some(a), Some(b)) => a.to_lowercase() == b.to_lowercase(), - _ => false, - } + root.components().all(|r| path.next() == Some(r)) } /// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file. @@ -571,6 +561,14 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + #[test] + fn inside_compares_components_exactly() { + assert!(inside(Path::new("/work/in/a"), Path::new("/work/in"))); + assert!(inside(Path::new("/work/in"), Path::new("/work/in"))); + assert!(!inside(Path::new("/work/In/a"), Path::new("/work/in")), "a case-variant sibling is another folder"); + assert!(!inside(Path::new("/work/in2/a"), Path::new("/work/in"))); + } + #[test] fn device_names() { for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.designcraft", "NUL "] { diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index eb6d99886..25256cbc5 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -441,6 +441,49 @@ fn files(dir: &Path, uid: u64) -> (PathBuf, PathBuf) { (dir.join(format!("{uid}.designcraft")), dir.join(format!("{uid}.json"))) } +/// The bytes of the recovery entry file at `path`, which must be a regular file: the folder was +/// checked, and a link planted among its entries would lead the read anywhere. +fn read_entry_file(path: &Path) -> std::io::Result> { + use std::io::Read; + let refuse = || std::io::Error::other(format!("{}: a recovery entry must be a regular file", path.display())); + let before = std::fs::symlink_metadata(path)?; + #[cfg(not(target_arch = "wasm32"))] + if is_link_like(&before) { + return Err(refuse()); + } + if !before.file_type().is_file() { + return Err(refuse()); + } + #[cfg(windows)] + let mut file = { + use std::os::windows::fs::OpenOptionsExt; + // A reparse point swapped in after the check is opened as itself, not followed. + const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; + std::fs::OpenOptions::new().read(true).custom_flags(FILE_FLAG_OPEN_REPARSE_POINT).open(path)? + }; + #[cfg(not(windows))] + let mut file = std::fs::File::open(path)?; + let opened = file.metadata()?; + #[cfg(windows)] + if is_link_like(&opened) { + return Err(refuse()); + } + if !opened.file_type().is_file() { + return Err(refuse()); + } + // The name was checked, then opened: make sure what was opened is what was checked. + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if opened.dev() != before.dev() || opened.ino() != before.ino() { + return Err(refuse()); + } + } + let mut bytes = Vec::new(); + file.read_to_end(&mut bytes)?; + Ok(bytes) +} + /// Remove a document's recovery entry (it was saved or closed). In a folder that is not this /// run's own, only an entry this run wrote or recovered is removed. pub fn discard(dir: &Path, uid: u64) { @@ -761,9 +804,9 @@ pub fn list(dir: &Path) -> Vec<(u64, Value)> { } let Some(uid) = p.file_stem().and_then(std::ffi::OsStr::to_str).and_then(|s| s.parse::().ok()) else { continue }; // Metadata is a file on disk: anything but an object (corrupt, hand-edited) counts as none. - let meta = std::fs::read_to_string(p.with_extension("json")) + let meta = read_entry_file(&p.with_extension("json")) .ok() - .and_then(|t| serde_json::from_str::(&t).ok()) + .and_then(|t| serde_json::from_slice::(&t).ok()) .filter(Value::is_object) .unwrap_or(json!({})); out.push((uid, meta)); @@ -810,7 +853,7 @@ fn open_with_publisher(s: &mut Session, dir: &Path, mut publish: impl FnMut(&Pat #[cfg(not(target_arch = "wasm32"))] validate_recovery_dir(dir)?; let (doc, _) = files(dir, uid); - let Ok(bytes) = std::fs::read(&doc) else { continue }; + let Ok(bytes) = read_entry_file(&doc) else { continue }; let mut d = match crate::cmd::from_bytes(&bytes) { Ok(d) => d, Err(_) => continue, diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index 395e8385b..c23a2c831 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -183,6 +183,37 @@ fn symlink_recovery_directory_is_rejected() { assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink()); } +/// A link planted among a checked folder's entries doesn't get its target read: not as metadata +/// (listed as is) and not as a document (recovered). +#[cfg(unix)] +#[test] +fn linked_recovery_entries_are_not_read() { + use std::os::unix::fs::symlink; + + let root = tempfile::tempdir().unwrap(); + let (dir, elsewhere) = (root.path().join("recovery"), root.path().join("elsewhere")); + std::fs::create_dir(&dir).unwrap(); + std::fs::create_dir(&elsewhere).unwrap(); + // A real document whose metadata is a link to a private file. + assert_eq!(save(&unsaved("real"), &dir).unwrap(), 1); + let uid = list(&dir)[0].0; + std::fs::write(elsewhere.join("secret.json"), br#"{"path": "/home/someone/secret.designcraft"}"#).unwrap(); + std::fs::remove_file(dir.join(format!("{uid}.json"))).unwrap(); + symlink(elsewhere.join("secret.json"), dir.join(format!("{uid}.json"))).unwrap(); + // A document entry that is a link to a document elsewhere. + assert_eq!(save(&unsaved("elsewhere"), &elsewhere).unwrap(), 1); + let linked = list(&elsewhere)[0].0; + symlink(elsewhere.join(format!("{linked}.designcraft")), dir.join("9000000.designcraft")).unwrap(); + + let entries = list(&dir); + assert_eq!(entries.iter().map(|e| e.0).collect::>(), [uid, 9_000_000]); + assert_eq!(entries[0].1, json!({}), "the linked metadata counts as none"); + let mut s = Session::new(); + assert_eq!(open(&mut s, &dir).unwrap().len(), 1); + assert_eq!(texts(&s), ["real"]); + assert!(std::fs::symlink_metadata(dir.join("9000000.designcraft")).unwrap().file_type().is_symlink(), "left as it was"); +} + #[test] fn a_run_has_a_locked_folder_of_its_own() { let root = tempfile::tempdir().unwrap(); From 8d59590449f5a26d3b734ad651449fb9c664ec49 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 16:19:20 -0500 Subject: [PATCH 0905/1349] Package: copy each font as it was loaded, check read roots, number duplicate names in one pass (#2208) * fix(engine): package fonts from their loaded bytes under the read roots * address review: a font's own file is neither overwritten nor packaged when it changed since loading * Apply review fixes - crates/engine/src/cmd/package.rs * address review: compare packaged font file in fixed-size chunks --------- Co-authored-by: aiongg <67543387+aiongg@users.noreply.github.com> --- crates/engine/src/cmd/package.rs | 79 ++++++++++++++++++++------ crates/engine/src/cmd/package/tests.rs | 61 +++++++++++++++++++- 2 files changed, 120 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd/package.rs b/crates/engine/src/cmd/package.rs index 8d706a2b3..870ae2194 100644 --- a/crates/engine/src/cmd/package.rs +++ b/crates/engine/src/cmd/package.rs @@ -1,11 +1,10 @@ //! File › Package and Links › Copy Links To: gather a document with the files it uses. +use std::collections::HashMap; use std::fs::Metadata; use std::path::{Path, PathBuf}; use std::sync::Arc; -#[cfg(not(target_arch = "wasm32"))] -use std::fs::File; #[cfg(not(target_arch = "wasm32"))] use std::io::Write; @@ -172,23 +171,31 @@ impl OutputRoot { } } - fn copy(&self, from: &Path, to: &Path) -> Result<()> { + /// Write `bytes`, the contents of the file `from` as they were loaded, to `to` with the + /// permissions of `from`. The file isn't opened again: what is at its path now may be + /// something else (a link put there since), and the package must hold what the document used. + fn copy(&self, from: &Path, bytes: &[u8], to: &Path) -> Result<()> { if self.validate_file_entry(to)? && std::fs::canonicalize(to).is_ok_and(|target| std::fs::canonicalize(from).is_ok_and(|source| source == target)) { - return Ok(()); + // The destination is the font's own file: nothing to write while it still holds what + // was loaded. Overwriting it with the loaded bytes would undo a change made since, and + // leaving it would package that change instead of the font the document used. + if same_contents(to, bytes) { + return Ok(()); + } + return Err(path_error(to, "the font file changed on disk after it was loaded, and this is that file; package to another folder")); } #[cfg(target_arch = "wasm32")] { - let _ = from; + let _ = bytes; return Err(EngineError::Other("package files are unavailable on the web".into())); } #[cfg(not(target_arch = "wasm32"))] { - let mut source = File::open(from).map_err(|e| path_error(from, e))?; - let permissions = Some(source.metadata().map_err(|e| path_error(from, e))?.permissions()); + let permissions = Some(std::fs::metadata(from).map_err(|e| path_error(from, e))?.permissions()); let mut target = self.temporary_file(to, permissions)?; - std::io::copy(&mut source, &mut target).map_err(|e| path_error(to, e))?; + target.write_all(bytes).map_err(|e| path_error(to, e))?; self.validate_file_entry(to)?; target.persist(to).map_err(|e| path_error(to, e.error))?; Ok(()) @@ -196,6 +203,26 @@ impl OutputRoot { } } +/// Whether the file at `path` holds exactly `bytes` (read only as far as they go). +fn same_contents(path: &Path, bytes: &[u8]) -> bool { + use std::io::Read; + let Ok(mut file) = std::fs::File::open(path) else { return false }; + if file.metadata().map_or(true, |m| m.len() != bytes.len() as u64) { + return false; + } + // Fixed-size chunks: no second font-sized buffer. + let mut chunk = [0u8; 64 * 1024]; + for expected in bytes.chunks(chunk.len()) { + let got = &mut chunk[..expected.len()]; + if file.read_exact(got).is_err() || got != expected { + return false; + } + } + // A file that grew since the length check is not the same. + let mut extra = [0u8; 1]; + matches!(file.read(&mut extra), Ok(0)) +} + pub fn specs() -> Vec { vec![ cmd!( @@ -263,25 +290,34 @@ fn package_output_path(dir: &Path, title: &str, extension: &str) -> Result) -> String { +fn link_name(name: &str, id: AssetId, taken: &mut Taken) -> String { let fallback = format!("asset-{}", id.0); unique_name(safe_component(name, &fallback), taken) } +/// The names given out so far, and the next number to try for each base name (so a thousand +/// `logo.png` don't try `logo 2.png` a thousand times each). +#[derive(Default)] +struct Taken { + names: Vec, + next: HashMap, +} + /// `base`, or `base` numbered ("logo 2.png"), unique under portable Unicode normalization and /// case-insensitive comparison. -fn unique_name(base: String, taken: &mut Vec) -> String { +fn unique_name(base: String, taken: &mut Taken) -> String { let (stem, ext) = match base.rsplit_once('.') { Some((s, e)) => (s.to_string(), format!(".{e}")), None => (base.clone(), String::new()), }; - let mut n = base; - let mut k = 2; - while taken.iter().any(|t| portable_names_equal(t, &n)) { + let mut n = base.clone(); + let mut k = taken.next.get(&base).copied().unwrap_or(2); + while taken.names.iter().any(|t| portable_names_equal(t, &n)) { n = format!("{stem} {k}{ext}"); k += 1; } - taken.push(n.clone()); + taken.next.insert(base, k); + taken.names.push(n.clone()); n } @@ -292,7 +328,7 @@ fn unique_name(base: String, taken: &mut Vec) -> String { fn write_links(d: &Document, root: &OutputRoot, dir: &Path, only: Option<&[AssetId]>, relative_to: Option<&str>) -> Result<(Document, Vec)> { root.validate_directory(dir)?; let mut out = d.clone(); - let mut taken = Vec::new(); + let mut taken = Taken::default(); let mut written = Vec::new(); // Only files something places; the saved document leaves the others out. let ids = d.used_assets(); @@ -327,7 +363,7 @@ fn write_links(d: &Document, root: &OutputRoot, dir: &Path, only: Option<&[Asset /// Copy the font file of `face` into `dir` (created when first needed) unless its licence /// restricts it or it is already there (`copied`: the source files copied) → what the package /// report adds after the font's name (nothing when copied). -fn copy_font(root: &OutputRoot, face: &FontFace, dir: &Path, copied: &mut Vec, taken: &mut Vec, files: &mut Vec) -> String { +fn copy_font(root: &OutputRoot, face: &FontFace, dir: &Path, copied: &mut Vec, taken: &mut Taken, files: &mut Vec) -> String { let from = match &face.source { FontSource::Bundled => return " — included with DesignCraft".into(), FontSource::Memory => return " — not copied: no font file".into(), @@ -339,9 +375,16 @@ fn copy_font(root: &OutputRoot, face: &FontFace, dir: &Path, copied: &mut Vec { copied.push(from.clone()); files.push(to); @@ -420,7 +463,7 @@ fn package(s: &mut Session, p: &Value) -> Result { // The font files, and what the report says about each font. let db = designcraft_fonts::FontDb::global().scoped(d.font_scope); let fonts_dir = root.child(designcraft_fonts::DOCUMENT_FONTS_FOLDER)?; - let (mut copied, mut taken) = (Vec::new(), Vec::new()); + let (mut copied, mut taken) = (Vec::new(), Taken::default()); let (mut font_lines, mut named) = (Vec::new(), Vec::new()); for f in fonts.as_array().into_iter().flatten() { let (family, style) = (f["family"].as_str().unwrap_or(""), f["style"].as_str().unwrap_or("")); diff --git a/crates/engine/src/cmd/package/tests.rs b/crates/engine/src/cmd/package/tests.rs index 1848d5b5d..be0d297cb 100644 --- a/crates/engine/src/cmd/package/tests.rs +++ b/crates/engine/src/cmd/package/tests.rs @@ -450,6 +450,56 @@ fn package_copies_the_fallback_fonts_that_draw_text() { let _ = std::fs::remove_dir_all(&dir); } +/// The package holds the font as the document loaded it: a link put at its path since (to a +/// private file, say) isn't followed, and its permissions are the file's. +#[cfg(unix)] +#[test] +fn packaged_fonts_are_the_loaded_bytes_not_what_is_at_the_path_now() { + use designcraft_fonts::DOCUMENT_FONTS_FOLDER; + use designcraft_fonts::testing::{font_with, installed_face}; + let dir = std::env::temp_dir().join(format!("dc-package-font-swapped-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let from = dir.join("loaded.ttf"); + let bytes = font_with("DocFont Package Swapped", &['S']).unwrap(); + std::fs::write(&from, &bytes).unwrap(); + let face = installed_face(bytes.clone(), from.clone()).unwrap(); + std::fs::remove_file(&from).unwrap(); + std::fs::write(dir.join("secret"), b"private").unwrap(); + std::os::unix::fs::symlink(dir.join("secret"), &from).unwrap(); + let root = OutputRoot::new(dir.clone()).unwrap(); + let fonts = dir.join("Pkg").join(DOCUMENT_FONTS_FOLDER); + std::fs::create_dir_all(&fonts).unwrap(); + let (mut copied, mut taken, mut files) = (Vec::new(), Taken::default(), Vec::new()); + assert_eq!(copy_font(&root, &face, &fonts, &mut copied, &mut taken, &mut files), ""); + assert_eq!(std::fs::read(fonts.join("loaded.ttf")).unwrap(), bytes); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn packaging_into_a_fonts_own_folder_neither_overwrites_nor_packages_a_changed_font() { + use designcraft_fonts::testing::{font_with, installed_face}; + let dir = std::env::temp_dir().join(format!("dc-package-font-same-file-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let from = dir.join("loaded.ttf"); + let bytes = font_with("DocFont Package Same File", &['S']).unwrap(); + std::fs::write(&from, &bytes).unwrap(); + let face = installed_face(bytes.clone(), from.clone()).unwrap(); + let root = OutputRoot::new(dir.clone()).unwrap(); + let copy = |taken: &mut Taken| copy_font(&root, &face, &dir, &mut Vec::new(), taken, &mut Vec::new()); + // Unchanged since it loaded: already where it is wanted. + assert_eq!(copy(&mut Taken::default()), ""); + assert_eq!(std::fs::read(&from).unwrap(), bytes); + // Changed on disk since: the package can't hold the loaded font there, and the new file is kept. + let newer = font_with("DocFont Package Same File", &['S', 'T']).unwrap(); + std::fs::write(&from, &newer).unwrap(); + let note = copy(&mut Taken::default()); + assert!(note.contains("not copied") && note.contains("changed on disk"), "{note}"); + assert_eq!(std::fs::read(&from).unwrap(), newer); + let _ = std::fs::remove_dir_all(&dir); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn packaged_fonts_keep_a_font_extension() { @@ -467,7 +517,7 @@ fn packaged_fonts_keep_a_font_extension() { let root = OutputRoot::new(dir.clone()).unwrap(); let fonts = dir.join("Pkg").join(DOCUMENT_FONTS_FOLDER); std::fs::create_dir_all(&fonts).unwrap(); - let (mut copied, mut taken, mut files) = (Vec::new(), Vec::new(), Vec::new()); + let (mut copied, mut taken, mut files) = (Vec::new(), Taken::default(), Vec::new()); assert_eq!(copy_font(&root, &face, &fonts, &mut copied, &mut taken, &mut files), ""); assert_eq!(files, [fonts.join("12345.ttf")]); let db = designcraft_fonts::FontDb::global(); @@ -495,13 +545,20 @@ fn package_uses_portable_names_inside_the_selected_directory() { for name in ["COM¹", "COM²", "COM³", "LPT¹", "LPT²", "LPT³"] { assert!(is_reserved_windows_name(name), "{name}"); } - let mut taken = Vec::new(); + let mut taken = Taken::default(); assert_eq!(unique_name("Logo.svg".into(), &mut taken), "Logo.svg"); assert_eq!(unique_name("logo.svg".into(), &mut taken), "logo 2.svg"); assert_eq!(unique_name("Résumé.pdf".into(), &mut taken), "Résumé.pdf"); assert_eq!(unique_name("Re\u{301}sume\u{301}.pdf".into(), &mut taken), "Re\u{301}sume\u{301} 2.pdf"); assert_eq!(unique_name("ΟΣ.txt".into(), &mut taken), "ΟΣ.txt"); assert_eq!(unique_name("ος.txt".into(), &mut taken), "ος 2.txt"); + // Many files of one name are numbered in order, each without trying every earlier number. + let mut taken = Taken::default(); + for k in 1..=2000 { + let expected = if k == 1 { "logo.png".to_string() } else { format!("logo {k}.png") }; + assert_eq!(unique_name("logo.png".into(), &mut taken), expected); + } + assert_eq!(unique_name("logo 7.png".into(), &mut taken), "logo 7 2.png", "a name already given out is still numbered"); let dir = std::env::temp_dir().join(format!("dc-package-safe-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); From 5a3507510edf0703a3ebb5499a08b1b1ffbb8584 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 16:19:45 -0500 Subject: [PATCH 0906/1349] File reads: refuse devices and pipes, cap whole-file reads (#2227) * fix(engine): whole-file reads take regular files only, up to the format limit * Apply review fixes - crates/engine/src/io.rs * Apply review fixes - crates/engine/src/io.rs * Fix failing CI check - crates/engine/src/io.rs * address review: refuse to save an encoded document longer than the open limit * address review: open files for reading without blocking (FIFOs, stream-backed pseudo-files) --------- Co-authored-by: aiongg <67543387+aiongg@users.noreply.github.com> --- crates/engine/src/cmd/file/bytes.rs | 7 +- crates/engine/src/io.rs | 123 ++++++++++++++++++++++++++-- 2 files changed, 120 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/file/bytes.rs b/crates/engine/src/cmd/file/bytes.rs index f42925034..5fd6d4e0b 100644 --- a/crates/engine/src/cmd/file/bytes.rs +++ b/crates/engine/src/cmd/file/bytes.rs @@ -60,7 +60,12 @@ pub(super) fn to_bytes_with_preview(d: &Document, cache: &crate::Cache) -> Resul }); let png = preview.and_then(|scale| designcraft_render::Renderer::new().render_page(d, cache, 0, scale, false, &Default::default())).map(|r| r.to_png()); - save_bytes(d, png.as_deref()) + let bytes = save_bytes(d, png.as_deref())?; + // `file.open` and `file.revert` refuse a longer file, so don't write one the app can't read back. + if bytes.len() as u64 > crate::io::MAX_FILE_BYTES { + return Err(EngineError::Other(format!("could not write the document: encoded file is longer than {} bytes", crate::io::MAX_FILE_BYTES))); + } + Ok(bytes) } pub fn from_bytes(b: &[u8]) -> Result { diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index a05b067b1..15e76a99e 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -55,12 +55,64 @@ fn touch(path: &Path) { let _ = path; } +/// The most a whole file read in one piece ([`read_file`], [`read`], [`read_to_string`]) may +/// hold: the format's own limit on what a document unpacks to. What is opened must be a regular +/// file: a device or a pipe (`/dev/zero`, a FIFO) has no end, and reading it to the end would +/// take all the memory there is. +pub const MAX_FILE_BYTES: u64 = 4 << 30; + +/// `File::open` for reading that never blocks in the open or the reads: a FIFO with no writer would +/// otherwise hang the open, and a stream-backed pseudo-file that reports as regular (a tracefs +/// `trace_pipe`) would hang the read. A read that would block is a `WouldBlock` error. Regular +/// files are unaffected by the flag. Elsewhere (Windows, wasm) it is a plain open. +fn open_read(path: &Path) -> std::io::Result { + let mut options = std::fs::OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + // `O_NONBLOCK` differs by OS and architecture; std exposes no constant for it. + #[cfg(any(target_os = "linux", target_os = "android"))] + const O_NONBLOCK: i32 = if cfg!(any(target_arch = "mips", target_arch = "mips64")) { + 0x80 + } else if cfg!(any(target_arch = "sparc", target_arch = "sparc64")) { + 0x4000 + } else { + 0o4000 + }; + #[cfg(not(any(target_os = "linux", target_os = "android")))] + const O_NONBLOCK: i32 = 0x4; // macOS, iOS and the BSDs + options.custom_flags(O_NONBLOCK); + } + options.open(path) +} + +/// The whole of the regular file at `path`, at most [`MAX_FILE_BYTES`] (the path checked already). +fn read_whole(path: &Path) -> std::io::Result> { + use std::io::Read; + if !std::fs::metadata(path)?.is_file() { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "not a regular file")); + } + let file = open_read(path)?; + let meta = file.metadata()?; + if !meta.is_file() { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "not a regular file")); + } + if meta.len() > MAX_FILE_BYTES { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, format!("longer than {MAX_FILE_BYTES} bytes"))); + } + let mut bytes = Vec::new(); + file.take(MAX_FILE_BYTES + 1).read_to_end(&mut bytes)?; + if bytes.len() as u64 > MAX_FILE_BYTES { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, format!("longer than {MAX_FILE_BYTES} bytes"))); + } + Ok(bytes) +} + /// The bytes of the file at `path`, inside the automation read root when there is one. pub fn read_file(path: impl AsRef) -> Result, String> { let path = path.as_ref(); - touch(path); - crate::file_access::check_read(path)?; - std::fs::read(path).map_err(|e| format!("{}: {e}", path.display())) + read(path).map_err(|e| format!("{}: {e}", path.display())) } /// [`read_file`] with the file system's own error, for callers that tell "missing" from other @@ -69,7 +121,7 @@ pub fn read(path: impl AsRef) -> std::io::Result> { let path = path.as_ref(); touch(path); crate::file_access::check_read(path).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?; - std::fs::read(path) + read_whole(path) } /// [`read`] that stops past `cap` bytes: at most `cap + 1` bytes are read, so a device or a file @@ -80,7 +132,7 @@ pub fn read_capped(path: impl AsRef, cap: u64) -> std::io::Result> touch(path); crate::file_access::check_read(path).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?; let mut b = Vec::new(); - std::fs::File::open(path)?.take(cap.saturating_add(1)).read_to_end(&mut b)?; + open_read(path)?.take(cap.saturating_add(1)).read_to_end(&mut b)?; Ok(b) } @@ -91,15 +143,14 @@ pub fn open(path: impl AsRef) -> std::io::Result { let path = path.as_ref(); touch(path); crate::file_access::check_read(path).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?; - std::fs::File::open(path) + open_read(path) } /// The text of the file at `path`, inside the automation read root when there is one. pub fn read_to_string(path: impl AsRef) -> Result { let path = path.as_ref(); - touch(path); - crate::file_access::check_read(path)?; - std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display())) + let bytes = read_file(path)?; + String::from_utf8(bytes).map_err(|_| format!("{}: stream did not contain valid UTF-8", path.display())) } /// Make the folder at `path` and the folders above it, inside the automation write root when @@ -185,3 +236,57 @@ pub fn read_dir(path: impl AsRef) -> std::io::Result { crate::file_access::check_read(path).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?; std::fs::read_dir(path) } + +#[cfg(test)] +mod read_tests { + use super::*; + + /// A device has no end: a whole-file read refuses it instead of reading until memory runs out. + #[cfg(unix)] + #[test] + fn whole_file_reads_refuse_devices() { + let e = read_file("/dev/zero").unwrap_err(); + assert!(e.contains("not a regular file"), "{e}"); + assert!(read("/dev/zero").is_err()); + assert!(read_to_string("/dev/zero").is_err()); + assert!(read_capped("/dev/zero", 16).is_ok_and(|b| b.len() == 17), "a capped read stops by itself"); + assert!(read_file("/dev/null/missing").is_err()); + } + + #[test] + fn whole_file_reads_read_whole_files() { + let dir = std::env::temp_dir().join(format!("dc-io-read-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("a.txt"); + std::fs::write(&path, "héllo").unwrap(); + assert_eq!(read_file(&path).unwrap(), "héllo".as_bytes()); + assert_eq!(read_to_string(&path).unwrap(), "héllo"); + std::fs::write(&path, [0xff, 0xfe]).unwrap(); + assert!(read_to_string(&path).unwrap_err().contains("UTF-8")); + let _ = std::fs::remove_dir_all(&dir); + } +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + + /// A FIFO nobody writes to must not hang a read (the open used to block forever). + #[test] + fn fifo_without_a_writer_does_not_block() { + let dir = std::env::temp_dir().join(format!("dc-fifo-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let fifo = dir.join("f"); + if !std::process::Command::new("mkfifo").arg(&fifo).status().is_ok_and(|s| s.success()) { + return; // no mkfifo on this host + } + let (tx, rx) = std::sync::mpsc::channel(); + let p = fifo.clone(); + std::thread::spawn(move || { + let _ = tx.send((read_whole(&p).is_err(), read_capped(&p, 9).is_ok())); + }); + let got = rx.recv_timeout(std::time::Duration::from_secs(10)); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(got, Ok((true, true)), "reads of a FIFO must return"); + } +} From 15bea9fa7afd5b64db4bcb22db3d15b36372d0d8 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 16:20:09 -0500 Subject: [PATCH 0907/1349] Tagged Text, RTF, EPUB classes and PDF layers: lookups by set or map instead of list searches (#2212) * fix: index style, font, class and layer name lookups in exporters and importers * Apply review fixes - crates/epub/src/css.rs --------- Co-authored-by: aiongg <67543387+aiongg@users.noreply.github.com> --- crates/epub/src/css.rs | 28 +++++++++++++++++++++++++++- crates/render/src/pdf_layers.rs | 3 ++- crates/textimport/src/export.rs | 26 ++++++++++++++++++-------- crates/textimport/src/tagged.rs | 11 +++++++---- 4 files changed, 54 insertions(+), 14 deletions(-) diff --git a/crates/epub/src/css.rs b/crates/epub/src/css.rs index f066d6b3d..1af0be208 100644 --- a/crates/epub/src/css.rs +++ b/crates/epub/src/css.rs @@ -7,14 +7,18 @@ use super::*; fn class_names<'a>(names: impl Iterator) -> BTreeMap<&'a str, String> { let mut out = BTreeMap::new(); let mut used = std::collections::BTreeSet::new(); + // The last suffix given for each slug: the next name that slugs alike carries on from it + // (still checked against every class, since a name can itself end in `-2`). + let mut last: std::collections::HashMap = std::collections::HashMap::new(); for name in names { let base = slug(name); let mut class = base.clone(); - let mut n = 1; + let mut n = last.get(&base).copied().unwrap_or(1); while !used.insert(class.clone()) { n += 1; class = format!("{base}-{n}"); } + last.insert(base, n); out.insert(name, class); } out @@ -251,3 +255,25 @@ fn class_selector(tag: &str, class: &str) -> Option { } Some(selector) } + +#[cfg(test)] +mod class_name_tests { + use super::class_names; + + /// Names that slug alike are numbered in order, each carrying on from the last number given, + /// and a name that already ends in a number never takes another's class. + #[test] + fn colliding_names_get_unique_classes_in_one_pass() { + // 20,000 distinct names that all slug to `body-text` (any non-ASCII letter is a `-`). + let names: Vec = (0..20_000u32).filter_map(|i| char::from_u32(0x4E00 + i)).map(|c| format!("Body{c}Text")).collect(); + let mut all: Vec<&str> = vec!["Body Text", "body-text-3"]; + all.extend(names.iter().map(String::as_str)); + let classes = class_names(all.iter().copied()); + assert_eq!(classes["Body Text"], "body-text"); + assert_eq!(classes["body-text-3"], "body-text-3"); + assert_eq!(classes[names[0].as_str()], "body-text-2"); + assert_eq!(classes[names[1].as_str()], "body-text-4", "-3 is the class of the name that is it"); + let distinct: std::collections::HashSet<&String> = classes.values().collect(); + assert_eq!(distinct.len(), classes.len()); + } +} diff --git a/crates/render/src/pdf_layers.rs b/crates/render/src/pdf_layers.rs index bf3a7509d..f428b522e 100644 --- a/crates/render/src/pdf_layers.rs +++ b/crates/render/src/pdf_layers.rs @@ -19,7 +19,8 @@ fn ocgs(pdf: &Pdf) -> Vec<(ObjRef, String, bool)> { cfg.as_ref().and_then(|c| c.get::>(key)).map(|a| a.raw_iter().filter_map(|o| o.as_obj_ref()).collect()).unwrap_or_default() }; let base_off = cfg.as_ref().and_then(|c| c.get::>(b"BaseState")).is_some_and(|n| n.as_ref() == b"OFF"); - let (on, off) = (ids_in(b"ON"), ids_in(b"OFF")); + let (on, off): (std::collections::HashSet, std::collections::HashSet) = + (ids_in(b"ON").into_iter().collect(), ids_in(b"OFF").into_iter().collect()); list.raw_iter() .filter_map(|o| o.as_obj_ref()) // A layer listed again is one layer: it gets one name, not one per entry. diff --git a/crates/textimport/src/export.rs b/crates/textimport/src/export.rs index 7d614f640..2493f7f98 100644 --- a/crates/textimport/src/export.rs +++ b/crates/textimport/src/export.rs @@ -87,13 +87,24 @@ pub fn rtf(doc: &Document, story: &Story) -> String { let styles = &doc.styles; // Resolve every run first so the font table can be written up front. let ranges = story.para_ranges(); + // The story's runs once; each paragraph takes those reaching it by binary search. + let all_runs: Vec<_> = story.runs().collect(); let mut paras = Vec::with_capacity(ranges.len()); let mut fonts: Vec = Vec::new(); + // Each font's number in the table (`fonts` keeps the table's order). + let mut font_index: std::collections::HashMap = std::collections::HashMap::new(); + let mut add_font = |fonts: &mut Vec, name: &str| { + if !font_index.contains_key(name) { + font_index.insert(name.to_string(), fonts.len()); + fonts.push(name.to_string()); + } + }; for (i, r) in ranges.iter().enumerate() { let pf = story.paras.get(i).cloned().unwrap_or_default(); let (pp, base) = styles.resolve_para(&pf); let mut runs = Vec::new(); - for (rr, f) in story.runs() { + let first = all_runs.partition_point(|(rr, _)| rr.end <= r.start); + for (rr, f) in all_runs.iter().skip(first).take_while(|(rr, _)| rr.start < r.end) { let (a, b) = (rr.start.max(r.start), rr.end.min(r.end)); if a >= b { continue; @@ -103,13 +114,11 @@ pub fn rtf(doc: &Document, story: &Story) -> String { if doc.conditions_hide(&cp.conditions) || cp.change == designcraft_doc::ChangeMark::Deleted { continue; } - if !fonts.contains(&cp.font_family) { - fonts.push(cp.font_family.clone()); - } + add_font(&mut fonts, &cp.font_family); runs.push((a..b, cp)); } - if runs.is_empty() && !fonts.contains(&base.font_family) { - fonts.push(base.font_family.clone()); + if runs.is_empty() { + add_font(&mut fonts, &base.font_family); } paras.push((pp, base, pf.table, runs)); } @@ -122,6 +131,7 @@ pub fn rtf(doc: &Document, story: &Story) -> String { out.push_str(";}"); } out.push_str("}\n"); + let font_index: std::collections::HashMap<&str, usize> = fonts.iter().enumerate().map(|(i, f)| (f.as_str(), i)).collect(); for (pp, base, table, runs) in ¶s { let q = match pp.align { Align::Center => "\\qc", @@ -139,11 +149,11 @@ pub fn rtf(doc: &Document, story: &Story) -> String { twips(pp.space_after) ); if runs.is_empty() { - let f = fonts.iter().position(|x| *x == base.font_family).unwrap_or(0); + let f = font_index.get(base.font_family.as_str()).copied().unwrap_or(0); let _ = write!(out, "\\plain\\f{f}\\fs{} ", (base.size * 2.0).round() as i64); } for (r, cp) in runs { - let f = fonts.iter().position(|x| *x == cp.font_family).unwrap_or(0); + let f = font_index.get(cp.font_family.as_str()).copied().unwrap_or(0); let st = cp.font_style.to_ascii_lowercase(); let _ = write!(out, "{{\\plain\\f{f}\\fs{}", (cp.size * 2.0).round() as i64); if st.contains("bold") || st.contains("black") || st.contains("heavy") || st.contains("semibold") { diff --git a/crates/textimport/src/tagged.rs b/crates/textimport/src/tagged.rs index 3fa209126..c3668614d 100644 --- a/crates/textimport/src/tagged.rs +++ b/crates/textimport/src/tagged.rs @@ -143,6 +143,8 @@ pub fn import(bytes: &[u8]) -> Result { let mut fmt = CharFormat::default(); let mut para_styles: Vec = Vec::new(); let mut char_styles: Vec = Vec::new(); + // The names in each list, for membership (the lists keep the order the file names them). + let (mut para_seen, mut char_seen) = (std::collections::HashSet::new(), std::collections::HashSet::new()); let mut warnings = Vec::new(); let push = |paras: &mut Vec<(String, Vec<(String, CharFormat)>)>, c: char, fmt: &CharFormat| { let Some((_, runs)) = paras.last_mut() else { return }; @@ -198,7 +200,7 @@ pub fn import(bytes: &[u8]) -> Result { "ParaStyle" => { started = true; let v = unescape_value(value); - if !v.is_empty() && !para_styles.contains(&v) { + if !v.is_empty() && para_seen.insert(v.clone()) { para_styles.push(v.clone()); } if let Some(p) = paras.last_mut() { @@ -208,7 +210,7 @@ pub fn import(bytes: &[u8]) -> Result { "CharStyle" => { let v = unescape_value(value); fmt.style = if v.is_empty() { NO_CHAR_STYLE.into() } else { v.clone() }; - if !v.is_empty() && !char_styles.contains(&v) { + if !v.is_empty() && char_seen.insert(v.clone()) { char_styles.push(v); } } @@ -219,8 +221,9 @@ pub fn import(bytes: &[u8]) -> Result { "cSize" => fmt.over.size = value.trim().parse().ok().and_then(designcraft_doc::attrs::imported_type_size), "DefineParaStyle" | "DefineCharStyle" => { let nm = crate::capped_name(value.split('=').next().unwrap_or("").to_string()); - let list = if name == "DefineParaStyle" { &mut para_styles } else { &mut char_styles }; - if !nm.is_empty() && !list.contains(&nm) { + let (list, seen) = + if name == "DefineParaStyle" { (&mut para_styles, &mut para_seen) } else { (&mut char_styles, &mut char_seen) }; + if !nm.is_empty() && seen.insert(nm.clone()) { list.push(nm); } } From eba00a0deca4f7bba04ec656efe79b4e63aeaec6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 16:20:34 -0500 Subject: [PATCH 0908/1349] Opening documents: index lookups in Document::check and the format-1 style upgrade (#2218) * fix(doc): index items, threads and styles when opening a document * Apply review fixes - crates/doc/src/tests.rs * address review: borrow style names in pin_para_default --------- Co-authored-by: aiongg <67543387+aiongg@users.noreply.github.com> Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com> --- crates/doc/src/lib.rs | 24 +++++++++++++++++++----- crates/doc/src/styles.rs | 19 +++++++++++++++++-- crates/doc/src/tests.rs | 19 +++++++++++++++++++ crates/format/src/lib.rs | 9 ++++++--- crates/format/src/tests.rs | 17 +++++++++++++++++ 5 files changed, 78 insertions(+), 10 deletions(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 8d1f99456..2be595e3d 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -1136,6 +1136,11 @@ impl Document { } } let mut ids = std::collections::HashSet::new(); + // Every item's story (text frames), by id, and every (story, frame) of the threads: built + // once, so checking each reference both ways is a lookup, not a search of the document. + let mut frame_story: std::collections::HashMap> = std::collections::HashMap::new(); + let threads: std::collections::HashSet<(StoryId, ItemId)> = + self.stories.iter().flat_map(|(sid, st)| st.frames.iter().map(move |f| (*sid, *f))).collect(); for sp in self.spreads.iter().chain(self.parents.iter()) { for it in &sp.items { let mut dup = None; @@ -1143,20 +1148,30 @@ impl Document { if !ids.insert(i.id.0) { dup = Some(i.id); } + frame_story.insert(i.id, i.text_frame().map(|t| t.story)); }); if let Some(d) = dup { return Err(DocError::Invalid(format!("duplicate item id {d}"))); } } } + let embedded = self.anchored_items(); + // An anchored item's story, by id (the first of an id, as a search would find it). + let mut anchored: std::collections::HashMap> = std::collections::HashMap::new(); + for (_, item) in &embedded { + anchored.entry(item.id).or_insert_with(|| item.text_frame().map(|t| t.story)); + } for (sid, st) in &self.stories { st.check().map_err(DocError::Invalid)?; if st.id != *sid { return Err(DocError::Invalid(format!("story key {sid} != id {}", st.id))); } for f in &st.frames { - let item = self.item(*f).or_else(|| self.anchored_item(*f)).ok_or(DocError::NoItem(*f))?; - match item.text_frame().map(|t| t.story) { + let story = match frame_story.get(f) { + Some(story) => *story, + None => anchored.get(f).copied().ok_or(DocError::NoItem(*f))?, + }; + match story { Some(s) if s == *sid => {} other => return Err(DocError::Invalid(format!("frame {f} in story {sid} points at {other:?}"))), } @@ -1168,7 +1183,7 @@ impl Document { let mut bad = None; it.walk(&mut |i| { if let Some(t) = i.text_frame() - && !self.stories.get(&t.story).is_some_and(|s| s.frames.contains(&i.id)) + && !threads.contains(&(t.story, i.id)) { bad = Some(i.id); } @@ -1178,14 +1193,13 @@ impl Document { } } } - let embedded = self.anchored_items(); let mut edges: std::collections::HashMap> = std::collections::HashMap::new(); for (owner, item) in embedded { if !ids.insert(item.id.0) { return Err(DocError::Invalid(format!("duplicate item id {}", item.id))); } if let Some(tf) = item.text_frame() { - if !self.stories.get(&tf.story).is_some_and(|s| s.frames.contains(&item.id)) { + if !threads.contains(&(tf.story, item.id)) { return Err(DocError::Invalid(format!("embedded text frame {} not in its story's thread", item.id))); } edges.entry(owner).or_default().push(tf.story); diff --git a/crates/doc/src/styles.rs b/crates/doc/src/styles.rs index 7605cc447..8aa5c8132 100644 --- a/crates/doc/src/styles.rs +++ b/crates/doc/src/styles.rs @@ -775,14 +775,29 @@ impl Styles { /// The paragraph style chain from root to `name` (cycle-safe): resolution starts at its first. pub fn para_chain(&self, name: &str) -> Vec<&ParagraphStyle> { + Self::para_chain_by(name, |n| self.para(n)) + } + + /// The paragraph styles by name, the first of each name (as [`Self::para`] finds it), for + /// callers that look up every style: one map instead of a search per style. + pub fn para_index(&self) -> std::collections::HashMap<&str, &ParagraphStyle> { + let mut index = std::collections::HashMap::new(); + for s in &self.paragraph { + index.entry(s.name.as_str()).or_insert(s); + } + index + } + + /// [`Self::para_chain`] with styles found through `find` (a [`Self::para_index`]). + pub fn para_chain_by<'a>(name: &str, find: impl Fn(&str) -> Option<&'a ParagraphStyle>) -> Vec<&'a ParagraphStyle> { let mut chain = Vec::new(); - let mut cur = self.para(name); + let mut cur = find(name); while let Some(s) = cur { if chain.len() >= MAX_DEPTH || chain.iter().any(|c: &&ParagraphStyle| c.name == s.name) { break; } chain.push(s); - cur = s.based_on.as_deref().and_then(|b| self.para(b)); + cur = s.based_on.as_deref().and_then(&find); } chain.reverse(); chain diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 08a525251..dd6805f41 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -370,6 +370,25 @@ fn placed_pdf_without_a_crop_choice_loads_with_the_crop_box() { assert_eq!(Asset { pdf_box: Some([0.5, 0.5, 0.5, 0.9]), ..back }.shown_box(), None); } +/// Checking a document looks each frame up once: 20,000 text frames check in well under a +/// second (each lookup searched every item before). +#[test] +fn check_is_linear_in_the_frames() { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + for i in 0..20_000 { + let y = f64::from(i % 100); + d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, y, 10.0, y + 1.0), lid, "x", ParaFormat::default()).unwrap(); + } + let t = std::time::Instant::now(); + d.check().unwrap(); + assert!(t.elapsed() < std::time::Duration::from_secs(10), "{:?}", t.elapsed()); + // A frame its story names but the document doesn't have is still refused. + let sid = *d.stories.keys().next().unwrap(); + Arc::make_mut(d.stories.get_mut(&sid).unwrap()).frames.push(ItemId(u64::MAX)); + assert!(matches!(d.check(), Err(DocError::NoItem(ItemId(u64::MAX))))); +} + #[test] fn adjust_text_ranges_tracks_and_prunes_hyperlinks_and_placeholders() { let mut d = doc(); diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 09bdfe334..8f9d8856e 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -312,12 +312,14 @@ fn upgrade(doc: &mut Document, from: u32) { /// is missing. fn pin_para_default(doc: &mut Document, field: fn(&mut ParaAttrs) -> &mut Option, old: T) { let unset = |a: &ParaAttrs| field(&mut a.clone()).is_none(); + // Every style is looked up by name: through one index, not a search of all styles each time. + let index = doc.styles.para_index(); let roots: std::collections::HashSet = doc .styles .paragraph .iter() .filter_map(|s| { - let chain = doc.styles.para_chain(&s.name); + let chain = designcraft_doc::Styles::para_chain_by(&s.name, |n| index.get(n).copied()); if chain.iter().all(|c| unset(&c.para)) { chain.first().map(|c| c.name.clone()) } else { None } }) .collect(); @@ -326,9 +328,10 @@ fn pin_para_default(doc: &mut Document, field: fn(&mut ParaAttrs) -> & *field(&mut s.para) = Some(old.clone()); } } - let styles = doc.styles.clone(); + // Borrowed names: one entry per style already in memory, so no copy and no extra bound needed. + let names: std::collections::HashSet<&str> = doc.styles.paragraph.iter().map(|s| s.name.as_str()).collect(); let mut pin = |st: &mut Story| { - for p in st.paras.iter_mut().filter(|p| styles.para(&p.style).is_none()) { + for p in st.paras.iter_mut().filter(|p| !names.contains(p.style.as_str())) { let v = field(&mut p.para); if v.is_none() { *v = Some(old.clone()); diff --git a/crates/format/src/tests.rs b/crates/format/src/tests.rs index a95bee160..ca57c7770 100644 --- a/crates/format/src/tests.rs +++ b/crates/format/src/tests.rs @@ -355,6 +355,23 @@ fn format_1_keep_lines_without_mode_stays_all_lines() { assert!(!designcraft_doc::ParaProps::default().keep_all_lines); } +/// A format-1 file with many styles upgrades in time linear in them (each style's chain was +/// found by searching every style, twice over). +#[test] +fn format_1_upgrade_of_many_styles_is_linear() { + let mut d = Document::new(&NewDocument::default()); + let st = d.styles_mut(); + for i in 0..20_000 { + st.paragraph.push(para_style(&format!("S{i}"), (i % 2 == 1).then(|| format!("S{}", i - 1)).as_deref(), None)); + } + let bytes = save_v1(&d); + let t = std::time::Instant::now(); + let back = load(&bytes).unwrap(); + assert!(t.elapsed() < std::time::Duration::from_secs(10), "{:?}", t.elapsed()); + assert_eq!(back.styles.para("S0").unwrap().para.keep_all_lines, Some(true)); + assert_eq!(back.styles.para("S1").unwrap().para.keep_all_lines, None, "based on S0, which is pinned"); +} + /// Format 1 wrote paragraph rules, text frame options and numbered lists in full, so their /// old defaults (black rules, auto-size from the top centre, lists continuing across stories) /// load as saved. New documents take InDesign's. From dc9eea2695be7d8200e06453e49cfd85c48a3e1d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 16:20:58 -0500 Subject: [PATCH 0909/1349] Small bounds: outline simplification, table row insertion, note ids, xtask stats (#2232) * fix: iterative outline simplification, bulk row insertion, linear note ids, no symlink walking in xtask stats * Apply review fixes - crates/doc/src/tests.rs - crates/geom/src/trace.rs * Apply review fixes - crates/geom/src/trace.rs * address review: cover a maximal note id in tests, format trace test --------- Co-authored-by: aiongg <67543387+aiongg@users.noreply.github.com> --- crates/doc/src/endnotes.rs | 6 ++- crates/doc/src/notes.rs | 6 ++- crates/doc/src/table.rs | 7 ++++ crates/doc/src/table/edit.rs | 12 +++--- crates/doc/src/tests.rs | 29 +++++++++++++++ crates/geom/src/trace.rs | 71 +++++++++++++++++++++++++++--------- xtask/src/stats.rs | 4 +- 7 files changed, 107 insertions(+), 28 deletions(-) diff --git a/crates/doc/src/endnotes.rs b/crates/doc/src/endnotes.rs index b15bb745c..4c7a60a39 100644 --- a/crates/doc/src/endnotes.rs +++ b/crates/doc/src/endnotes.rs @@ -103,8 +103,12 @@ impl Story { /// Insert empty endnotes for `n` new reference characters before which `k` references sit. pub(crate) fn endnotes_inserted(&mut self, k: usize, n: usize) { + // As for footnotes: the largest id kept as ids are given out, and the free-id search past + // the largest one (`+ 1` overflowed there). + let mut max = self.endnotes.iter().map(|x| x.id).max().unwrap_or(0); for i in 0..n { - let id = self.endnotes.iter().map(|x| x.id).max().unwrap_or(0) + 1; + let id = max.checked_add(1).unwrap_or_else(|| crate::ids::next_local_id(self.endnotes.iter().map(|x| x.id))); + max = max.max(id); let mut text = Story::new(StoryId(0)); text.chars[0].format = CharFormat::default(); self.endnotes.insert((k + i).min(self.endnotes.len()), Arc::new(Footnote { id, text })); diff --git a/crates/doc/src/notes.rs b/crates/doc/src/notes.rs index 0811c549c..0e6b0f03b 100644 --- a/crates/doc/src/notes.rs +++ b/crates/doc/src/notes.rs @@ -186,8 +186,12 @@ impl Story { /// Insert empty footnotes for `n` new reference characters before which `k` references sit. pub(crate) fn notes_inserted(&mut self, k: usize, n: usize) { + // The largest id so far, kept as ids are given out (finding it again for every new note + // was quadratic in a batch); past the largest id, the free-id search as before. + let mut max = self.notes.iter().map(|x| x.id).max().unwrap_or(0); for i in 0..n { - let id = self.next_note_id(); + let id = max.checked_add(1).unwrap_or_else(|| self.next_note_id()); + max = max.max(id); let mut text = Story::new(StoryId(0)); text.chars[0].format = CharFormat::default(); self.notes.insert((k + i).min(self.notes.len()), Arc::new(Footnote { id, text })); diff --git a/crates/doc/src/table.rs b/crates/doc/src/table.rs index 3782c0181..4c726b743 100644 --- a/crates/doc/src/table.rs +++ b/crates/doc/src/table.rs @@ -264,6 +264,13 @@ mod tests { t.check().unwrap(); assert_eq!(t.cell(1, 1).unwrap().row_span, 3); assert_eq!(t.nrows(), 5); + // Several rows at once go in together, in order, inside the merged region. + t.insert_rows(2, 3); + t.check().unwrap(); + assert_eq!(t.cell(1, 1).unwrap().row_span, 6); + assert_eq!(t.nrows(), 8); + t.delete_rows(2, 3); + t.check().unwrap(); // Header stays first. t.insert_rows(0, 1); t.check().unwrap(); diff --git a/crates/doc/src/table/edit.rs b/crates/doc/src/table/edit.rs index 8b140fde1..a4a1c876d 100644 --- a/crates/doc/src/table/edit.rs +++ b/crates/doc/src/table/edit.rs @@ -35,13 +35,11 @@ impl Table { } }) .collect(); - for k in 0..n { - self.rows.insert(at + k, row.clone()); - let i = (at + k) * nc; - for (c, cell) in template.iter().enumerate() { - self.cells.insert(i + c, cell.clone()); - } - } + // All the new rows and cells in one move each (one at a time moved every later cell + // again for each one). + self.rows.splice(at..at, std::iter::repeat_n(row, n)); + let i = at * nc; + self.cells.splice(i..i, (0..n).flat_map(|_| template.iter().cloned())); self.set_regions(®ions); } diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index dd6805f41..ac050a457 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -568,6 +568,35 @@ fn set_story_text_prunes_story_hyperlinks_and_placeholders() { assert_eq!(d.data_merge.placeholders[0].id, 20); } +/// Many note references put in at once each get a note with an id of its own, in one pass. +#[test] +fn many_note_references_get_their_notes_at_once() { + let n = 20_000; + let mut st = Story::new(StoryId(1)); + let refs = format!("{}{}", FOOTNOTE_REF.to_string().repeat(n), crate::ENDNOTE_REF.to_string().repeat(n)); + st.insert(0, &refs); + assert_eq!((st.notes.len(), st.endnotes.len()), (n, n)); + let ids: std::collections::HashSet = st.notes.iter().map(|x| x.id).collect(); + assert_eq!(ids.len(), n); + let ids: std::collections::HashSet = st.endnotes.iter().map(|x| x.id).collect(); + assert_eq!(ids.len(), n); +} + +/// An existing note whose id is `u64::MAX` can't be counted past: the next note still gets an id +/// of its own. +#[test] +fn note_ids_survive_a_maximal_existing_id() { + let mut st = Story::new(StoryId(1)); + st.insert(0, &FOOTNOTE_REF.to_string()); + st.insert(0, &crate::ENDNOTE_REF.to_string()); + Arc::make_mut(&mut st.notes[0]).id = u64::MAX; + Arc::make_mut(&mut st.endnotes[0]).id = u64::MAX; + st.insert(0, &FOOTNOTE_REF.to_string()); + st.insert(0, &crate::ENDNOTE_REF.to_string()); + assert_ne!(st.notes[0].id, st.notes[1].id); + assert_ne!(st.endnotes[0].id, st.endnotes[1].id); +} + /// Exceptions are read in one pass: breaks are char positions of the lowercased word, a break /// at the start, at the end or twice in a row counts once or not at all, and a long exception /// full of breaks takes no longer than its length. diff --git a/crates/geom/src/trace.rs b/crates/geom/src/trace.rs index 292f82e87..4a085211d 100644 --- a/crates/geom/src/trace.rs +++ b/crates/geom/src/trace.rs @@ -81,33 +81,68 @@ fn simplify_closed(p: &[Point], tol: f64) -> Vec { a } +/// Ramer–Douglas–Peucker on `p`, keeping its ends. Spans wait on a stack of their own rather +/// than in nested calls: an outline of many points can split one point at a time, deeper than +/// the call stack goes. A tolerance that isn't a number or is below zero counts as zero (each +/// split must take a point strictly inside its span, or the span would never get shorter). fn rdp(p: &[Point], tol: f64) -> Vec { - if p.len() < 3 { - return p.to_vec(); - } - let (a, b) = (p[0], p[p.len() - 1]); - let d = b - a; - let len = d.hypot(); - let (mut best, mut idx) = (0.0, 0); - for (i, q) in p.iter().enumerate().take(p.len() - 1).skip(1) { - let dist = if len < 1e-12 { (*q - a).hypot() } else { ((*q - a).cross(d) / len).abs() }; - if dist > best { - (best, idx) = (dist, i); + let (Some(_), Some(last)) = (p.first(), p.len().checked_sub(1)) else { return Vec::new() }; + let tol = if tol >= 0.0 { tol } else { 0.0 }; + let mut keep = vec![false; p.len()]; + keep[0] = true; + keep[last] = true; + let mut spans = vec![(0, last)]; + while let Some((s, e)) = spans.pop() { + if e < s + 2 { + continue; + } + let (a, b) = (p[s], p[e]); + let d = b - a; + let len = d.hypot(); + let (mut best, mut idx) = (0.0, s); + for (i, q) in p.iter().enumerate().take(e).skip(s + 1) { + let dist = if len < 1e-12 { (*q - a).hypot() } else { ((*q - a).cross(d) / len).abs() }; + if dist > best { + (best, idx) = (dist, i); + } + } + if best > tol && idx > s { + keep[idx] = true; + spans.push((idx, e)); + spans.push((s, idx)); } } - if best <= tol { - return vec![a, b]; - } - let mut left = rdp(&p[..=idx], tol); - left.pop(); - left.extend(rdp(&p[idx..], tol)); - left + p.iter().zip(keep).filter_map(|(q, k)| k.then_some(*q)).collect() } #[cfg(test)] mod tests { use super::*; + /// A tolerance below zero or NaN ends (each split shrinks its span), and a 200,000-point + /// path simplifies to completion. + #[test] + fn simplification_ends_for_any_tolerance_and_depth() { + let line: Vec = (0..10).map(|i| Point::new(f64::from(i), 0.0)).collect(); + for tol in [-1.0, f64::NAN, 0.0] { + assert_eq!(rdp(&line, tol).len(), 2, "{tol}"); + } + // A long convex curve simplifies to completion. + let n = 200_000; + let curve: Vec = (0..n).map(|i| Point::new(f64::from(i), (f64::from(i) * 1e-3).powi(3))).collect(); + assert!(rdp(&curve, 1e-12).len() > 2); + // A zigzag of growing amplitude: every split takes the point next to the span's end. + let zigzag: Vec = (0..10_000) + .map(|i| { + let x = f64::from(i); + Point::new(x, if i % 2 == 0 { x } else { -x }) + }) + .collect(); + assert_eq!(rdp(&zigzag, 0.0).len(), zigzag.len()); + assert!(rdp(&[], 1.0).is_empty()); + assert_eq!(rdp(&line[..1], 1.0).len(), 1); + } + #[test] fn traces_a_disc_and_its_hole() { let (w, h) = (40, 40); diff --git a/xtask/src/stats.rs b/xtask/src/stats.rs index f40b1300a..d9379327a 100644 --- a/xtask/src/stats.rs +++ b/xtask/src/stats.rs @@ -18,7 +18,9 @@ fn walk(dir: &Path, c: &mut Counts) { let p = e.path(); let name = e.file_name(); let name = name.to_string_lossy(); - if p.is_dir() { + // A link to a folder isn't followed: links can lead back up the tree or to the same + // folder many times over. + if e.file_type().is_ok_and(|t| t.is_dir()) { // Nested fuzz workspaces and build output are not part of the crate. if name != "target" && name != "fuzz" && !name.starts_with('.') { walk(&p, c); From d6a09639bf5fea750b599e73e289217e17624a13 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 16:21:23 -0500 Subject: [PATCH 0910/1349] Repagination, IDML swatch import and style folders: linear work, bounded depth (#2237) * Repagination, swatch import and style folders: linear page numbers, resumed duplicate suffixes, bounded folder depth * fix Section initializer after merging main --------- Co-authored-by: aiongg <67543387+aiongg@users.noreply.github.com> --- crates/doc/src/build.rs | 2 +- crates/doc/src/lib.rs | 28 ++++++++++++++++++++++++++++ crates/doc/src/tests.rs | 22 ++++++++++++++++++++++ crates/idml/src/export/item.rs | 26 +++++++++++++++++++++++++- crates/idml/src/import/swatches.rs | 7 ++++++- 5 files changed, 82 insertions(+), 3 deletions(-) diff --git a/crates/doc/src/build.rs b/crates/doc/src/build.rs index 89e4b5ee7..f64394e03 100644 --- a/crates/doc/src/build.rs +++ b/crates/doc/src/build.rs @@ -365,7 +365,7 @@ impl Document { /// number is a right page (a left page bound right to left), so a section that starts at 1 on /// a left page moves it to the right and the pages after it follow. pub fn repaginate(&mut self) { - let odd: Vec = (0..self.page_count()).map(|i| self.page_number(i) % 2 == 1).collect(); + let odd: Vec = self.page_numbers(self.page_count()).into_iter().map(|n| n % 2 == 1).collect(); // A layout starts a spread of its own. let layout_starts: HashSet = self.sections.iter().filter(|s| s.layout.is_some() && s.start > 0).map(|s| s.start).collect(); let mut breaks: Vec = Vec::new(); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 2be595e3d..d9ee6d3e9 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -983,6 +983,34 @@ impl Document { } } + /// [`Self::page_number`] of pages `0..count` in one pass (a document of continuing sections + /// would otherwise walk back through every earlier section for every page). + pub fn page_numbers(&self, count: usize) -> Vec { + let mut secs: Vec<&Section> = self.sections.iter().collect(); + secs.sort_by_key(|s| s.start); // stable: of equal starts the last wins, as in `section_of` + let (mut nums, mut next): (Vec, usize) = (Vec::with_capacity(count.min(1 << 20)), 0); + for abs in 0..count { + while secs.get(next).is_some_and(|s| s.start <= abs) { + next += 1; + } + let n = match next.checked_sub(1).and_then(|i| secs.get(i)) { + None => u32::try_from(abs).unwrap_or(u32::MAX).saturating_add(1), + Some(sec) => { + let into = u32::try_from(abs - sec.start).unwrap_or(u32::MAX); + match sec.start_number { + Some(n) => n.saturating_add(into), + None => match sec.start.checked_sub(1).and_then(|p| nums.get(p)) { + Some(prev) => prev.saturating_add(into).saturating_add(1), + None => into.saturating_add(1), + }, + } + } + }; + nums.push(n); + } + nums + } + /// The displayed page name ("1", "iv", "A-3"…) for an absolute page index, per sections. /// The chapter number in its style (`3`, `III`, `c`, `03`). pub fn chapter_label(&self) -> String { diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index ac050a457..93aeae2b1 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -389,6 +389,28 @@ fn check_is_linear_in_the_frames() { assert!(matches!(d.check(), Err(DocError::NoItem(ItemId(u64::MAX))))); } +#[test] +fn page_numbers_in_one_pass_match_page_number() { + let mut d = crate::Document::new(&crate::build::NewDocument { pages: 12, facing_pages: false, ..Default::default() }); + let sec = |start, start_number| crate::Section { + start, + start_number, + style: Default::default(), + prefix: String::new(), + marker: String::new(), + include_prefix: false, + layout: None, + }; + // Out of order, a repeated start, continuing sections and one with its own number. + d.sections = vec![sec(7, None), sec(2, Some(10)), sec(4, None), sec(7, Some(3)), sec(9, None), sec(11, Some(u32::MAX)), sec(12, None)]; + assert_eq!(d.page_numbers(14), (0..14).map(|i| d.page_number(i)).collect::>()); + d.sections = vec![sec(3, None)]; + assert_eq!(d.page_numbers(6), (0..6).map(|i| d.page_number(i)).collect::>()); + // Many continuing sections: one pass, not one walk per page. + d.sections = (1..5000).map(|i| sec(i, None)).collect(); + assert_eq!(d.page_numbers(5000)[4999], 5000); +} + #[test] fn adjust_text_ranges_tracks_and_prunes_hyperlinks_and_placeholders() { let mut d = doc(); diff --git a/crates/idml/src/export/item.rs b/crates/idml/src/export/item.rs index 371718b65..457172253 100644 --- a/crates/idml/src/export/item.rs +++ b/crates/idml/src/export/item.rs @@ -324,6 +324,9 @@ impl<'a> Ex<'a> { } } +/// Most nested style folders one style name can create. +const MAX_STYLE_GROUP_DEPTH: usize = 32; + /// Style folder tree (names `A/B/C` → groups A, B). #[derive(Default)] pub(super) struct Group { @@ -337,7 +340,8 @@ impl Group { let mut segs: Vec<&str> = if builtin { vec![name] } else { name.split('/').collect() }; let _leaf = segs.pop(); let mut g = self; - for s in segs { + // Deeper folders than this are not made (the style lands in the deepest one), so the recursive `emit` is bounded. + for s in segs.into_iter().take(MAX_STYLE_GROUP_DEPTH) { let i = match g.groups.iter().position(|(n, _)| n == s) { Some(i) => i, None => { @@ -514,3 +518,23 @@ pub(crate) fn path_to_uri(path: &str) -> String { } out } + +#[cfg(test)] +mod group_depth_tests { + use super::*; + + #[test] + fn a_style_name_with_many_separators_makes_bounded_folders() { + let mut g = Group::default(); + g.insert(&"a/".repeat(10_000), El::new("S")); + let (mut depth, mut cur) = (0, &g); + while let Some((_, next)) = cur.groups.first() { + depth += 1; + cur = next; + } + assert_eq!(depth, MAX_STYLE_GROUP_DEPTH); + assert_eq!(cur.styles.len(), 1); + let mut root = El::new("Root"); + g.emit(&mut root, "K", ""); + } +} diff --git a/crates/idml/src/import/swatches.rs b/crates/idml/src/import/swatches.rs index bdf00d9cb..ee1742d38 100644 --- a/crates/idml/src/import/swatches.rs +++ b/crates/idml/src/import/swatches.rs @@ -154,10 +154,15 @@ impl<'r> Importer<'r> { } let mut names: HashSet = self.swatches.iter().map(|s| s.name.clone()).collect(); let first_new = self.swatches.len(); + let mut next_suffix: HashMap = HashMap::new(); for (id, mut s) in order { if names.contains(&s.name) { let base = s.name.clone(); - s.name = Styles::unique_name(|n| names.contains(n), &base); + // Resume after the last suffix given to this base, so N duplicates cost O(N), not O(N^2). + let from = next_suffix.get(&base).copied().unwrap_or(2); + let (i, name) = (from..).map(|i| (i, format!("{base} {i}"))).find(|(_, n)| !names.contains(n)).unwrap_or((from, base.clone())); + next_suffix.insert(base, i.saturating_add(1)); + s.name = name; self.swatch_names.insert(id, s.name.clone()); } names.insert(s.name.clone()); From 9f4bc29c3e9e654f67463bc63b6e61e40f4f9c53 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 13:31:04 -0800 Subject: [PATCH 0911/1349] Tables: a malformed table id is refused with nothing in a table selected With nothing in a table selected, a table command given a `table` that is not a nonnegative integer (`null`, a string, a negative number) was refused as disabled, since the enablement check read it as no table. It is now refused with "`table` must be a nonnegative integer", as it is with a table selected. --- crates/engine/src/cmd.rs | 12 ++++++++---- crates/engine/src/lib.rs | 4 ++-- crates/engine/src/tests/table.rs | 9 +++++++++ 3 files changed, 19 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index dc1acaf15..b9bc2b9c2 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -332,12 +332,16 @@ pub(crate) fn named_targets(spec: &CommandSpec, p: &Value) -> Option } /// The table a call names with `table`, for a command whose params document an optional `table`. -/// `None` when the call names no table. [`table_story`] reads the `story` that goes with it. -pub(crate) fn named_table(spec: &CommandSpec, p: &Value) -> Option { +/// `None` when the call names no table. A `table` that is present but not a non-negative integer, +/// `null` included, is an error. [`table_story`] reads the `story` that goes with it. +pub(crate) fn named_table(spec: &CommandSpec, p: &Value, cmd: &str) -> Result> { if !spec.params.split(|c: char| !c.is_ascii_alphanumeric() && c != '?').any(|w| w == "table?") { - return None; + return Ok(None); + } + match p.get("table") { + None => Ok(None), + Some(v) => v.as_u64().map(Some).ok_or_else(|| bad(cmd, "`table` must be a nonnegative integer")), } - p.get("table").and_then(Value::as_u64) } /// The `story` a table command's call names alongside `table`, or `None` when the call has no diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3d43a80e0..716068c89 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -686,8 +686,8 @@ impl Session { // A table command that takes `story` and `table` acts on the table the call names, so // the selection doesn't matter: with nothing selected, the caret outside a table, or // selected rows the command can't act on, `{"table": 3}` still runs. - if let Some(table) = cmd::named_table(spec, params) - && cmd::has_doc(self).is_ok() + if cmd::has_doc(self).is_ok() + && let Some(table) = cmd::named_table(spec, params, id)? { let story = cmd::table_story(params, id)?; let st = self.doc()?; diff --git a/crates/engine/src/tests/table.rs b/crates/engine/src/tests/table.rs index 2546fa667..7626005f4 100644 --- a/crates/engine/src/tests/table.rs +++ b/crates/engine/src/tests/table.rs @@ -78,6 +78,15 @@ fn table_target_rejects_wrong_typed_story_and_table_ids() { let error = s.execute("table.get", ¶ms).unwrap_err(); assert!(error.to_string().contains("no table"), "{error}"); } + // With nothing in a table selected, a malformed `table` is refused as such, not as disabled. + s.execute("edit.deselectAll", &json!({})).unwrap(); + for id in ["table.selectTable", "table.insertRow"] { + for value in [json!("other"), json!(-1), Value::Null] { + let error = s.execute(id, &json!({ "table": value })).unwrap_err(); + assert!(!matches!(error, crate::EngineError::Disabled(..)) && error.to_string().contains("`table`"), "{id} {value}: {error}"); + } + } + assert_eq!(s.doc().unwrap().history.undo.len(), undo); } #[test] From 4bdc03676916353e08998c20ef279ab4cec7f554 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 11 Nov 2026 23:03:58 +0100 Subject: [PATCH 0912/1349] CI: nightly release dry run (#2633) release.yml also runs nightly on main with craft-common-actions' dry-run: every release build except macOS, with nothing signed, pushed or drafted. Breakage that only the release build hits (riscv64, Flatpak, FreeBSD, packaging) then shows up the next morning instead of on release day, as it did on 11 Nov 2026. --- .github/workflows/release.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index aa9693e28..d8eabea47 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,6 +1,10 @@ name: Release on: + # A nightly dry run on main: every release build except macOS, nothing signed or released + # (craft-common-actions release.yml `dry-run`). Finds release-only breakage before release day. + schedule: + - cron: "24 1 * * *" push: branches: [release] workflow_dispatch: @@ -77,6 +81,7 @@ jobs: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: + dry-run: ${{ github.event_name == 'schedule' }} app-name: designcraft app-title: DesignCraft craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 From 27d8eabb103f8cc4baaaf6a2304260693a65d38e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 19:33:50 -0500 Subject: [PATCH 0913/1349] Render: clamp the blur size before the filter planner squares it (#2640) * Render: a blur size is clamped to 1,000,000 pt before the filter planner squares it * address review: bound effect extents and sigma before spread, padding and reach arithmetic --- crates/render/src/fx.rs | 67 ++++++++++++++++++++++++++++++----------- 1 file changed, 50 insertions(+), 17 deletions(-) diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index af3c0227c..7c7c91fe1 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -29,6 +29,7 @@ use designcraft_compose::ShownOn; /// Shadow offset (spread units) for an InDesign angle (degrees, light direction) and distance. pub(crate) fn offset(angle: f64, distance: f64) -> Vec2 { let a = angle.to_radians(); + let distance = bound(distance); Vec2::new(-a.cos() * distance, a.sin() * distance) } @@ -37,33 +38,43 @@ pub(crate) fn outset(it: &Item) -> f64 { let e = &it.effects; let mut o: f64 = 0.0; if e.drop_shadow.on { - o = o.max(e.drop_shadow.distance.abs() + e.drop_shadow.size.abs() * 1.6 + 1.0); + o = o.max(bound(e.drop_shadow.distance).abs() + bound(e.drop_shadow.size).abs() * 1.6 + 1.0); } if e.outer_glow.on { - o = o.max(e.outer_glow.size.abs() * 1.6 + 1.0); + o = o.max(bound(e.outer_glow.size).abs() * 1.6 + 1.0); } o } /// (blur σ, growth) in points for an effect `size` with `pct` percent hardened. fn split(size: f64, pct: f64) -> (f64, f64) { - let size = size.max(0.0); + let size = bound(size).max(0.0); let p = (pct / 100.0).clamp(0.0, 1.0); (size * (1.0 - p) / 2.0, size * p) } +/// Largest blur standard deviation handed to the filter planner, in points: far wider than any +/// page, so a larger one looks the same. Its planner squares the value in f32, so an unbounded +/// finite size would overflow to infinity there and never finish. +const MAX_SIGMA: f64 = 1.0e6; + +/// Largest effect extent (size, distance, feather width) used for geometry, in points: twice the +/// largest blur, so a size of any finite value, or infinity, cannot overflow later arithmetic +/// (`sigma * 3.0`, padding, reach). NaN is 0. +fn bound(v: f64) -> f64 { + if v.is_nan() { 0.0 } else { v.clamp(-2.0 * MAX_SIGMA, 2.0 * MAX_SIGMA) } +} + +fn std_dev(sigma: f64) -> f32 { + if sigma.is_nan() { 0.0 } else { sigma.clamp(0.0, MAX_SIGMA) as f32 } +} + fn blur(sigma: f64) -> Filter { - Filter::from_primitive(FilterPrimitive::GaussianBlur { std_deviation: sigma.max(0.0) as f32, edge_mode: EdgeMode::None }) + Filter::from_primitive(FilterPrimitive::GaussianBlur { std_deviation: std_dev(sigma), edge_mode: EdgeMode::None }) } fn shadow(sigma: f64, color: peniko::Color) -> Filter { - Filter::from_primitive(FilterPrimitive::DropShadowOnly { - dx: 0.0, - dy: 0.0, - std_deviation: sigma.max(0.0) as f32, - color, - edge_mode: EdgeMode::None, - }) + Filter::from_primitive(FilterPrimitive::DropShadowOnly { dx: 0.0, dy: 0.0, std_deviation: std_dev(sigma), color, edge_mode: EdgeMode::None }) } /// Keep what was drawn in the current layer as much as `it`'s gradient feather says. Cover the @@ -150,7 +161,7 @@ impl Renderer { // fade); Sharp and Rounded corners follow the inset shape more tightly than Diffused. if e.feather > 0.0 && it.path.is_closed() { let fo = &e.feather_options; - let w = e.feather * (1.0 - fo.choke.clamp(0.0, 100.0) / 100.0).max(0.01); + let w = bound(e.feather) * (1.0 - fo.choke.clamp(0.0, 100.0) / 100.0).max(0.01); let (sigma, join) = match fo.corners { designcraft_doc::FeatherCorners::Diffused => (w / 4.0, kurbo::Join::Round), designcraft_doc::FeatherCorners::Rounded => (w / 3.0, kurbo::Join::Round), @@ -266,7 +277,7 @@ impl Renderer { c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestOut)), None, None, None); c.set_transform(fr.view * xf); c.set_paint(peniko::Color::BLACK); - c.set_stroke(kurbo::Stroke::new((g.size - choke).max(0.5) * 2.0).with_join(kurbo::Join::Round)); + c.set_stroke(kurbo::Stroke::new((bound(g.size) - choke).max(0.5) * 2.0).with_join(kurbo::Join::Round)); c.stroke_path(bp); c.pop_layer(); c.pop_layer(); @@ -281,7 +292,7 @@ impl Renderer { { let st = &e.satin; let off = offset(st.angle, st.distance / 2.0); - let sigma = st.size.max(0.0) / 2.0; + let sigma = bound(st.size).max(0.0) / 2.0; let paint = color_of(&c, st.opacity.clamp(0.0, 1.0)); let invert = st.invert; self.with_blended_filters(ctx, f, reach, sigma, Mix::Multiply, (bp, xf), |_, c, fr| { @@ -309,8 +320,8 @@ impl Renderer { // Bevel and Emboss (inner bevel): highlight from the lit side, shadow from the other. if e.bevel.on { let b = &e.bevel; - let off = offset(doc.light_angle(b.angle, b.global_light), b.size * (b.depth / 100.0).clamp(0.01, 10.0) * 0.5); - let sigma = b.size.max(0.0) / 2.0; + let off = offset(doc.light_angle(b.angle, b.global_light), bound(b.size) * (b.depth / 100.0).clamp(0.01, 10.0) * 0.5); + let sigma = bound(b.size).max(0.0) / 2.0; if let Some(c) = doc.resolve_color(&b.highlight, 1.0) { // The inverse shape moved away from the light lights the edges facing it. self.inner_edge(ctx, f, reach, bp, xf, off, sigma, 0.0, color_of(&c, b.highlight_opacity.clamp(0.0, 1.0)), Mix::Screen, painted); @@ -340,6 +351,8 @@ impl Renderer { mix: Mix, painted: Option<(&Item, ShownOn)>, ) { + let sigma = bound(sigma).max(0.0); + let choke = bound(choke); if let Some((it, page)) = painted { self.with_blended_filters(ctx, f, reach, sigma, mix, (bp, xf), |me, c, fr| { let pad = sigma * 4.0 + choke + off.hypot() + 4.0 * fr.px; @@ -425,8 +438,9 @@ impl Renderer { clip: Option<(&BezPath, Affine)>, draw: impl FnOnce(&mut Self, &mut RenderContext, &Frame), ) { + let sigma = bound(sigma).max(0.0); // 3σ of the Gaussian in pixels, plus a pixel of antialiasing. - let spread = sigma.max(0.0) * 3.0 / f.px + 2.0; + let spread = sigma * 3.0 / f.px + 2.0; if !f.mt && spread <= MAX_BLUR_SPREAD { push_clip(ctx, f, clip); draw(self, ctx, f); @@ -498,6 +512,25 @@ fn offscreen(reach: Rect, spread: f64, width: u16, height: u16) -> Option Date: Wed, 11 Nov 2026 17:30:21 -0800 Subject: [PATCH 0914/1349] Type: type.align without a value is an error (#2645) type.align with no `align` key applied Align Left, so a call that misspelled the key, or passed a bare string, changed the paragraphs to left alignment instead of failing. The command now returns an error, leaves the text unchanged and records no undo step. A named value still applies, and `align: null` still removes the override. --- crates/engine/src/cmd/text.rs | 5 +++-- crates/engine/src/cmd/text/format.rs | 31 ++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index bee08c167..4bcbd6cc4 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -238,8 +238,9 @@ pub fn specs() -> Vec { has_text_or_frames, |s, p| format_paras(s, p.get("attrs").unwrap_or(p)) ), - cmd!("type.align", "Align", [], None, "{align: left|center|right|leftJustified|…}", has_text_or_frames, |s, p| { - format_paras(s, &json!({"align": p.get("align").cloned().unwrap_or(json!("left"))})) + cmd!("type.align", "Align", [], None, "{align: left|center|right|leftJustified|…|null} (required)", has_text_or_frames, |s, p| { + let align = p.get("align").cloned().ok_or_else(|| bad("type.align", "`align` required"))?; + format_paras(s, &json!({ "align": align })) }), cmd!("type.alignLeft", "Align Left", [], Some("Cmd+Shift+L"), "{}", has_text_or_frames, |s, _| format_paras(s, &json!({"align": "left"}))), cmd!("type.alignCenter", "Align Center", [], Some("Cmd+Shift+C"), "{}", has_text_or_frames, |s, _| format_paras( diff --git a/crates/engine/src/cmd/text/format.rs b/crates/engine/src/cmd/text/format.rs index d915da91d..10bce4841 100644 --- a/crates/engine/src/cmd/text/format.rs +++ b/crates/engine/src/cmd/text/format.rs @@ -1074,6 +1074,37 @@ mod pick_up_format_tests { } } +#[cfg(test)] +mod align_param_tests { + use serde_json::json; + + use crate::Session; + + /// `type.align` with no `align` applied Align Left, so a script that misspelled the key + /// (`{"alignment": "center"}`) changed the paragraph to the opposite of what it asked for. + #[test] + fn type_align_without_a_value_is_refused_and_changes_nothing() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 1})).unwrap(); + let f = s.execute("frame.create", &json!({"rect": [20, 20, 400, 300], "content": "text", "text": "Hello world"})).unwrap(); + s.execute("text.select", &json!({"story": f["story"].clone(), "anchor": 0, "focus": 5})).unwrap(); + s.execute("type.align", &json!({"align": "right"})).unwrap(); + let align = |s: &mut Session| s.execute("type.selectionAttrs", &json!({})).unwrap()["para"]["align"].clone(); + assert_eq!(align(&mut s), json!("right")); + let steps = s.doc().unwrap().history.undo.len(); + for params in [json!({}), json!({"alignment": "center"}), json!("center"), json!({"align": "middle"})] { + assert!(s.execute("type.align", ¶ms).is_err(), "{params}"); + assert_eq!(align(&mut s), json!("right"), "{params}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{params}: no undo step"); + } + // A named value still applies, and null removes the override. + s.execute("type.align", &json!({"align": "center"})).unwrap(); + assert_eq!(align(&mut s), json!("center")); + s.execute("type.align", &json!({"align": null})).unwrap(); + assert_eq!(align(&mut s), json!("left")); + } +} + #[cfg(test)] mod size_bounds_tests { use serde_json::json; From 54652717c041cc03105a876dcfa5b94ff6e181ed Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 17:30:44 -0800 Subject: [PATCH 0915/1349] Text Frame Options: a non-rectangular frame shows one Inset field For an oval, a polygon or a frame with corner options, Inset Spacing dims Top, Left, Bottom, Right and the link and shows one Inset field. OK sends it as `object.textFrameOptions {inset: }`, which sets all four sides; compose keeps that inset from the frame's outline. Rectangular frames keep the four fields. --- crates/ui-egui/src/dialogs.rs | 57 ++++++++++++++--- crates/ui-egui/src/dialogs/tests.rs | 94 +++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/cs.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/hu.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ka.rs | 1 + crates/ui-egui/src/i18n/pl.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/ru.rs | 1 + crates/ui-egui/src/i18n/sv.rs | 1 + crates/ui-egui/src/i18n/table.rs | 1 + crates/ui-egui/src/i18n/uk.rs | 1 + docs/target-app-parity.md | 1 + 16 files changed, 155 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a6400054d..158b9d07d 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1005,6 +1005,23 @@ fn selected_frame_options(app: &DesignApp) -> Option bool { + let shaped = || { + let st = app.session.active()?; + let fid = st.selection.items.first().copied().or_else(|| st.selection.text.and_then(|t| t.frame))?; + let item = st.doc.item(fid)?; + if item.text_frame()?.options.path.is_some() { + return Some(false); + } + let bp = if item.corners.is_none() { item.path.to_bezpath() } else { designcraft_geom::corners::apply(&item.path, &item.corners) }; + Some(designcraft_compose::FrameOutline::new(&bp, 0.0).is_some()) + }; + shaped().unwrap_or(false) +} + /// Object › Text Frame Options shows the selected frame's options. `_shown` keeps what it showed, /// so OK sends only the fields the user changed. Fields given when the dialog opened count as /// changed. @@ -1032,7 +1049,7 @@ fn seed_text_frame_options(app: &DesignApp, d: &mut Dialog) { }; designcraft_doc::FrameBaselineGrid { start: g.start, increment: g.increment, relative_to } }); - let shown = json!({ + let mut shown = json!({ "columns": o.columns, "gutter": fm(o.gutter), "columnsKind": kind(serde_json::to_value(o.columns_kind).unwrap_or_default()), "columnWidth": fm(width), "balanceColumns": o.balance_columns, "ignoreWrap": o.ignore_wrap, @@ -1051,6 +1068,12 @@ fn seed_text_frame_options(app: &DesignApp, d: &mut Dialog) { "customGrid": o.baseline_grid.is_some(), "gridStart": fm(grid.start), "gridIncrement": fm(grid.increment), "gridRelativeTo": grid.relative_to.name(), }); + // A non-rectangular frame shows one Inset (its top inset, the one kept from the outline). + let shaped = selected_frame_is_shaped(app); + if shaped && let Value::Object(m) = &mut shown { + m.insert("inset".into(), fm(o.inset[0])); + } + d.fields.insert("_shaped".into(), json!(shaped)); if let Value::Object(m) = &shown { for (k, v) in m { d.fields.entry(k.clone()).or_insert_with(|| v.clone()); @@ -1218,8 +1241,9 @@ fn text_frame_preview(app: &mut DesignApp, d: &mut Dialog) { } /// Text Frame Options › General, as InDesign's: Columns (kind, number and width, gutter and -/// maximum, Balance Columns), Inset Spacing (top and bottom, the link, left and right), Vertical -/// Justification (align, paragraph spacing limit) and Ignore Text Wrap. +/// maximum, Balance Columns), Inset Spacing (top and bottom, the link, left and right; one Inset +/// for a non-rectangular frame), Vertical Justification (align, paragraph spacing limit) and +/// Ignore Text Wrap. fn general(lang: &str, ui: &mut egui::Ui, d: &mut Dialog) { let tr = |s: &'static str| crate::i18n::tr(lang, s); let (cap, field, cap2) = (64.0, 110.0, 70.0); @@ -1243,8 +1267,10 @@ fn general(lang: &str, ui: &mut egui::Ui, d: &mut Dialog) { // Fixed Number: each column's width, from the frame, the insets and the gutter. let frame = d.fields.get("_frameWidth").and_then(Value::as_f64); let n = d.n("columns").unwrap_or(1.0).max(1.0); + // A non-rectangular frame keeps its sides until its one Inset is changed. + let (left, right) = if d.b("_shaped") && edited(d, "inset") { ("inset", "inset") } else { ("insetLeft", "insetRight") }; let width = frame.map(|w| { - let inner = w - d.m("insetLeft").unwrap_or(0.0) - d.m("insetRight").unwrap_or(0.0); + let inner = w - d.m(left).unwrap_or(0.0) - d.m(right).unwrap_or(0.0); ((inner - d.m("gutter").unwrap_or(0.0) * (n - 1.0)) / n).max(0.0) }); let _ = crate::widgets::NumField::measure("tfo_auto_width", width, d.unit).width(field).spinner().enabled(false).show(ui); @@ -1262,6 +1288,9 @@ fn general(lang: &str, ui: &mut egui::Ui, d: &mut Dialog) { check(ui, d, "balanceColumns", tr("Balance Columns")); }); framed(ui, Some(tr("Inset Spacing")), |ui| { + // A non-rectangular frame: the four sides are dimmed and one Inset sets the distance kept + // from the outline. + let shaped = d.b("_shaped"); // While linked, a side typed in sets all four ("Make all settings the same"). let sides = ["insetTop", "insetLeft", "insetBottom", "insetRight"]; let before: Vec = sides.iter().map(|k| d.s(k)).collect(); @@ -1270,24 +1299,32 @@ fn general(lang: &str, ui: &mut egui::Ui, d: &mut Dialog) { { ui.horizontal(|ui| { caption_at(ui, tr(l1), cap); - spin_measure(ui, d, k1, field, true); + spin_measure(ui, d, k1, field, !shaped); ui.add_space(8.0); if r == 0 { let linked = d.b("insetLinked"); let tip = tr("Make all settings the same"); - if crate::widgets::icon_toggle_sized(ui, if linked { "link" } else { "link-broken" }, linked, tip, egui::vec2(22.0, 21.0)) - .clicked() - { + let toggle = ui.add_enabled_ui(!shaped, |ui| { + crate::widgets::icon_toggle_sized(ui, if linked { "link" } else { "link-broken" }, linked, tip, egui::vec2(22.0, 21.0)) + }); + if toggle.inner.clicked() { d.fields.insert("insetLinked".into(), json!(!linked)); } } else { ui.add_space(22.0 + ui.spacing().item_spacing.x); } caption_at(ui, tr(l2), cap2 - 30.0); - spin_measure(ui, d, k2, field, true); + spin_measure(ui, d, k2, field, !shaped); }); } - if d.b("insetLinked") + if shaped { + ui.horizontal(|ui| { + caption_at(ui, tr("Inset:"), cap); + spin_measure(ui, d, "inset", field, true); + }); + } + if !shaped + && d.b("insetLinked") && let Some(k) = sides.iter().zip(&before).find(|(k, b)| d.s(k) != **b).map(|(k, _)| *k) { let v = d.fields.get(k).cloned().unwrap_or_default(); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 272165b08..a11bd2f3f 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1436,6 +1436,100 @@ fn text_frame_options_set_a_custom_baseline_grid_relative_to() { assert_eq!(grid(&app), None); } +/// A non-rectangular frame (an oval, or a rectangle with rounded corners) shows one Inset, the +/// distance kept from its outline, and OK sends it as one value for all four sides. A rectangle +/// keeps the four side fields. +#[test] +fn text_frame_options_set_one_inset_for_a_non_rectangular_frame() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let oval = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "shape": "ellipse", "content": "text", "text": "Hello"})).unwrap(); + let oval = designcraft_doc::ItemId(oval["id"].as_u64().unwrap()); + let rect = app.run("frame.create", json!({"rect": [36, 300, 336, 500], "content": "text", "text": "Hello"})).unwrap(); + let rect = designcraft_doc::ItemId(rect["id"].as_u64().unwrap()); + app.run("object.textFrameOptions", json!({"ids": [oval.0, rect.0], "inset": [6, 2, 3, 4]})).unwrap(); + let opts = |app: &DesignApp, id| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.clone(); + let open = |app: &mut DesignApp, id: designcraft_doc::ItemId| { + app.run("selection.set", json!({"ids": [id.0]})).unwrap(); + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(app, &mut d); + d + }; + // The oval shows its top inset as the one Inset. + let d = open(&mut app, oval); + assert!(d.b("_shaped")); + assert_eq!(d.s("inset"), "0p6"); + // OK without edits changes nothing, and adds no undo step. + let undo = app.session.doc().unwrap().history.undo.len(); + app.ui.dialog = Some(d); + assert_eq!(confirm(&mut app).unwrap(), Value::Null); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + // Inset set to 1p0: all four sides take it. + let mut d = open(&mut app, oval); + d.fields.insert("inset".into(), json!("1p0")); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + assert_eq!(opts(&app, oval).inset, [12.0; 4]); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + // A value that isn't a measure is refused and the frame keeps its inset. + let mut d = open(&mut app, oval); + d.fields.insert("inset".into(), json!("not a measure")); + app.ui.dialog = Some(d); + assert!(confirm(&mut app).unwrap_err().to_string().contains("the inset is not a measure")); + assert_eq!(opts(&app, oval).inset, [12.0; 4]); + // A rectangle shows the four sides; with rounded corners it is not rectangular either. + let d = open(&mut app, rect); + assert!(!d.b("_shaped") && !d.fields.contains_key("inset"), "a rectangle shows the four sides"); + app.run("object.cornerOptions", json!({"ids": [rect.0], "shape": "rounded", "size": 12})).unwrap(); + let d = open(&mut app, rect); + assert!(d.b("_shaped")); + assert_eq!(d.s("inset"), "0p6"); +} + +/// The dialog dims Top, Left, Bottom, Right and the link for a non-rectangular frame and adds an +/// Inset field; for a rectangle it shows no Inset field and the sides stay editable. +#[test] +fn text_frame_options_dims_the_sides_for_a_non_rectangular_frame() { + use egui_kittest::{ + Harness, + kittest::{NodeT, Queryable}, + }; + for shaped in [true, false] { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let shape = if shaped { "ellipse" } else { "rectangle" }; + let r = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "shape": shape, "content": "text", "text": "Hello"})).unwrap(); + app.run("selection.set", json!({"ids": [r["id"]]})).unwrap(); + app.ui.dialog = Some(Dialog::new("textFrameOptions", json!({}))); + // The General tab's Columns and Align dropdowns have no accessible name yet. + let mut h = Harness::builder().with_size(egui::vec2(1000.0, 800.0)).with_accessibility_check(false).build_ui_state( + |ui, app: &mut DesignApp| { + let key = egui::Id::unique("text_frame_inset_test_fonts"); + if ui.data(|d| d.get_temp::(key)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(key, true)); + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(3); + for side in ["insetTop", "insetLeft", "insetBottom", "insetRight"] { + let label = format!("Increase tfo_{side}"); + assert_eq!(h.get_by_label(&label).accesskit_node().is_disabled(), shaped, "{shape}: {side}"); + } + assert_eq!(h.query_by_label("Inset:").is_some(), shaped, "{shape}: the Inset caption"); + assert_eq!(h.query_by_label("Increase tfo_inset").is_some(), shaped, "{shape}: the Inset field"); + // The link toggles only for a rectangle. + let linked = |h: &Harness<'_, DesignApp>| h.state().ui.dialog.as_ref().unwrap().b("insetLinked"); + let before = linked(&h); + h.get_by_label("Make all settings the same").click(); + h.run_steps(3); + assert_eq!(linked(&h) != before, !shaped, "{shape}: the link"); + } +} + #[test] fn text_frame_options_change_only_what_was_edited() { let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index adf22f4fb..28dda77d0 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1858,6 +1858,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Keep Options", "خيارات الإبقاء"), ("Span Columns", "امتداد الأعمدة"), ("Top:", "أعلى:"), + ("Inset:", "الإزاحة الداخلية:"), ("Left:", "يسار:"), ("Bottom:", "أسفل:"), ("Right:", "يمين:"), diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index 5310e8d12..32bf1803c 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -1913,6 +1913,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Third Space", "Třetina čtverčíku"), ("Title Case", "Velká Počáteční Písmena"), ("Top:", "Nahoře:"), + ("Inset:", "Odsazení:"), ("Trademark Symbol", "Symbol ochranné známky"), ("Transform Again Individually", "Transformovat znovu jednotlivě"), ("Transform Sequence Again", "Transformovat posloupnost znovu"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 2e9920126..15009e53a 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1864,6 +1864,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Third Space", "Drittelgeviert"), ("Title Case", "Wortanfänge groß"), ("Top:", "Oben:"), + ("Inset:", "Versatz:"), ("Trademark Symbol", "Markensymbol"), ("Transform Again Individually", "Erneut einzeln transformieren"), ("Transform Sequence Again", "Abfolge erneut transformieren"), diff --git a/crates/ui-egui/src/i18n/hu.rs b/crates/ui-egui/src/i18n/hu.rs index ab30bce8d..8ca23c858 100644 --- a/crates/ui-egui/src/i18n/hu.rs +++ b/crates/ui-egui/src/i18n/hu.rs @@ -1727,6 +1727,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Top Margin", "Felső margó"), ("Top of Page", "Oldal teteje"), ("Top:", "Fent:"), + ("Inset:", "Belső margó:"), ("Track Changes", "Változások követése"), ("Track Changes in All Stories", "Változások követése minden szövegfolyamban"), ("Tracking", "Betűköz"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 131875d46..9f0cf29c0 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1918,6 +1918,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Keep Options", "Opzioni di unione"), ("Span Columns", "Estendi su colonne"), ("Top:", "Superiore:"), + ("Inset:", "Rientro:"), ("Left:", "Sinistra:"), ("Bottom:", "Inferiore:"), ("Right:", "Destra:"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index ae2dd653f..9c6a9772f 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -2057,6 +2057,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Third Space", "三分スペース"), ("Title Case", "各単語の先頭を大文字に"), ("Top:", "上:"), + ("Inset:", "フレーム内マージン:"), ("Trademark Symbol", "商標記号"), ("Transform Again Individually", "個別に再変形"), ("Transform Sequence Again", "一連の変形を再実行"), diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index 1ba9a61a9..74b688a10 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -1955,6 +1955,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Third Space", "მესამედი შორისი"), ("Title Case", "ყოველი სიტყვა მთავრულით"), ("Top:", "ზემოთ:"), + ("Inset:", "შეწევა:"), ("Trademark Symbol", "სავაჭრო ნიშნის სიმბოლო"), ("Transform Again Individually", "გარდაქმნის ცალ-ცალკე გამეორება"), ("Transform Sequence Again", "გარდაქმნების მიმდევრობის გამეორება"), diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index 7aac5d74b..b37f8de3e 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -1888,6 +1888,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Third Space", "Trzecia firetu"), ("Title Case", "Wielkie Litery Wyrazów"), ("Top:", "Góra:"), + ("Inset:", "Margines wewnętrzny:"), ("Trademark Symbol", "Symbol znaku towarowego"), ("Transform Again Individually", "Przekształć ponownie osobno"), ("Transform Sequence Again", "Powtórz sekwencję przekształceń"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 147947dbd..a5c47c386 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1468,6 +1468,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Keep Options", "Opções de manter"), ("Span Columns", "Abranger colunas"), ("Top:", "Superior:"), + ("Inset:", "Recuo:"), ("Left:", "Esquerda:"), ("Bottom:", "Inferior:"), ("Right:", "Direita:"), diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 178cc9bc3..3cfb7fff0 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -1898,6 +1898,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Third Space", "Треть шпации"), ("Title Case", "Каждое слово с прописной"), ("Top:", "Сверху:"), + ("Inset:", "Отступ:"), ("Trademark Symbol", "Знак товарного знака"), ("Transform Again Individually", "Повторить трансформирование по отдельности"), ("Transform Sequence Again", "Повторить последовательность трансформирования"), diff --git a/crates/ui-egui/src/i18n/sv.rs b/crates/ui-egui/src/i18n/sv.rs index 766ba32da..f3def92b5 100644 --- a/crates/ui-egui/src/i18n/sv.rs +++ b/crates/ui-egui/src/i18n/sv.rs @@ -65,6 +65,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Gutter:", "Spaltmellanrum:"), ("Fit Guides to:", "Anpassa stödlinjer till:"), ("Top:", "Överkant:"), + ("Inset:", "Infällning:"), ("Bottom:", "Nederkant:"), ("Inside:", "Inre:"), ("Outside:", "Yttre:"), diff --git a/crates/ui-egui/src/i18n/table.rs b/crates/ui-egui/src/i18n/table.rs index ebde2b629..0aea8e244 100644 --- a/crates/ui-egui/src/i18n/table.rs +++ b/crates/ui-egui/src/i18n/table.rs @@ -479,6 +479,7 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[ ("Gutter:", ["Steg:", "Gouttière :", "Medianil:", "間隔:", "栏间距:"]), ("Fit Guides to:", ["Hilfslinien einpassen in:", "Ajuster les repères à :", "Ajustar guías a:", "ガイドの適用先:", "参考线适合:"]), ("Top:", ["Oben:", "Haut :", "Superior:", "天:", "上:"]), + ("Inset:", ["Versatz:", "Marge intérieure :", "Margen interior:", "フレーム内マージン :", "内边距:"]), ("Bottom:", ["Unten:", "Bas :", "Inferior:", "地:", "下:"]), ("Inside:", ["Innen:", "Intérieur :", "Interior:", "ノド:", "内:"]), ("Outside:", ["Außen:", "Extérieur :", "Exterior:", "小口:", "外:"]), diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 4b2853eae..16a983abe 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -1885,6 +1885,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Keep Options", "Параметри утримання"), ("Span Columns", "Охоплення колонок"), ("Top:", "Зверху:"), + ("Inset:", "Відступ:"), ("Left:", "Ліворуч:"), ("Bottom:", "Знизу:"), ("Right:", "Праворуч:"), diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 193d3ae9a..4207507dc 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -352,6 +352,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - Auto-size (Text Frame Options › Auto-Size, `object.textFrameOptions {autoSize: off|heightOnly|widthOnly|heightAndWidth|heightAndWidthProportionally, autoSizeReference, useMinimumHeight, minimumHeight, useMinimumWidth, minimumWidth, noLineBreaks}`): the frame fits its text exactly after every edit (typing, pasting, style changes, option changes) in the same undo step (opening a file keeps the frame sizes it gives); it grows and shrinks around the reference point, which stays put in spread space for rotated frames too, never below the minimum height/width and never past 10,000 pt. Width Only and No Line Breaks set each paragraph on one line; Height and Width without No Line Breaks keeps the width; Keep Proportions scales both sides until the text fits. IDML keeps all the options (`AutoSizing…`, `…ForAutoSizing` attributes). Not covered: frames of a thread other than the last, vertical frames, type on a path, and multi-column balancing in Keep Proportions. - Balance Columns (Text Frame Options › Balance Columns, `object.textFrameOptions {balanceColumns}`, IDML `VerticalBalanceColumns`): in the frame the story ends in, the columns after the last explicit column break fill to about the same depth (the last may be shorter by a line per column); keep options hold, spanning and split paragraphs keep their own balancing, vertical justification then applies to each column as usual, and vertical frames balance their bands. A frame the text runs on from, or that is overset, fills normally. - Text Frame Options dialog, laid out as InDesign's (General, Column Rules, Baseline Options, Auto-Size; framed Columns, Inset Spacing and Vertical Justification groups with spinner fields; Fixed Number shows each column's width as the fields change). Preview shows the edits on the page until OK (one undo step) or Cancel. An invalid value (such as a gutter that isn't a measure) takes the preview off the page, so the frame shows as it was, and the dialog's status line gives the reason; OK refuses the value too. Preview stays checked and shows the edits again once the value is valid. Vertical Justification › Paragraph Spacing Limit (`object.textFrameOptions {paragraphSpacingLimit}`, IDML `VerticalThreshold`): with Justify, the extra space goes between paragraphs up to the limit, the rest between lines. +- Text Frame Options › Inset Spacing for a non-rectangular frame (an oval, a polygon, a frame with corner options): Top, Left, Bottom, Right and the link are dimmed, and one Inset field sets the distance kept between the text and the frame's outline (`object.textFrameOptions {inset: }`, all four sides). - Place a page of an IDML or DesignCraft document (`file.place {layoutPage}`): its objects, stories, styles and swatches as one group (INDD files are not readable). - Articles panel (`article.new/add/remove/options/delete/list`): reading order and content of EPUB and HTML exports. - Object ▸ Clipping Path (`object.clippingPath {type: alpha|edges, threshold, tolerance}`): traces the placed image and makes the outline the frame. Clipping paths saved in IDML (Detect Edges, Alpha Channel, Photoshop Path, User-Modified Path; Invert) hide the image outside the path on screen and in PDF and survive IDML export; `object.clippingPathOptions` reports, inverts or removes one (Object ▸ Clipping Path ▸ None). From 86867e8e42f0a1f8749ebf1f23359a61e51ad0f3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 17:31:56 -0800 Subject: [PATCH 0916/1349] Compose: vertical Center, Bottom and Justify measure to the last baseline Vertical justification measured the free space down to the bottom of the last line's descenders, so Center set text too high (most visibly with a Cap Height first baseline) and Bottom and Justify left the descender depth empty. The last baseline is now the bottom of the text: Bottom and Justify put it on the bottom inset, and Center leaves as much room below it as above the first line. The descenders may reach into the bottom inset but not past the frame's edge; above footnotes, in vertical frames and in shaped frames they stay inside the text area. Tables keep their bottom. A shaped frame no longer tests the part of a line above its text area against the outline, so a small corner radius leaves a Cap Height first line where a rectangular frame puts it. Fixes #1999 --- crates/compose/src/lib.rs | 39 ++++++++++----- crates/compose/src/tests.rs | 98 +++++++++++++++++++++++++++++++++++++ 2 files changed, 126 insertions(+), 11 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index abac72985..858cf0433 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -4311,9 +4311,10 @@ fn wrap_slot( #[allow(clippy::too_many_arguments)] fn free_slots(f: &FrameSpec, col: Rect, y0: f64, y1: f64, desc: f64, size: f64, rtl: bool, line_start: usize) -> Vec<(f64, f64)> { // A shaped frame: the parts of the band its outline covers (a concave one can give several), - // descenders included: they stay inside the frame. + // descenders included: they stay inside the frame. The part of the band above the column's + // top is not tested, as in a rectangular frame: a Cap Height first line reaches above it. let mut free = match &f.outline { - Some(o) => o.intervals(col.x0, col.x1, y0, y1 + desc.max(0.0)), + Some(o) => o.intervals(col.x0, col.x1, y0.max(col.y0).min(y1), y1 + desc.max(0.0)), None => vec![(col.x0, col.x1)], }; let mut cut = f.outline.is_some(); @@ -5495,23 +5496,39 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de let ncols = if spanned { 1 } else { ft.columns.len().max(1) as u32 }; for c in 0..ncols { let idx: Vec = ft.lines.iter().enumerate().filter(|(_, l)| spanned || l.column == c).map(|(i, _)| i).collect(); - let (Some(&a), Some(_)) = (idx.first(), idx.last()) else { continue }; - let bottom = idx.iter().map(|&i| ft.lines[i].baseline + ft.lines[i].descent).fold(f64::NEG_INFINITY, f64::max); - let bottom = ft.tables.iter().filter(|t| spanned || t.column == c).map(|t| t.rect.y1).fold(bottom, f64::max); - let limit = ft + if idx.is_empty() { + continue; + } + let note_top = ft .notes .iter() .filter(|n| spanned || notes.span_columns || n.column == c) .map(|n| n.rect.y0 - notes.space_before) - .fold(f.area.y1, f64::min); - let space = limit - bottom; - if space <= 0.0 { + .fold(f64::INFINITY, f64::min); + let limit = note_top.min(f.area.y1); + let tables = ft.tables.iter().filter(|t| spanned || t.column == c).map(|t| t.rect.y1).fold(f64::NEG_INFINITY, f64::max); + let last_baseline = idx.iter().map(|&i| ft.lines[i].baseline).fold(tables, f64::max); + let ink_bottom = idx.iter().map(|&i| ft.lines[i].baseline + ft.lines[i].descent).fold(tables, f64::max); + // The bottom of the text is the last baseline, as the top is the first baseline: the + // descenders of the last line may reach into the bottom inset, but not past the frame's + // edge, and in a shaped frame not past the text area (its outline holds the descenders). + // Above footnotes, and in vertical frames, the descenders stay inside the text area, as + // when the lines are fitted. + // `space`: the room under the bottom of the text; `room`: how far its last line may move. + let (space, room) = if f.vertical || note_top <= f.area.y1 { + (limit - ink_bottom, f64::INFINITY) + } else { + let edge = if f.outline.is_some() { f.area.y1 } else { f.area.y1 + f.opts.inset[2].max(0.0) }; + (limit - last_baseline, edge - ink_bottom) + }; + if space <= 0.0 || room <= 0.0 { continue; } - let _ = a; + let center = (space / 2.0).min(room); + let space = space.min(room); let before: Vec = idx.iter().map(|&i| ft.lines[i].baseline).collect(); match f.opts.vertical_justification { - VerticalJustification::Center => idx.iter().for_each(|&i| ft.lines[i].baseline += space / 2.0), + VerticalJustification::Center => idx.iter().for_each(|&i| ft.lines[i].baseline += center), VerticalJustification::Bottom => idx.iter().for_each(|&i| ft.lines[i].baseline += space), VerticalJustification::Justify => { // Segments of one line (beside an object) share a row and move together. diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index f15f1e33d..d9e3df22e 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -2300,6 +2300,104 @@ fn vertical_justification_counts_table_fragment_bottoms() { } } +/// Center, Bottom and Justify place the text between its first baseline (where Top sets it) and +/// its last baseline: Bottom and Justify put the last baseline on the bottom inset, and Center +/// leaves as much room under the last baseline as above the first line (#1999). +#[test] +fn vertical_justification_measures_to_the_last_baseline() { + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify, Top}; + let compose_inset = |mode: VerticalJustification, first: FirstBaseline, bottom_inset: f64| { + let (mut d, sid, fid) = doc_with("Typography\ngypsy", Rect::new(0.0, 0.0, 200.0, 300.0), ParaAttrs::default()); + let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.first_baseline = first; + o.inset = [6.0, 6.0, bottom_inset, 6.0]; + let area = frame_specs(&d, sid)[0].area; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + (area, all_lines(&cs).iter().map(|l| (l.baseline, l.descent)).collect::>()) + }; + let compose_with = |mode, first| compose_inset(mode, first, 9.0); + for first in [FirstBaseline::Ascent, FirstBaseline::CapHeight] { + let (area, top) = compose_with(Top, first); + assert!((area.y1 - 291.0).abs() < 1e-9, "the bottom inset bounds the text area: {area:?}"); + assert_eq!(top.len(), 2); + let last = |v: &[(f64, f64)]| v[v.len() - 1]; + + let (_, bottom) = compose_with(Bottom, first); + assert!((last(&bottom).0 - area.y1).abs() < 1e-6, "{first:?}: Bottom puts the last baseline on the inset: {bottom:?}"); + assert!(last(&bottom).0 + last(&bottom).1 > area.y1 + 1.0, "{first:?}: the descenders reach into the inset"); + assert!((bottom[1].0 - bottom[0].0 - (top[1].0 - top[0].0)).abs() < 1e-6, "{first:?}: Bottom keeps the leading"); + + let (_, justify) = compose_with(Justify, first); + assert!((justify[0].0 - top[0].0).abs() < 1e-6, "{first:?}: Justify keeps the first baseline: {justify:?}"); + assert!((last(&justify).0 - area.y1).abs() < 1e-6, "{first:?}: Justify puts the last baseline on the inset: {justify:?}"); + + let (_, center) = compose_with(Center, first); + let shift = center[0].0 - top[0].0; + assert!(shift > 1.0); + assert!((center[1].0 - top[1].0 - shift).abs() < 1e-6, "{first:?}: Center moves every line alike"); + assert!((area.y1 - last(¢er).0 - shift).abs() < 1e-6, "{first:?}: Center leaves equal room above and below: {center:?}"); + + // A bottom inset smaller than the descent: the descenders end on the frame's edge. + for inset in [0.0, 1.0] { + for mode in [Bottom, Justify] { + let (area, lines) = compose_inset(mode, first, inset); + let (b, desc) = last(&lines); + assert!(desc > inset + 0.5); + assert!((b + desc - (area.y1 + inset)).abs() < 1e-6, "{first:?} {mode:?} inset {inset}: descenders end at {}", b + desc); + } + } + } +} + +/// A corner radius leaves a Cap Height first line where it sits in a rectangular frame, with Top +/// and with Center: a line's band above the text area isn't held to the frame's outline (#1999). +#[test] +fn a_corner_radius_keeps_a_cap_height_line_in_place() { + use designcraft_doc::VerticalJustification::{self, Center, Top}; + use designcraft_geom::corners::{CornerOptions, CornerShape}; + let mm = 72.0 / 25.4; + let rect = Rect::new(0.0, 0.0, 29.553 * mm, 9.593 * mm); + let compose_with = |radius: f64, mode: VerticalJustification| { + let (mut d, sid, fid) = doc_with("137mm", rect, ParaAttrs::default()); + let item = d.item_mut(fid).unwrap(); + item.corners = CornerOptions::uniform(CornerShape::Rounded, radius); + let o = &mut item.text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.first_baseline = FirstBaseline::CapHeight; + o.inset = [0.0; 4]; + d.story_mut(sid).unwrap().format_chars(0.."137mm".len(), |f| { + f.over.size = Some(19.0); + f.over.leading = Some(designcraft_doc::Leading::Points(19.0)); + }); + let spec = frame_specs(&d, sid).remove(0); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + (spec.outline.is_some(), spec.area, cs.frames[0].lines[0].baseline) + }; + let (square, area, top) = compose_with(0.0, Top); + let (rounded, _, rounded_top) = compose_with(0.1 * mm, Top); + assert!(!square && rounded, "only the radius gives the frame an outline"); + assert!((rounded_top - top).abs() < 1e-6, "Top: {rounded_top} with a radius, {top} without"); + let (_, _, center) = compose_with(0.0, Center); + let (_, _, rounded_center) = compose_with(0.1 * mm, Center); + assert!((center - (area.y1 + top) / 2.0).abs() < 1e-6, "Center: the last baseline halfway between {top} and {}: {center}", area.y1); + assert!((rounded_center - center).abs() < 1e-6, "Center: {rounded_center} with a radius, {center} without"); + + // In a shaped frame the outline holds the descenders: with Bottom they end on the text area's + // bottom, not in the bottom inset. + let (mut d, sid, fid) = doc_with("gypsy", Rect::new(0.0, 0.0, 200.0, 100.0), ParaAttrs::default()); + let item = d.item_mut(fid).unwrap(); + item.corners = CornerOptions::uniform(CornerShape::Rounded, 6.0); + let o = &mut item.text_frame_mut().unwrap().options; + o.vertical_justification = designcraft_doc::VerticalJustification::Bottom; + o.inset = [0.0, 0.0, 12.0, 0.0]; + let area = frame_specs(&d, sid)[0].area; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let l = &cs.frames[0].lines[0]; + assert!((l.baseline + l.descent - area.y1).abs() < 1e-6, "descenders end at {}, text area at {}", l.baseline + l.descent, area.y1); +} + #[test] fn table_rows_clear_footnotes_and_continue_in_the_next_column() { for span in [false, true] { From e362820bc45f497fb4188bd98e44cf5b37fde8fc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 17:42:24 -0800 Subject: [PATCH 0917/1349] Data merge: an image field in text places the image, not its path An image field inserted at a text insertion point, or typed there as <>, merged as text, so each record showed the image's path. It now merges as an inline image at its natural size, scaled down to fit the smallest text column of the story's frames. A missing file is listed in missingImages and its marker is removed. An explicit image role at a text insertion point places an inline image too. An image path that starts with one separator (\Photos\a.jpg) is tried from the drive's root first, then beside the data file and the document. --- crates/engine/src/cmd/datamerge.rs | 18 ++- crates/engine/src/cmd/datamerge/fill.rs | 190 ++++++++++++++++++----- crates/engine/src/cmd/datamerge/parse.rs | 7 +- crates/engine/src/cmd/datamerge/tests.rs | 151 ++++++++++++++++++ docs/agents.md | 5 +- 5 files changed, 324 insertions(+), 47 deletions(-) diff --git a/crates/engine/src/cmd/datamerge.rs b/crates/engine/src/cmd/datamerge.rs index 7cb332fd3..6fac73836 100644 --- a/crates/engine/src/cmd/datamerge.rs +++ b/crates/engine/src/cmd/datamerge.rs @@ -58,7 +58,7 @@ pub fn specs() -> Vec { "Insert Field", [], None, - "{field, role?: text|image|qr|hyperlink, story?, at?, end?, item?} → {id}", + "{field, role?: text|image|qr|hyperlink, story?, at?, end?, item?} → {id}; an image field at a text insertion point merges as an inline image", has_doc, placeholder_add ), @@ -484,8 +484,11 @@ fn add_placeholder(d: &mut Document, sel: &Selection, p: &Value, name: &str) -> true } else if explicit_story || role_param == Some("text") { false - } else if matches!(role_param, Some("image" | "qr")) { + } else if role_param == Some("qr") { true + } else if role_param == Some("image") { + // An image role with the insertion point in text places an inline image there. + sel.text.is_none() } else { sel.text.is_none() && !sel.items.is_empty() }; @@ -497,6 +500,9 @@ fn add_placeholder(d: &mut Document, sel: &Selection, p: &Value, name: &str) -> DataFieldKind::Qr => PlaceholderRole::Qr, DataFieldKind::Text => return Err(bad("data.placeholder.add", "say which role to use on this frame")), } + } else if field.kind == DataFieldKind::Image { + // An image field at the insertion point places the image inline in the text. + PlaceholderRole::Image } else { PlaceholderRole::Text }; @@ -515,14 +521,14 @@ fn add_placeholder(d: &mut Document, sel: &Selection, p: &Value, name: &str) -> } PlaceholderAnchor::Item { id: item } } else { - if matches!(role, PlaceholderRole::Image | PlaceholderRole::Qr) { - return Err(bad("data.placeholder.add", "image and qr placeholders bind to a frame")); + if role == PlaceholderRole::Qr { + return Err(bad("data.placeholder.add", "qr placeholders bind to a frame")); } let (story, at, end) = text_target(p, sel).ok_or_else(|| bad("data.placeholder.add", "select text or a frame"))?; if d.story(story).is_none() { return Err(bad("data.placeholder.add", "no story")); } - if role == PlaceholderRole::Text { + if matches!(role, PlaceholderRole::Text | PlaceholderRole::Image) { let marker = format!("<<{name}>>"); let at = { let text = d.story(story).map(|st| st.text.clone()).unwrap_or_default(); @@ -574,7 +580,7 @@ pub(crate) fn sync_placeholders(doc: &mut Document) { } PlaceholderAnchor::Text { story, start, end } => { let text = doc.story(story).map(|st| st.text.clone()).unwrap_or_default(); - if ph.role != PlaceholderRole::Text { + if !matches!(ph.role, PlaceholderRole::Text | PlaceholderRole::Image) { if start <= end && end <= text.len() { keep.push(ph); } diff --git a/crates/engine/src/cmd/datamerge/fill.rs b/crates/engine/src/cmd/datamerge/fill.rs index a7b4a0ba6..caea4d67e 100644 --- a/crates/engine/src/cmd/datamerge/fill.rs +++ b/crates/engine/src/cmd/datamerge/fill.rs @@ -8,10 +8,10 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; use designcraft_doc::{ - Asset, AssetId, Content, DataField, Fill, Fitting, Graphic, Hyperlink, HyperlinkDest, HyperlinkSource, Item, ItemId, MergeOptions, - PlaceholderAnchor, PlaceholderRole, Shape, SpreadRef, Story, StoryId, + AnchorPosition, AnchoredObject, Asset, AssetId, Content, DataField, DataFieldKind, Fill, Fitting, Graphic, Hyperlink, HyperlinkDest, + HyperlinkSource, Item, ItemId, MergeOptions, OBJECT_MARK, PlaceholderAnchor, PlaceholderRole, Shape, SpreadRef, Story, StoryId, }; -use designcraft_geom::{Affine, Rect, Vec2}; +use designcraft_geom::{Affine, Rect, Vec2, shapes}; use super::parse::image_candidates; use crate::EngineError; @@ -147,6 +147,16 @@ struct Rep { start: usize, end: usize, text: String, + /// An inline image that takes the range's place; `text` is then its object mark. + object: Option, +} + +/// An image field at a text range: the placed image goes into the text in the marker's place. +struct InlineImage { + story: StoryId, + start: usize, + end: usize, + field: String, } /// Where `fill_row` looks for linked images: the merge options and the two search folders. @@ -199,6 +209,7 @@ impl ImageCache { #[derive(Default)] struct Pending { reps: Vec, + images: Vec, links: Vec<(PlaceholderAnchor, HyperlinkDest, String)>, parent: bool, report: FillReport, @@ -225,8 +236,14 @@ pub fn fill_row( PlaceholderAnchor::Item { .. } => plan_item(doc, maps, ph, &cell, record, sources, &mut pending), } } - let Pending { mut reps, links, parent, mut report } = pending; - typed_reps(doc, fields, row, maps, &placeholders, &mut reps); + let Pending { mut reps, mut images, links, parent, mut report } = pending; + typed_reps(doc, fields, row, maps, &placeholders, &mut reps, &mut images); + for InlineImage { story, start, end, field } in images { + let cell = cell_of(fields, row, &field); + let object = inline_image(doc, story, &field, cell, record, sources, &mut report); + let text = if object.is_some() { OBJECT_MARK.to_string() } else { String::new() }; + reps.push(Rep { story, start, end, text, object }); + } apply_reps(doc, &reps); for (anchor, dest, field) in links { let anchor = match anchor { @@ -261,13 +278,14 @@ fn plan_text( return; }; match ph.role { - PlaceholderRole::Text => pending.reps.push(Rep { story: mapped, start, end, text: cell }), + PlaceholderRole::Text => pending.reps.push(Rep { story: mapped, start, end, text: cell, object: None }), + PlaceholderRole::Image => pending.images.push(InlineImage { story: mapped, start, end, field: ph.field.clone() }), PlaceholderRole::Hyperlink => { if let Some(dest) = classify_link(&cell) { pending.links.push((PlaceholderAnchor::Text { story: mapped, start, end }, dest, ph.field.clone())); } } - PlaceholderRole::Image | PlaceholderRole::Qr => {} + PlaceholderRole::Qr => {} } } @@ -306,6 +324,7 @@ fn typed_reps( maps: &Maps, placeholders: &[designcraft_doc::Placeholder], reps: &mut Vec, + images: &mut Vec, ) { let mut stories: Vec<(StoryId, StoryId)> = maps.stories.iter().map(|(a, b)| (*a, *b)).collect(); stories.sort_by_key(|(a, _)| a.0); @@ -315,7 +334,9 @@ fn typed_reps( let covers: Vec<(usize, usize)> = placeholders .iter() .filter_map(|ph| match (&ph.role, &ph.anchor) { - (PlaceholderRole::Text, PlaceholderAnchor::Text { story, start, end }) if *story == original => Some((*start, *end)), + (PlaceholderRole::Text | PlaceholderRole::Image, PlaceholderAnchor::Text { story, start, end }) if *story == original => { + Some((*start, *end)) + } _ => None, }) .collect(); @@ -323,10 +344,12 @@ fn typed_reps( if covers.iter().any(|(a, b)| start < *b && end > *a) { continue; } - if !fields.iter().any(|f| f.name == name) { + let Some(field) = fields.iter().find(|f| f.name == name) else { continue }; + if field.kind == DataFieldKind::Image { + images.push(InlineImage { story: mapped, start, end, field: name }); continue; } - reps.push(Rep { story: mapped, start, end, text: cell_of(fields, row, &name).to_string() }); + reps.push(Rep { story: mapped, start, end, text: cell_of(fields, row, &name).to_string(), object: None }); } } } @@ -367,6 +390,15 @@ fn apply_reps(doc: &mut designcraft_doc::Document, reps: &[Rep]) { for r in mine { if r.start <= r.end && r.end <= st.text.len() { st.replace(r.start..r.end, &r.text); + // The replacement made a blank object for its mark; the image takes that slot. + if let Some(obj) = &r.object + && st.text.get(r.start..).is_some_and(|t| t.starts_with(OBJECT_MARK)) + { + let k = st.text[..r.start].matches(OBJECT_MARK).count(); + if let Some(slot) = st.objects.get_mut(k) { + *slot = Arc::new(obj.clone()); + } + } } } } @@ -420,10 +452,19 @@ fn create_link(doc: &mut designcraft_doc::Document, anchor: PlaceholderAnchor, d true } -fn place_image(doc: &mut designcraft_doc::Document, item: ItemId, field: &str, cell: &str, record: u32, sources: &Sources, report: &mut FillReport) { - let Sources { options, data_dir, doc_dir, images } = *sources; +/// An image file named by a cell: where it was found, its bytes, its pixel size and its natural size. +struct LoadedImage { + path: PathBuf, + bytes: Arc>, + pixels: (u32, u32), + natural: (f64, f64), +} + +/// The first candidate for `cell` that reads and decodes; `None` when none does. +fn load_image(cell: &str, sources: &Sources) -> Option { + let Sources { data_dir, doc_dir, images, .. } = *sources; let cands = image_candidates(cell, data_dir, doc_dir); - let found = cands.iter().find_map(|p| { + let (path, bytes) = cands.iter().find_map(|p| { // Read once per merge: many records naming one file is the normal case, and reading it // per record is the amplification (#1595). let bytes = images.get_or_read(p, || { @@ -435,23 +476,98 @@ fn place_image(doc: &mut designcraft_doc::Document, item: ItemId, field: &str, c crate::io::read_file(p).ok().filter(|b| !b.is_empty()) })?; Some((p.clone(), bytes)) + })?; + let (pixels, natural) = designcraft_render::image_size(&bytes).zip(designcraft_render::natural_size(&bytes, 0))?; + Some(LoadedImage { path, bytes, pixels, natural }) +} + +fn report_missing(report: &mut FillReport, record: u32, field: &str, cell: &str) { + report.missing.push(MissingImage { record, field: field.to_string(), path: cell.to_string() }); + report.warnings.push(format!("Record {record}, field {field}: missing image {cell}.")); +} + +/// Add `image` to the document as a new asset, linked to its file when the options say so. +fn add_image_asset(doc: &mut designcraft_doc::Document, image: LoadedImage, field: &str, options: &MergeOptions) -> AssetId { + let fresh = AssetId(doc.alloc()); + let name = image.path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| field.to_string()); + let link = options.link_images.then(|| image.path.to_string_lossy().into_owned()); + doc.add_asset(Asset { + id: fresh, + name, + mime: designcraft_render::image_mime(&image.bytes).to_string(), + link, + // The cached buffer is shared with every other record naming this file, rather than + // copied per record (#1595). + data: image.bytes, + pixels: Some(image.pixels), + ..Default::default() + }) +} + +/// The image `cell` names, as an inline object for the text of `story`. It comes in at its +/// natural size, scaled down to fit the smallest text column of the story's frames (never scaled up). +fn inline_image( + doc: &mut designcraft_doc::Document, + story: StoryId, + field: &str, + cell: &str, + record: u32, + sources: &Sources, + report: &mut FillReport, +) -> Option { + let Some(image) = load_image(cell, sources) else { + report_missing(report, record, field, cell); + return None; + }; + let (nw, nh) = image.natural; + let frame = doc.story(story).and_then(|st| st.frames.first().copied()).and_then(|id| doc.item(id)); + let layer = frame.map_or_else(|| doc.default_layer(), |it| it.layer); + // The marker may flow into any of the story's frames: fit the smallest column among them. + let fit = designcraft_compose::frame_specs(doc, story) + .iter() + .flat_map(|f| f.columns()) + .map(|b| (b.width() / nw).min(b.height() / nh)) + .reduce(f64::min) + .unwrap_or(1.0); + let k = if fit.is_finite() && fit > 0.0 { fit.min(1.0) } else { 1.0 }; + let rect = Rect::new(0.0, 0.0, nw * k, nh * k); + let xf = Affine::scale(k); + if super::super::file::validate_placement((nw, nh), rect, xf, "data.merge").is_err() { + report.missing.push(MissingImage { record, field: field.to_string(), path: cell.to_string() }); + report.warnings.push(format!("Record {record}, field {field}: image {cell} exceeds finite geometry limits.")); + return None; + } + let asset = add_image_asset(doc, image, field, sources.options); + let mut it = Item::new(ItemId(doc.alloc()), layer, Shape::Rectangle, shapes::rectangle(rect)); + it.object_style = doc.styles.default_graphic_frame.clone(); + if let Some(e) = doc.styles.object_effects(&it.object_style) { + it.effects = e.clone(); + } + it.content = Content::Graphic(Graphic { + layer_options: None, + asset, + size: (nw, nh), + xf, + auto_fit: Fitting::None, + fit_align: 0, + crop: [0.0; 4], + wrap: Default::default(), + clip: None, + fill: Default::default(), }); - let Some((path, bytes)) = found else { + Some(AnchoredObject::new(it, AnchorPosition::default())) +} + +fn place_image(doc: &mut designcraft_doc::Document, item: ItemId, field: &str, cell: &str, record: u32, sources: &Sources, report: &mut FillReport) { + let options = sources.options; + let Some(image) = load_image(cell, sources) else { if let Some(it) = doc.item_mut(item) { it.content = Content::Unassigned; } - report.missing.push(MissingImage { record, field: field.to_string(), path: cell.to_string() }); - report.warnings.push(format!("Record {record}, field {field}: missing image {cell}.")); - return; - }; - let Some(((pw, ph), (nw, nh))) = designcraft_render::image_size(&bytes).zip(designcraft_render::natural_size(&bytes, 0)) else { - if let Some(it) = doc.item_mut(item) { - it.content = Content::Unassigned; - } - report.missing.push(MissingImage { record, field: field.to_string(), path: cell.to_string() }); - report.warnings.push(format!("Record {record}, field {field}: missing image {cell}.")); + report_missing(report, record, field, cell); return; }; + let (nw, nh) = image.natural; let Some(inner) = doc.item(item).map(|it| it.inner_bounds()) else { report.warnings.push(format!("Record {record}, field {field}: missing image {cell}.")); report.missing.push(MissingImage { record, field: field.to_string(), path: cell.to_string() }); @@ -488,20 +604,7 @@ fn place_image(doc: &mut designcraft_doc::Document, item: ItemId, field: &str, c report.warnings.push(format!("Record {record}, field {field}: image {cell} exceeds finite geometry limits.")); return; } - let fresh = AssetId(doc.alloc()); - let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| field.to_string()); - let link = options.link_images.then(|| path.to_string_lossy().into_owned()); - g.asset = doc.add_asset(Asset { - id: fresh, - name, - mime: designcraft_render::image_mime(&bytes).to_string(), - link, - // The cached buffer is shared with every other record naming this file, rather than - // copied per record (#1595). - data: bytes, - pixels: Some((pw, ph)), - ..Default::default() - }); + g.asset = add_image_asset(doc, image, field, options); if let Some(it) = doc.item_mut(item) { it.content = Content::Graphic(g); } @@ -662,4 +765,15 @@ mod image_path_tests { let found = image_candidates("img/x.png", Some(data), Some(doc)); assert_eq!(found, [data.join("img").join("x.png"), doc.join("img").join("x.png")]); } + + /// A path that starts with one separator is tried as it is, then beside the data file and the + /// document without the separator. Two separators still name another computer. + #[cfg(unix)] + #[test] + fn a_rooted_image_cell_is_also_tried_beside_the_data_and_the_document() { + let (data, doc) = (Path::new("/work/data"), Path::new("/work/doc")); + let found = image_candidates("/img/x.png", Some(data), Some(doc)); + assert_eq!(found, [Path::new("/img/x.png").to_path_buf(), data.join("img").join("x.png"), doc.join("img").join("x.png")]); + assert!(image_candidates("//192.0.2.1/img/x.png", Some(data), Some(doc)).is_empty()); + } } diff --git a/crates/engine/src/cmd/datamerge/parse.rs b/crates/engine/src/cmd/datamerge/parse.rs index dfc49e842..5b8717baa 100644 --- a/crates/engine/src/cmd/datamerge/parse.rs +++ b/crates/engine/src/cmd/datamerge/parse.rs @@ -288,15 +288,18 @@ fn next_slot(col: i32, row: i32, rows_first: bool, fits_col: &impl Fn(i32) -> bo /// Files to try for an image cell: an absolute path as it is, a relative one beside the data /// file, then beside the document. Relative paths are not resolved against the process working /// directory, and paths that may not be followed ([`crate::io::document_path`]: URLs, other -/// computers, devices) are not candidates. +/// computers, devices) are not candidates. A path that starts with one separator (`\Photos\x.jpg`) +/// is tried as it is first, then beside the data file and the document with that separator dropped. pub fn image_candidates(cell: &str, data_dir: Option<&Path>, doc_dir: Option<&Path>) -> Vec { let cell = cell.trim(); if cell.is_empty() { return Vec::new(); } + let below = cell.strip_prefix(['\\', '/']).filter(|rest| !rest.is_empty() && !rest.starts_with(['\\', '/'])); let found = std::iter::once(crate::io::document_path(cell, None)) .chain(data_dir.map(|dir| crate::io::folder_path(cell, dir))) - .chain(doc_dir.map(|dir| crate::io::folder_path(cell, dir))); + .chain(doc_dir.map(|dir| crate::io::folder_path(cell, dir))) + .chain(below.into_iter().flat_map(|rest| [data_dir, doc_dir].into_iter().flatten().map(move |dir| crate::io::folder_path(rest, dir)))); let mut out: Vec = Vec::new(); for p in found.flatten() { if !out.contains(&p) { diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index 4793aac17..8ca5291a6 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -749,6 +749,157 @@ fn role_overrides_column_kind_qr_and_hyperlink() { assert_eq!(kinds, vec!["email:a@b.c".to_string(), "url:https://example.com".to_string()]); } +fn write_png_sized(path: &Path, width: u32, height: u32) { + let pixels = vec![255; width as usize * height as usize * 4]; + let bytes = designcraft_render::Rendered { width, height, pixels }.to_png(); + assert_eq!(designcraft_render::image_size(&bytes), Some((width, height)), "the fixture png must decode"); + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).unwrap(); + } + std::fs::write(path, bytes).unwrap(); +} + +/// The images anchored in the stories of document `index`, as (file name, width, height), by name. +fn inline_images(s: &Session, index: usize) -> Vec<(String, f64, f64)> { + let doc = &s.documents()[index].doc; + let mut out = Vec::new(); + for st in doc.stories.values() { + for o in &st.objects { + if let Content::Graphic(g) = &o.item.content { + let name = doc.assets.get(&g.asset).map(|a| a.name.clone()).unwrap_or_default(); + let (w, h) = o.size(); + out.push((name, w, h)); + } + } + } + out.sort_by(|a, b| a.0.cmp(&b.0)); + out +} + +/// An image field inserted at a text insertion point placed the path as text. It places the +/// image in the text: at its natural size, scaled down to fit the frame, with a missing file +/// reported and its marker removed. +#[test] +fn an_image_field_at_the_insertion_point_merges_as_an_inline_image() { + let dir = scratch("inline-image"); + let data = dir.join("data"); + write_png_sized(&data.join("pics").join("small.png"), 40, 20); + write_png_sized(&data.join("pics").join("wide.png"), 800, 100); + write(&data.join("cards.csv"), "Name,@Photo\nAda,pics/small.png\nGrace,pics/wide.png\nKai,pics/none.png\n"); + + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": data.join("cards.csv")})); + let made = text_frame(&mut s, [36.0, 36.0, 236.0, 236.0], "Photo: ", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 7, "focus": 7})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo"})); + let template = &s.documents()[0].doc; + assert_eq!(template.stories.values().next().unwrap().text, "Photo: <>"); + let width = template.item(designcraft_doc::ItemId(made["id"].as_u64().unwrap())).unwrap().inner_bounds().width(); + + exec(&mut s, "data.preview", json!({"record": 1})); + assert_eq!(inline_images(&s, 0).len(), 1, "the preview shows the image"); + exec(&mut s, "data.preview.stop", json!({})); + + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["records"], 3); + let missing = r["missingImages"].as_array().unwrap(); + assert_eq!(missing.len(), 1, "{missing:?}"); + assert_eq!((missing[0]["record"].as_u64(), missing[0]["path"].as_str()), (Some(3), Some("pics/none.png"))); + let mark = designcraft_doc::OBJECT_MARK; + assert_eq!(texts(&s), vec!["Photo: ".to_string(), format!("Photo: {mark}"), format!("Photo: {mark}")]); + let placed = inline_images(&s, s.active_index().unwrap()); + assert_eq!(placed.len(), 2, "{placed:?}"); + let (small, wide) = (&placed[0], &placed[1]); + assert_eq!(small.0, "small.png"); + assert!((small.1 - 40.0).abs() < 0.01 && (small.2 - 20.0).abs() < 0.01, "a small image keeps its natural size: {small:?}"); + assert_eq!(wide.0, "wide.png"); + assert!((wide.1 - width).abs() < 0.01 && (wide.2 - width / 8.0).abs() < 0.01, "a wide image is scaled down to the frame: {wide:?}"); +} + +/// A typed `<>` marker for an image column places the image too, from an absolute path; +/// an explicit text role still writes the path as text. +#[test] +fn a_typed_image_marker_places_the_image_and_a_text_role_keeps_the_path() { + let dir = scratch("typed-image"); + let pic = dir.join("pic.png"); + write_png_sized(&pic, 10, 30); + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, &format!("@Photo\n{}\n", pic.display())); + text_frame(&mut s, [36.0, 36.0, 300.0, 300.0], "A <> B", None); + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["missingImages"].as_array().map(Vec::len), Some(0)); + assert_eq!(texts(&s), vec![format!("A {} B", designcraft_doc::OBJECT_MARK)]); + let placed = inline_images(&s, s.active_index().unwrap()); + assert_eq!(placed.len(), 1); + assert!((placed[0].1 - 10.0).abs() < 0.01 && (placed[0].2 - 30.0).abs() < 0.01, "{placed:?}"); + + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, &format!("@Photo\n{}\n", pic.display())); + let made = text_frame(&mut s, [36.0, 36.0, 300.0, 300.0], "", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 0})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "role": "text"})); + exec(&mut s, "data.merge", json!({})); + assert_eq!(texts(&s), vec![pic.display().to_string()]); + assert!(inline_images(&s, s.active_index().unwrap()).is_empty()); +} + +/// An explicit image role at a text insertion point places an inline image too, and in a frame +/// with two columns the image is scaled down to one column's width. +#[test] +fn an_inline_image_role_at_text_fits_one_column() { + let dir = scratch("inline-columns"); + let pic = dir.join("wide.png"); + write_png_sized(&pic, 800, 100); + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, &format!("@Photo\n{}\n", pic.display())); + let made = text_frame(&mut s, [36.0, 36.0, 456.0, 336.0], "", None); + exec(&mut s, "object.textFrameOptions", json!({"ids": [made["id"]], "columns": 2, "gutter": 20})); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 0})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "role": "image"})); + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["missingImages"].as_array().map(Vec::len), Some(0), "{r}"); + let placed = inline_images(&s, s.active_index().unwrap()); + assert_eq!(placed.len(), 1, "{placed:?}"); + // 420 pt wide, less the 20 pt gutter, gives two 200 pt columns. + assert!((placed[0].1 - 200.0).abs() < 0.01 && (placed[0].2 - 25.0).abs() < 0.01, "{placed:?}"); + + // The story threads on into a 100 pt frame: the image fits that one, wherever the marker lands. + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, &format!("@Photo\n{}\n", pic.display())); + let made = text_frame(&mut s, [36.0, 36.0, 456.0, 336.0], "", None); + let small = exec(&mut s, "frame.create", json!({"rect": [36.0, 400.0, 136.0, 500.0], "content": "unassigned"})); + exec(&mut s, "text.thread", json!({"from": made["id"], "to": small["id"]})); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 0})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo"})); + exec(&mut s, "data.merge", json!({})); + let placed = inline_images(&s, s.active_index().unwrap()); + assert_eq!(placed.len(), 1, "{placed:?}"); + assert!(placed[0].1 <= 100.0 + 0.01, "{placed:?}"); +} + +/// A cell that starts with one separator (`\pics\a.png`) and names no file from the drive's root +/// is found beside the data file. +#[test] +fn an_image_path_with_a_leading_separator_is_found_beside_the_data_file() { + let dir = scratch("rooted-image"); + let data = dir.join("data"); + write_png_sized(&data.join("dc-merge-rooted-pics").join("a.png"), 12, 12); + write(&data.join("cards.csv"), "@Photo\n\\dc-merge-rooted-pics\\a.png\n/dc-merge-rooted-pics/a.png\n"); + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": data.join("cards.csv")})); + let frame = exec(&mut s, "frame.create", json!({"rect": [36.0, 36.0, 80.0, 80.0], "content": "graphic"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "item": frame["id"]})); + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["records"], 2); + assert_eq!(r["missingImages"].as_array().map(Vec::len), Some(0), "{r}"); +} + #[test] fn single_record_merge_copies_pages_and_leaves_the_template() { let mut s = Session::new(); diff --git a/docs/agents.md b/docs/agents.md index 621173a85..d2f416c83 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -88,7 +88,10 @@ external PDF/X certification. `data.source.select {path, sheet?}` links a CSV/TSV/`.xlsx` file to the document (`data.source.update` re-reads it, `data.source.remove` drops it); `data.fields` lists its fields. `data.placeholder.add {field, role?, story?, at?, end?, item?}` -marks text or a frame as a field (`role`: text, image, qr, hyperlink); `data.options` sets records, tiling and image +marks text or a frame as a field (`role`: text, image, qr, hyperlink). An image field (a `@` column) inserted at a text +insertion point, or typed there as `<>`, merges as an inline image at its natural size, scaled down to fit the +frame. An image path is absolute or relative to the data file's folder, then the document's; a path that starts with +one separator (`\Photos\a.jpg`) is tried from the drive's root first. `data.options` sets records, tiling and image fitting; `data.preview {record}` / `data.preview.stop` show one record without saving it. `data.merge` now **creates a new document** and leaves the template unchanged (the old `spread` parameter, which From e90517be4512195cf54e27293d5f4330e598c7bf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 17:50:38 -0800 Subject: [PATCH 0918/1349] Text: paragraph spacing and justification values are checked type.para, style.paragraph.create and style.paragraph.edit accepted any number for paragraph spacing and justification. They now refuse Space Before, Space After and same-style spacing outside 0 to 15552 pt, word spacing outside 0% to 1000%, letter spacing outside -100% to 500%, glyph scaling outside 50% to 200%, Auto Leading outside 0% to 500%, and a Single Word Justification other than left, center, right or fullyJustified. Each justification row needs Minimum <= Desired <= Maximum over the values the paragraph or style resolves to after the change, including the styles based on an edited style and the paragraphs, table cells and notes that use them. object.textFrameOptions refuses an inset outside 0 to 15552 pt or a list that is not four sides, and a verticalJustification, firstBaseline, autoSize or columnsKind that is not one of its names. These were applied or skipped without an error before. IDML import reads these values as before. --- crates/engine/src/cmd/object.rs | 118 ++++++++++-- crates/engine/src/cmd/style/paragraph.rs | 56 ++++++ crates/engine/src/cmd/text.rs | 5 +- crates/engine/src/cmd/text/format.rs | 234 ++++++++++++++++++++++- docs/target-app-parity.md | 1 + 5 files changed, 390 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 634c90a61..69e2d2b04 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -2595,6 +2595,14 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { let column_width = ranged("columnWidth", 0.0, 15552.0, "a number of points")?; let first_baseline_min = ranged("firstBaselineMin", 0.0, 15552.0, "a number of points")?; let spacing_limit = ranged("paragraphSpacingLimit", 0.0, 15552.0, "a number of points")?; + let inset = frame_inset_param(p)?; + let vertical_justification: Option = + frame_choice_param(p, "verticalJustification", "top|center|bottom|justify")?; + let first_baseline: Option = + frame_choice_param(p, "firstBaseline", "ascent|capHeight|leading|xHeight|fixed|emboxHeight")?; + let auto_size: Option = + frame_choice_param(p, "autoSize", "off|heightOnly|widthOnly|heightAndWidth|heightAndWidthProportionally")?; + let columns_kind: Option = frame_choice_param(p, "columnsKind", "fixedNumber|fixedWidth|flexibleWidth")?; let reference = match p.get("autoSizeReference") { None | Some(Value::Null) => None, Some(v) => Some( @@ -2655,28 +2663,22 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { if let Some(v) = p.get("gutter").and_then(Value::as_f64) { o.gutter = v.max(0.0); } - match p.get("inset") { - Some(Value::Number(n)) => o.inset = [n.as_f64().unwrap_or(0.0); 4], - Some(v @ Value::Array(_)) => { - if let Ok(a) = serde_json::from_value::<[Option; 4]>(v.clone()) { - for (side, v) in o.inset.iter_mut().zip(a) { - if let Some(v) = v { - *side = v; - } - } - } + for (side, v) in o.inset.iter_mut().zip(inset.unwrap_or_default()) { + if let Some(v) = v { + *side = v; } - _ => {} } - for (k, which) in [("verticalJustification", 0), ("firstBaseline", 1), ("autoSize", 2), ("columnsKind", 3)] { - if let Some(v) = p.get(k).cloned() { - let _ = match which { - 0 => serde_json::from_value(v).map(|x| o.vertical_justification = x), - 1 => serde_json::from_value(v).map(|x| o.first_baseline = x), - 2 => serde_json::from_value(v).map(|x| o.auto_size = x), - _ => serde_json::from_value(v).map(|x| o.columns_kind = x), - }; - } + if let Some(v) = vertical_justification { + o.vertical_justification = v; + } + if let Some(v) = first_baseline { + o.first_baseline = v; + } + if let Some(v) = auto_size { + o.auto_size = v; + } + if let Some(v) = columns_kind { + o.columns_kind = v; } if let Some(v) = reference { o.auto_size_ref = v; @@ -2752,6 +2754,40 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { }) } +/// `object.textFrameOptions` Inset Spacing: one number for every side, or [top, left, bottom, +/// right] with null for a side that keeps its value; each side 0 to 15552 pt. +fn frame_inset_param(p: &Value) -> Result; 4]>> { + const ID: &str = "object.textFrameOptions"; + let side = |v: &Value| match v.as_f64() { + Some(x) if x.is_finite() && (0.0..=15552.0).contains(&x) => Ok(x), + _ => Err(bad(ID, format!("inset must be a number of points from 0 to 15552, not {v}"))), + }; + match p.get("inset") { + None | Some(Value::Null) => Ok(None), + Some(v @ Value::Number(_)) => Ok(Some([Some(side(v)?); 4])), + Some(Value::Array(a)) if a.len() == 4 => { + let mut sides = [None; 4]; + for (s, v) in sides.iter_mut().zip(a) { + if !v.is_null() { + *s = Some(side(v)?); + } + } + Ok(Some(sides)) + } + Some(v) => Err(bad(ID, format!("inset must be a number or [top, left, bottom, right], not {v}"))), + } +} + +/// An `object.textFrameOptions` choice: absent or null leaves it, a name outside `names` is an error. +fn frame_choice_param(p: &Value, key: &str, names: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => { + serde_json::from_value(v.clone()).map(Some).map_err(|_| bad("object.textFrameOptions", format!("{key} must be one of {names}, not {v}"))) + } + } +} + fn apply_custom_frame_grid( options: &mut TextFrameOptions, custom: Option, Option, Option)>>, @@ -6005,6 +6041,48 @@ mod frame_baseline_grid_tests { s.execute("object.textFrameOptions", &json!({"ids": [id.0], "baselineGrid": null})).unwrap(); assert_eq!(grid(&s), None); } + + /// A negative or huge inset, an inset list that isn't four sides, and a vertical + /// justification or first baseline that isn't one of the names were applied or skipped + /// without a word. They are refused and the frame keeps its options. + #[test] + fn text_frame_options_refuse_insets_and_names_outside_their_ranges() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "Hello"})).unwrap(); + let id = ItemId(r["id"].as_u64().unwrap()); + let options = |s: &Session| s.doc().unwrap().doc.item(id).and_then(|i| i.text_frame()).map(|t| t.options.clone()).unwrap(); + let before = options(&s); + for (params, says) in [ + (json!({"inset": -1}), "inset must be a number of points from 0 to 15552"), + (json!({"inset": 15553}), "inset must be a number of points from 0 to 15552"), + (json!({"inset": [1, 2, 3]}), "inset must be a number or [top, left, bottom, right]"), + (json!({"inset": [1, 2, 3, -4]}), "inset must be a number of points from 0 to 15552"), + (json!({"inset": [1, "2", 3, 4]}), "inset must be a number of points from 0 to 15552"), + (json!({"inset": "6pt"}), "inset must be a number or [top, left, bottom, right]"), + (json!({"verticalJustification": "middle"}), "verticalJustification must be one of top|center|bottom|justify"), + (json!({"firstBaseline": "baseline"}), "firstBaseline must be one of"), + (json!({"autoSize": "both"}), "autoSize must be one of"), + (json!({"columnsKind": "flexible"}), "columnsKind must be one of"), + (json!({"paragraphSpacingLimit": -1}), "paragraphSpacingLimit must be a number of points from 0 to 15552"), + (json!({"firstBaselineMin": 20000}), "firstBaselineMin must be a number of points from 0 to 15552"), + ] { + let mut p = params.clone(); + p["ids"] = json!([id.0]); + let e = s.execute("object.textFrameOptions", &p).expect_err("refused").to_string(); + assert!(e.contains(says), "{params}: {e}"); + assert_eq!(options(&s), before, "{params}"); + } + // Values in range apply, the ends included, and null keeps a side. + s.execute("object.textFrameOptions", &json!({"ids": [id.0], "inset": [0, null, 15552, 4.5], "verticalJustification": "bottom"})).unwrap(); + let o = options(&s); + assert_eq!(o.inset, [0.0, before.inset[1], 15552.0, 4.5]); + assert_eq!(o.vertical_justification, designcraft_doc::VerticalJustification::Bottom); + s.execute("object.textFrameOptions", &json!({"ids": [id.0], "inset": 6, "firstBaseline": "capHeight"})).unwrap(); + let o = options(&s); + assert_eq!(o.inset, [6.0; 4]); + assert_eq!(o.first_baseline, designcraft_doc::FirstBaseline::CapHeight); + } } #[cfg(test)] diff --git a/crates/engine/src/cmd/style/paragraph.rs b/crates/engine/src/cmd/style/paragraph.rs index 16671fbd8..04a3f6a8d 100644 --- a/crates/engine/src/cmd/style/paragraph.rs +++ b/crates/engine/src/cmd/style/paragraph.rs @@ -416,6 +416,51 @@ fn continue_numbering(p: Option<&Value>, para: &mut ParaAttrs) { } } +/// After an edit of paragraph style `name`: Minimum ≤ Desired ≤ Maximum in `rows` for the style, +/// the styles based on it and the story paragraphs that use any of them. +fn check_justification_after_edit(d: &designcraft_doc::Document, name: &str, rows: [bool; 3]) -> Result<()> { + const ID: &str = "style.paragraph.edit"; + if !rows.contains(&true) { + return Ok(()); + } + let styles = &d.styles; + let affected: Vec<&str> = styles.paragraph.iter().map(|st| st.name.as_str()).filter(|n| styles.para_based_on_cycles(name, n)).collect(); + for n in &affected { + if let Some(m) = crate::cmd::text::justification_order_error(&styles.resolve_para_style(n).0, rows) { + return Err(bad(ID, if *n == name { m } else { format!("paragraph style {n:?}: {m}") })); + } + } + for st in d.stories.values() { + let mut check = |pf: &designcraft_doc::ParaFormat| { + if affected.contains(&pf.style.as_str()) { crate::cmd::text::justification_order_error(&styles.resolve_para(pf).0, rows) } else { None } + }; + if let Some(m) = first_in_nested_paras(st, &mut check) { + return Err(bad(ID, format!("a paragraph of story {}: {m}", st.id.0))); + } + } + Ok(()) +} + +/// The first answer `f` gives for a paragraph of `story`, its table cells, footnotes or endnotes, +/// at any depth. The walk keeps its own stack, so a deeply nested document can't exhaust the +/// call stack. +fn first_in_nested_paras(story: &designcraft_doc::Story, f: &mut impl FnMut(&designcraft_doc::ParaFormat) -> Option) -> Option { + let mut pending = vec![story]; + while let Some(story) = pending.pop() { + if let Some(m) = story.paras.iter().find_map(&mut *f) { + return Some(m); + } + pending.extend(story.tables.values().flat_map(|t| t.cells.iter().map(|c| &c.text))); + pending.extend(story.notes.iter().chain(&story.endnotes).map(|n| &n.text)); + } + None +} + +/// The justification rows the `para` object of `p` sets or clears. +fn justification_rows_given(p: &Value) -> [bool; 3] { + crate::cmd::text::justification_rows_named(p.get("para").and_then(Value::as_object).into_iter().flat_map(|o| o.keys().map(String::as_str))) +} + /// The style `p[key]` names: none when absent or null; anything but a name is refused. fn style_name_param(cmd: &str, p: &Value, key: &str) -> Result> { match p.get(key) { @@ -434,6 +479,8 @@ pub(super) fn create_para(s: &mut Session, p: &Value) -> Result { continue_numbering(p.get("para"), &mut para); explicit_default_kinsoku(&mut para, p.get("para")); check_grep_styles("style.paragraph.create", ¶)?; + crate::cmd::text::validate_para_values(¶, "style.paragraph.create")?; + let rows = justification_rows_given(p); let mut chars: CharAttrs = attrs("style.paragraph.create", "chars", p, |a: &mut CharAttrs, k, v| a.set_json(k, v))?; // Validate caller-supplied fills, not selection fills retained after a swatch is deleted. crate::cmd::text::validate_char_fill(&s.doc()?.doc, &chars, "style.paragraph.create")?; @@ -467,6 +514,9 @@ pub(super) fn create_para(s: &mut Session, p: &Value) -> Result { return Err(bad("style.paragraph.create", format!("no style `{n}`"))); } d.styles_mut().paragraph.push(ParagraphStyle { name: name.clone(), based_on, next_style: next, para, chars, shortcut: String::new() }); + // Minimum ≤ Desired ≤ Maximum holds over what the style resolves to. + let (resolved, _) = d.styles.resolve_para_style(&name); + crate::cmd::text::validate_justification_order(&resolved, rows, "style.paragraph.create")?; Ok(json!({"name": name})) }) } @@ -578,9 +628,15 @@ pub(super) fn edit_para(s: &mut Session, p: &Value) -> Result { continue_numbering(p.get("para"), &mut para); explicit_default_kinsoku(&mut para, p.get("para")); check_grep_styles("style.paragraph.edit", ¶)?; + crate::cmd::text::validate_para_values(¶, "style.paragraph.edit")?; let st = d.styles_mut().para_mut(&name).ok_or_else(|| bad("style.paragraph.edit", format!("no style `{name}`")))?; st.para.merge(¶); st.chars.merge(&chars); + // Minimum ≤ Desired ≤ Maximum holds over what the style resolves to: in the rows the edit + // names, or in every row when it changes Based On or resets the style. + let rows = if reset || based.is_some() { [true; 3] } else { justification_rows_given(p) }; + check_justification_after_edit(d, &name, rows)?; + let st = d.styles_mut().para_mut(&name).ok_or_else(|| bad("style.paragraph.edit", format!("no style `{name}`")))?; match next { Some(Value::String(n)) => st.next_style = Some(n), Some(Value::Null) => st.next_style = None, diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index bee08c167..421df09bc 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -25,7 +25,8 @@ pub use edit::{PLACEHOLDER, quote_marks}; use edit::{change_case, delete, delete_surrounding, fill_placeholder, insert}; pub(crate) use format::{ Target, TypingFormat, apply_char_attrs, effective_char_format, format_chars, format_paras, format_targets, format_targets_pub, - rename_typing_swatch, validate_char_fill, + justification_order_error, justification_rows_named, rename_typing_swatch, validate_char_fill, validate_justification_order, + validate_para_values, }; use format::{break_link, kern_pair, kern_step, link_style, para_toggle, pick_up_format, step_size, swap_fill_stroke}; use opentype::{open_type, open_type_features, set_features}; @@ -234,7 +235,7 @@ pub fn specs() -> Vec { "Paragraph Formatting", [], None, - "{attrs: {align?, leftIndent?, firstLineIndent?, spaceBefore?, spaceAfter?, dropCapLines?, dropCapChars?, dropCapStyle?, dropCapAlignLeft?, dropCapScaleDescenders?, hyphenate?: bool (default true), composer?, opticalMargin?: bool (hang at each character's own size; a story with story.options opticalMargin overrides it), ignoreOpticalMargin?: bool (no hang in the paragraph), tabs?, ruleAbove?/ruleBelow?: {on?, weight?, color?, tint?, columnWidth?, offset?, leftIndent?, rightIndent?} (only the named rule fields change), …}}", + "{attrs: {align?, leftIndent?, firstLineIndent?, spaceBefore?, spaceAfter?, sameParaStyleSpacing? (pt, each 0..15552), wordSpaceMin?/wordSpaceDesired?/wordSpaceMax? (0..10, 1 = 100%), letterSpaceMin?/…Desired?/…Max? (-1..5), glyphScaleMin?/…Desired?/…Max? (0.5..2) (each row Minimum ≤ Desired ≤ Maximum), autoLeading? (0..5 of the type size), singleWordJustify?: left|center|right|fullyJustified, dropCapLines?, dropCapChars?, dropCapStyle?, dropCapAlignLeft?, dropCapScaleDescenders?, hyphenate?: bool (default true), composer?, opticalMargin?: bool (hang at each character's own size; a story with story.options opticalMargin overrides it), ignoreOpticalMargin?: bool (no hang in the paragraph), tabs?, ruleAbove?/ruleBelow?: {on?, weight?, color?, tint?, columnWidth?, offset?, leftIndent?, rightIndent?} (only the named rule fields change), …}}", has_text_or_frames, |s, p| format_paras(s, p.get("attrs").unwrap_or(p)) ), diff --git a/crates/engine/src/cmd/text/format.rs b/crates/engine/src/cmd/text/format.rs index d915da91d..23d84bed6 100644 --- a/crates/engine/src/cmd/text/format.rs +++ b/crates/engine/src/cmd/text/format.rs @@ -146,6 +146,98 @@ pub(crate) const MIN_TYPE_SIZE: f64 = 0.1; pub(crate) const MAX_TYPE_SIZE: f64 = 1296.0; +/// Space Before, Space After and Space Between Paragraphs Using Same Style: 0 to 15552 pt, the +/// limit `object.textFrameOptions` applies to its Paragraph Spacing Limit. +pub(crate) const MAX_PARA_SPACE: f64 = 15552.0; + +/// The justification rows as fractions (1.0 = 100%): key stem, label, range. +const JUSTIFICATION_ROWS: [(&str, &str, f64, f64); 3] = + [("wordSpace", "word spacing", 0.0, 10.0), ("letterSpace", "letter spacing", -1.0, 5.0), ("glyphScale", "glyph scaling", 0.5, 2.0)]; + +/// Auto Leading: 0% to 500% of the type size. +const MAX_AUTO_LEADING: f64 = 5.0; + +/// A fraction shown as a percent, without float noise (1.33 is "133"). +fn percent(v: f64) -> String { + let p = (v * 100.0 * 1000.0).round() / 1000.0; + format!("{p}") +} + +/// Checks the paragraph spacing and justification values `attrs` sets: Space Before, Space After +/// and same-style spacing 0 to [`MAX_PARA_SPACE`] pt; word spacing 0% to 1000%, letter spacing +/// -100% to 500% and glyph scaling 50% to 200%; Auto Leading 0% to 500%; Single Word +/// Justification left, center, right or fullyJustified. [`validate_justification_order`] checks +/// the order of each row once the values are applied. +pub(crate) fn validate_para_values(attrs: &ParaAttrs, command_id: &str) -> Result<()> { + use designcraft_doc::Align; + let spaces = + [("spaceBefore", attrs.space_before), ("spaceAfter", attrs.space_after), ("sameParaStyleSpacing", attrs.same_para_style_spacing.flatten())]; + for (key, v) in spaces { + if let Some(v) = v + && !(0.0..=MAX_PARA_SPACE).contains(&v) + { + return Err(bad(command_id, format!("{key} {v}: 0 to {MAX_PARA_SPACE} pt"))); + } + } + let rows = [ + [attrs.word_space_min, attrs.word_space_desired, attrs.word_space_max], + [attrs.letter_space_min, attrs.letter_space_desired, attrs.letter_space_max], + [attrs.glyph_scale_min, attrs.glyph_scale_desired, attrs.glyph_scale_max], + ]; + for ((stem, label, lo, hi), given) in JUSTIFICATION_ROWS.into_iter().zip(rows) { + for (suffix, v) in ["Min", "Desired", "Max"].into_iter().zip(given) { + if let Some(v) = v + && !(lo..=hi).contains(&v) + { + return Err(bad(command_id, format!("{stem}{suffix} {}%: {label} is {}% to {}%", percent(v), percent(lo), percent(hi)))); + } + } + } + if let Some(v) = attrs.auto_leading + && !(0.0..=MAX_AUTO_LEADING).contains(&v) + { + return Err(bad(command_id, format!("autoLeading {}%: 0% to {}%", percent(v), percent(MAX_AUTO_LEADING)))); + } + if let Some(a) = attrs.single_word_justify + && !matches!(a, Align::Left | Align::Center | Align::Right | Align::FullyJustified) + { + return Err(bad(command_id, format!("singleWordJustify {}: left, center, right or fullyJustified", json!(a)))); + } + Ok(()) +} + +/// The justification rows (word spacing, letter spacing, glyph scaling) that attribute names in +/// `keys` set or clear. +pub(crate) fn justification_rows_named<'a>(keys: impl IntoIterator) -> [bool; 3] { + let mut rows = [false; 3]; + for key in keys { + let key = key.replace('_', "").to_ascii_lowercase(); + for (row, (stem, ..)) in rows.iter_mut().zip(JUSTIFICATION_ROWS) { + *row |= key.starts_with(&stem.to_ascii_lowercase()); + } + } + rows +} + +/// Each justification row marked in `rows` needs Minimum ≤ Desired ≤ Maximum in `resolved`, the +/// attributes of the paragraph or style after the change. +pub(crate) fn validate_justification_order(resolved: &designcraft_doc::ParaProps, rows: [bool; 3], command_id: &str) -> Result<()> { + justification_order_error(resolved, rows).map_or(Ok(()), |m| Err(bad(command_id, m))) +} + +/// What [`validate_justification_order`] refuses, as a message. +pub(crate) fn justification_order_error(resolved: &designcraft_doc::ParaProps, rows: [bool; 3]) -> Option { + let values = [ + [resolved.word_space_min, resolved.word_space_desired, resolved.word_space_max], + [resolved.letter_space_min, resolved.letter_space_desired, resolved.letter_space_max], + [resolved.glyph_scale_min, resolved.glyph_scale_desired, resolved.glyph_scale_max], + ]; + JUSTIFICATION_ROWS.into_iter().zip(values).zip(rows).find_map(|(((_, label, ..), [min, desired, max]), checked)| { + (checked && (min > desired || desired > max)) + .then(|| format!("{label} needs Minimum ≤ Desired ≤ Maximum, not {}%, {}%, {}%", percent(min), percent(desired), percent(max))) + }) +} + /// Byte `pos` is the hidden paragraph mark of an *empty* paragraph: the only character on that /// line, and so the one a line-affecting attribute like leading can land on right away instead of /// waiting for the next typed character (otherwise an empty line could never get its own leading). @@ -315,11 +407,15 @@ pub(crate) fn format_paras(s: &mut Session, attrs: &Value) -> Result { a.set_json_over(k, v, &designcraft_doc::ParaProps::default()).map_err(|e| bad("type.para", e))?; } crate::cmd::style::check_grep_styles("type.para", &a)?; + validate_para_values(&a, "type.para")?; + let rows = justification_rows_named(obj.keys().map(String::as_str)); // `null` removes the override (back to the style's value). let cleared: Vec = obj.iter().filter(|(_, v)| v.is_null()).map(|(k, _)| k.clone()).collect(); let targets = format_targets(s); s.edit(|d, _| { let styles = d.styles.clone(); + // Minimum ≤ Desired ≤ Maximum holds over each paragraph's own values once they change. + let mut refused = None; for t in &targets { if let Some(st) = d.text_story_mut(t.story, t.cell) { st.format_paras(t.range.clone(), |p| { @@ -332,10 +428,15 @@ pub(crate) fn format_paras(s: &mut Session, attrs: &Value) -> Result { for k in &cleared { let _ = p.para.set_json(k, &Value::Null); } + if refused.is_none() + && let Err(e) = validate_justification_order(&styles.resolve_para(p).0, rows, "type.para") + { + refused = Some(e); + } }); } } - ok() + refused.map_or_else(ok, Err) }) } @@ -1076,7 +1177,7 @@ mod pick_up_format_tests { #[cfg(test)] mod size_bounds_tests { - use serde_json::json; + use serde_json::{Value, json}; use crate::Session; @@ -1111,6 +1212,135 @@ mod size_bounds_tests { assert!(e.contains("0.1 to 1296 pt"), "{command}: {e}"); } } + + /// `type.para` set any number for paragraph spacing and justification: a negative Space + /// Before, word spacing of 5000% and a Minimum above Maximum all went into the paragraph, + /// and Single Word Justification took any alignment. Values outside the ranges are refused, + /// nothing changes, and the ends of each range still apply. + #[test] + fn paragraph_spacing_and_justification_outside_their_ranges_are_refused() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 1})).unwrap(); + let f = s.execute("frame.create", &json!({"rect": [20, 20, 400, 300], "content": "text", "text": "Hello world\nSecond"})).unwrap(); + let select_all = |s: &mut Session| { + s.execute("text.select", &json!({"story": f["story"].clone(), "anchor": 0, "focus": 18})).unwrap(); + }; + let para = |s: &mut Session| s.execute("type.selectionAttrs", &json!({})).unwrap()["para"].clone(); + select_all(&mut s); + let before = para(&mut s); + for (attrs, says) in [ + (json!({"spaceBefore": -1}), "spaceBefore -1: 0 to 15552 pt"), + (json!({"spaceAfter": 15553}), "spaceAfter 15553: 0 to 15552 pt"), + (json!({"sameParaStyleSpacing": -2}), "sameParaStyleSpacing -2: 0 to 15552 pt"), + (json!({"wordSpaceMax": 10.5}), "wordSpaceMax 1050%: word spacing is 0% to 1000%"), + (json!({"wordSpaceMin": -0.1}), "wordSpaceMin -10%: word spacing is 0% to 1000%"), + (json!({"letterSpaceMin": -1.5}), "letterSpaceMin -150%: letter spacing is -100% to 500%"), + (json!({"letterSpaceMax": 5.5}), "letterSpaceMax 550%: letter spacing is -100% to 500%"), + (json!({"glyphScaleMin": 0.4}), "glyphScaleMin 40%: glyph scaling is 50% to 200%"), + (json!({"glyphScaleDesired": 2.1}), "glyphScaleDesired 210%: glyph scaling is 50% to 200%"), + (json!({"autoLeading": 6}), "autoLeading 600%: 0% to 500%"), + (json!({"autoLeading": -0.1}), "autoLeading -10%: 0% to 500%"), + (json!({"singleWordJustify": "leftJustified"}), "singleWordJustify \"leftJustified\": left, center, right or fullyJustified"), + // Desired word spacing is 100%, so a Minimum of 120% alone is out of order. + (json!({"wordSpaceMin": 1.2}), "word spacing needs Minimum ≤ Desired ≤ Maximum, not 120%, 100%, 133%"), + ( + json!({"glyphScaleMin": 0.9, "glyphScaleDesired": 1.1, "glyphScaleMax": 1.0}), + "glyph scaling needs Minimum ≤ Desired ≤ Maximum, not 90%, 110%, 100%", + ), + ] { + select_all(&mut s); + let e = s.execute("type.para", &json!({"attrs": attrs})).expect_err("refused").to_string(); + assert!(e.contains(says), "{attrs}: {e}"); + assert_eq!(para(&mut s), before, "{attrs}"); + } + // The ends of each range apply and read back. + for attrs in [ + json!({"spaceBefore": 0, "spaceAfter": 15552, "sameParaStyleSpacing": 15552}), + json!({"wordSpaceMin": 0, "wordSpaceDesired": 0, "wordSpaceMax": 10}), + json!({"letterSpaceMin": -1, "letterSpaceDesired": 0, "letterSpaceMax": 5}), + json!({"glyphScaleMin": 0.5, "glyphScaleDesired": 1, "glyphScaleMax": 2}), + json!({"autoLeading": 5}), + json!({"autoLeading": 0, "singleWordJustify": "center"}), + ] { + select_all(&mut s); + s.execute("type.para", &json!({"attrs": attrs})).unwrap_or_else(|e| panic!("{attrs}: {e}")); + let got = para(&mut s); + let same = |a: &Value, b: &Value| a.as_f64().zip(b.as_f64()).map_or(a == b, |(a, b)| a == b); + for (k, v) in attrs.as_object().unwrap() { + assert!(same(&got[k], v), "{k}: {} for {v}", got[k]); + } + } + // The order holds over each paragraph's own values: with Desired 300% in the second + // paragraph only, a Maximum of 200% for both is refused and neither paragraph changes. + s.execute("text.select", &json!({"story": f["story"].clone(), "anchor": 12, "focus": 18})).unwrap(); + s.execute("type.para", &json!({"attrs": {"wordSpaceMax": 5, "wordSpaceDesired": 3}})).unwrap(); + select_all(&mut s); + let before = para(&mut s); + let e = s.execute("type.para", &json!({"attrs": {"wordSpaceMax": 2}})).expect_err("refused").to_string(); + assert!(e.contains("not 0%, 300%, 200%"), "{e}"); + assert_eq!(para(&mut s), before); + // Clearing a value is checked too: with Minimum 250% in the second paragraph, clearing + // its Desired back to the style's 100% is refused. + let second = |s: &mut Session| { + s.execute("text.select", &json!({"story": f["story"].clone(), "anchor": 12, "focus": 18})).unwrap(); + }; + second(&mut s); + s.execute("type.para", &json!({"attrs": {"wordSpaceMin": 2.5}})).unwrap(); + second(&mut s); + let e = s.execute("type.para", &json!({"attrs": {"wordSpaceDesired": null}})).expect_err("refused").to_string(); + assert!(e.contains("word spacing needs Minimum ≤ Desired ≤ Maximum, not 250%, 100%, 500%"), "{e}"); + second(&mut s); + assert_eq!(para(&mut s)["wordSpaceDesired"].as_f64(), Some(3.0)); + // Paragraph styles are checked the same way, over what the style resolves to. + let e = s.execute("style.paragraph.create", &json!({"name": "Loose", "para": {"autoLeading": 6}})).expect_err("refused").to_string(); + assert!(e.contains("autoLeading 600%"), "{e}"); + s.execute("style.paragraph.create", &json!({"name": "Body", "para": {"wordSpaceDesired": 1.2}})).unwrap(); + let e = s.execute("style.paragraph.create", &json!({"name": "Tight", "para": {"wordSpaceMax": 0.9}})).expect_err("refused").to_string(); + assert!(e.contains("not 80%, 100%, 90%"), "{e}"); + let e = s + .execute("style.paragraph.create", &json!({"name": "Child", "basedOn": "Body", "para": {"wordSpaceMax": 1.1}})) + .expect_err("refused") + .to_string(); + assert!(e.contains("not 80%, 120%, 110%"), "{e}"); + let e = s.execute("style.paragraph.edit", &json!({"name": "Body", "para": {"wordSpaceMin": 1.3}})).expect_err("refused").to_string(); + assert!(e.contains("not 130%, 120%, 133%"), "{e}"); + let e = s.execute("style.paragraph.edit", &json!({"name": "Body", "para": {"spaceAfter": -3}})).expect_err("refused").to_string(); + assert!(e.contains("spaceAfter -3: 0 to 15552 pt"), "{e}"); + let style = s.doc().unwrap().doc.styles.para("Body").unwrap().para.clone(); + assert_eq!((style.word_space_min, style.space_after), (None, None)); + for name in ["Loose", "Tight", "Child"] { + assert!(s.doc().unwrap().doc.styles.para(name).is_none(), "{name}"); + } + // A new Based On is checked over every row of what the style then resolves to. + s.execute("style.paragraph.create", &json!({"name": "Wide", "para": {"wordSpaceMin": 1.2, "wordSpaceDesired": 1.3}})).unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Narrow", "para": {"wordSpaceMax": 1.1}})).unwrap(); + let e = s.execute("style.paragraph.edit", &json!({"name": "Wide", "basedOn": "Narrow"})).expect_err("refused").to_string(); + assert!(e.contains("not 120%, 130%, 110%"), "{e}"); + assert_eq!(s.doc().unwrap().doc.styles.para("Wide").unwrap().based_on, None); + // An edit is checked over the styles based on the edited style and the paragraphs using + // them, too. + s.execute("style.paragraph.create", &json!({"name": "Parent"})).unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Kid", "basedOn": "Parent", "para": {"wordSpaceMax": 1.1}})).unwrap(); + let e = s.execute("style.paragraph.edit", &json!({"name": "Parent", "para": {"wordSpaceDesired": 1.2}})).expect_err("refused").to_string(); + assert!(e.contains("paragraph style \"Kid\": word spacing needs Minimum ≤ Desired ≤ Maximum, not 80%, 120%, 110%"), "{e}"); + // A footnote paragraph with its own Maximum of 10%, under a style edit that sets Desired + // to 20%. + select_all(&mut s); + s.execute("style.paragraph.apply", &json!({"name": "Parent", "clearOverrides": true})).unwrap(); + s.execute("text.select", &json!({"story": f["story"].clone(), "anchor": 5, "focus": 5})).unwrap(); + s.execute("footnote.insert", &json!({"text": "Note"})).unwrap(); + s.execute("style.paragraph.apply", &json!({"name": "Parent", "clearOverrides": true})).unwrap(); + s.execute("type.para", &json!({"attrs": {"letterSpaceMax": 0.1}})).unwrap(); + let e = s + .execute("style.paragraph.edit", &json!({"name": "Parent", "para": {"letterSpaceDesired": 0.2, "letterSpaceMax": 0.5}})) + .expect_err("refused") + .to_string(); + assert!( + e.contains(&format!("a paragraph of story {}: letter spacing needs Minimum ≤ Desired ≤ Maximum, not 0%, 20%, 10%", f["story"])), + "{e}" + ); + assert_eq!(s.doc().unwrap().doc.styles.para("Parent").unwrap().para.letter_space_desired, None); + } } #[cfg(test)] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 193d3ae9a..63da03254 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -285,6 +285,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - Data Merge (one linked CSV, TSV, text, or Excel file; text, image, QR, and hyperlink placeholders; preview; a new document with one record per page or records tiled on a single page), spell checking (public-domain Moby list + document dictionary, suggestions), Step and Repeat (count or grid, with a previewing dialog), snippets, object styles, Numbering & Section Options. - Footnotes: Type › Insert Footnote (caret moves into the note), Document Footnote Options (numbering style incl. symbols, start/restart per page/spread/section, prefix/suffix, reference position/character style, paragraph style, separator, spacing, first baseline, rule above); notes composed at the bottom of the referencing column with the body text making room, or across all the columns of the frame with Span Footnotes Across Columns; edited in place on the canvas; rendered, exported to PDF (real text) and IDML (InDesign's structure, verified opening in InDesign 2026) and imported from IDML; `footnote.*` commands. - Paragraph Rules: Rule Above / Rule Below (on, weight, colour, tint, column or text width, offset, left/right indent) set in the Paragraph panel menu and Paragraph Style Options › Paragraph Rules; inherited style values shown, and `type.para` / `style.paragraph.edit` change only the rule fields named. +- Paragraph spacing and justification values are checked: `type.para`, `style.paragraph.create` and `style.paragraph.edit` refuse Space Before, Space After and same-style spacing outside 0 to 15552 pt, word spacing outside 0% to 1000%, letter spacing outside -100% to 500%, glyph scaling outside 50% to 200%, a Minimum above Desired or a Desired above Maximum, Auto Leading outside 0% to 500%, and a Single Word Justification other than left, center, right or fullyJustified. A style edit is also checked over the styles based on it and the paragraphs that use them. `object.textFrameOptions` refuses an inset outside 0 to 15552 pt or a list that isn't four sides, and a vertical justification, first baseline, auto-size or columns kind that isn't one of its names. IDML import reads these values as before. - Cross-references and text anchors: Insert Cross-Reference (paragraph by style, or text anchor), 11 formats with InDesign's building blocks (full/partial paragraph, paragraph text/number, page number, anchor name, chapter, file name) plus user formats; resolved live at composition — never out of date, no Update step; unresolved destinations show `??`; PDF link annotations to the destination page; IDML export/import as InDesign cross-reference sources, hyperlinks, text destinations and formats (verified in InDesign 2026); `xref.*` / `anchor.*` commands. - Index: page references (topic from the selection or up to 4 levels, sort keys; current page, to end of story, next n paragraphs, suppressed, See / See also), Generate / Update Index (section headings, nested or run-in, page ranges merged, Index Title / Section Head / Level 1–4 styles); IDML export/import as InDesign topics, page references and topic cross-references (verified in InDesign 2026); `index.*` commands. - Text clipboard keeps formatting (character/paragraph formats, footnotes, cross-references, index markers, tables) and falls back to plain text when the system clipboard changed; Paste without Formatting (⇧⌘V); Change Case (UPPERCASE, lowercase, Title Case, Sentence case — formatting kept); Type › Insert Special Character / White Space / Break Character submenus. From 9041fd315322af923a21e55e05eb7b2ee0d92cf7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 17:53:41 -0800 Subject: [PATCH 0919/1349] Compose: Bottom, Center and Justify ignore corner radius and descent room Bottom and Justify now put the last baseline on the bottom inset in a frame with a corner radius as in a rectangular one, so a radius no longer moves the text when the bottom inset is above 0. Center puts the last baseline halfway between where Top sets it and the bottom inset even when the frame is too short for the descenders under it, so Cap Height text in a tight frame is centered. The last line's descenders hang below its baseline, into the bottom inset and past the frame's edge when the inset is smaller than the descent. An earlier line whose descenders reach below the last baseline (tight leading) is not moved past the text area. Above footnotes and in vertical frames the descenders still stay inside the text area. --- crates/compose/src/lib.rs | 109 ++++++++++++++++++++---------------- crates/compose/src/tests.rs | 93 ++++++++++++++++++++++++------ 2 files changed, 137 insertions(+), 65 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 858cf0433..72c0f69cb 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -5510,63 +5510,76 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de let last_baseline = idx.iter().map(|&i| ft.lines[i].baseline).fold(tables, f64::max); let ink_bottom = idx.iter().map(|&i| ft.lines[i].baseline + ft.lines[i].descent).fold(tables, f64::max); // The bottom of the text is the last baseline, as the top is the first baseline: the - // descenders of the last line may reach into the bottom inset, but not past the frame's - // edge, and in a shaped frame not past the text area (its outline holds the descenders). - // Above footnotes, and in vertical frames, the descenders stay inside the text area, as - // when the lines are fitted. - // `space`: the room under the bottom of the text; `room`: how far its last line may move. - let (space, room) = if f.vertical || note_top <= f.area.y1 { - (limit - ink_bottom, f64::INFINITY) - } else { - let edge = if f.outline.is_some() { f.area.y1 } else { f.area.y1 + f.opts.inset[2].max(0.0) }; - (limit - last_baseline, edge - ink_bottom) - }; - if space <= 0.0 || room <= 0.0 { + // descenders of the last line hang below it, into the bottom inset and past it, in shaped + // frames as in rectangular ones. Above footnotes, and in vertical frames, the descenders + // stay inside the text area, as when the lines are fitted. + // `space`: the room under the bottom of the text. + let space = if f.vertical || note_top <= f.area.y1 { limit - ink_bottom } else { limit - last_baseline }; + if space <= 0.0 { continue; } - let center = (space / 2.0).min(room); - let space = space.min(room); - let before: Vec = idx.iter().map(|&i| ft.lines[i].baseline).collect(); - match f.opts.vertical_justification { - VerticalJustification::Center => idx.iter().for_each(|&i| ft.lines[i].baseline += center), - VerticalJustification::Bottom => idx.iter().for_each(|&i| ft.lines[i].baseline += space), - VerticalJustification::Justify => { - // Segments of one line (beside an object) share a row and move together. - let rows: Vec = idx - .iter() - .scan((0usize, f64::NAN), |(row, prev), &i| { - let b = ft.lines[i].baseline; - if !prev.is_nan() && (b - *prev).abs() > 1e-9 { - *row += 1; - } - *prev = b; - Some(*row) - }) - .collect(); - let n = rows.last().copied().unwrap_or(0); - if n > 0 { - // Paragraph Spacing Limit: the space goes between paragraphs, up to the limit - // each; what is left spreads over every line (all of it with no limit). - let mut starts = vec![false; n + 1]; - for (&i, &k) in idx.iter().zip(&rows) { - if k > 0 && ft.lines[i].first_in_para { - starts[k] = true; - } - } - let gaps = starts.iter().filter(|s| **s).count(); - let limit = f.opts.vj_paragraph_spacing_limit.max(0.0); - let para = if gaps > 0 && limit > 0.0 { (space / gaps as f64).min(limit) } else { 0.0 }; + // Segments of one line (beside an object) share a row and move together. + let rows: Vec = idx + .iter() + .scan((0usize, f64::NAN), |(row, prev), &i| { + let b = ft.lines[i].baseline; + if !prev.is_nan() && (b - *prev).abs() > 1e-9 { + *row += 1; + } + *prev = b; + Some(*row) + }) + .collect(); + let n = rows.last().copied().unwrap_or(0); + // Paragraph Spacing Limit: with Justify the space goes between paragraphs, up to the limit + // each; what is left spreads over every line (all of it with no limit). + let mut starts = vec![false; n + 1]; + for (&i, &k) in idx.iter().zip(&rows) { + if k > 0 && ft.lines[i].first_in_para { + starts[k] = true; + } + } + let gaps = starts.iter().filter(|s| **s).count(); + let para_limit = f.opts.vj_paragraph_spacing_limit.max(0.0); + // How far each row moves when the text takes `space` more room. + let shifts = |space: f64| -> Vec { + match f.opts.vertical_justification { + VerticalJustification::Center => vec![space / 2.0; n + 1], + VerticalJustification::Bottom => vec![space; n + 1], + VerticalJustification::Justify if n > 0 => { + let para = if gaps > 0 && para_limit > 0.0 { (space / gaps as f64).min(para_limit) } else { 0.0 }; let per = (space - para * gaps as f64) / n as f64; let mut shift = vec![0.0; n + 1]; for k in 1..=n { shift[k] = shift[k - 1] + per + if starts[k] { para } else { 0.0 }; } - for (&i, &k) in idx.iter().zip(&rows) { - ft.lines[i].baseline += shift[k]; - } + shift + } + _ => vec![0.0; n + 1], + } + }; + // Only the last row's descenders hang below the bottom of the text: an earlier line whose + // ink reaches below the last baseline (tight leading) isn't moved past the text area. + let fits = |shift: &[f64]| { + idx.iter().zip(&rows).all(|(&i, &k)| k == n || shift[k] <= 0.0 || ft.lines[i].baseline + ft.lines[i].descent + shift[k] <= limit + 1e-9) + }; + // Every row moves no less as `space` grows, so the most room that fits is found by halving. + let mut shift = shifts(space); + if !fits(&shift) { + let (mut lo, mut hi) = (0.0, space); + for _ in 0..60 { + let mid = (lo + hi) / 2.0; + if fits(&shifts(mid)) { + lo = mid; + } else { + hi = mid; } } - _ => {} + shift = shifts(lo); + } + let before: Vec = idx.iter().map(|&i| ft.lines[i].baseline).collect(); + for (&i, &k) in idx.iter().zip(&rows) { + ft.lines[i].baseline += shift[k]; } // A drop cap moves with its line. for (&i, b) in idx.iter().zip(before) { diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index d9e3df22e..b94d94000 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -2338,27 +2338,63 @@ fn vertical_justification_measures_to_the_last_baseline() { assert!((center[1].0 - top[1].0 - shift).abs() < 1e-6, "{first:?}: Center moves every line alike"); assert!((area.y1 - last(¢er).0 - shift).abs() < 1e-6, "{first:?}: Center leaves equal room above and below: {center:?}"); - // A bottom inset smaller than the descent: the descenders end on the frame's edge. + // A bottom inset smaller than the descent: the last baseline still sits on the inset, and + // the descenders reach past the frame's edge. for inset in [0.0, 1.0] { for mode in [Bottom, Justify] { let (area, lines) = compose_inset(mode, first, inset); let (b, desc) = last(&lines); assert!(desc > inset + 0.5); - assert!((b + desc - (area.y1 + inset)).abs() < 1e-6, "{first:?} {mode:?} inset {inset}: descenders end at {}", b + desc); + assert!((b - area.y1).abs() < 1e-6, "{first:?} {mode:?} inset {inset}: last baseline at {b}, inset at {}", area.y1); } } } } +/// With tight leading an earlier line's descenders can reach below the last baseline: Bottom keeps +/// them inside the text area, and only the last line's descenders hang into the bottom inset. +#[test] +fn vertical_justification_keeps_earlier_descenders_inside() { + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify}; + let compose_with = |mode: VerticalJustification| { + let (mut d, sid, fid) = doc_with("Big\nx", Rect::new(0.0, 0.0, 200.0, 300.0), ParaAttrs::default()); + let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.inset = [6.0; 4]; + let st = d.story_mut(sid).unwrap(); + st.format_chars(0..3, |f| f.over.size = Some(48.0)); + st.format_chars(4..5, |f| f.over.leading = Some(designcraft_doc::Leading::Points(2.0))); + let area = frame_specs(&d, sid)[0].area; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines: Vec<(f64, f64)> = all_lines(&cs).iter().map(|l| (l.baseline, l.descent)).collect(); + assert_eq!(lines.len(), 2); + if mode != Justify { + assert!(lines[0].0 + lines[0].1 > lines[1].0 + 1.0, "the first line's ink reaches below the last baseline: {lines:?}"); + } + (area, lines[0].0 + lines[0].1, lines[1].0) + }; + // Bottom moves both lines until the first line's ink meets the text area's bottom. + let (area, ink, _) = compose_with(Bottom); + assert!((ink - area.y1).abs() < 1e-6, "Bottom: first line's ink ends at {ink}, text area at {}", area.y1); + // Center moves both lines, as far as the first line's ink allows. + let (area, ink, _) = compose_with(Center); + assert!(ink <= area.y1 + 1e-6, "Center: first line's ink ends at {ink}, text area at {}", area.y1); + // Justify leaves the first line where it is, so the last baseline still reaches the inset. + let (area, _, last) = compose_with(Justify); + assert!((last - area.y1).abs() < 1e-6, "Justify: last baseline at {last}, text area at {}", area.y1); +} + /// A corner radius leaves a Cap Height first line where it sits in a rectangular frame, with Top /// and with Center: a line's band above the text area isn't held to the frame's outline (#1999). +/// Center puts the last baseline halfway between where Top sets it and the bottom inset, also in +/// a frame too short for the descenders below it. #[test] fn a_corner_radius_keeps_a_cap_height_line_in_place() { - use designcraft_doc::VerticalJustification::{self, Center, Top}; + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify, Top}; use designcraft_geom::corners::{CornerOptions, CornerShape}; let mm = 72.0 / 25.4; - let rect = Rect::new(0.0, 0.0, 29.553 * mm, 9.593 * mm); - let compose_with = |radius: f64, mode: VerticalJustification| { + let compose_tall = |height: f64, radius: f64, mode: VerticalJustification| { + let rect = Rect::new(0.0, 0.0, 29.553 * mm, height); let (mut d, sid, fid) = doc_with("137mm", rect, ParaAttrs::default()); let item = d.item_mut(fid).unwrap(); item.corners = CornerOptions::uniform(CornerShape::Rounded, radius); @@ -2375,6 +2411,7 @@ fn a_corner_radius_keeps_a_cap_height_line_in_place() { assert!(!cs.is_overset()); (spec.outline.is_some(), spec.area, cs.frames[0].lines[0].baseline) }; + let compose_with = |radius: f64, mode: VerticalJustification| compose_tall(9.593 * mm, radius, mode); let (square, area, top) = compose_with(0.0, Top); let (rounded, _, rounded_top) = compose_with(0.1 * mm, Top); assert!(!square && rounded, "only the radius gives the frame an outline"); @@ -2384,18 +2421,40 @@ fn a_corner_radius_keeps_a_cap_height_line_in_place() { assert!((center - (area.y1 + top) / 2.0).abs() < 1e-6, "Center: the last baseline halfway between {top} and {}: {center}", area.y1); assert!((rounded_center - center).abs() < 1e-6, "Center: {rounded_center} with a radius, {center} without"); - // In a shaped frame the outline holds the descenders: with Bottom they end on the text area's - // bottom, not in the bottom inset. - let (mut d, sid, fid) = doc_with("gypsy", Rect::new(0.0, 0.0, 200.0, 100.0), ParaAttrs::default()); - let item = d.item_mut(fid).unwrap(); - item.corners = CornerOptions::uniform(CornerShape::Rounded, 6.0); - let o = &mut item.text_frame_mut().unwrap().options; - o.vertical_justification = designcraft_doc::VerticalJustification::Bottom; - o.inset = [0.0, 0.0, 12.0, 0.0]; - let area = frame_specs(&d, sid)[0].area; - let cs = compose_story(&d, sid, &ComposeOptions::default()); - let l = &cs.frames[0].lines[0]; - assert!((l.baseline + l.descent - area.y1).abs() < 1e-6, "descenders end at {}, text area at {}", l.baseline + l.descent, area.y1); + // Frames too short for the descenders under a centered last baseline. + for height in [22.0, 20.0, 19.0] { + let (_, area, top) = compose_tall(height, 0.0, Top); + let (_, _, center) = compose_tall(height, 0.0, Center); + assert!((center - (area.y1 + top) / 2.0).abs() < 1e-6, "{height} pt: Center at {center}, Top at {top}, inset at {}", area.y1); + } + + // A corner radius doesn't change where Bottom and Justify put the last baseline: on the + // bottom inset, as in a rectangular frame, with the descenders in the inset. + for insets in [[6.0; 4], [0.0, 0.0, 12.0, 0.0]] { + for mode in [Bottom, Justify] { + let compose_frame = |radius: f64| { + let (mut d, sid, fid) = doc_with("Typography\ngypsy", Rect::new(0.0, 0.0, 200.0, 100.0), ParaAttrs::default()); + let item = d.item_mut(fid).unwrap(); + item.corners = CornerOptions::uniform(CornerShape::Rounded, radius); + let o = &mut item.text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.inset = insets; + let area = frame_specs(&d, sid)[0].area; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + (area, all_lines(&cs).iter().map(|l| l.baseline).collect::>()) + }; + let (area, square) = compose_frame(0.0); + for radius in [0.1 * mm, 6.0] { + let (_, rounded) = compose_frame(radius); + assert_eq!(rounded.len(), square.len()); + for (r, s) in rounded.iter().zip(&square) { + assert!((r - s).abs() < 1e-6, "{mode:?} insets {insets:?} radius {radius}: {rounded:?} with a radius, {square:?} without"); + } + } + let last = square[square.len() - 1]; + assert!((last - area.y1).abs() < 1e-6, "{mode:?} insets {insets:?}: last baseline at {last}, inset at {}", area.y1); + } + } } #[test] From c93e93414c1156589137b394172abb9da3882b2b Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 02:02:22 +0000 Subject: [PATCH 0920/1349] Apply review fixes - crates/ui-egui/src/dialogs.rs - docs/target-app-parity.md --- crates/ui-egui/src/dialogs.rs | 15 ++++++++++----- docs/target-app-parity.md | 2 +- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 158b9d07d..6335f8fca 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1005,13 +1005,14 @@ fn selected_frame_options(app: &DesignApp) -> Option bool { - let shaped = || { - let st = app.session.active()?; - let fid = st.selection.items.first().copied().or_else(|| st.selection.text.and_then(|t| t.frame))?; + let Some(st) = app.session.active() else { return false }; + let shaped = |fid: designcraft_doc::ItemId| -> Option { let item = st.doc.item(fid)?; if item.text_frame()?.options.path.is_some() { return Some(false); @@ -1019,7 +1020,11 @@ fn selected_frame_is_shaped(app: &DesignApp) -> bool { let bp = if item.corners.is_none() { item.path.to_bezpath() } else { designcraft_geom::corners::apply(&item.path, &item.corners) }; Some(designcraft_compose::FrameOutline::new(&bp, 0.0).is_some()) }; - shaped().unwrap_or(false) + if st.selection.items.is_empty() { + let Some(fid) = st.selection.text.and_then(|t| t.frame) else { return false }; + return shaped(fid).unwrap_or(false); + } + st.selection.items.iter().all(|&fid| shaped(fid).unwrap_or(false)) } /// Object › Text Frame Options shows the selected frame's options. `_shown` keeps what it showed, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4207507dc..f950eb12c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -352,7 +352,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - Auto-size (Text Frame Options › Auto-Size, `object.textFrameOptions {autoSize: off|heightOnly|widthOnly|heightAndWidth|heightAndWidthProportionally, autoSizeReference, useMinimumHeight, minimumHeight, useMinimumWidth, minimumWidth, noLineBreaks}`): the frame fits its text exactly after every edit (typing, pasting, style changes, option changes) in the same undo step (opening a file keeps the frame sizes it gives); it grows and shrinks around the reference point, which stays put in spread space for rotated frames too, never below the minimum height/width and never past 10,000 pt. Width Only and No Line Breaks set each paragraph on one line; Height and Width without No Line Breaks keeps the width; Keep Proportions scales both sides until the text fits. IDML keeps all the options (`AutoSizing…`, `…ForAutoSizing` attributes). Not covered: frames of a thread other than the last, vertical frames, type on a path, and multi-column balancing in Keep Proportions. - Balance Columns (Text Frame Options › Balance Columns, `object.textFrameOptions {balanceColumns}`, IDML `VerticalBalanceColumns`): in the frame the story ends in, the columns after the last explicit column break fill to about the same depth (the last may be shorter by a line per column); keep options hold, spanning and split paragraphs keep their own balancing, vertical justification then applies to each column as usual, and vertical frames balance their bands. A frame the text runs on from, or that is overset, fills normally. - Text Frame Options dialog, laid out as InDesign's (General, Column Rules, Baseline Options, Auto-Size; framed Columns, Inset Spacing and Vertical Justification groups with spinner fields; Fixed Number shows each column's width as the fields change). Preview shows the edits on the page until OK (one undo step) or Cancel. An invalid value (such as a gutter that isn't a measure) takes the preview off the page, so the frame shows as it was, and the dialog's status line gives the reason; OK refuses the value too. Preview stays checked and shows the edits again once the value is valid. Vertical Justification › Paragraph Spacing Limit (`object.textFrameOptions {paragraphSpacingLimit}`, IDML `VerticalThreshold`): with Justify, the extra space goes between paragraphs up to the limit, the rest between lines. -- Text Frame Options › Inset Spacing for a non-rectangular frame (an oval, a polygon, a frame with corner options): Top, Left, Bottom, Right and the link are dimmed, and one Inset field sets the distance kept between the text and the frame's outline (`object.textFrameOptions {inset: }`, all four sides). +- Text Frame Options › Inset Spacing for a non-rectangular frame (an oval, a polygon, a frame with corner options; when every selected text frame is one, a mixed selection keeps the four sides): Top, Left, Bottom, Right and the link are dimmed, and one Inset field sets the distance kept between the text and the frame's outline (`object.textFrameOptions {inset: }`, all four sides). - Place a page of an IDML or DesignCraft document (`file.place {layoutPage}`): its objects, stories, styles and swatches as one group (INDD files are not readable). - Articles panel (`article.new/add/remove/options/delete/list`): reading order and content of EPUB and HTML exports. - Object ▸ Clipping Path (`object.clippingPath {type: alpha|edges, threshold, tolerance}`): traces the placed image and makes the outline the frame. Clipping paths saved in IDML (Detect Edges, Alpha Channel, Photoshop Path, User-Modified Path; Invert) hide the image outside the path on screen and in PDF and survive IDML export; `object.clippingPathOptions` reports, inverts or removes one (Object ▸ Clipping Path ▸ None). From 058815cd802a81877fab31fa396aa4622faebd64 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 29 Oct 2026 17:27:32 -0500 Subject: [PATCH 0921/1349] Honor embedded raster resolution when placing graphics (#1991) A 600px photo saved at 600dpi places 1in wide, as in InDesign, instead of one pixel per point. Reads JFIF/EXIF (JPEG), pHYs (PNG), EXIF (WebP), pixels-per-meter (BMP) and TIFF resolution tags; insane metadata falls back to 72ppi. --- crates/engine/src/cmd/file/place.rs | 40 +++++ crates/images/src/lib.rs | 15 +- crates/images/src/resolution.rs | 236 ++++++++++++++++++++++++++++ crates/images/src/tests.rs | 228 +++++++++++++++++++++++++++ 4 files changed, 516 insertions(+), 3 deletions(-) create mode 100644 crates/images/src/resolution.rs diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index a30cb2321..29358d834 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -589,6 +589,46 @@ pub(super) mod image_place_tests { } } + #[test] + fn placed_photo_honors_its_embedded_resolution() { + // #1991: a placed graphic's embedded density sets its size (600 dpi: 40 px place + // 4.8 pt wide), instead of a pixel always becoming a point. + fn crc32(data: &[u8]) -> u32 { + let mut crc = 0xFFFF_FFFFu32; + for &b in data { + crc ^= b as u32; + for _ in 0..8 { + crc = if crc & 1 == 1 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 }; + } + } + !crc + } + let png = designcraft_render::Rendered { width: 40, height: 20, pixels: [30, 90, 180, 255].repeat(800) }.to_png(); + assert_eq!(&png[12..16], b"IHDR"); + let mut phys = Vec::new(); + phys.extend_from_slice(&23622u32.to_be_bytes()); + phys.extend_from_slice(&23622u32.to_be_bytes()); + phys.push(1); + let mut bytes = png[..33].to_vec(); + bytes.extend_from_slice(&(phys.len() as u32).to_be_bytes()); + bytes.extend_from_slice(b"pHYs"); + bytes.extend_from_slice(&phys); + let mut c = b"pHYs".to_vec(); + c.extend_from_slice(&phys); + bytes.extend_from_slice(&crc32(&c).to_be_bytes()); + bytes.extend_from_slice(&png[33..]); + let file = tempfile::Builder::new().suffix(".png").tempfile().unwrap(); + std::fs::write(file.path(), bytes).unwrap(); + let mut session = Session::new(); + session.execute("file.new", &json!({})).unwrap(); + let placed = session.execute("file.place", &json!({"path": file.path(), "x": 10.0, "y": 20.0})).unwrap(); + let document = &session.doc().unwrap().doc; + let item = document.item(ItemId(placed["id"].as_u64().unwrap())).unwrap(); + let b = item.bounds(); + assert!((b.x0 - 10.0).abs() < 1e-9 && (b.y0 - 20.0).abs() < 1e-9, "{b:?}"); + assert!((b.width() - 4.8).abs() < 0.01 && (b.height() - 2.4).abs() < 0.01, "{b:?}"); + } + #[test] fn explicit_frame_wins_over_placement_and_selection() { let image = image_file().unwrap(); diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 83c540e6e..7540eee90 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -12,6 +12,7 @@ pub mod colour; mod eps; mod jpeg; mod psd; +mod resolution; mod tone; pub use eps::{bounding_box as eps_bounding_box, eps_pixel_size, eps_png, eps_proxy, eps_size, is_eps}; pub use tone::{Tone, tone}; @@ -358,8 +359,11 @@ pub fn svg_tree(bytes: &[u8]) -> Option { usvg::Tree::from_data(&xml, svg_options()).ok() } -/// Natural size of a placed graphic in points: rasters at 72 ppi (one pixel per point), PSDs -/// likewise, SVGs from their width/height (CSS pixels), PDFs are the caller's. +pub use resolution::raster_resolution; + +/// Natural size of a placed graphic in points: rasters at their embedded resolution when sane +/// (one pixel per point, 72 ppi, without usable metadata), PSDs likewise, SVGs from their +/// width/height (CSS pixels), PDFs are the caller's. pub fn natural_size(bytes: &[u8]) -> Option<(f64, f64)> { if is_svg(bytes) { let s = svg_tree(bytes)?.size(); @@ -370,7 +374,12 @@ pub fn natural_size(bytes: &[u8]) -> Option<(f64, f64)> { return Some((bb[2] - bb[0], bb[3] - bb[1])).filter(|(w, h)| w.is_finite() && h.is_finite() && *w > 0.0 && *h > 0.0); } let (w, h) = pixel_size(bytes)?; - Some((w as f64, h as f64)) + // Honor the file's density (#1991): a 600 px photo saved at 600 dpi places one inch wide, + // as in InDesign. Absurd metadata falls back to a pixel per point. + match raster_resolution(bytes) { + Some(dpi) if resolution::sane_resolution(dpi) => Some((w as f64 * 72.0 / dpi.0, h as f64 * 72.0 / dpi.1)), + _ => Some((w as f64, h as f64)), + } } /// Pixel dimensions of a raster. diff --git a/crates/images/src/resolution.rs b/crates/images/src/resolution.rs new file mode 100644 index 000000000..ab1dc119f --- /dev/null +++ b/crates/images/src/resolution.rs @@ -0,0 +1,236 @@ +//! Embedded raster resolution: the density a placed graphic was saved with, so placing honors +//! it instead of assuming 72 ppi (#1991: a 600 px photo saved at 600 dpi places one inch wide, +//! as in InDesign). Reads JFIF/EXIF from JPEG (and EXIF from WebP), pHYs from PNG, the resolution +//! tags from TIFF, and the header density from BMP. GIF, PSD and files without (usable) metadata +//! report nothing and keep the pixel-is-a-point size. + +/// Dots per inch in x and y, when the file carries usable resolution metadata. +pub fn raster_resolution(bytes: &[u8]) -> Option<(f64, f64)> { + if bytes.len() < 8 { + return None; + } + if bytes.starts_with(b"\xFF\xD8\xFF") { + return jpeg_resolution(bytes); + } + if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { + return png_resolution(bytes); + } + if bytes.starts_with(b"RIFF") && bytes.get(8..12) == Some(b"WEBP".as_slice()) { + return webp_resolution(bytes); + } + if bytes.starts_with(b"BM") { + return bmp_resolution(bytes); + } + if is_classic_tiff(bytes) { + return tiff_resolution(bytes); + } + None +} + +/// A parsed density is usable when both axes are finite, positive and below the absurdity cap +/// (a corrupt or hostile value falls back to 72 ppi at the call site). +pub fn sane_resolution(dpi: (f64, f64)) -> bool { + let (dx, dy) = dpi; + dx.is_finite() && dy.is_finite() && dx > 0.0 && dy > 0.0 && dx <= 100_000.0 && dy <= 100_000.0 +} + +fn is_classic_tiff(bytes: &[u8]) -> bool { + bytes.starts_with(b"II*\x00") || bytes.starts_with(b"MM\x00*") +} + +// ---------- JPEG ---------- + +/// Scan JPEG markers for a JFIF density, preferring an EXIF resolution when both are present. +/// Stops at the start of scan (entropy data can contain marker-like bytes). +fn jpeg_resolution(bytes: &[u8]) -> Option<(f64, f64)> { + let mut pos = 2; + let mut jfif: Option<(f64, f64)> = None; + for _ in 0..512 { + // Markers are FF-prefixed; skip fill bytes. Running out of bytes ends the scan + // (a truncated file keeps a JFIF density found before the truncation). + let Some(mut m) = bytes.get(pos).copied() else { break }; + while m == 0xFF { + pos += 1; + let Some(b) = bytes.get(pos).copied() else { break }; + m = b; + if m != 0xFF { + break; + } + } + if m == 0xFF { + break; + } + pos += 1; + // Standalone markers carry no payload; SOS starts entropy-coded data. + if m == 0xD8 || m == 0xD9 || (0xD0..=0xD7).contains(&m) || m == 0x01 { + continue; + } + if m == 0xDA { + break; + } + let Some(&a) = bytes.get(pos) else { break }; + let Some(&b) = bytes.get(pos + 1) else { break }; + let len = u16::from_be_bytes([a, b]) as usize; + if len < 2 || pos + len > bytes.len() { + break; + } + let payload = &bytes[pos + 2..pos + len]; + if m == 0xE0 && jfif.is_none() { + jfif = jfif_density(payload); + } else if m == 0xE1 && let Some(dpi) = exif_resolution(payload) { + // A non-EXIF APP1 (XMP, ICC, ...) parses to nothing: keep scanning, since a + // later APP1 can still carry the EXIF resolution. + return Some(dpi); + } + pos += len; + } + jfif +} + +/// JFIF APP0 density: version, units (0 aspect, 1 dpi, 2 dots/cm), x/y density. +fn jfif_density(payload: &[u8]) -> Option<(f64, f64)> { + if !payload.starts_with(b"JFIF\x00") || payload.len() < 14 { + return None; + } + let units = payload[7]; + let (x, y) = (u16::from_be_bytes([payload[8], payload[9]]), u16::from_be_bytes([payload[10], payload[11]])); + match (units, x, y) { + (1, 1.., 1..) => Some((x as f64, y as f64)), + (2, 1.., 1..) => Some((x as f64 * 2.54, y as f64 * 2.54)), + _ => None, + } +} + +/// EXIF APP1 payload ("Exif\0\0" + a TIFF header): the resolution tags of IFD0. +fn exif_resolution(payload: &[u8]) -> Option<(f64, f64)> { + let tiff = payload.strip_prefix(b"Exif\x00\x00")?; + if !is_classic_tiff(tiff) { + return None; + } + tiff_resolution(tiff) +} + +// ---------- TIFF (also the body of EXIF) ---------- + +/// Classic TIFF resolution tags of the first IFD: XResolution/YResolution rationals scaled by +/// ResolutionUnit (2 = inch, 3 = cm; a missing unit defaults to inch per the spec). +pub fn tiff_resolution(tiff: &[u8]) -> Option<(f64, f64)> { + let le = match &tiff[..2] { + b"II" => true, + b"MM" => false, + _ => return None, + }; + let u16at = |i: usize| -> Option { + let b: [u8; 2] = tiff.get(i..i + 2)?.try_into().ok()?; + Some(if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) }) + }; + let u32at = |i: usize| -> Option { + let b: [u8; 4] = tiff.get(i..i + 4)?.try_into().ok()?; + Some(if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) }) + }; + let ifd = u32at(4)? as usize; + let count = u16at(ifd)? as usize; + if count > 512 { + return None; + } + let mut xres: Option<(u32, u32)> = None; + let mut yres: Option<(u32, u32)> = None; + let mut unit: Option = None; + for n in 0..count { + let e = ifd.checked_add(2)?.checked_add(n.checked_mul(12)?)?; + let (tag, typ, cnt) = (u16at(e)?, u16at(e + 2)?, u32at(e + 4)?); + // SHORT values of count 1 live inline in the value field (low bytes LE, high bytes BE). + let short_inline = || -> Option { + let raw = u32at(e + 8)?; + Some(if le { (raw & 0xFFFF) as u16 } else { (raw >> 16) as u16 }) + }; + // RATIONAL values of count 1 live at the offset (relative to the TIFF header start). + let rational_at = || -> Option<(u32, u32)> { + if cnt != 1 { + return None; + } + let off = u32at(e + 8)? as usize; + if off.checked_add(8)? > tiff.len() { + return None; + } + Some((u32at(off)?, u32at(off + 4)?)) + }; + match (tag, typ) { + (0x011A, 5) if xres.is_none() => xres = rational_at(), + (0x011B, 5) if yres.is_none() => yres = rational_at(), + (0x0128, 3) if unit.is_none() => unit = short_inline(), + _ => {} + } + } + let num = |(n, d): (u32, u32)| (d != 0).then(|| n as f64 / d as f64); + let (x, y) = (num(xres?)?, num(yres?)?); + match unit.unwrap_or(2) { + 2 => Some((x, y)), + 3 => Some((x * 2.54, y * 2.54)), + _ => None, + } +} + +// ---------- PNG ---------- + +/// The pHYs chunk: pixels-per-unit in x and y plus the unit (1 = meter → dpi). +fn png_resolution(bytes: &[u8]) -> Option<(f64, f64)> { + let mut pos = 8; + for _ in 0..64 { + let len = u32::from_be_bytes(bytes.get(pos..pos + 4)?.try_into().ok()?) as usize; + let kind = bytes.get(pos + 4..pos + 8)?; + if kind == b"pHYs" { + let data = bytes.get(pos + 8..pos + 8 + 9)?; + let (x, y) = (u32::from_be_bytes(data[0..4].try_into().ok()?), u32::from_be_bytes(data[4..8].try_into().ok()?)); + if data[8] == 1 && x > 0 && y > 0 { + return Some((x as f64 * 0.0254, y as f64 * 0.0254)); + } + return None; + } + if kind == b"IEND" { + return None; + } + pos = pos.checked_add(8)?.checked_add(len)?.checked_add(4)?; + if pos >= bytes.len() { + return None; + } + } + None +} + +// ---------- WebP ---------- + +/// A WebP EXIF chunk carries a TIFF header: reuse the TIFF resolution tags. +fn webp_resolution(bytes: &[u8]) -> Option<(f64, f64)> { + let riff = u32::from_le_bytes(bytes.get(4..8)?.try_into().ok()?) as usize; + let end = 12usize.checked_add(riff)?.min(bytes.len()); + let mut pos = 12; + for _ in 0..64 { + let kind = bytes.get(pos..pos + 4)?; + let size = u32::from_le_bytes(bytes.get(pos + 4..pos + 8)?.try_into().ok()?) as usize; + let data = pos.checked_add(8)?; + if data.checked_add(size)? > end { + return None; + } + if kind == b"EXIF" && is_classic_tiff(bytes.get(data..data + size.min(4)).unwrap_or_default()) { + return tiff_resolution(&bytes[data..(data + size).min(bytes.len())]); + } + pos = data.checked_add(size.checked_add(size & 1)?)?; + } + None +} + +// ---------- BMP ---------- + +/// BITMAPINFOHEADER pixels-per-meter (offset 38/42): meters → dpi. +fn bmp_resolution(bytes: &[u8]) -> Option<(f64, f64)> { + if bytes.len() < 46 || u32::from_le_bytes(bytes.get(14..18)?.try_into().ok()?) < 40 { + return None; + } + let ppm = |i: usize| -> Option { Some(i32::from_le_bytes(bytes.get(i..i + 4)?.try_into().ok()?)) }; + let (x, y) = (ppm(38)?, ppm(42)?); + if x > 0 && y > 0 { + return Some((x as f64 * 0.0254, y as f64 * 0.0254)); + } + None +} diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index 3e5daf8ab..917693f87 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -432,6 +432,234 @@ fn cmyk_tiff_with_alpha_reports_its_pixel_size() { assert_eq!(pixel_size(&b), Some((2, 1))); } +// ---------- embedded resolution (#1991) ---------- + +/// A real encoder-written 600x900 JPEG with an APPn segment inserted after SOI (decoders skip +/// APPn, so the file stays fully valid and dimension readers exercise the real path). +fn jpeg_with(app: &[u8]) -> Vec { + use image::codecs::jpeg::JpegEncoder; + let img = image::RgbaImage::from_pixel(600, 900, image::Rgba([200, 30, 30, 255])); + let mut b = Vec::new(); + JpegEncoder::new_with_quality(&mut b, 90).encode_image(&img).unwrap(); + assert_eq!(&b[..2], &[0xFF, 0xD8]); + let mut out = b[..2].to_vec(); + out.extend_from_slice(app); + out.extend_from_slice(&b[2..]); + out +} + +/// JFIF APP0 with the given units (0 aspect, 1 dpi, 2 per cm) and densities. +fn jfif_app(units: u8, x: u16, y: u16) -> Vec { + let mut a = vec![0xFF, 0xE0, 0x00, 0x10, b'J', b'F', b'I', b'F', 0x00, 0x01, 0x02, units]; + a.extend_from_slice(&x.to_be_bytes()); + a.extend_from_slice(&y.to_be_bytes()); + a.extend_from_slice(&[0x00, 0x00]); + a +} + +/// Minimal little-endian TIFF with X/YResolution rationals and an optional ResolutionUnit. +fn tiff_bytes(x: (u32, u32), y: (u32, u32), unit: Option) -> Vec { + let mut t = vec![b'I', b'I', 0x2A, 0x00, 0x08, 0x00, 0x00, 0x00]; + let n = if unit.is_some() { 3 } else { 2 }; + t.extend_from_slice(&(n as u16).to_le_bytes()); + let data = 8 + 2 + n * 12 + 4; + let mut entry = |tag: u16, typ: u16, val: u32| { + t.extend_from_slice(&tag.to_le_bytes()); + t.extend_from_slice(&typ.to_le_bytes()); + t.extend_from_slice(&1u32.to_le_bytes()); + t.extend_from_slice(&val.to_le_bytes()); + }; + entry(0x011A, 5, data as u32); + entry(0x011B, 5, (data + 8) as u32); + if let Some(u) = unit { + // SHORT count 1: the value sits inline in the low bytes. + t.extend_from_slice(&0x0128u16.to_le_bytes()); + t.extend_from_slice(&3u16.to_le_bytes()); + t.extend_from_slice(&1u32.to_le_bytes()); + t.extend_from_slice(&u.to_le_bytes()); + t.extend_from_slice(&[0, 0]); + } + t.extend_from_slice(&[0, 0, 0, 0]); + assert_eq!(t.len(), data); + for (num, den) in [x, y] { + t.extend_from_slice(&num.to_le_bytes()); + t.extend_from_slice(&den.to_le_bytes()); + } + t +} + +/// EXIF APP1 wrapping a TIFF header. +fn exif_app(tiff: &[u8]) -> Vec { + let mut a = vec![0xFF, 0xE1]; + a.extend_from_slice(&((tiff.len() + 8) as u16).to_be_bytes()); + a.extend_from_slice(b"Exif\x00\x00"); + a.extend_from_slice(tiff); + a +} + +/// #1991: a 600x900 px photo saved at 600 dpi places 1 x 1.5 in, not 600 x 900 pt. +#[test] +fn jpeg_jfif_density_sets_natural_size() { + let jpg = jpeg_with(&jfif_app(1, 600, 600)); + assert_eq!(pixel_size(&jpg), Some((600, 900))); + assert_eq!(raster_resolution(&jpg), Some((600.0, 600.0))); + assert_eq!(natural_size(&jpg), Some((72.0, 108.0))); + // Dots per cm convert to dpi; aspect-only JFIF (units 0) carries no density. + let cm = jpeg_with(&jfif_app(2, 100, 100)); + assert_eq!(raster_resolution(&cm), Some((254.0, 254.0))); + let aspect = jpeg_with(&jfif_app(0, 600, 600)); + assert_eq!(raster_resolution(&aspect), None); + assert_eq!(natural_size(&aspect), Some((600.0, 900.0))); +} + +#[test] +fn jpeg_exif_resolution_beats_jfif() { + // EXIF wins over a conflicting JFIF density. + let mut app = jfif_app(1, 72, 72); + app.extend_from_slice(&exif_app(&tiff_bytes((300, 1), (300, 1), Some(2)))); + let jpg = jpeg_with(&app); + assert_eq!(raster_resolution(&jpg), Some((300.0, 300.0))); + assert_eq!(natural_size(&jpg), Some((600.0 * 72.0 / 300.0, 900.0 * 72.0 / 300.0))); + // A missing unit defaults to inch; per-cm scales by 2.54. + let no_unit = jpeg_with(&exif_app(&tiff_bytes((300, 1), (300, 1), None))); + assert_eq!(raster_resolution(&no_unit), Some((300.0, 300.0))); + // A non-EXIF APP1 (XMP) before the EXIF one does not stop the scan. + let mut xmp = vec![0xFF, 0xE1]; + let xmp_payload = b"http://ns.adobe.com/xap/1.0/\x00"; + xmp.extend_from_slice(&((xmp_payload.len() + 2) as u16).to_be_bytes()); + xmp.extend_from_slice(xmp_payload); + xmp.extend_from_slice(&exif_app(&tiff_bytes((300, 1), (300, 1), Some(2)))); + assert_eq!(raster_resolution(&jpeg_with(&xmp)), Some((300.0, 300.0))); + let cm = jpeg_with(&exif_app(&tiff_bytes((100, 1), (100, 1), Some(3)))); + assert_eq!(raster_resolution(&cm), Some((254.0, 254.0))); + // A zero denominator or a missing axis is unusable: back to a pixel per point. + let zero = jpeg_with(&exif_app(&tiff_bytes((300, 0), (300, 1), Some(2)))); + assert_eq!(raster_resolution(&zero), None); +} + +/// Big-endian EXIF parses too. +#[test] +fn jpeg_exif_big_endian_parses() { + let mut t = vec![b'M', b'M', 0x00, 0x2A, 0x00, 0x00, 0x00, 0x08]; + t.extend_from_slice(&[0x00, 0x02]); + let mut entry = |tag: u16, val: u32| { + t.extend_from_slice(&tag.to_be_bytes()); + t.extend_from_slice(&5u16.to_be_bytes()); + t.extend_from_slice(&1u32.to_be_bytes()); + t.extend_from_slice(&val.to_be_bytes()); + }; + entry(0x011A, 38); + entry(0x011B, 46); + t.extend_from_slice(&[0, 0, 0, 0]); + assert_eq!(t.len(), 38); + for (num, den) in [(600u32, 2u32), (600u32, 2u32)] { + t.extend_from_slice(&num.to_be_bytes()); + t.extend_from_slice(&den.to_be_bytes()); + } + let jpg = jpeg_with(&exif_app(&t)); + assert_eq!(raster_resolution(&jpg), Some((300.0, 300.0))); + assert_eq!(natural_size(&jpg), Some((144.0, 216.0))); +} + +fn crc32(data: &[u8]) -> u32 { + let mut crc = 0xFFFF_FFFFu32; + for &b in data { + crc ^= b as u32; + for _ in 0..8 { + crc = if crc & 1 == 1 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 }; + } + } + !crc +} + +/// A real encoder-written PNG with a pHYs chunk spliced in after IHDR (valid CRC, so the +/// file stays fully decodable and exercises the real dimension path). +fn png_with_phys(ppu: u32) -> Vec { + let img = image::RgbaImage::from_pixel(600, 900, image::Rgba([30, 200, 30, 255])); + let mut b = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut b), image::ImageFormat::Png).unwrap(); + // Signature (8) + IHDR chunk (length 4 + type 4 + data 13 + CRC 4). + assert_eq!(&b[..8], b"\x89PNG\r\n\x1a\n"); + assert_eq!(&b[12..16], b"IHDR"); + let mut out = b[..33].to_vec(); + let mut phys = Vec::new(); + phys.extend_from_slice(&ppu.to_be_bytes()); + phys.extend_from_slice(&ppu.to_be_bytes()); + phys.push(1); + out.extend_from_slice(&(phys.len() as u32).to_be_bytes()); + out.extend_from_slice(b"pHYs"); + out.extend_from_slice(&phys); + let mut c = b"pHYs".to_vec(); + c.extend_from_slice(&phys); + out.extend_from_slice(&crc32(&c).to_be_bytes()); + out.extend_from_slice(&b[33..]); + out +} + +#[test] +fn png_phys_sets_natural_size() { + // 23622 px/m = 600 dpi: the photo places 1 x 1.5 in. + let png = png_with_phys(23622); + assert_eq!(pixel_size(&png), Some((600, 900))); + let (dx, _) = raster_resolution(&png).unwrap(); + assert!((dx - 600.0).abs() < 0.05, "{dx}"); + let (w, h) = natural_size(&png).unwrap(); + assert!((w - 72.0).abs() < 0.01 && (h - 108.0).abs() < 0.02, "{w} x {h}"); + // No pHYs: a pixel is a point. + let plain_img = image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 0, 0, 255])); + let mut plain = Vec::new(); + plain_img.write_to(&mut std::io::Cursor::new(&mut plain), image::ImageFormat::Png).unwrap(); + assert_eq!(raster_resolution(&plain), None); + assert_eq!(natural_size(&plain), Some((4.0, 4.0))); +} + +/// A real encoder-written BMP with the header pixels-per-meter patched (compression and image +/// size stay zero, as the encoder writes them). +fn bmp_with_ppm(ppm: i32) -> Vec { + let img = image::RgbaImage::from_pixel(600, 900, image::Rgba([30, 30, 200, 255])); + let mut b = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut b), image::ImageFormat::Bmp).unwrap(); + assert_eq!(&b[..2], b"BM"); + b[38..42].copy_from_slice(&ppm.to_le_bytes()); + b[42..46].copy_from_slice(&ppm.to_le_bytes()); + b +} + +#[test] +fn bmp_density_sets_natural_size() { + // 2835 px/m = 72 dpi: the bitmap keeps its pixel size in points. + let bmp = bmp_with_ppm(2835); + assert_eq!(pixel_size(&bmp), Some((600, 900))); + let (dx, _) = raster_resolution(&bmp).unwrap(); + assert!((dx - 72.0).abs() < 0.05, "{dx}"); + // 600 dpi (23622 px/m): the bitmap places 1 x 1.5 in. + let dense = bmp_with_ppm(23622); + let (w, h) = natural_size(&dense).unwrap(); + assert!((w - 72.0).abs() < 0.01 && (h - 108.0).abs() < 0.02, "{w} x {h}"); + // Zero density: no metadata, a pixel is a point. + let flat = bmp_with_ppm(0); + assert_eq!(raster_resolution(&flat), None); + assert_eq!(natural_size(&flat), Some((600.0, 900.0))); +} + +#[test] +fn tiff_resolution_tags_set_natural_size() { + use tiff::encoder::colortype::Gray8; + // A TIFF the encoder writes carries no density: pixels are points. + let mut plain = Vec::new(); + { + let mut enc = tiff::encoder::TiffEncoder::new(std::io::Cursor::new(&mut plain)).unwrap(); + enc.new_image::(6, 9).unwrap().write_data(&[0u8; 54]).unwrap(); + } + assert_eq!(pixel_size(&plain), Some((6, 9))); + assert_eq!(natural_size(&plain), Some((6.0, 9.0))); + // The hand-built tag body parses (300 dpi, inch default and explicit). + for unit in [None, Some(2)] { + let t = tiff_bytes((300, 1), (300, 1), unit); + assert_eq!(resolution::tiff_resolution(&t), Some((300.0, 300.0))); + } +} + #[test] fn bmp_decodes() { let mut bmp = Vec::new(); From 581af01d88dffdabb0b96393f08dbb61868d7f49 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:42:32 +0000 Subject: [PATCH 0922/1349] Apply review fixes - crates/images/src/resolution.rs --- crates/images/src/resolution.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/crates/images/src/resolution.rs b/crates/images/src/resolution.rs index ab1dc119f..3a04f5fef 100644 --- a/crates/images/src/resolution.rs +++ b/crates/images/src/resolution.rs @@ -31,7 +31,7 @@ pub fn raster_resolution(bytes: &[u8]) -> Option<(f64, f64)> { /// (a corrupt or hostile value falls back to 72 ppi at the call site). pub fn sane_resolution(dpi: (f64, f64)) -> bool { let (dx, dy) = dpi; - dx.is_finite() && dy.is_finite() && dx > 0.0 && dy > 0.0 && dx <= 100_000.0 && dy <= 100_000.0 + dx.is_finite() && dy.is_finite() && dx >= 1.0 && dy >= 1.0 && dx <= 100_000.0 && dy <= 100_000.0 } fn is_classic_tiff(bytes: &[u8]) -> bool { @@ -115,17 +115,17 @@ fn exif_resolution(payload: &[u8]) -> Option<(f64, f64)> { /// Classic TIFF resolution tags of the first IFD: XResolution/YResolution rationals scaled by /// ResolutionUnit (2 = inch, 3 = cm; a missing unit defaults to inch per the spec). pub fn tiff_resolution(tiff: &[u8]) -> Option<(f64, f64)> { - let le = match &tiff[..2] { + let le = match tiff.get(..2)? { b"II" => true, b"MM" => false, _ => return None, }; let u16at = |i: usize| -> Option { - let b: [u8; 2] = tiff.get(i..i + 2)?.try_into().ok()?; + let b: [u8; 2] = tiff.get(i..i.checked_add(2)?)?.try_into().ok()?; Some(if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) }) }; let u32at = |i: usize| -> Option { - let b: [u8; 4] = tiff.get(i..i + 4)?.try_into().ok()?; + let b: [u8; 4] = tiff.get(i..i.checked_add(4)?)?.try_into().ok()?; Some(if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) }) }; let ifd = u32at(4)? as usize; @@ -212,8 +212,12 @@ fn webp_resolution(bytes: &[u8]) -> Option<(f64, f64)> { if data.checked_add(size)? > end { return None; } - if kind == b"EXIF" && is_classic_tiff(bytes.get(data..data + size.min(4)).unwrap_or_default()) { - return tiff_resolution(&bytes[data..(data + size).min(bytes.len())]); + if kind == b"EXIF" { + let exif = bytes.get(data..data + size)?; + let tiff = exif.strip_prefix(b"Exif\x00\x00").unwrap_or(exif); + if is_classic_tiff(tiff) { + return tiff_resolution(tiff); + } } pos = data.checked_add(size.checked_add(size & 1)?)?; } From 0f1f51cbd43b561e7205744e1a42f318a45eefa3 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:17:26 +0000 Subject: [PATCH 0923/1349] Fix failing CI check - crates/images/src/resolution.rs --- crates/images/src/resolution.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/images/src/resolution.rs b/crates/images/src/resolution.rs index 3a04f5fef..c4a95e8e5 100644 --- a/crates/images/src/resolution.rs +++ b/crates/images/src/resolution.rs @@ -77,7 +77,9 @@ fn jpeg_resolution(bytes: &[u8]) -> Option<(f64, f64)> { let payload = &bytes[pos + 2..pos + len]; if m == 0xE0 && jfif.is_none() { jfif = jfif_density(payload); - } else if m == 0xE1 && let Some(dpi) = exif_resolution(payload) { + } else if m == 0xE1 + && let Some(dpi) = exif_resolution(payload) + { // A non-EXIF APP1 (XMP, ICC, ...) parses to nothing: keep scanning, since a // later APP1 can still carry the EXIF resolution. return Some(dpi); From d490e0fb185b472c82c5e320d77b66e7b262b8a0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 18:14:15 -0800 Subject: [PATCH 0924/1349] Data merge: a QR field at a text insertion point is refused instead of written as text Insert Field with a QR column and the text cursor in a frame added a text placeholder, so a merge wrote the QR payload as plain text. It now returns "qr placeholders bind to a frame" and leaves the story unchanged. --- crates/engine/src/cmd/datamerge.rs | 3 +++ crates/engine/src/cmd/datamerge/tests.rs | 14 ++++++++++++++ docs/agents.md | 7 ++++--- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/datamerge.rs b/crates/engine/src/cmd/datamerge.rs index 6fac73836..411fd545c 100644 --- a/crates/engine/src/cmd/datamerge.rs +++ b/crates/engine/src/cmd/datamerge.rs @@ -503,6 +503,9 @@ fn add_placeholder(d: &mut Document, sel: &Selection, p: &Value, name: &str) -> } else if field.kind == DataFieldKind::Image { // An image field at the insertion point places the image inline in the text. PlaceholderRole::Image + } else if field.kind == DataFieldKind::Qr { + // A QR field at the insertion point is refused below: QR codes bind to a frame. + PlaceholderRole::Qr } else { PlaceholderRole::Text }; diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index 8ca5291a6..39b1988e2 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -817,6 +817,20 @@ fn an_image_field_at_the_insertion_point_merges_as_an_inline_image() { assert!((wide.1 - width).abs() < 0.01 && (wide.2 - width / 8.0).abs() < 0.01, "a wide image is scaled down to the frame: {wide:?}"); } +/// A QR field at a text insertion point is refused instead of merging its payload as text. +#[test] +fn a_qr_field_at_the_insertion_point_is_refused() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "@Photo,#Code\n/x.png,hello\n"); + let made = text_frame(&mut s, [36.0, 36.0, 300.0, 300.0], "Hi ", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 3, "focus": 3})); + let msg = err(&mut s, "data.placeholder.add", json!({"field": "Code"})); + assert!(msg.contains("bind to a frame"), "{msg}"); + assert_eq!(texts(&s), vec!["Hi ".to_string()]); + assert!(s.documents()[0].doc.data_merge.placeholders.is_empty()); +} + /// A typed `<>` marker for an image column places the image too, from an absolute path; /// an explicit text role still writes the path as text. #[test] diff --git a/docs/agents.md b/docs/agents.md index d2f416c83..13977d2af 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -90,9 +90,10 @@ external PDF/X certification. `data.source.remove` drops it); `data.fields` lists its fields. `data.placeholder.add {field, role?, story?, at?, end?, item?}` marks text or a frame as a field (`role`: text, image, qr, hyperlink). An image field (a `@` column) inserted at a text insertion point, or typed there as `<>`, merges as an inline image at its natural size, scaled down to fit the -frame. An image path is absolute or relative to the data file's folder, then the document's; a path that starts with -one separator (`\Photos\a.jpg`) is tried from the drive's root first. `data.options` sets records, tiling and image -fitting; `data.preview {record}` / `data.preview.stop` show one record without saving it. +frame. A QR field (a `#` column) inserted at a text insertion point is refused; bind it to a frame instead. An image +path is absolute or relative to the data file's folder, then the document's; a path that starts with one separator +(`\Photos\a.jpg`) is tried from the drive's root first. `data.options` sets records, tiling and image fitting; +`data.preview {record}` / `data.preview.stop` show one record without saving it. `data.merge` now **creates a new document** and leaves the template unchanged (the old `spread` parameter, which appended pages to the template, is an error). It uses the linked source, or inline `csv` / `rows` / `path` / `bytes`: From c8136c538ba91a6b977bc83ee15de87fd2bd1623 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 18:20:51 -0800 Subject: [PATCH 0925/1349] Place: an unusable EXIF resolution falls back to the JFIF density A JPEG whose EXIF resolution is 0 ppi or outside 1 to 100,000 ppi now takes its size from its JFIF density instead of one point per pixel. Tests place an 11 x 17 in image (330 x 510 px at 30 ppi) with a click, check that it comes in at 792 x 1224 pt and keeps that size through a save and reopen, and that an image with no stored resolution comes in at 72 ppi. --- crates/engine/src/cmd/file/place.rs | 84 +++++++++++++++++++++++------ crates/images/src/lib.rs | 4 +- crates/images/src/resolution.rs | 10 ++-- crates/images/src/tests.rs | 13 +++++ crates/render/src/decode.rs | 2 +- 5 files changed, 88 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index 29358d834..e0d285702 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -589,10 +589,8 @@ pub(super) mod image_place_tests { } } - #[test] - fn placed_photo_honors_its_embedded_resolution() { - // #1991: a placed graphic's embedded density sets its size (600 dpi: 40 px place - // 4.8 pt wide), instead of a pixel always becoming a point. + /// A `width` x `height` PNG with a pHYs chunk of `ppm` pixels per meter on both axes, or none. + fn png_with_density(width: u32, height: u32, ppm: Option) -> std::io::Result { fn crc32(data: &[u8]) -> u32 { let mut crc = 0xFFFF_FFFFu32; for &b in data { @@ -603,22 +601,33 @@ pub(super) mod image_place_tests { } !crc } - let png = designcraft_render::Rendered { width: 40, height: 20, pixels: [30, 90, 180, 255].repeat(800) }.to_png(); + let pixels = [30, 90, 180, 255].repeat((width * height) as usize); + let png = designcraft_render::Rendered { width, height, pixels }.to_png(); assert_eq!(&png[12..16], b"IHDR"); - let mut phys = Vec::new(); - phys.extend_from_slice(&23622u32.to_be_bytes()); - phys.extend_from_slice(&23622u32.to_be_bytes()); - phys.push(1); let mut bytes = png[..33].to_vec(); - bytes.extend_from_slice(&(phys.len() as u32).to_be_bytes()); - bytes.extend_from_slice(b"pHYs"); - bytes.extend_from_slice(&phys); - let mut c = b"pHYs".to_vec(); - c.extend_from_slice(&phys); - bytes.extend_from_slice(&crc32(&c).to_be_bytes()); + if let Some(ppm) = ppm { + let mut phys = Vec::new(); + phys.extend_from_slice(&ppm.to_be_bytes()); + phys.extend_from_slice(&ppm.to_be_bytes()); + phys.push(1); + bytes.extend_from_slice(&(phys.len() as u32).to_be_bytes()); + bytes.extend_from_slice(b"pHYs"); + bytes.extend_from_slice(&phys); + let mut c = b"pHYs".to_vec(); + c.extend_from_slice(&phys); + bytes.extend_from_slice(&crc32(&c).to_be_bytes()); + } bytes.extend_from_slice(&png[33..]); - let file = tempfile::Builder::new().suffix(".png").tempfile().unwrap(); - std::fs::write(file.path(), bytes).unwrap(); + let file = tempfile::Builder::new().suffix(".png").tempfile()?; + std::fs::write(file.path(), bytes)?; + Ok(file) + } + + #[test] + fn placed_photo_honors_its_embedded_resolution() { + // #1991: a placed graphic's embedded density sets its size (600 dpi: 40 px place + // 4.8 pt wide), instead of a pixel always becoming a point. + let file = png_with_density(40, 20, Some(23622)).unwrap(); let mut session = Session::new(); session.execute("file.new", &json!({})).unwrap(); let placed = session.execute("file.place", &json!({"path": file.path(), "x": 10.0, "y": 20.0})).unwrap(); @@ -629,6 +638,47 @@ pub(super) mod image_place_tests { assert!((b.width() - 4.8).abs() < 0.01 && (b.height() - 2.4).abs() < 0.01, "{b:?}"); } + /// File › Place, then a click: an 11 x 17 in image (330 x 510 px at 30 ppi) comes in at + /// 792 x 1224 pt, keeps that size through a save and reopen, and an image with no stored + /// resolution comes in at 72 ppi (330 x 510 pt). + #[test] + fn a_clicked_image_keeps_its_print_size_through_save_and_reopen() { + // 1181 pixels per meter is 29.9974 ppi. + let (w, h) = (330.0 * 72.0 / (1181.0 * 0.0254), 510.0 * 72.0 / (1181.0 * 0.0254)); + for (ppm, (ew, eh)) in [(Some(1181), (w, h)), (None, (330.0, 510.0))] { + let image = png_with_density(330, 510, ppm).unwrap(); + let mut session = Session::new(); + session.execute("file.new", &json!({})).unwrap(); + session.execute("file.place", &json!({"path": image.path(), "loadCursor": true})).unwrap(); + session.execute("place.drop", &json!({"x": 0, "y": 0})).unwrap(); + // The bounds and natural size of the document's one placed graphic. + let shown = |session: &Session| { + let doc = &session.doc().unwrap().doc; + let graphics: Vec<_> = doc + .all_items() + .into_iter() + .filter_map(|id| doc.item(id)) + .filter_map(|item| match &item.content { + Content::Graphic(g) => Some((item.bounds(), g.size)), + _ => None, + }) + .collect(); + assert_eq!(graphics.len(), 1, "{graphics:?}"); + graphics[0] + }; + let (b, size) = shown(&session); + assert!((b.width() - ew).abs() < 1e-6 && (b.height() - eh).abs() < 1e-6, "{ppm:?}: {b:?}"); + assert!((size.0 - ew).abs() < 1e-6 && (size.1 - eh).abs() < 1e-6, "{ppm:?}: {size:?}"); + + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("placed.designcraft"); + session.execute("file.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let mut reopened = Session::new(); + reopened.execute("file.open", &json!({"path": path.to_string_lossy()})).unwrap(); + assert_eq!(shown(&reopened), (b, size), "{ppm:?}"); + } + } + #[test] fn explicit_frame_wins_over_placement_and_selection() { let image = image_file().unwrap(); diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 7540eee90..b32be1063 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -374,8 +374,8 @@ pub fn natural_size(bytes: &[u8]) -> Option<(f64, f64)> { return Some((bb[2] - bb[0], bb[3] - bb[1])).filter(|(w, h)| w.is_finite() && h.is_finite() && *w > 0.0 && *h > 0.0); } let (w, h) = pixel_size(bytes)?; - // Honor the file's density (#1991): a 600 px photo saved at 600 dpi places one inch wide, - // as in InDesign. Absurd metadata falls back to a pixel per point. + // Honor the file's density (#1991): a 600 px photo saved at 600 dpi places one inch wide. + // Absurd metadata falls back to a pixel per point. match raster_resolution(bytes) { Some(dpi) if resolution::sane_resolution(dpi) => Some((w as f64 * 72.0 / dpi.0, h as f64 * 72.0 / dpi.1)), _ => Some((w as f64, h as f64)), diff --git a/crates/images/src/resolution.rs b/crates/images/src/resolution.rs index c4a95e8e5..dabaf1c61 100644 --- a/crates/images/src/resolution.rs +++ b/crates/images/src/resolution.rs @@ -1,6 +1,6 @@ //! Embedded raster resolution: the density a placed graphic was saved with, so placing honors -//! it instead of assuming 72 ppi (#1991: a 600 px photo saved at 600 dpi places one inch wide, -//! as in InDesign). Reads JFIF/EXIF from JPEG (and EXIF from WebP), pHYs from PNG, the resolution +//! it instead of assuming 72 ppi (#1991: a 600 px photo saved at 600 dpi places one inch wide). +//! Reads JFIF/EXIF from JPEG (and EXIF from WebP), pHYs from PNG, the resolution //! tags from TIFF, and the header density from BMP. GIF, PSD and files without (usable) metadata //! report nothing and keep the pixel-is-a-point size. @@ -78,10 +78,10 @@ fn jpeg_resolution(bytes: &[u8]) -> Option<(f64, f64)> { if m == 0xE0 && jfif.is_none() { jfif = jfif_density(payload); } else if m == 0xE1 - && let Some(dpi) = exif_resolution(payload) + && let Some(dpi) = exif_resolution(payload).filter(|dpi| sane_resolution(*dpi)) { - // A non-EXIF APP1 (XMP, ICC, ...) parses to nothing: keep scanning, since a - // later APP1 can still carry the EXIF resolution. + // A non-EXIF APP1 (XMP, ICC, ...) or an unusable EXIF density parses to nothing: + // keep scanning, so a later APP1 or the JFIF density still sets the size. return Some(dpi); } pos += len; diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index 917693f87..f2fcf2bf0 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -537,6 +537,19 @@ fn jpeg_exif_resolution_beats_jfif() { assert_eq!(raster_resolution(&zero), None); } +/// An EXIF density of 0 ppi (or any value outside the usable range) does not hide the JFIF +/// density: the 600x900 px photo at a JFIF 300 dpi still places 144 x 216 pt. +#[test] +fn unusable_exif_density_keeps_the_jfif_density() { + for exif in [(0, 1), (1, 4), (1_000_000, 1)] { + let mut app = jfif_app(1, 300, 300); + app.extend_from_slice(&exif_app(&tiff_bytes(exif, exif, Some(2)))); + let jpg = jpeg_with(&app); + assert_eq!(raster_resolution(&jpg), Some((300.0, 300.0)), "EXIF {exif:?}"); + assert_eq!(natural_size(&jpg), Some((144.0, 216.0)), "EXIF {exif:?}"); + } +} + /// Big-endian EXIF parses too. #[test] fn jpeg_exif_big_endian_parses() { diff --git a/crates/render/src/decode.rs b/crates/render/src/decode.rs index 135dbf108..df8e1f047 100644 --- a/crates/render/src/decode.rs +++ b/crates/render/src/decode.rs @@ -87,7 +87,7 @@ pub fn image_size(bytes: &[u8]) -> Option<(u32, u32)> { } /// Natural size of a placed graphic, unrounded: a PDF page (crop box) and an SVG in points, a raster -/// in pixels, an EPS its bounding box independently of preview pixels. Placed graphics are drawn at +/// at its stored resolution (72 ppi without one), an EPS its bounding box independently of preview pixels. Placed graphics are drawn at /// this size; `image_size` rounds it to whole pixels for display. pub fn natural_size(bytes: &[u8], page: usize) -> Option<(f64, f64)> { if is_pdf(bytes) { From 293fe55a4d9c1841b8dea9cae4b3162b5d1280e3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 18:25:01 -0800 Subject: [PATCH 0926/1349] Text Frame Options: test the four sides for a mixed selection An oval selected first with a rectangle shows the four side fields, and a changed top inset leaves the rectangle's other sides as they were. --- crates/ui-egui/src/dialogs/tests.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index a11bd2f3f..8f1681611 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1486,6 +1486,34 @@ fn text_frame_options_set_one_inset_for_a_non_rectangular_frame() { assert_eq!(d.s("inset"), "0p6"); } +/// A selection that mixes a non-rectangular frame with a rectangle shows the four sides, even with +/// the oval first, and a changed side leaves the rectangle's other sides as they were. +#[test] +fn text_frame_options_show_four_sides_for_a_mixed_selection() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let oval = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "shape": "ellipse", "content": "text", "text": "Hello"})).unwrap(); + let oval = designcraft_doc::ItemId(oval["id"].as_u64().unwrap()); + let rect = app.run("frame.create", json!({"rect": [36, 300, 336, 500], "content": "text", "text": "Hello"})).unwrap(); + let rect = designcraft_doc::ItemId(rect["id"].as_u64().unwrap()); + app.run("object.textFrameOptions", json!({"ids": [oval.0, rect.0], "inset": [6, 2, 3, 4]})).unwrap(); + let opts = |app: &DesignApp, id| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.clone(); + app.run("selection.set", json!({"ids": [oval.0, rect.0]})).unwrap(); + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(&app, &mut d); + assert!(!d.b("_shaped") && !d.fields.contains_key("inset"), "a mixed selection shows the four sides"); + d.fields.insert("insetTop".into(), json!("1p0")); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + assert_eq!(opts(&app, rect).inset, [12.0, 2.0, 3.0, 4.0]); + assert_eq!(opts(&app, oval).inset, [12.0, 2.0, 3.0, 4.0]); + // Two non-rectangular frames still show the one Inset. + app.run("object.cornerOptions", json!({"ids": [rect.0], "shape": "rounded", "size": 12})).unwrap(); + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(&app, &mut d); + assert!(d.b("_shaped")); +} + /// The dialog dims Top, Left, Bottom, Right and the link for a non-rectangular frame and adds an /// Inset field; for a rectangle it shows no Inset field and the sides stay editable. #[test] From 0db4ba3dd426834935aa8a9c300aa346b61c58ad Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 18:39:10 -0800 Subject: [PATCH 0927/1349] Text Frame Options: the dialog is one row taller for a non-rectangular frame The Inset row made the General tab taller than the dialog's fixed height, so the buttons moved when switching tabs. The fixed height now includes that row. --- crates/ui-egui/src/dialogs.rs | 8 +++++--- crates/ui-egui/src/dialogs/tests.rs | 8 ++++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6335f8fca..702c6bcc2 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1106,9 +1106,11 @@ fn text_frame_options_dialog(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) } ui.set_min_width(560.0); ui.horizontal_top(|ui| { - // A fixed height: the separator would otherwise stretch the dialog to the window. - ui.set_min_height(330.0); - ui.set_max_height(330.0); + // A fixed height: the separator would otherwise stretch the dialog to the window. A + // non-rectangular frame's Inset row needs one more row. + let height = if d.b("_shaped") { 360.0 } else { 330.0 }; + ui.set_min_height(height); + ui.set_max_height(height); section_list( &lang, ui, diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 8f1681611..38ffc28cb 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1549,6 +1549,14 @@ fn text_frame_options_dims_the_sides_for_a_non_rectangular_frame() { } assert_eq!(h.query_by_label("Inset:").is_some(), shaped, "{shape}: the Inset caption"); assert_eq!(h.query_by_label("Increase tfo_inset").is_some(), shaped, "{shape}: the Inset field"); + // The General tab fits in the dialog's fixed height: the buttons stay put on another tab. + let (wrap, cancel) = (h.get_by_label("Ignore Text Wrap").rect().bottom(), h.get_by_label("Cancel").rect().top()); + assert!(wrap < cancel, "{shape}: Ignore Text Wrap ends at {wrap}, below the top of Cancel at {cancel}"); + h.get_by_label("Auto-Size").click(); + h.run_steps(3); + assert_eq!(h.get_by_label("Cancel").rect().top(), cancel, "{shape}: the buttons stay put on another tab"); + h.get_by_label("General").click(); + h.run_steps(3); // The link toggles only for a rectangle. let linked = |h: &Harness<'_, DesignApp>| h.state().ui.dialog.as_ref().unwrap().b("insetLinked"); let before = linked(&h); From 510269744ac3cc0b9bd9a3bab307ce30d5bf7b65 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 18:21:39 -0800 Subject: [PATCH 0928/1349] Text: Text Frame Options open from the Type tool and change the frame holding the caret Object > Text Frame Options and Cmd+B are enabled with a text caret or a text selection. Without ids or selected objects, object.textFrameOptions changes the frame that shows the insertion point, or every frame that holds part of the selected text, instead of every frame of the story. The dialog shows that frame's options and keeps the frames it opened with while the preview reflows the text. An empty ids list and an id that is not in the document are refused. Options a frame already has leave the document unchanged and add no undo step. Fixes #2396 --- ROADMAP.md | 1 + crates/engine/src/cmd.rs | 1 + crates/engine/src/cmd/object.rs | 267 +++++++++++++++++++++++++++++- crates/ui-egui/src/dialogs.rs | 73 ++++++-- crates/ui-egui/src/menus/tests.rs | 27 +++ docs/mcp.md | 9 + docs/target-app-parity.md | 1 + 7 files changed, 359 insertions(+), 20 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 006396b1d..42a160c94 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -387,6 +387,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log +- **2026-11-12** · Object › Text Frame Options… (Cmd+B) opens with the Type tool in a frame, so inset spacing and vertical justification can be changed while typing; it changes the frame that shows the insertion point, or every frame that holds part of the selected text (#2396). No readiness percentage change. - **2026-11-04** · Striped strokes retain out-and-back cubic segments whose second control point is away from the coincident endpoints and first control point. A geometry regression checks the offset extent and both stripe bands. No readiness percentage change. - **2026-11-04** · Esperanto is a text language (Character › Language, `type.char {language: "Esperanto"}`, IDML `$ID/Esperanto`): tag `eo`, English-style quotes; not hyphenated yet (#1201). No readiness percentage change. diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index dc1acaf15..4fdd375e0 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -41,6 +41,7 @@ mod mathexpr; mod media; mod notes; mod object; +pub use object::text_frame_options_frames; mod overrides; mod package; pub mod params; diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 634c90a61..67b1d21d4 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -610,8 +610,8 @@ pub fn specs() -> Vec { "Text Frame Options…", ["Object"], Some("Cmd+B"), - "{columns?, gutter?, inset?: number|[t,l,b,r] (null keeps that side), verticalJustification?: top|center|bottom|justify, paragraphSpacingLimit? (pt: Justify adds at most this between paragraphs, the rest between lines), columnsKind?: fixedNumber|fixedWidth, columnWidth? (pt, Fixed Width), firstBaseline?: ascent|capHeight|leading|xHeight|emboxHeight|fixed, firstBaselineMin? (pt), autoSize?: off|heightOnly|widthOnly|heightAndWidth|heightAndWidthProportionally, autoSizeReference?: topLeft|topCenter|topRight|leftCenter|center|rightCenter|bottomLeft|bottomCenter|bottomRight (the point that stays put), useMinimumHeight?: bool, minimumHeight? (pt), useMinimumWidth?: bool, minimumWidth? (pt), noLineBreaks?: bool, ignoreWrap?, balanceColumns?, columnRule?: bool, columnRuleWeight? (pt), columnRuleColor? (swatch name), columnRuleTint? (0..1), columnRuleOffset? (pt, horizontal), columnRuleTopInset? (pt), columnRuleBottomInset? (pt), baselineGrid?: {start? (pt), increment? (pt), relativeTo?: page|margin|frame|inset} (the frame's custom baseline grid; fields not given keep the frame's, or come from the document grid; null turns it off), vertical?: bool (sets the story direction of the frames' stories, as Type ▸ Story Direction), ids?}", - has_selection, + "{columns?, gutter?, inset?: number|[t,l,b,r] (null keeps that side), verticalJustification?: top|center|bottom|justify, paragraphSpacingLimit? (pt: Justify adds at most this between paragraphs, the rest between lines), columnsKind?: fixedNumber|fixedWidth, columnWidth? (pt, Fixed Width), firstBaseline?: ascent|capHeight|leading|xHeight|emboxHeight|fixed, firstBaselineMin? (pt), autoSize?: off|heightOnly|widthOnly|heightAndWidth|heightAndWidthProportionally, autoSizeReference?: topLeft|topCenter|topRight|leftCenter|center|rightCenter|bottomLeft|bottomCenter|bottomRight (the point that stays put), useMinimumHeight?: bool, minimumHeight? (pt), useMinimumWidth?: bool, minimumWidth? (pt), noLineBreaks?: bool, ignoreWrap?, balanceColumns?, columnRule?: bool, columnRuleWeight? (pt), columnRuleColor? (swatch name), columnRuleTint? (0..1), columnRuleOffset? (pt, horizontal), columnRuleTopInset? (pt), columnRuleBottomInset? (pt), baselineGrid?: {start? (pt), increment? (pt), relativeTo?: page|margin|frame|inset} (the frame's custom baseline grid; fields not given keep the frame's, or come from the document grid; null turns it off), vertical?: bool (sets the story direction of the frames' stories, as Type ▸ Story Direction), ids? (without ids or selected objects: the frame showing the text caret, or every frame holding part of the selected text)}", + has_selection_or_text, text_frame_options ), cmd!( @@ -2569,14 +2569,38 @@ fn content_type(s: &mut Session, p: &Value) -> Result { }) } +/// The frames `object.textFrameOptions` changes when the call names none: the selected objects, +/// or with the Type tool the frame that shows the caret or every frame holding part of the +/// selected text. +pub fn text_frame_options_frames(s: &Session) -> Vec { + let Ok(st) = s.doc() else { return Vec::new() }; + if !st.selection.items.is_empty() { + return st.selection.items.clone(); + } + st.selection.text.map(|t| text_selection_frames(s, &t)).unwrap_or_default() +} + +/// Text Frame Options act on the selected objects, or with the Type tool on the frames that hold +/// the caret or the selected text. +fn has_selection_or_text(s: &Session) -> std::result::Result<(), String> { + if s.active().is_some_and(|d| d.selection.text.is_some()) { + return Ok(()); + } + has_selection(s) +} + fn text_frame_options(s: &mut Session, p: &Value) -> Result { const ID: &str = "object.textFrameOptions"; let st = s.doc()?; - let mut ids = targets(s, p)?; - if ids.is_empty() - && let Some(t) = st.selection.text - { - ids = st.doc.story(t.story).map(|s| s.frames.clone()).unwrap_or_default(); + // A call that names its objects acts on those; an empty `ids` names nothing. + let named = p.get("ids").is_some() || p.get("id").is_some(); + let ids = if named { targets(s, p)? } else { text_frame_options_frames(s) }; + // With a text caret the command runs before named objects are checked. + if let Some(gone) = ids.iter().find(|i| st.doc.item(**i).is_none()) { + return Err(bad(ID, format!("no object with id {}", gone.0))); + } + if ids.is_empty() { + return Err(bad(ID, super::NOTHING_SELECTED)); } let ranged = |key: &str, lo: f64, hi: f64, what: &str| match p.get(key) { None | Some(Value::Null) => Ok(None), @@ -2644,8 +2668,10 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { Some(Value::String(c)) if st.doc.swatch(c).is_some() => Some(c.clone()), Some(v) => return Err(bad(ID, format!("no swatch {v}"))), }; + let (before, revision) = (Arc::clone(&st.doc), st.revision); + let find = s.find_context.take(); let p = p.clone(); - s.edit(|d, _| { + let edited = s.edit(|d, _| { for id in &ids { let Some(tf) = d.item_mut(*id).and_then(Item::text_frame_mut) else { continue }; let o = &mut tf.options; @@ -2738,6 +2764,7 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { if fixed_width && ["columnsKind", "columnWidth", "columns", "gutter", "inset"].iter().any(|k| p.get(*k).is_some()) && let Some(r) = d.item(*id).map(Item::inner_bounds) + && ((r.width() - width).abs() >= 1e-9 || !width.is_finite()) { let r = super::finite_rect("object.textFrameOptions", Rect::new(r.x0, r.y0, r.x0 + width, r.y1))?; crate::autosize::resize(d, *id, r); @@ -2749,7 +2776,71 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { super::text::set_story_direction(d, &stories, v); } Ok(json!({"changed": ids.len()})) - }) + }); + let changed = match edited { + Ok(v) => v, + Err(e) => { + s.find_context = find; + return Err(e); + } + }; + // Options the frames already have: the document, its revision and the Find Next scope go back + // to what they were, which leaves no undo step. Only the frames and their stories are compared. + let st = s.doc_mut()?; + let same = ids.iter().all(|id| { + let (now, was) = (st.doc.item(*id), before.item(*id)); + now == was && now.and_then(Item::text_frame).is_none_or(|t| st.doc.story(t.story) == before.story(t.story)) + }); + if same { + st.doc = before; + st.revision = revision; + s.find_context = find; + return Ok(json!({"changed": 0})); + } + Ok(changed) +} + +/// The frames Text Frame Options acts on from the Type tool: the frame that shows the caret, or +/// every frame that holds part of the selected text. Text past the last frame counts as the last +/// frame's. +fn text_selection_frames(s: &Session, t: &TextSel) -> Vec { + let Ok(st) = s.doc() else { return Vec::new() }; + let Some(story) = st.doc.story(t.story) else { return Vec::new() }; + let last = story.frames.last().copied(); + // In a table cell, `anchor` and `focus` index the cell's text: the frame the caret is shown in. + if t.cell.is_some() { + return t.frame.filter(|f| story.frames.contains(f)).or(last).into_iter().collect(); + } + let cs = s.cache.get(&st.doc, t.story, None); + let r = t.range(); + // The frame the caret at the start is drawn in; the caret's stored frame only when no line + // holds it. + let caret_frame = || { + designcraft_compose::caret(&cs, r.start) + .and_then(|(fi, ..)| cs.frames.get(fi)) + .map(|f| f.frame) + .or_else(|| t.frame.filter(|f| story.frames.contains(f) && cs.overset_at.is_none_or(|o| r.start < o))) + }; + // A frame's range stops before the paragraph return that ends its last line; the return + // belongs to that frame. + let end_of = |f: &designcraft_compose::FrameText| f.range.end + usize::from(story.text.as_bytes().get(f.range.end) == Some(&b'\n')); + let mut frames: Vec = if t.is_caret() { + caret_frame().into_iter().collect() + } else { + cs.frames.iter().filter(|f| f.range.start < r.end && r.start < end_of(f)).map(|f| f.frame).collect() + }; + // Selected text no frame holds goes with the line before it. + if frames.is_empty() { + frames.extend(caret_frame()); + } + let overset = cs.overset_at.is_some_and(|o| r.end > o); + if let Some(l) = last + && (frames.is_empty() || overset) + && !frames.contains(&l) + { + frames.push(l); + } + frames } fn apply_custom_frame_grid( @@ -4820,6 +4911,7 @@ mod named_target_tests { s.execute("file.new", &json!({})).unwrap(); let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "Hello"})).unwrap(); assert!(s.doc().unwrap().selection.items.is_empty(), "frame.create leaves a text caret"); + s.execute("edit.deselectAll", &json!({})).unwrap(); let e = s.execute("object.textFrameOptions", &json!({"columns": 2})).unwrap_err().to_string(); assert!(e.contains("nothing selected"), "{e}"); s.execute("object.textFrameOptions", &json!({"ids": [r["id"]], "columns": 2})).unwrap(); @@ -4839,6 +4931,163 @@ mod named_target_tests { } } +#[cfg(test)] +mod type_tool_frame_options_tests { + use super::*; + use designcraft_doc::VerticalJustification; + + /// One story threaded through two frames, with text in both: (first frame, second frame, story). + fn two_frame_thread(s: &mut Session) -> (ItemId, ItemId, StoryId) { + s.execute("file.new", &json!({})).unwrap(); + let text = (0..40).map(|i| format!("Line {i} of the threaded story.")).collect::>().join(" "); + let a = s.execute("frame.create", &json!({"rect": [36, 36, 300, 120], "content": "text", "text": text})).unwrap(); + let b = s.execute("frame.create", &json!({"rect": [36, 200, 300, 700], "content": "text", "text": ""})).unwrap(); + let (a, b) = (ItemId(a["id"].as_u64().unwrap()), ItemId(b["id"].as_u64().unwrap())); + s.execute("text.thread", &json!({"from": a.0, "to": b.0})).unwrap(); + let sid = s.doc().unwrap().doc.item(a).and_then(Item::text_frame).unwrap().story; + (a, b, sid) + } + + /// The story bytes `frame` shows. + fn shown(s: &Session, sid: StoryId, frame: ItemId) -> std::ops::Range { + let cs = designcraft_compose::compose_story(&s.doc().unwrap().doc, sid, &Default::default()); + cs.frame(frame).unwrap().range.clone() + } + + fn options(s: &Session, id: ItemId) -> TextFrameOptions { + s.doc().unwrap().doc.item(id).and_then(Item::text_frame).unwrap().options.clone() + } + + fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() + } + + /// With the Type tool, Text Frame Options change the frame that shows the caret, not every + /// frame of the story. + #[test] + fn a_caret_changes_the_frame_it_is_in() { + let mut s = Session::new(); + let (a, b, sid) = two_frame_thread(&mut s); + let (ra, rb) = (shown(&s, sid, a), shown(&s, sid, b)); + assert!(!ra.is_empty() && !rb.is_empty(), "both frames hold text: {ra:?} {rb:?}"); + s.execute("text.select", &json!({"story": sid.0, "anchor": rb.start + 2})).unwrap(); + assert!(s.doc().unwrap().selection.items.is_empty()); + let steps = undo_steps(&s); + s.execute("object.textFrameOptions", &json!({"columns": 3, "verticalJustification": "center", "inset": 6})).unwrap(); + assert_eq!( + (options(&s, b).columns, options(&s, b).vertical_justification, options(&s, b).inset), + (3, VerticalJustification::Center, [6.0; 4]) + ); + assert_eq!((options(&s, a).columns, options(&s, a).vertical_justification), (1, VerticalJustification::Top), "the first frame is left alone"); + assert_eq!(undo_steps(&s), steps + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(options(&s, b).columns, 1); + // A caret in the first frame changes the first frame. + s.execute("text.select", &json!({"story": sid.0, "anchor": ra.start + 2})).unwrap(); + s.execute("object.textFrameOptions", &json!({"verticalJustification": "bottom"})).unwrap(); + assert_eq!( + (options(&s, a).vertical_justification, options(&s, b).vertical_justification), + (VerticalJustification::Bottom, VerticalJustification::Top) + ); + } + + /// A caret moved to the start of the second frame keeps the first frame as its stored frame; + /// the options go to the frame the caret is drawn in. + #[test] + fn a_caret_at_a_frame_boundary_changes_the_frame_it_is_drawn_in() { + let mut s = Session::new(); + let (a, b, sid) = two_frame_thread(&mut s); + let rb = shown(&s, sid, b); + let cs = designcraft_compose::compose_story(&s.doc().unwrap().doc, sid, &Default::default()); + let drawn = designcraft_compose::caret(&cs, rb.start).and_then(|(fi, ..)| cs.frames.get(fi)).map(|f| f.frame); + assert_eq!(drawn, Some(b), "the caret at the boundary is drawn in the second frame"); + s.doc_mut().unwrap().selection = Selection::text(TextSel { story: sid, anchor: rb.start, focus: rb.start, frame: Some(a), cell: None }); + s.execute("object.textFrameOptions", &json!({"columns": 2})).unwrap(); + assert_eq!((options(&s, a).columns, options(&s, b).columns), (1, 2)); + } + + /// Selected text that runs from one frame into the next changes both frames. + #[test] + fn selected_text_changes_every_frame_it_runs_through() { + let mut s = Session::new(); + let (a, b, sid) = two_frame_thread(&mut s); + let (ra, rb) = (shown(&s, sid, a), shown(&s, sid, b)); + s.execute("text.select", &json!({"story": sid.0, "anchor": ra.end - 3, "focus": rb.start + 3})).unwrap(); + s.execute("object.textFrameOptions", &json!({"columns": 2})).unwrap(); + assert_eq!((options(&s, a).columns, options(&s, b).columns), (2, 2)); + // Text inside one frame changes that frame only. + s.execute("text.select", &json!({"story": sid.0, "anchor": rb.start + 1, "focus": rb.start + 6})).unwrap(); + s.execute("object.textFrameOptions", &json!({"columns": 4})).unwrap(); + assert_eq!((options(&s, a).columns, options(&s, b).columns), (2, 4)); + } + + /// A selected paragraph return at the end of the first frame changes the first frame. + #[test] + fn a_selected_return_at_the_end_of_a_frame_changes_that_frame() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let text = (0..40).map(|i| format!("Paragraph {i}")).collect::>().join("\n"); + let a = s.execute("frame.create", &json!({"rect": [36, 36, 300, 120], "content": "text", "text": text})).unwrap(); + let b = s.execute("frame.create", &json!({"rect": [36, 200, 300, 700], "content": "text", "text": ""})).unwrap(); + let (a, b) = (ItemId(a["id"].as_u64().unwrap()), ItemId(b["id"].as_u64().unwrap())); + s.execute("text.thread", &json!({"from": a.0, "to": b.0})).unwrap(); + let sid = s.doc().unwrap().doc.item(a).and_then(Item::text_frame).unwrap().story; + let (ra, rb) = (shown(&s, sid, a), shown(&s, sid, b)); + assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text.as_bytes()[ra.end], b'\n', "the first frame ends before a return"); + assert_eq!(rb.start, ra.end + 1, "the second frame starts after it"); + s.execute("text.select", &json!({"story": sid.0, "anchor": ra.end, "focus": ra.end + 1})).unwrap(); + s.execute("object.textFrameOptions", &json!({"columns": 2})).unwrap(); + assert_eq!((options(&s, a).columns, options(&s, b).columns), (2, 1)); + // From that return into the second frame, with the first frame back as it was: both frames. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((shown(&s, sid, a), shown(&s, sid, b)), (ra.clone(), rb.clone())); + s.execute("text.select", &json!({"story": sid.0, "anchor": ra.end, "focus": rb.start + 3})).unwrap(); + s.execute("object.textFrameOptions", &json!({"columns": 3})).unwrap(); + assert_eq!((options(&s, a).columns, options(&s, b).columns), (3, 3)); + } + + /// An empty `ids` names no frame, so it does not fall back to the caret's frame. + #[test] + fn empty_ids_with_a_caret_is_an_error() { + let mut s = Session::new(); + let (a, b, sid) = two_frame_thread(&mut s); + s.execute("text.select", &json!({"story": sid.0, "anchor": 2})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let e = s.execute("object.textFrameOptions", &json!({"ids": [], "columns": 3})).unwrap_err().to_string(); + assert!(e.contains("nothing selected"), "{e}"); + // An id that is not in the document is refused too. + let e = s.execute("object.textFrameOptions", &json!({"ids": [99999, b.0], "columns": 3})).unwrap_err().to_string(); + assert!(e.contains("no object with id 99999"), "{e}"); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "nothing changed"); + assert_eq!((options(&s, a).columns, options(&s, b).columns), (1, 1)); + } + + /// Options the frame already has change nothing and add no undo step. + #[test] + fn unchanged_options_add_no_undo_step() { + let mut s = Session::new(); + let (_, b, sid) = two_frame_thread(&mut s); + let rb = shown(&s, sid, b); + s.execute("text.select", &json!({"story": sid.0, "anchor": rb.start + 2})).unwrap(); + let steps = undo_steps(&s); + let (before, revision) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().revision); + let r = s.execute("object.textFrameOptions", &json!({"columns": 1, "verticalJustification": "top", "inset": 0})).unwrap(); + assert_eq!(r["changed"], 0); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "nothing changed"); + assert_eq!(s.doc().unwrap().revision, revision, "the revision stays"); + assert_eq!(undo_steps(&s), steps); + // The same holds for selected frames, Fixed Width columns included. + s.execute("selection.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("object.textFrameOptions", &json!({"gutter": options(&s, b).gutter})).unwrap(); + assert_eq!(undo_steps(&s), steps); + let fixed = json!({"columnsKind": "fixedWidth", "columnWidth": 100.3, "columns": 2, "gutter": 12.1}); + s.execute("object.textFrameOptions", &fixed).unwrap(); + assert_eq!(undo_steps(&s), steps + 1); + assert_eq!(s.execute("object.textFrameOptions", &fixed).unwrap()["changed"], 0); + assert_eq!(undo_steps(&s), steps + 1, "the same Fixed Width options again add no undo step"); + } +} + #[cfg(test)] mod column_rule_tests { use super::*; diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a6400054d..f2689c927 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -556,6 +556,39 @@ mod color_theme_tests { assert_eq!(opts(&app).columns, 1, "one undo step"); } + /// Opened with the caret on the last line of a frame, Text Frame Options keep acting on that + /// frame while a preview pushes the caret's line into the next frame of the thread. + #[test] + fn text_frame_options_keep_their_frame_while_the_preview_reflows_the_caret() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let text = (0..40).map(|i| format!("Line {i} of the threaded story.")).collect::>().join(" "); + let a = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": text})).unwrap(); + let b = app.run("frame.create", json!({"rect": [36, 200, 300, 700], "content": "text", "text": "", "caret": false})).unwrap(); + let (a, b, sid) = + (designcraft_doc::ItemId(a["id"].as_u64().unwrap()), designcraft_doc::ItemId(b["id"].as_u64().unwrap()), a["story"].as_u64().unwrap()); + app.run("text.thread", json!({"from": a.0, "to": b.0})).unwrap(); + let shown = |app: &DesignApp, f| { + let cs = designcraft_compose::compose_story(&app.session.doc().unwrap().doc, designcraft_doc::StoryId(sid), &Default::default()); + cs.frame(f).unwrap().range.clone() + }; + let caret = shown(&app, a).end - 1; + app.run("text.select", json!({"story": sid, "anchor": caret})).unwrap(); + let inset = |app: &DesignApp, f| app.session.doc().unwrap().doc.item(f).unwrap().text_frame().unwrap().options.inset[0]; + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(&app, &mut d); + d.fields.insert("inset".into(), json!("2p0")); + d.fields.insert("preview".into(), json!(true)); + text_frame_preview(&mut app, &mut d); + assert!(shown(&app, b).contains(&caret), "the preview moved the caret's line into the next frame"); + d.fields.insert("columns".into(), json!("2")); + text_frame_preview(&mut app, &mut d); + assert_eq!((inset(&app, a), inset(&app, b)), (24.0, 0.0), "the preview stays on the first frame"); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + assert_eq!((inset(&app, a), inset(&app, b)), (24.0, 0.0)); + } + #[test] fn toc_right_indent_separator_survives_the_dialog_and_update() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); @@ -991,18 +1024,22 @@ fn pdf_export(app: &crate::DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { } } +/// The first frame Text Frame Options changes: the first selected item, the frame that shows the +/// caret, or the first frame holding selected text. +fn options_frame(app: &DesignApp) -> Option { + designcraft_engine::cmd::text_frame_options_frames(&app.session).first().copied() +} + /// The selected text frame's width (its own, before rotation). fn selected_frame_width(app: &DesignApp) -> Option { let st = app.session.active()?; - let fid = st.selection.items.first().copied().or_else(|| st.selection.text.and_then(|t| t.frame))?; - Some(st.doc.item(fid)?.inner_bounds().width()) + Some(st.doc.item(options_frame(app)?)?.inner_bounds().width()) } -/// The options of the selected text frame (the first selected item, or the frame of the caret). +/// The options of the frame Text Frame Options shows. fn selected_frame_options(app: &DesignApp) -> Option { let st = app.session.active()?; - let fid = st.selection.items.first().copied().or_else(|| st.selection.text.and_then(|t| t.frame))?; - st.doc.item(fid)?.text_frame().map(|t| t.options.clone()) + st.doc.item(options_frame(app)?)?.text_frame().map(|t| t.options.clone()) } /// Object › Text Frame Options shows the selected frame's options. `_shown` keeps what it showed, @@ -1061,9 +1098,25 @@ fn seed_text_frame_options(app: &DesignApp, d: &mut Dialog) { if let Some(w) = selected_frame_width(app) { d.fields.insert("_frameWidth".into(), json!(w)); } + // Typing in a frame: the frames taken when the dialog opens, so a preview that reflows the + // text into another frame does not change which frames the options apply to. + if let Some(ids) = typing_frame_ids(app) { + d.fields.insert("_targets".into(), ids); + } d.fields.insert("_shown".into(), shown); } +/// With the Type tool and no frame selected: the frame that shows the caret, or every frame that +/// holds part of the selected text. +fn typing_frame_ids(app: &DesignApp) -> Option { + let st = app.session.active()?; + if !st.selection.items.is_empty() || st.selection.text.is_none() { + return None; + } + let ids: Vec = designcraft_engine::cmd::text_frame_options_frames(&app.session).iter().map(|f| f.0).collect(); + Some(json!(ids)) +} + /// A 0..1 tint as a percentage ("40", "12.5"). fn percent(t: f32) -> String { let s = format!("{:.2}", f64::from(t) * 100.0); @@ -1552,12 +1605,10 @@ fn text_frame_params(app: &DesignApp, d: &Dialog) -> Result, json!(d.m("paragraphSpacingLimit").filter(|v| *v >= 0.0).ok_or_else(|| bad("the paragraph spacing limit is not a measure"))?), ); } - // Typing in a frame: the options apply to that frame. - if let Some(st) = app.session.active() - && st.selection.items.is_empty() - && let Some(f) = st.selection.text.and_then(|t| t.frame) - { - p.insert("ids".into(), json!([f.0])); + // Typing in a frame: the options apply to the frame that showed the caret, or to every frame + // that held part of the selected text, when the dialog opened. + if let Some(ids) = d.fields.get("_targets").cloned().or_else(|| typing_frame_ids(app)) { + p.insert("ids".into(), ids); } Ok(p) } diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index e977c6733..c3b679b1b 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -335,6 +335,33 @@ fn pdf_export_menu_item_opens_the_dialog_or_exports() { assert!(app.ui.dialog.is_none()); } +/// With the Type tool in the second frame of a thread, Cmd+B opens Text Frame Options, and OK +/// changes the frame that shows the caret. +#[test] +fn text_frame_options_open_from_the_type_tool() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let text = (0..40).map(|i| format!("Line {i} of the threaded story.")).collect::>().join(" "); + let a = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": text})).unwrap(); + let b = app.run("frame.create", json!({"rect": [36, 200, 300, 700], "content": "text", "text": "", "caret": false})).unwrap(); + let (a, b, sid) = (a["id"].as_u64().unwrap(), b["id"].as_u64().unwrap(), a["story"].as_u64().unwrap()); + app.run("text.thread", json!({"from": a, "to": b})).unwrap(); + // The end of the story is in the second frame. + app.run("text.select", json!({"story": sid, "anchor": text.len()})).unwrap(); + assert!(super::state::enabled(&app, "object.textFrameOptions"), "the menu item is enabled while typing"); + let ctx = egui::Context::default(); + press_keys(&mut app, &ctx, &[(egui::Key::B, egui::Modifiers::COMMAND)]); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("textFrameOptions"), "Cmd+B opens the dialog while typing"); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("columns".into(), json!(3)); + } + crate::dialogs::confirm(&mut app).unwrap(); + let columns = |app: &crate::DesignApp, id: u64| { + app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).and_then(|i| i.text_frame().map(|t| t.options.columns)) + }; + assert_eq!((columns(&app, a), columns(&app, b)), (Some(1), Some(3))); +} + #[test] fn snap_preferences_are_a_command() { let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/docs/mcp.md b/docs/mcp.md index f7e0b8187..17c7e330b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -225,6 +225,15 @@ execute {"command": "type.para", "params": {"attrs": {"hyphenate": fals With a text selection, this formats the selected paragraphs; with selected text frames, it formats their whole stories. +`object.textFrameOptions` (columns, inset spacing, vertical justification and the rest of Text Frame Options) acts on +the selected frames or on the `ids` the call passes. With the Type tool and no frame selected, it acts on the frame that +shows the insertion point, or on every frame that holds part of the selected text, not on the other frames of the +thread. An empty `ids` is an error. Options a frame already has leave the document unchanged and add no undo step. + +```text +execute {"command": "object.textFrameOptions", "params": {"verticalJustification": "center", "inset": 6}} +``` + Use `execute` with `object.fit` to fit a selected graphic frame (or pass `ids`): | `mode` | What it does | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 193d3ae9a..1f6e0ff14 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -351,6 +351,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - Column rules (Text Frame Options › Column Rules, `object.textFrameOptions {columnRule, columnRuleWeight, columnRuleColor, columnRuleTint, columnRuleOffset, columnRuleTopInset, columnRuleBottomInset}`, reported by `document.inspect`): a bar centred in each gutter of a multi-column frame from the top line's ascent to the bottom line's descent, between the columns of right-to-left and vertical frames too, broken around paragraphs that span columns, with weight, colour, tint, horizontal offset and top/bottom insets; on screen, in PDF (tagged as an artifact) and in IDML (`ColumnRule…` attributes of `TextFramePreference`, also in object styles). The dialog shows the frame's options and changes only the fields edited. Rule stroke types and overprint aren't there yet. - Auto-size (Text Frame Options › Auto-Size, `object.textFrameOptions {autoSize: off|heightOnly|widthOnly|heightAndWidth|heightAndWidthProportionally, autoSizeReference, useMinimumHeight, minimumHeight, useMinimumWidth, minimumWidth, noLineBreaks}`): the frame fits its text exactly after every edit (typing, pasting, style changes, option changes) in the same undo step (opening a file keeps the frame sizes it gives); it grows and shrinks around the reference point, which stays put in spread space for rotated frames too, never below the minimum height/width and never past 10,000 pt. Width Only and No Line Breaks set each paragraph on one line; Height and Width without No Line Breaks keeps the width; Keep Proportions scales both sides until the text fits. IDML keeps all the options (`AutoSizing…`, `…ForAutoSizing` attributes). Not covered: frames of a thread other than the last, vertical frames, type on a path, and multi-column balancing in Keep Proportions. - Balance Columns (Text Frame Options › Balance Columns, `object.textFrameOptions {balanceColumns}`, IDML `VerticalBalanceColumns`): in the frame the story ends in, the columns after the last explicit column break fill to about the same depth (the last may be shorter by a line per column); keep options hold, spanning and split paragraphs keep their own balancing, vertical justification then applies to each column as usual, and vertical frames balance their bands. A frame the text runs on from, or that is overset, fills normally. +- Text Frame Options from the Type tool (Object › Text Frame Options…, Cmd+B, `object.textFrameOptions` without `ids`): with the insertion point in a frame, the options change the frame it is drawn in; with text selected, every frame that holds part of it. Options a frame already has add no undo step. - Text Frame Options dialog, laid out as InDesign's (General, Column Rules, Baseline Options, Auto-Size; framed Columns, Inset Spacing and Vertical Justification groups with spinner fields; Fixed Number shows each column's width as the fields change). Preview shows the edits on the page until OK (one undo step) or Cancel. An invalid value (such as a gutter that isn't a measure) takes the preview off the page, so the frame shows as it was, and the dialog's status line gives the reason; OK refuses the value too. Preview stays checked and shows the edits again once the value is valid. Vertical Justification › Paragraph Spacing Limit (`object.textFrameOptions {paragraphSpacingLimit}`, IDML `VerticalThreshold`): with Justify, the extra space goes between paragraphs up to the limit, the rest between lines. - Place a page of an IDML or DesignCraft document (`file.place {layoutPage}`): its objects, stories, styles and swatches as one group (INDD files are not readable). - Articles panel (`article.new/add/remove/options/delete/list`): reading order and content of EPUB and HTML exports. From 7809f5e9da01c84672333a4f0840233567b6ba83 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 18:34:25 -0800 Subject: [PATCH 0929/1349] Text: frame columns, gutter, switches and indents are checked too object.textFrameOptions refuses a gutter outside 0 to 15552 pt, a column count outside 1 to 40 (it was clamped) and an on/off option that is not true or false (it was skipped). The Control bar's Columns field stops at 40, as the other column fields do. The params text gives the ranges and lists flexibleWidth. type.para and paragraph style create and edit refuse left and right indents outside 0 to 15552 pt and first and last line indents outside -15552 to 15552 pt. A style made from the selection is checked with the values it takes from the selection. style.paragraph.apply and style.paragraph.redefine check that Minimum, Desired and Maximum stay in order in each justification row they change, over the overrides paragraphs keep, and refuse the change otherwise. --- crates/engine/src/cmd/object.rs | 90 ++++++++++++---- crates/engine/src/cmd/style/paragraph.rs | 34 ++++-- crates/engine/src/cmd/text.rs | 6 +- crates/engine/src/cmd/text/format.rs | 127 ++++++++++++++++++++--- crates/ui-egui/src/object_control.rs | 2 +- docs/target-app-parity.md | 2 +- 6 files changed, 213 insertions(+), 48 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 69e2d2b04..d8f6eddb5 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -610,7 +610,7 @@ pub fn specs() -> Vec { "Text Frame Options…", ["Object"], Some("Cmd+B"), - "{columns?, gutter?, inset?: number|[t,l,b,r] (null keeps that side), verticalJustification?: top|center|bottom|justify, paragraphSpacingLimit? (pt: Justify adds at most this between paragraphs, the rest between lines), columnsKind?: fixedNumber|fixedWidth, columnWidth? (pt, Fixed Width), firstBaseline?: ascent|capHeight|leading|xHeight|emboxHeight|fixed, firstBaselineMin? (pt), autoSize?: off|heightOnly|widthOnly|heightAndWidth|heightAndWidthProportionally, autoSizeReference?: topLeft|topCenter|topRight|leftCenter|center|rightCenter|bottomLeft|bottomCenter|bottomRight (the point that stays put), useMinimumHeight?: bool, minimumHeight? (pt), useMinimumWidth?: bool, minimumWidth? (pt), noLineBreaks?: bool, ignoreWrap?, balanceColumns?, columnRule?: bool, columnRuleWeight? (pt), columnRuleColor? (swatch name), columnRuleTint? (0..1), columnRuleOffset? (pt, horizontal), columnRuleTopInset? (pt), columnRuleBottomInset? (pt), baselineGrid?: {start? (pt), increment? (pt), relativeTo?: page|margin|frame|inset} (the frame's custom baseline grid; fields not given keep the frame's, or come from the document grid; null turns it off), vertical?: bool (sets the story direction of the frames' stories, as Type ▸ Story Direction), ids?}", + "{columns? (1..40), gutter? (pt, 0..15552), inset?: number|[t,l,b,r] (pt, each 0..15552; a list has four sides, null keeps that side), verticalJustification?: top|center|bottom|justify, paragraphSpacingLimit? (pt: Justify adds at most this between paragraphs, the rest between lines), columnsKind?: fixedNumber|fixedWidth|flexibleWidth, columnWidth? (pt, Fixed Width), firstBaseline?: ascent|capHeight|leading|xHeight|emboxHeight|fixed, firstBaselineMin? (pt), autoSize?: off|heightOnly|widthOnly|heightAndWidth|heightAndWidthProportionally, autoSizeReference?: topLeft|topCenter|topRight|leftCenter|center|rightCenter|bottomLeft|bottomCenter|bottomRight (the point that stays put), useMinimumHeight?: bool, minimumHeight? (pt), useMinimumWidth?: bool, minimumWidth? (pt), noLineBreaks?: bool, ignoreWrap?, balanceColumns?, columnRule?: bool, columnRuleWeight? (pt), columnRuleColor? (swatch name), columnRuleTint? (0..1), columnRuleOffset? (pt, horizontal), columnRuleTopInset? (pt), columnRuleBottomInset? (pt), baselineGrid?: {start? (pt), increment? (pt), relativeTo?: page|margin|frame|inset} (the frame's custom baseline grid; fields not given keep the frame's, or come from the document grid; null turns it off), vertical?: bool (sets the story direction of the frames' stories, as Type ▸ Story Direction), ids?}", has_selection, text_frame_options ), @@ -2569,6 +2569,9 @@ fn content_type(s: &mut Session, p: &Value) -> Result { }) } +/// The most columns a text frame takes. +const MAX_FRAME_COLUMNS: u64 = 40; + fn text_frame_options(s: &mut Session, p: &Value) -> Result { const ID: &str = "object.textFrameOptions"; let st = s.doc()?; @@ -2595,6 +2598,27 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { let column_width = ranged("columnWidth", 0.0, 15552.0, "a number of points")?; let first_baseline_min = ranged("firstBaselineMin", 0.0, 15552.0, "a number of points")?; let spacing_limit = ranged("paragraphSpacingLimit", 0.0, 15552.0, "a number of points")?; + let gutter = ranged("gutter", 0.0, 15552.0, "a number of points")?; + let columns = match p.get("columns") { + None | Some(Value::Null) => None, + Some(v) => Some( + v.as_u64() + .filter(|n| (1..=MAX_FRAME_COLUMNS).contains(n)) + .ok_or_else(|| bad(ID, format!("columns must be a whole number from 1 to {MAX_FRAME_COLUMNS}, not {v}")))? as u32, + ), + }; + let flag = |key: &str| match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Bool(b)) => Ok(Some(*b)), + Some(v) => Err(bad(ID, format!("{key} must be true or false, not {v}"))), + }; + let use_min_height = flag("useMinimumHeight")?; + let use_min_width = flag("useMinimumWidth")?; + let no_line_breaks = flag("noLineBreaks")?; + let ignore_wrap = flag("ignoreWrap")?; + let balance_columns = flag("balanceColumns")?; + let column_rule = flag("columnRule")?; + let vertical = flag("vertical")?; let inset = frame_inset_param(p)?; let vertical_justification: Option = frame_choice_param(p, "verticalJustification", "top|center|bottom|justify")?; @@ -2657,11 +2681,11 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { for id in &ids { let Some(tf) = d.item_mut(*id).and_then(Item::text_frame_mut) else { continue }; let o = &mut tf.options; - if let Some(v) = p.get("columns").and_then(Value::as_u64) { - o.columns = v.clamp(1, 40) as u32; + if let Some(v) = columns { + o.columns = v; } - if let Some(v) = p.get("gutter").and_then(Value::as_f64) { - o.gutter = v.max(0.0); + if let Some(v) = gutter { + o.gutter = v; } for (side, v) in o.inset.iter_mut().zip(inset.unwrap_or_default()) { if let Some(v) = v { @@ -2684,22 +2708,22 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { o.auto_size_ref = v; } o.vj_paragraph_spacing_limit = spacing_limit.unwrap_or(o.vj_paragraph_spacing_limit); - if let Some(v) = p.get("useMinimumHeight").and_then(Value::as_bool) { + if let Some(v) = use_min_height { o.auto_size_use_min_height = v; } if let Some(v) = min_height { o.auto_size_min_height = v; } - if let Some(v) = p.get("useMinimumWidth").and_then(Value::as_bool) { + if let Some(v) = use_min_width { o.auto_size_use_min_width = v; } if let Some(v) = min_width { o.auto_size_min_width = v; } - if let Some(v) = p.get("noLineBreaks").and_then(Value::as_bool) { + if let Some(v) = no_line_breaks { o.auto_size_no_line_breaks = v; } - if let Some(v) = p.get("ignoreWrap").and_then(Value::as_bool) { + if let Some(v) = ignore_wrap { o.ignore_wrap = v; } if let Some(v) = column_width { @@ -2708,10 +2732,10 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { if let Some(v) = first_baseline_min { o.first_baseline_min = v; } - if let Some(v) = p.get("balanceColumns").and_then(Value::as_bool) { + if let Some(v) = balance_columns { o.balance_columns = v; } - if let Some(v) = p.get("columnRule").and_then(Value::as_bool) { + if let Some(v) = column_rule { o.column_rule = v; } if let Some(w) = rule_weight { @@ -2746,7 +2770,7 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { } } // Story direction belongs to the story: every frame of the thread turns. - if let Some(v) = p.get("vertical").and_then(Value::as_bool) { + if let Some(v) = vertical { let stories: Vec = ids.iter().filter_map(|id| d.item(*id).and_then(Item::text_frame).map(|t| t.story)).collect(); super::text::set_story_direction(d, &stories, v); } @@ -4925,18 +4949,23 @@ mod column_rule_tests { assert_eq!(opts(&s), before); } - /// A column count past `u32::MAX` was cast to `u32` before the clamp, so - /// 2^32 + 1 wrapped to 1 column instead of clamping to the maximum, 40. + /// A column count outside 1 to 40 is refused, past `u32::MAX` too (2^32 + 1 must not + /// wrap to 1 column), and the frame keeps its columns. #[test] - fn huge_column_count_clamps_to_the_maximum() { + fn column_count_outside_one_to_forty_is_refused() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text"})).unwrap(); let id = ItemId(r["id"].as_u64().unwrap()); let columns = |s: &Session| s.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.columns; - for (given, want) in [(4_294_967_297_u64, 40), (u64::MAX, 40), (0, 1)] { + for given in [4_294_967_297_u64, u64::MAX, 41, 0] { + let e = s.execute("object.textFrameOptions", &json!({"ids": [id.0], "columns": given})).expect_err("refused").to_string(); + assert!(e.contains("columns must be a whole number from 1 to 40"), "columns {given}: {e}"); + assert_eq!(columns(&s), 1, "columns {given}"); + } + for given in [40, 1] { s.execute("object.textFrameOptions", &json!({"ids": [id.0], "columns": given})).unwrap(); - assert_eq!(columns(&s), want, "columns {given}"); + assert_eq!(columns(&s), given as u32, "columns {given}"); } } } @@ -6042,9 +6071,10 @@ mod frame_baseline_grid_tests { assert_eq!(grid(&s), None); } - /// A negative or huge inset, an inset list that isn't four sides, and a vertical - /// justification or first baseline that isn't one of the names were applied or skipped - /// without a word. They are refused and the frame keeps its options. + /// A negative or huge inset or gutter, an inset list that isn't four sides, a column count + /// outside 1 to 40, a switch that isn't true or false, and a vertical justification or first + /// baseline that isn't one of the names were applied, clamped or skipped without a word. They + /// are refused and the frame keeps its options. #[test] fn text_frame_options_refuse_insets_and_names_outside_their_ranges() { let mut s = Session::new(); @@ -6066,6 +6096,19 @@ mod frame_baseline_grid_tests { (json!({"columnsKind": "flexible"}), "columnsKind must be one of"), (json!({"paragraphSpacingLimit": -1}), "paragraphSpacingLimit must be a number of points from 0 to 15552"), (json!({"firstBaselineMin": 20000}), "firstBaselineMin must be a number of points from 0 to 15552"), + (json!({"gutter": -5}), "gutter must be a number of points from 0 to 15552"), + (json!({"gutter": 1e300}), "gutter must be a number of points from 0 to 15552"), + (json!({"gutter": "12pt"}), "gutter must be a number of points from 0 to 15552"), + (json!({"columns": 99}), "columns must be a whole number from 1 to 40"), + (json!({"columns": "two"}), "columns must be a whole number from 1 to 40"), + (json!({"columns": 2.5}), "columns must be a whole number from 1 to 40"), + (json!({"balanceColumns": "yes"}), "balanceColumns must be true or false"), + (json!({"ignoreWrap": 1}), "ignoreWrap must be true or false"), + (json!({"columnRule": "on"}), "columnRule must be true or false"), + (json!({"noLineBreaks": 0}), "noLineBreaks must be true or false"), + (json!({"useMinimumHeight": "true"}), "useMinimumHeight must be true or false"), + (json!({"useMinimumWidth": []}), "useMinimumWidth must be true or false"), + (json!({"vertical": "yes"}), "vertical must be true or false"), ] { let mut p = params.clone(); p["ids"] = json!([id.0]); @@ -6082,6 +6125,13 @@ mod frame_baseline_grid_tests { let o = options(&s); assert_eq!(o.inset, [6.0; 4]); assert_eq!(o.first_baseline, designcraft_doc::FirstBaseline::CapHeight); + s.execute("object.textFrameOptions", &json!({"ids": [id.0], "columns": 3, "gutter": 15552, "balanceColumns": true, "ignoreWrap": true})) + .unwrap(); + let o = options(&s); + assert_eq!((o.columns, o.gutter, o.balance_columns, o.ignore_wrap), (3, 15552.0, true, true)); + s.execute("object.textFrameOptions", &json!({"ids": [id.0], "gutter": 0, "balanceColumns": false})).unwrap(); + let o = options(&s); + assert_eq!((o.gutter, o.balance_columns), (0.0, false)); } } diff --git a/crates/engine/src/cmd/style/paragraph.rs b/crates/engine/src/cmd/style/paragraph.rs index 04a3f6a8d..e336b0f4f 100644 --- a/crates/engine/src/cmd/style/paragraph.rs +++ b/crates/engine/src/cmd/style/paragraph.rs @@ -241,9 +241,14 @@ pub(super) fn redefine(s: &mut Session, p: &Value, paragraph: bool) -> Result Result { s.edit(|d, _| { let styles = d.styles.clone(); let (style_para, style_chars) = styles.resolve_para_style(&name); + // Minimum ≤ Desired ≤ Maximum holds in each justification row the style changes in a + // paragraph, over the overrides the paragraph keeps. + let mut refused = None; for t in &targets { if let Some(st) = d.text_story_mut(t.story, t.cell) { + let last = if t.range.is_empty() { t.range.start } else { t.range.end.saturating_sub(1) }; + let touched = st.para_at(t.range.start)..=st.para_at(last); + let before: Vec<_> = st.paras.get(touched.clone()).unwrap_or_default().iter().map(|pf| styles.resolve_para(pf).0).collect(); apply_para_in_story(st, &t.range, &name, clear, (&style_para, &style_chars), &styles); + if refused.is_none() { + refused = st.paras.get(touched).unwrap_or_default().iter().zip(&before).find_map(|(pf, old)| { + let new = styles.resolve_para(pf).0; + crate::cmd::text::justification_order_error(&new, crate::cmd::text::justification_rows_changed(old, &new)) + }); + } } } - ok() + refused.map_or_else(ok, |m| Err(bad("style.paragraph.apply", m))) }) } @@ -418,8 +435,7 @@ fn continue_numbering(p: Option<&Value>, para: &mut ParaAttrs) { /// After an edit of paragraph style `name`: Minimum ≤ Desired ≤ Maximum in `rows` for the style, /// the styles based on it and the story paragraphs that use any of them. -fn check_justification_after_edit(d: &designcraft_doc::Document, name: &str, rows: [bool; 3]) -> Result<()> { - const ID: &str = "style.paragraph.edit"; +fn check_justification_after_edit(d: &designcraft_doc::Document, name: &str, rows: [bool; 3], command_id: &str) -> Result<()> { if !rows.contains(&true) { return Ok(()); } @@ -427,7 +443,7 @@ fn check_justification_after_edit(d: &designcraft_doc::Document, name: &str, row let affected: Vec<&str> = styles.paragraph.iter().map(|st| st.name.as_str()).filter(|n| styles.para_based_on_cycles(name, n)).collect(); for n in &affected { if let Some(m) = crate::cmd::text::justification_order_error(&styles.resolve_para_style(n).0, rows) { - return Err(bad(ID, if *n == name { m } else { format!("paragraph style {n:?}: {m}") })); + return Err(bad(command_id, if *n == name { m } else { format!("paragraph style {n:?}: {m}") })); } } for st in d.stories.values() { @@ -435,7 +451,7 @@ fn check_justification_after_edit(d: &designcraft_doc::Document, name: &str, row if affected.contains(&pf.style.as_str()) { crate::cmd::text::justification_order_error(&styles.resolve_para(pf).0, rows) } else { None } }; if let Some(m) = first_in_nested_paras(st, &mut check) { - return Err(bad(ID, format!("a paragraph of story {}: {m}", st.id.0))); + return Err(bad(command_id, format!("a paragraph of story {}: {m}", st.id.0))); } } Ok(()) @@ -479,8 +495,7 @@ pub(super) fn create_para(s: &mut Session, p: &Value) -> Result { continue_numbering(p.get("para"), &mut para); explicit_default_kinsoku(&mut para, p.get("para")); check_grep_styles("style.paragraph.create", ¶)?; - crate::cmd::text::validate_para_values(¶, "style.paragraph.create")?; - let rows = justification_rows_given(p); + let mut rows = justification_rows_given(p); let mut chars: CharAttrs = attrs("style.paragraph.create", "chars", p, |a: &mut CharAttrs, k, v| a.set_json(k, v))?; // Validate caller-supplied fills, not selection fills retained after a swatch is deleted. crate::cmd::text::validate_char_fill(&s.doc()?.doc, &chars, "style.paragraph.create")?; @@ -492,6 +507,7 @@ pub(super) fn create_para(s: &mut Session, p: &Value) -> Result { let mut full = ParaProps_to_attrs(&pp); full.merge(¶); para = full; + rows = [true; 3]; } if let Ok(cp) = serde_json::from_value::(cur["chars"].clone()) { let mut full = CharProps_to_attrs(&cp); @@ -499,6 +515,8 @@ pub(super) fn create_para(s: &mut Session, p: &Value) -> Result { chars = full; } } + // The values taken from the selection are checked with the given ones. + crate::cmd::text::validate_para_values(¶, "style.paragraph.create")?; s.edit(|d, _| { let name = Styles::unique_name(|n| d.styles.para(n).is_some(), &base); if let Some(b) = &based_on @@ -635,7 +653,7 @@ pub(super) fn edit_para(s: &mut Session, p: &Value) -> Result { // Minimum ≤ Desired ≤ Maximum holds over what the style resolves to: in the rows the edit // names, or in every row when it changes Based On or resets the style. let rows = if reset || based.is_some() { [true; 3] } else { justification_rows_given(p) }; - check_justification_after_edit(d, &name, rows)?; + check_justification_after_edit(d, &name, rows, "style.paragraph.edit")?; let st = d.styles_mut().para_mut(&name).ok_or_else(|| bad("style.paragraph.edit", format!("no style `{name}`")))?; match next { Some(Value::String(n)) => st.next_style = Some(n), diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index 421df09bc..ae016d4f9 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -25,8 +25,8 @@ pub use edit::{PLACEHOLDER, quote_marks}; use edit::{change_case, delete, delete_surrounding, fill_placeholder, insert}; pub(crate) use format::{ Target, TypingFormat, apply_char_attrs, effective_char_format, format_chars, format_paras, format_targets, format_targets_pub, - justification_order_error, justification_rows_named, rename_typing_swatch, validate_char_fill, validate_justification_order, - validate_para_values, + justification_order_error, justification_rows_changed, justification_rows_named, rename_typing_swatch, validate_char_fill, + validate_justification_order, validate_para_values, }; use format::{break_link, kern_pair, kern_step, link_style, para_toggle, pick_up_format, step_size, swap_fill_stroke}; use opentype::{open_type, open_type_features, set_features}; @@ -235,7 +235,7 @@ pub fn specs() -> Vec { "Paragraph Formatting", [], None, - "{attrs: {align?, leftIndent?, firstLineIndent?, spaceBefore?, spaceAfter?, sameParaStyleSpacing? (pt, each 0..15552), wordSpaceMin?/wordSpaceDesired?/wordSpaceMax? (0..10, 1 = 100%), letterSpaceMin?/…Desired?/…Max? (-1..5), glyphScaleMin?/…Desired?/…Max? (0.5..2) (each row Minimum ≤ Desired ≤ Maximum), autoLeading? (0..5 of the type size), singleWordJustify?: left|center|right|fullyJustified, dropCapLines?, dropCapChars?, dropCapStyle?, dropCapAlignLeft?, dropCapScaleDescenders?, hyphenate?: bool (default true), composer?, opticalMargin?: bool (hang at each character's own size; a story with story.options opticalMargin overrides it), ignoreOpticalMargin?: bool (no hang in the paragraph), tabs?, ruleAbove?/ruleBelow?: {on?, weight?, color?, tint?, columnWidth?, offset?, leftIndent?, rightIndent?} (only the named rule fields change), …}}", + "{attrs: {align?, leftIndent?, rightIndent?, spaceBefore?, spaceAfter?, sameParaStyleSpacing? (pt, each 0..15552), firstLineIndent?, lastLineIndent? (pt, each -15552..15552), wordSpaceMin?/wordSpaceDesired?/wordSpaceMax? (0..10, 1 = 100%), letterSpaceMin?/…Desired?/…Max? (-1..5), glyphScaleMin?/…Desired?/…Max? (0.5..2) (each row Minimum ≤ Desired ≤ Maximum), autoLeading? (0..5 of the type size), singleWordJustify?: left|center|right|fullyJustified, dropCapLines?, dropCapChars?, dropCapStyle?, dropCapAlignLeft?, dropCapScaleDescenders?, hyphenate?: bool (default true), composer?, opticalMargin?: bool (hang at each character's own size; a story with story.options opticalMargin overrides it), ignoreOpticalMargin?: bool (no hang in the paragraph), tabs?, ruleAbove?/ruleBelow?: {on?, weight?, color?, tint?, columnWidth?, offset?, leftIndent?, rightIndent?} (only the named rule fields change), …}}", has_text_or_frames, |s, p| format_paras(s, p.get("attrs").unwrap_or(p)) ), diff --git a/crates/engine/src/cmd/text/format.rs b/crates/engine/src/cmd/text/format.rs index 23d84bed6..25a0c87ba 100644 --- a/crates/engine/src/cmd/text/format.rs +++ b/crates/engine/src/cmd/text/format.rs @@ -146,8 +146,9 @@ pub(crate) const MIN_TYPE_SIZE: f64 = 0.1; pub(crate) const MAX_TYPE_SIZE: f64 = 1296.0; -/// Space Before, Space After and Space Between Paragraphs Using Same Style: 0 to 15552 pt, the -/// limit `object.textFrameOptions` applies to its Paragraph Spacing Limit. +/// Left and right indents, Space Before, Space After and Space Between Paragraphs Using Same +/// Style: 0 to 15552 pt, the limit `object.textFrameOptions` applies to its Paragraph Spacing +/// Limit. First and last line indents may be negative, down to -15552 pt. pub(crate) const MAX_PARA_SPACE: f64 = 15552.0; /// The justification rows as fractions (1.0 = 100%): key stem, label, range. @@ -163,20 +164,28 @@ fn percent(v: f64) -> String { format!("{p}") } -/// Checks the paragraph spacing and justification values `attrs` sets: Space Before, Space After -/// and same-style spacing 0 to [`MAX_PARA_SPACE`] pt; word spacing 0% to 1000%, letter spacing +/// Checks the paragraph spacing and justification values `attrs` sets: left and right indents, +/// Space Before, Space After and same-style spacing 0 to [`MAX_PARA_SPACE`] pt, first and last +/// line indents -[`MAX_PARA_SPACE`] to [`MAX_PARA_SPACE`] pt; word spacing 0% to 1000%, letter spacing /// -100% to 500% and glyph scaling 50% to 200%; Auto Leading 0% to 500%; Single Word /// Justification left, center, right or fullyJustified. [`validate_justification_order`] checks /// the order of each row once the values are applied. pub(crate) fn validate_para_values(attrs: &ParaAttrs, command_id: &str) -> Result<()> { use designcraft_doc::Align; - let spaces = - [("spaceBefore", attrs.space_before), ("spaceAfter", attrs.space_after), ("sameParaStyleSpacing", attrs.same_para_style_spacing.flatten())]; - for (key, v) in spaces { + let spaces = [ + ("leftIndent", attrs.left_indent, 0.0), + ("rightIndent", attrs.right_indent, 0.0), + ("firstLineIndent", attrs.first_line_indent, -MAX_PARA_SPACE), + ("lastLineIndent", attrs.last_line_indent, -MAX_PARA_SPACE), + ("spaceBefore", attrs.space_before, 0.0), + ("spaceAfter", attrs.space_after, 0.0), + ("sameParaStyleSpacing", attrs.same_para_style_spacing.flatten(), 0.0), + ]; + for (key, v, lo) in spaces { if let Some(v) = v - && !(0.0..=MAX_PARA_SPACE).contains(&v) + && !(lo..=MAX_PARA_SPACE).contains(&v) { - return Err(bad(command_id, format!("{key} {v}: 0 to {MAX_PARA_SPACE} pt"))); + return Err(bad(command_id, format!("{key} {v}: {lo} to {MAX_PARA_SPACE} pt"))); } } let rows = [ @@ -225,13 +234,24 @@ pub(crate) fn validate_justification_order(resolved: &designcraft_doc::ParaProps justification_order_error(resolved, rows).map_or(Ok(()), |m| Err(bad(command_id, m))) } -/// What [`validate_justification_order`] refuses, as a message. -pub(crate) fn justification_order_error(resolved: &designcraft_doc::ParaProps, rows: [bool; 3]) -> Option { - let values = [ +/// The justification rows of resolved paragraph attributes: Minimum, Desired, Maximum. +fn justification_values(resolved: &designcraft_doc::ParaProps) -> [[f64; 3]; 3] { + [ [resolved.word_space_min, resolved.word_space_desired, resolved.word_space_max], [resolved.letter_space_min, resolved.letter_space_desired, resolved.letter_space_max], [resolved.glyph_scale_min, resolved.glyph_scale_desired, resolved.glyph_scale_max], - ]; + ] +} + +/// The justification rows whose values differ between `before` and `after`. +pub(crate) fn justification_rows_changed(before: &designcraft_doc::ParaProps, after: &designcraft_doc::ParaProps) -> [bool; 3] { + let (b, a) = (justification_values(before), justification_values(after)); + [b[0] != a[0], b[1] != a[1], b[2] != a[2]] +} + +/// What [`validate_justification_order`] refuses, as a message. +pub(crate) fn justification_order_error(resolved: &designcraft_doc::ParaProps, rows: [bool; 3]) -> Option { + let values = justification_values(resolved); JUSTIFICATION_ROWS.into_iter().zip(values).zip(rows).find_map(|(((_, label, ..), [min, desired, max]), checked)| { (checked && (min > desired || desired > max)) .then(|| format!("{label} needs Minimum ≤ Desired ≤ Maximum, not {}%, {}%, {}%", percent(min), percent(desired), percent(max))) @@ -1213,8 +1233,8 @@ mod size_bounds_tests { } } - /// `type.para` set any number for paragraph spacing and justification: a negative Space - /// Before, word spacing of 5000% and a Minimum above Maximum all went into the paragraph, + /// `type.para` set any number for paragraph indents, spacing and justification: a negative + /// left indent or Space Before, word spacing of 5000% and a Minimum above Maximum all went into the paragraph, /// and Single Word Justification took any alignment. Values outside the ranges are refused, /// nothing changes, and the ends of each range still apply. #[test] @@ -1232,6 +1252,11 @@ mod size_bounds_tests { (json!({"spaceBefore": -1}), "spaceBefore -1: 0 to 15552 pt"), (json!({"spaceAfter": 15553}), "spaceAfter 15553: 0 to 15552 pt"), (json!({"sameParaStyleSpacing": -2}), "sameParaStyleSpacing -2: 0 to 15552 pt"), + (json!({"leftIndent": -50}), "leftIndent -50: 0 to 15552 pt"), + (json!({"rightIndent": -20}), "rightIndent -20: 0 to 15552 pt"), + (json!({"rightIndent": 1e300}), "rightIndent 1"), + (json!({"firstLineIndent": -15553}), "firstLineIndent -15553: -15552 to 15552 pt"), + (json!({"lastLineIndent": 15553}), "lastLineIndent 15553: -15552 to 15552 pt"), (json!({"wordSpaceMax": 10.5}), "wordSpaceMax 1050%: word spacing is 0% to 1000%"), (json!({"wordSpaceMin": -0.1}), "wordSpaceMin -10%: word spacing is 0% to 1000%"), (json!({"letterSpaceMin": -1.5}), "letterSpaceMin -150%: letter spacing is -100% to 500%"), @@ -1256,6 +1281,8 @@ mod size_bounds_tests { // The ends of each range apply and read back. for attrs in [ json!({"spaceBefore": 0, "spaceAfter": 15552, "sameParaStyleSpacing": 15552}), + json!({"leftIndent": 0, "rightIndent": 15552, "firstLineIndent": -15552, "lastLineIndent": 15552}), + json!({"leftIndent": 18, "rightIndent": 0, "firstLineIndent": -18, "lastLineIndent": 0}), json!({"wordSpaceMin": 0, "wordSpaceDesired": 0, "wordSpaceMax": 10}), json!({"letterSpaceMin": -1, "letterSpaceDesired": 0, "letterSpaceMax": 5}), json!({"glyphScaleMin": 0.5, "glyphScaleDesired": 1, "glyphScaleMax": 2}), @@ -1341,6 +1368,76 @@ mod size_bounds_tests { ); assert_eq!(s.doc().unwrap().doc.styles.para("Parent").unwrap().para.letter_space_desired, None); } + + /// Applying or redefining a paragraph style could leave a paragraph's own override and the + /// style's values out of order: a Maximum of 10% kept over a style's Desired of 20%. Both are + /// refused and nothing changes; Clear Overrides still applies the style. + #[test] + fn applying_or_redefining_a_style_keeps_justification_in_order() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 1})).unwrap(); + let f = s.execute("frame.create", &json!({"rect": [20, 20, 400, 300], "content": "text", "text": "Hello world\nSecond"})).unwrap(); + let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap()); + let select = |s: &mut Session, anchor: u64, focus: u64| { + s.execute("text.select", &json!({"story": f["story"].clone(), "anchor": anchor, "focus": focus})).unwrap(); + }; + let styles = |s: &Session| s.doc().unwrap().doc.story(sid).unwrap().paras.iter().map(|p| p.style.clone()).collect::>(); + let letter = |s: &mut Session| { + let p = s.execute("type.selectionAttrs", &json!({})).unwrap()["para"].clone(); + [p["letterSpaceMin"].as_f64(), p["letterSpaceDesired"].as_f64(), p["letterSpaceMax"].as_f64()] + }; + s.execute("style.paragraph.create", &json!({"name": "Wide", "para": {"letterSpaceDesired": 0.2, "letterSpaceMax": 0.5}})).unwrap(); + select(&mut s, 0, 18); + s.execute("type.para", &json!({"attrs": {"letterSpaceMax": 0.1}})).unwrap(); + let before = styles(&s); + select(&mut s, 0, 18); + let e = s.execute("style.paragraph.apply", &json!({"name": "Wide"})).expect_err("refused").to_string(); + assert!(e.contains("style.paragraph.apply") && e.contains("letter spacing needs Minimum ≤ Desired ≤ Maximum, not 0%, 20%, 10%"), "{e}"); + assert_eq!(styles(&s), before); + select(&mut s, 0, 18); + assert_eq!(letter(&mut s), [Some(0.0), Some(0.0), Some(0.1)]); + // A style that changes no justification row applies over the same override. + s.execute("style.paragraph.create", &json!({"name": "Airy", "para": {"spaceAfter": 6}})).unwrap(); + select(&mut s, 0, 18); + s.execute("style.paragraph.apply", &json!({"name": "Airy"})).unwrap(); + select(&mut s, 0, 18); + s.execute("style.paragraph.apply", &json!({"name": "Wide", "clearOverrides": true})).unwrap(); + assert_eq!(styles(&s), ["Wide", "Wide"]); + select(&mut s, 0, 18); + assert_eq!(letter(&mut s), [Some(0.0), Some(0.2), Some(0.5)]); + + // Redefine Style from a paragraph whose Desired is 30% while the second paragraph keeps a + // Maximum of 25%. + select(&mut s, 12, 18); + s.execute("type.para", &json!({"attrs": {"letterSpaceMax": 0.25}})).unwrap(); + select(&mut s, 0, 5); + s.execute("type.para", &json!({"attrs": {"letterSpaceDesired": 0.3}})).unwrap(); + select(&mut s, 0, 5); + let e = s.execute("style.paragraph.redefine", &json!({})).expect_err("refused").to_string(); + assert!( + e.contains("style.paragraph.redefine") + && e.contains(&format!("a paragraph of story {}: letter spacing needs Minimum ≤ Desired ≤ Maximum, not 0%, 30%, 25%", sid.0)), + "{e}" + ); + assert_eq!(s.doc().unwrap().doc.styles.para("Wide").unwrap().para.letter_space_desired, Some(0.2)); + + // A new style from a selection whose paragraph holds a value no command sets (as an + // import could leave) is refused the same way as a given value. + s.edit(|d, _| { + for pf in &mut d.story_mut(sid).unwrap().paras { + pf.para.left_indent = Some(-30.0); + } + Ok(()) + }) + .unwrap(); + select(&mut s, 0, 5); + let e = s.execute("style.paragraph.create", &json!({"name": "Captured", "fromSelection": true})).expect_err("refused").to_string(); + assert!(e.contains("leftIndent -30: 0 to 15552 pt"), "{e}"); + assert!(s.doc().unwrap().doc.styles.para("Captured").is_none()); + select(&mut s, 0, 5); + s.execute("style.paragraph.create", &json!({"name": "Captured", "fromSelection": true, "para": {"leftIndent": 0}})).unwrap(); + assert_eq!(s.doc().unwrap().doc.styles.para("Captured").unwrap().para.left_indent, Some(0.0)); + } } #[cfg(test)] diff --git a/crates/ui-egui/src/object_control.rs b/crates/ui-egui/src/object_control.rs index 55ebd5e31..056ea68cf 100644 --- a/crates/ui-egui/src/object_control.rs +++ b/crates/ui-egui/src/object_control.rs @@ -304,7 +304,7 @@ pub(crate) fn show(app: &mut DesignApp, ui: &mut Ui) { group(ui, "columns", (caption_w + 2.0).ceil().max(48.0), |ui, rect| { cell(ui, rect, 0.0, 0, rect.width(), true, |ui| widgets::caption(ui, &caption)); if let Some(v) = cell(ui, rect, 0.0, 1, 48.0, true, |ui| { - NumField::number("ccols", Some(columns as f64), "", 0).width(48.0).spinner().range(1.0, 100.0).show(ui) + NumField::number("ccols", Some(columns as f64), "", 0).width(48.0).spinner().range(1.0, 40.0).show(ui) }) { let _ = app.run("object.textFrameOptions", json!({"columns": v as u64})); } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 63da03254..a71731243 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -285,7 +285,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - Data Merge (one linked CSV, TSV, text, or Excel file; text, image, QR, and hyperlink placeholders; preview; a new document with one record per page or records tiled on a single page), spell checking (public-domain Moby list + document dictionary, suggestions), Step and Repeat (count or grid, with a previewing dialog), snippets, object styles, Numbering & Section Options. - Footnotes: Type › Insert Footnote (caret moves into the note), Document Footnote Options (numbering style incl. symbols, start/restart per page/spread/section, prefix/suffix, reference position/character style, paragraph style, separator, spacing, first baseline, rule above); notes composed at the bottom of the referencing column with the body text making room, or across all the columns of the frame with Span Footnotes Across Columns; edited in place on the canvas; rendered, exported to PDF (real text) and IDML (InDesign's structure, verified opening in InDesign 2026) and imported from IDML; `footnote.*` commands. - Paragraph Rules: Rule Above / Rule Below (on, weight, colour, tint, column or text width, offset, left/right indent) set in the Paragraph panel menu and Paragraph Style Options › Paragraph Rules; inherited style values shown, and `type.para` / `style.paragraph.edit` change only the rule fields named. -- Paragraph spacing and justification values are checked: `type.para`, `style.paragraph.create` and `style.paragraph.edit` refuse Space Before, Space After and same-style spacing outside 0 to 15552 pt, word spacing outside 0% to 1000%, letter spacing outside -100% to 500%, glyph scaling outside 50% to 200%, a Minimum above Desired or a Desired above Maximum, Auto Leading outside 0% to 500%, and a Single Word Justification other than left, center, right or fullyJustified. A style edit is also checked over the styles based on it and the paragraphs that use them. `object.textFrameOptions` refuses an inset outside 0 to 15552 pt or a list that isn't four sides, and a vertical justification, first baseline, auto-size or columns kind that isn't one of its names. IDML import reads these values as before. +- Paragraph spacing and justification values are checked: `type.para`, `style.paragraph.create` and `style.paragraph.edit` refuse left and right indents, Space Before, Space After and same-style spacing outside 0 to 15552 pt, first and last line indents outside -15552 to 15552 pt, word spacing outside 0% to 1000%, letter spacing outside -100% to 500%, glyph scaling outside 50% to 200%, a Minimum above Desired or a Desired above Maximum, Auto Leading outside 0% to 500%, and a Single Word Justification other than left, center, right or fullyJustified. A style edit or redefinition is also checked over the styles based on it and the paragraphs that use them, and `style.paragraph.apply` refuses a style whose values would put a row out of order with a paragraph's own overrides. `object.textFrameOptions` refuses an inset or gutter outside 0 to 15552 pt, an inset list that isn't four sides, a column count outside 1 to 40, an on/off option that isn't true or false, and a vertical justification, first baseline, auto-size or columns kind that isn't one of its names. IDML import reads these values as before. - Cross-references and text anchors: Insert Cross-Reference (paragraph by style, or text anchor), 11 formats with InDesign's building blocks (full/partial paragraph, paragraph text/number, page number, anchor name, chapter, file name) plus user formats; resolved live at composition — never out of date, no Update step; unresolved destinations show `??`; PDF link annotations to the destination page; IDML export/import as InDesign cross-reference sources, hyperlinks, text destinations and formats (verified in InDesign 2026); `xref.*` / `anchor.*` commands. - Index: page references (topic from the selection or up to 4 levels, sort keys; current page, to end of story, next n paragraphs, suppressed, See / See also), Generate / Update Index (section headings, nested or run-in, page ranges merged, Index Title / Section Head / Level 1–4 styles); IDML export/import as InDesign topics, page references and topic cross-references (verified in InDesign 2026); `index.*` commands. - Text clipboard keeps formatting (character/paragraph formats, footnotes, cross-references, index markers, tables) and falls back to plain text when the system clipboard changed; Paste without Formatting (⇧⌘V); Change Case (UPPERCASE, lowercase, Title Case, Sentence case — formatting kept); Type › Insert Special Character / White Space / Break Character submenus. From 9994665436cb10eecfa39928753aecd8daf31875 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 18:43:13 -0800 Subject: [PATCH 0930/1349] Pages: an edit no longer renders every page thumbnail again While the Pages panel was shown, every edit made all page thumbnails out of date, and the next frame rendered one for every page of the document on the interface thread, including pages out of view. Each move step, drag step and typed character paid for it. - Only thumbnails of rows in view are rendered. - After an edit, the previous thumbnail stays on screen until the document has been unchanged for 0.4 s. Then one out-of-date thumbnail is rendered again per frame. - Thumbnails of deleted pages and parents are dropped. Part of #1411 --- crates/ui-egui/src/panels/pages.rs | 84 ++++++++++++++++++++---- crates/ui-egui/src/panels/pages/tests.rs | 56 ++++++++++++++-- 2 files changed, 123 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/panels/pages.rs b/crates/ui-egui/src/panels/pages.rs index f46868a35..ff8e2f3c7 100644 --- a/crates/ui-egui/src/panels/pages.rs +++ b/crates/ui-egui/src/panels/pages.rs @@ -17,22 +17,85 @@ enum ThumbOf { Parent(SpreadId), } -/// (document uid, revision, page or parent, thumbnail height). -type ThumbKey = (u64, u64, ThumbOf, u32); +/// (document uid, page or parent, thumbnail height). +type ThumbKey = (u64, ThumbOf, u32); -static THUMBS: Mutex>> = Mutex::new(None); +/// The newest thumbnail of each page and parent, with the document revision it shows. +static THUMBS: Mutex>> = Mutex::new(None); /// Widest parent thumbnail, in pixels (a spread of many pages stays a small texture). const MAX_THUMB_W: f64 = 1024.0; +/// Seconds the document stays unchanged before thumbnails of an older revision are drawn again. +const THUMB_QUIET_SECS: f64 = 0.4; + +/// Thumbnails of an older revision drawn again in one frame. +const THUMB_REFRESHES_PER_FRAME: usize = 1; + +/// When the active document's revision last changed, and how many thumbnails were drawn again in +/// the current frame. +#[derive(Clone, Copy, Debug, Default)] +struct ThumbClock { + doc: (u64, u64), + changed_at: f64, + frame: u64, + refreshed: usize, +} + +#[cfg(test)] +thread_local! { + /// Thumbnails rendered on this thread. + static THUMB_RENDERS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The thumbnail of `of`, `h` points high. A thumbnail of an older revision stays on screen until +/// the document has been unchanged for [`THUMB_QUIET_SECS`]; after that, at most +/// [`THUMB_REFRESHES_PER_FRAME`] of them are drawn again per frame. fn thumb(app: &mut DesignApp, ctx: &egui::Context, of: ThumbOf, h: f32) -> Option { let st = app.session.active()?; - let key = (st.uid, st.revision, of, h.round() as u32); + let key = (st.uid, of, h.round() as u32); + let clock_id = egui::Id::unique("pages_thumb_clock"); + let (now, frame) = (ctx.input(|i| i.time), ctx.cumulative_frame_nr()); + let mut clock = ctx.data(|d| d.get_temp::(clock_id)).unwrap_or_default(); + let changed = clock.doc != (st.uid, st.revision); + if changed { + clock = ThumbClock { doc: (st.uid, st.revision), changed_at: now, frame, refreshed: 0 }; + } + if clock.frame != frame { + clock.frame = frame; + clock.refreshed = 0; + } + if now < clock.changed_at { + clock.changed_at = now; + } let mut g = THUMBS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let map = g.get_or_insert_with(HashMap::new); - if let Some(t) = map.get(&key) { - return Some(t.clone()); + if changed { + // Drop the thumbnails of pages and parents the document no longer has. + let pages = st.doc.page_count(); + map.retain(|k, _| { + k.0 != st.uid + || match k.1 { + ThumbOf::Page(abs) => abs < pages, + ThumbOf::Parent(id) => st.doc.parent_index(id).is_some(), + } + }); } + if let Some((rev, t)) = map.get(&key) { + if *rev == st.revision { + return Some(t.clone()); + } + let wait = THUMB_QUIET_SECS - (now - clock.changed_at); + if wait > 0.0 || clock.refreshed >= THUMB_REFRESHES_PER_FRAME { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait.max(0.0))); + ctx.data_mut(|d| d.insert_temp(clock_id, clock)); + return Some(t.clone()); + } + clock.refreshed += 1; + } + ctx.data_mut(|d| d.insert_temp(clock_id, clock)); + #[cfg(test)] + THUMB_RENDERS.with(|n| n.set(n.get() + 1)); let px = h as f64 * ctx.pixels_per_point() as f64; let mut r = designcraft_render::Renderer::new(); r.threads = 0; @@ -59,10 +122,7 @@ fn thumb(app: &mut DesignApp, ctx: &egui::Context, of: ThumbOf, h: f32) -> Optio }; let ci = egui::ColorImage::from_rgba_premultiplied([img.width as usize, img.height as usize], &img.pixels); let tex = crate::widgets::load_texture(ctx, format!("{name}_{}", h.round()), ci, egui::TextureOptions::LINEAR); - // Drop thumbnails of older revisions. - let (uid, rev) = (st.uid, st.revision); - map.retain(|k, _| !(k.0 == uid && k.1 != rev)); - map.insert(key, tex.clone()); + map.insert(key, (st.revision, tex.clone())); Some(tex) } @@ -268,7 +328,7 @@ impl ParentRow { /// `thumbnails`), or blank pages for [None] and when the spread can't be rendered. fn parent_icon(app: &mut DesignApp, ui: &egui::Ui, right: egui::Pos2, row: &ParentRow, h: f32, thumbnails: bool, t: &Tokens) { let area = egui::Rect::from_min_size(egui::pos2(right.x - row.unit_w * h, right.y - h / 2.0), vec2(row.unit_w * h, h)); - let tex = if thumbnails { row.parent.and_then(|(_, id)| thumb(app, ui.ctx(), ThumbOf::Parent(id), h)) } else { None }; + let tex = if thumbnails && ui.is_rect_visible(area) { row.parent.and_then(|(_, id)| thumb(app, ui.ctx(), ThumbOf::Parent(id), h)) } else { None }; let p = ui.painter(); match tex { Some(tex) => { @@ -488,7 +548,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { egui::WidgetInfo::selected(egui::Role::Button, true, selected, format!("Page {}", app.session.page_label(abs))) }); let tint = if selected { SELECTED_TINT } else { Color32::WHITE }; - match thumbnails.then(|| thumb(app, ui.ctx(), ThumbOf::Page(abs), th)).flatten() { + match (thumbnails && ui.is_rect_visible(pr)).then(|| thumb(app, ui.ctx(), ThumbOf::Page(abs), th)).flatten() { Some(tex) => { ui.painter().image(tex.id(), pr, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), tint); } diff --git a/crates/ui-egui/src/panels/pages/tests.rs b/crates/ui-egui/src/panels/pages/tests.rs index 7e97a262d..62644227f 100644 --- a/crates/ui-egui/src/panels/pages/tests.rs +++ b/crates/ui-egui/src/panels/pages/tests.rs @@ -61,11 +61,11 @@ fn double_clicking_a_parent_shows_that_parent() { for name in names { assert_eq!(h.get_by_label(name).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True), name == "C-Parent", "{name}"); } - // Parent rows show a rendered thumbnail. + // Parent rows show a rendered thumbnail (of the revision before the double click until the + // document has been unchanged for THUMB_QUIET_SECS). let id = st.doc.parents[2].id; - let rev = (st.uid, st.revision); - let thumbs = super::THUMBS.lock().unwrap(); - assert!(thumbs.as_ref().unwrap().keys().any(|k| (k.0, k.1) == rev && k.2 == super::ThumbOf::Parent(id))); + let thumbs = super::THUMBS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert!(thumbs.as_ref().unwrap().keys().any(|k| k.0 == st.uid && k.1 == super::ThumbOf::Parent(id))); } fn harness(app: DesignApp) -> Harness<'static, DesignApp> { @@ -321,12 +321,58 @@ fn parent_thumbnails_follow_panel_options() { let id = st.doc.parents[0].id; let thumbs = super::THUMBS.lock().unwrap(); let keys = thumbs.as_ref().map(|m| m.keys().copied().collect::>()).unwrap_or_default(); - keys.into_iter().filter(|k| k.0 == st.uid && k.2 == super::ThumbOf::Parent(id)).map(|k| k.3).collect::>() + keys.into_iter().filter(|k| k.0 == st.uid && k.1 == super::ThumbOf::Parent(id)).map(|k| k.2).collect::>() }; assert_eq!(parent_thumb_heights(true), vec![IconSize::Large.row_h() as u32 - 5]); assert_eq!(parent_thumb_heights(false), Vec::::new()); } +/// Page thumbnails are rendered only for rows in view. After an edit the previous thumbnails stay +/// until the document has been unchanged for `THUMB_QUIET_SECS`, and then one is drawn again per +/// frame. Thumbnails of deleted pages are dropped. +#[test] +fn an_edit_redraws_only_thumbnails_in_view_one_per_frame() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 60, "facingPages": false})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut DesignApp, time: f64| { + let before = THUMB_RENDERS.with(std::cell::Cell::get); + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(280.0, 520.0))), + time: Some(time), + ..Default::default() + }; + ctx.run_ui(raw, |ui| show(app, ui)).textures_delta.clear(); + THUMB_RENDERS.with(std::cell::Cell::get) - before + }; + let shown: usize = (0..3).map(|_| frame(&mut app, 0.0)).sum(); + assert!(shown > 0 && shown < 60, "only the rows in view are rendered: {shown}"); + assert_eq!(frame(&mut app, 0.0), 0, "an unchanged document renders nothing"); + + app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap(); + assert_eq!(frame(&mut app, 1.0), 0, "the edit's frame keeps the previous thumbnails"); + assert_eq!(frame(&mut app, 1.0 + THUMB_QUIET_SECS / 2.0), 0, "still editing"); + let quiet = 1.0 + THUMB_QUIET_SECS + 0.01; + let mut redrawn = 0; + for _ in 0..shown { + let n = frame(&mut app, quiet); + assert_eq!(n, THUMB_REFRESHES_PER_FRAME, "one thumbnail per frame"); + redrawn += n; + } + assert_eq!(redrawn, shown); + assert_eq!(frame(&mut app, quiet), 0, "every thumbnail in view is current"); + + // Deleted pages lose their thumbnails. + let uid = app.session.active().unwrap().uid; + let cached = |abs: usize| { + THUMBS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).as_ref().unwrap().keys().any(|k| k.0 == uid && k.1 == ThumbOf::Page(abs)) + }; + assert!(cached(2)); + app.run("layout.pages.delete", json!({"pages": (2..60).collect::>()})).unwrap(); + frame(&mut app, quiet + 1.0); + assert!((2..60).all(|abs| !cached(abs)), "no thumbnail of a deleted page is kept"); +} + #[test] fn parents_are_added_duplicated_and_renamed_from_the_panel() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); From 81f0d766cfb54df1a61b11d07e7494cf19133949 Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 02:47:57 +0000 Subject: [PATCH 0931/1349] Apply review fixes - crates/images/src/resolution.rs - crates/render/src/decode.rs --- crates/images/src/resolution.rs | 8 +++----- crates/render/src/decode.rs | 2 +- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/crates/images/src/resolution.rs b/crates/images/src/resolution.rs index dabaf1c61..ea0a55eaa 100644 --- a/crates/images/src/resolution.rs +++ b/crates/images/src/resolution.rs @@ -178,7 +178,7 @@ pub fn tiff_resolution(tiff: &[u8]) -> Option<(f64, f64)> { /// The pHYs chunk: pixels-per-unit in x and y plus the unit (1 = meter → dpi). fn png_resolution(bytes: &[u8]) -> Option<(f64, f64)> { let mut pos = 8; - for _ in 0..64 { + loop { let len = u32::from_be_bytes(bytes.get(pos..pos + 4)?.try_into().ok()?) as usize; let kind = bytes.get(pos + 4..pos + 8)?; if kind == b"pHYs" { @@ -189,7 +189,7 @@ fn png_resolution(bytes: &[u8]) -> Option<(f64, f64)> { } return None; } - if kind == b"IEND" { + if kind == b"IEND" || kind == b"IDAT" { return None; } pos = pos.checked_add(8)?.checked_add(len)?.checked_add(4)?; @@ -197,7 +197,6 @@ fn png_resolution(bytes: &[u8]) -> Option<(f64, f64)> { return None; } } - None } // ---------- WebP ---------- @@ -207,7 +206,7 @@ fn webp_resolution(bytes: &[u8]) -> Option<(f64, f64)> { let riff = u32::from_le_bytes(bytes.get(4..8)?.try_into().ok()?) as usize; let end = 12usize.checked_add(riff)?.min(bytes.len()); let mut pos = 12; - for _ in 0..64 { + loop { let kind = bytes.get(pos..pos + 4)?; let size = u32::from_le_bytes(bytes.get(pos + 4..pos + 8)?.try_into().ok()?) as usize; let data = pos.checked_add(8)?; @@ -223,7 +222,6 @@ fn webp_resolution(bytes: &[u8]) -> Option<(f64, f64)> { } pos = data.checked_add(size.checked_add(size & 1)?)?; } - None } // ---------- BMP ---------- diff --git a/crates/render/src/decode.rs b/crates/render/src/decode.rs index df8e1f047..5047ca169 100644 --- a/crates/render/src/decode.rs +++ b/crates/render/src/decode.rs @@ -88,7 +88,7 @@ pub fn image_size(bytes: &[u8]) -> Option<(u32, u32)> { /// Natural size of a placed graphic, unrounded: a PDF page (crop box) and an SVG in points, a raster /// at its stored resolution (72 ppi without one), an EPS its bounding box independently of preview pixels. Placed graphics are drawn at -/// this size; `image_size` rounds it to whole pixels for display. +/// this size; `image_size` gives a raster's pixel size and rounds a PDF page or SVG to whole points. pub fn natural_size(bytes: &[u8], page: usize) -> Option<(f64, f64)> { if is_pdf(bytes) { return pdf_page_size(bytes, page).map(|(w, h)| (w.max(1e-3), h.max(1e-3))); From 099b89f53d40841bf79c4a6e2f24454e5e902ede Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 18:27:07 -0800 Subject: [PATCH 0932/1349] Preflight: check the document on a background worker, not on every edit The status bar's error count ran the whole-document preflight check on the interface thread for every new state of the document, so every drag step and every typed character waited for it. The Preflight panel ran the same check on every frame. The check composes every story and asks the file system about every linked graphic, so its cost grows with the document: on a 300-page document with 900 placed images it took 137 ms on a fast machine, and moving or resizing a frame and typing became unusable on large documents. The check now runs on a worker thread that takes the newest state of the document; the issues last found stay shown until it answers. An unchanged document is checked again every few seconds for linked files changed outside the app, a save under a new path or a font reload is checked again, and a check blocked on another document's linked file is handed off to a fresh worker after 200 ms. Tests and the web build check on the interface thread, once per state of the document. preflight::check_document takes the document, the composition cache and the save path, so the worker needs no session. --- ROADMAP.md | 1 + crates/engine/src/cmd/preflight.rs | 25 +- .../src/cmd/preflight/white_overprint.rs | 10 +- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/chrome/status_bar.rs | 2 +- crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/panels.rs | 18 +- crates/ui-egui/src/panels/properties/links.rs | 4 +- crates/ui-egui/src/preflight_worker.rs | 389 ++++++++++++++++++ crates/ui-egui/src/preflight_worker/tests.rs | 259 ++++++++++++ 10 files changed, 678 insertions(+), 34 deletions(-) create mode 100644 crates/ui-egui/src/preflight_worker.rs create mode 100644 crates/ui-egui/src/preflight_worker/tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index 006396b1d..4722bb5ba 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -387,6 +387,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log +- **2026-11-12** · The status bar's preflight count and the Preflight panel take their issues from a check on a background worker, which checks the newest state of the document and shows the issues last found meanwhile. Moving or resizing a frame and typing no longer wait for a check of the whole document on every drag step and keystroke. No readiness percentage change. - **2026-11-04** · Striped strokes retain out-and-back cubic segments whose second control point is away from the coincident endpoints and first control point. A geometry regression checks the offset extent and both stripe bands. No readiness percentage change. - **2026-11-04** · Esperanto is a text language (Character › Language, `type.char {language: "Esperanto"}`, IDML `$ID/Esperanto`): tag `eo`, English-style quotes; not hyphenated yet (#1201). No readiness percentage change. diff --git a/crates/engine/src/cmd/preflight.rs b/crates/engine/src/cmd/preflight.rs index 6fada503d..ff6512ad6 100644 --- a/crates/engine/src/cmd/preflight.rs +++ b/crates/engine/src/cmd/preflight.rs @@ -2,7 +2,7 @@ //! fonts and glyphs, missing or low-resolution graphics, RGB content in print documents, empty //! text frames, white or [Paper] set to overprint. -use designcraft_compose::ComposedStory; +use designcraft_compose::{Cache, ComposedStory}; use designcraft_doc::{Content, Document, Intent, Item, SpreadRef}; use designcraft_fonts::FaceRef; use designcraft_geom::Affine; @@ -99,8 +99,7 @@ fn missing_glyphs( /// its centre is on, and every page it reaches (see [`pages_of`]). type Located = (designcraft_doc::ItemId, Option, Vec); -fn overset_location(s: &Session, target: designcraft_doc::ItemId) -> Option { - let d = &s.active()?.doc; +fn overset_location(d: &Document, cache: &Cache, target: designcraft_doc::ItemId) -> Option { let at = |id: designcraft_doc::ItemId, loc: &designcraft_doc::ItemLoc| { let it = d.item(id); let xf = d.parent_xf(loc); @@ -131,7 +130,7 @@ fn overset_location(s: &Session, target: designcraft_doc::ItemId) -> Option) -> Vec { out.push(format!("a story with no text frame: {n} character(s) of it are not in the export")); continue; } - let location = last.and_then(|f| overset_location(s, f)); + let location = last.and_then(|f| overset_location(d, &s.cache, f)); let centre = location.as_ref().and_then(|(_, page, _)| *page); let touched: &[usize] = location.as_ref().map(|(_, _, ps)| ps.as_slice()).unwrap_or_default(); // A sheet draws its spread's items without asking which page they are on, so a frame @@ -263,8 +262,12 @@ pub fn overset_warnings(s: &Session, pages: Option<&[usize]>) -> Vec { pub fn check(s: &Session, min_ppi: f64) -> Vec { let Some(st) = s.active() else { return vec![] }; - let d = &st.doc; - let document = st.path.as_deref().map(std::path::Path::new); + check_document(&st.doc, &s.cache, st.path.as_deref().map(std::path::Path::new), min_ppi) +} + +/// [`check`] of document `d` saved at `document` (relative links resolve against it), with the +/// compositions in `cache`. It needs no session, so it can run on another thread. +pub fn check_document(d: &Document, cache: &Cache, document: Option<&std::path::Path>, min_ppi: f64) -> Vec { let mut out = Vec::new(); // Stories: overset and fonts. let mut missing_fonts: Vec = Vec::new(); @@ -274,11 +277,11 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec { // a cell's or an unplaced story, which has no frame of its own). let mut white_text: std::collections::BTreeMap, Vec<&'static str>> = std::collections::BTreeMap::new(); for story in d.stories.values() { - let cs = s.cache.get(d, story.id, None); + let cs = cache.get(d, story.id, None); missing_glyphs(&cs, None, 0, &mut missing); if cs.is_overset() { let last = story.frames.last().copied(); - let location = last.and_then(|f| overset_location(s, f)); + let location = last.and_then(|f| overset_location(d, cache, f)); let n = story.text.get(cs.overset_at.unwrap_or(0)..).unwrap_or("").chars().count(); let unplaced = story.frames.is_empty(); out.push(Issue { @@ -336,7 +339,7 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec { let props = d.styles.resolve_char(&base, f); let white = white_overprint::adornments(d, &props); if !white.is_empty() { - let shown = shown.get_or_insert_with(|| white_overprint::frame_ranges(s, d, story)); + let shown = shown.get_or_insert_with(|| white_overprint::frame_ranges(cache, d, story)); for frame in white_overprint::frames_showing(story, shown, run.start.max(range.start)..run.end.min(range.end)) { let parts = white_text.entry(frame).or_default(); for part in &white { @@ -386,7 +389,7 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec { for message in unsupported_typography { out.push(Issue { severity: "warning", kind: "unsupportedTypography", message, item: None, page: None }); } - let (white_items, printed_frames) = white_overprint::printed(s, d); + let (white_items, printed_frames) = white_overprint::printed(cache, d); for (item, parts) in white_text { // A frame PDF export leaves out (hidden, nonprinting, on a hidden or nonprintable layer, // on a parent page no page shows) prints none of its text. diff --git a/crates/engine/src/cmd/preflight/white_overprint.rs b/crates/engine/src/cmd/preflight/white_overprint.rs index 5df0d1fa2..7d9e8098a 100644 --- a/crates/engine/src/cmd/preflight/white_overprint.rs +++ b/crates/engine/src/cmd/preflight/white_overprint.rs @@ -12,13 +12,13 @@ use std::ops::Range; use std::sync::Arc; use designcraft_color::{Color, ColorType, SwatchValue, swatch}; +use designcraft_compose::Cache; use designcraft_doc::cjk_settings::AdornmentOverprint; use designcraft_doc::{AnchoredObject, CharProps, Content, Document, Item, ItemId, SpreadRef, Story, StrokeType}; use designcraft_geom::Affine; use designcraft_pdf::{drawn_children, item_exported, layer_exported, shown_parent_items}; use super::{Issue, page_of}; -use crate::Session; /// The issue's `kind`. pub(super) const KIND: &str = "whiteOverprint"; @@ -100,7 +100,7 @@ enum On { /// that show them, and anchored objects in the frames that place them. Returns the white /// overprint issues of those items, and the page each text frame among them is first drawn on /// (the frames whose ruby and kenten print). -pub(super) fn printed(s: &Session, d: &Document) -> (Vec, BTreeMap>) { +pub(super) fn printed(cache: &Cache, d: &Document) -> (Vec, BTreeMap>) { let mut issues = Vec::new(); let mut frames = BTreeMap::new(); // A parent page's item shows on every page based on it: it is reported once, on the first. @@ -129,7 +129,7 @@ pub(super) fn printed(s: &Session, d: &Document) -> (Vec, BTreeMap = drawn_children(it).map(|c| (Node::Item(c.clone()), inside, composed)).collect(); if let Content::Text(tf) = &it.content { frames.entry(it.id).or_insert(page); - let cs = s.cache.get(d, tf.story, composed); + let cs = cache.get(d, tf.story, composed); // The frame's anchored objects, and those in its footnotes and table cells. let mut pending: Vec<_> = cs.frame(it.id).into_iter().collect(); while let Some(frame) = pending.pop() { @@ -146,11 +146,11 @@ pub(super) fn printed(s: &Session, d: &Document) -> (Vec, BTreeMap Vec<(ItemId, Range)> { +pub(super) fn frame_ranges(cache: &Cache, d: &Document, story: &Story) -> Vec<(ItemId, Range)> { if story.frames.is_empty() { return Vec::new(); } - s.cache.get(d, story.id, None).frames.iter().map(|f| (f.frame, f.range.clone())).collect() + cache.get(d, story.id, None).frames.iter().map(|f| (f.frame, f.range.clone())).collect() } /// The frames of `story` that show the bytes `run` (`shown`: [`frame_ranges`]). `None` stands diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 88bd48c58..d848aa4ae 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -55,6 +55,7 @@ impl DesignApp { canvas: CanvasCache::new(), #[cfg(not(target_arch = "wasm32"))] links_worker: crate::links_worker::State::default(), + preflight: crate::preflight_worker::State::default(), canvas_rect: None, split: false, second_window: false, diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 5fde929be..c602b1721 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -164,7 +164,7 @@ pub fn status_bar(app: &mut DesignApp, ui: &mut egui::Ui) { crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "[Basic] (working) ▾")).font(small.clone())); ui.add_space(8.0); // Preflight: overset text is an error. - let errors = panels::preflight_errors(app); + let errors = panels::preflight_errors(app, ui.ctx()); let (r, dot) = ui.allocate_exact_size(vec2(9.0, 9.0), Sense::click()); ui.painter().circle_filled( r.center(), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 40bdfbcb3..77aa507f7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -38,6 +38,7 @@ pub mod package_dialog; mod page_history; mod panel_docking; pub mod panels; +mod preflight_worker; mod prefs; pub mod render_worker; mod rtl; @@ -158,6 +159,8 @@ pub struct DesignApp { /// operating-system timeout. #[cfg(not(target_arch = "wasm32"))] pub(crate) links_worker: links_worker::State, + /// Live preflight: the issues last found for the active document. + pub(crate) preflight: preflight_worker::State, pub canvas_rect: Option, /// Window › Arrange › Split Window: two views of the document side by side. pub split: bool, diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 2efdd9ec7..45606f4cd 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -299,21 +299,9 @@ pub fn text_attrs(app: &mut DesignApp) -> Option { if v.is_null() { None } else { Some(serde_json::to_value(v).ok()?) } } -/// Count preflight errors: overset stories (more checks land with the Preflight panel). -pub fn preflight_errors(app: &DesignApp) -> usize { - // Memoized per document snapshot (the status bar asks every frame). - static MEMO: std::sync::Mutex> = std::sync::Mutex::new(None); - let Some(st) = app.session.active() else { return 0 }; - let key = std::sync::Arc::as_ptr(&st.doc) as usize; - let mut g = MEMO.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if let Some((k, n)) = *g - && k == key - { - return n; - } - let n = designcraft_engine::cmd::preflight::check(&app.session, 150.0).iter().filter(|i| i.severity == "error").count(); - *g = Some((key, n)); - n +/// Count the preflight errors last found for the active document (0 until its first check ends). +pub fn preflight_errors(app: &mut DesignApp, ctx: &egui::Context) -> usize { + crate::preflight_worker::issues(app, ctx).map_or(0, |issues| issues.iter().filter(|i| i.severity == "error").count()) } /// Height of one swatch-menu row. diff --git a/crates/ui-egui/src/panels/properties/links.rs b/crates/ui-egui/src/panels/properties/links.rs index 5ee02ea79..7a1a6f0d0 100644 --- a/crates/ui-egui/src/panels/properties/links.rs +++ b/crates/ui-egui/src/panels/properties/links.rs @@ -300,7 +300,7 @@ pub fn info_panel(app: &mut DesignApp, ui: &mut egui::Ui) { pub fn preflight_panel(app: &mut DesignApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); - let issues = designcraft_engine::cmd::preflight::check(&app.session, 150.0); + let issues = crate::preflight_worker::issues(app, ui.ctx()).unwrap_or_default(); let errors = issues.iter().filter(|i| i.severity == "error").count(); ui.horizontal(|ui| { let (r, _) = ui.allocate_exact_size(vec2(10.0, 10.0), egui::Sense::hover()); @@ -323,7 +323,7 @@ pub fn preflight_panel(app: &mut DesignApp, ui: &mut egui::Ui) { ); }); divider(ui); - for i in issues { + for i in issues.iter() { let page = i.page.filter(|_| app.session.active().is_some()).map(|p| app.session.page_label(p)); let text = format!("{} {}", if i.severity == "error" { "⛔" } else { "⚠" }, i.message); let resp = ui.add(egui::Button::new(egui::RichText::new(text).size(11.0)).frame(false)); diff --git a/crates/ui-egui/src/preflight_worker.rs b/crates/ui-egui/src/preflight_worker.rs new file mode 100644 index 000000000..6abb67e0c --- /dev/null +++ b/crates/ui-egui/src/preflight_worker.rs @@ -0,0 +1,389 @@ +//! Live preflight for the status bar and the Preflight panel. +//! +//! A check reads every story's composition and every placed graphic's linked file, so on a long +//! document it takes much longer than a frame. On native builds it runs on a worker thread, which +//! checks the newest state of the document it was given; the issues last found for the document +//! stay shown until the check of its current state ends. The worker checks an unchanged document +//! again from time to time, for linked files changed outside the app. The web build and tests +//! check on the interface thread, once per state of the document. + +use std::sync::{Arc, Weak}; +#[cfg(not(target_arch = "wasm32"))] +use std::time::{Duration, Instant}; + +use designcraft_compose::Cache; +use designcraft_doc::Document; +use designcraft_engine::cmd::preflight::{Issue, check_document}; + +use crate::DesignApp; + +/// Lowest effective resolution, in pixels per inch, before a placed image is reported. +pub(crate) const MIN_PPI: f64 = 150.0; + +/// Documents whose issues are kept: going back to one shows its issues at once. +const MAX_DOCUMENTS: usize = 8; + +// An unchanged document is checked again after as long as its last check took, at least this +// long and at most `REFRESH_MAX`, so the worker is idle at least half the time. +#[cfg(not(target_arch = "wasm32"))] +const REFRESH_MIN: Duration = Duration::from_secs(2); +#[cfg(not(target_arch = "wasm32"))] +const REFRESH_MAX: Duration = Duration::from_secs(5 * 60); +// A check of another document still running this long after it was queued is blocked (a linked +// file on a share that doesn't answer): the active document gets a fresh worker. +#[cfg(not(target_arch = "wasm32"))] +const SUPERSEDE_AFTER: Duration = Duration::from_millis(200); +// Workers alive at once, counting replaced ones still blocked. +#[cfg(not(target_arch = "wasm32"))] +const MAX_WORKERS: usize = 4; +// A worker that couldn't be started, or that ended (a panic in a check), is tried again after +// this long. +#[cfg(not(target_arch = "wasm32"))] +const RETRY_AFTER: Duration = Duration::from_secs(30); + +/// A state of a document as a check sees it: which document, which state of it with which +/// compositions (a font reload replaces the cache and bumps the revision), and where it is saved +/// (relative links resolve against that). The state isn't kept alive: once it is dropped, no +/// later state can pass for it. +#[derive(Clone, Default)] +struct Checked { + uid: u64, + revision: u64, + doc: Weak, + cache: Weak, + path: Option, +} + +impl Checked { + fn new(app: &DesignApp) -> Option<(Self, Arc)> { + let st = app.session.active()?; + let of = Checked { + uid: st.uid, + revision: st.revision, + doc: Arc::downgrade(&st.doc), + cache: Arc::downgrade(&app.session.cache), + path: st.path.clone(), + }; + Some((of, Arc::clone(&st.doc))) + } + + fn same(&self, other: &Checked) -> bool { + self.uid == other.uid + && self.revision == other.revision + && self.path == other.path + && Weak::ptr_eq(&self.cache, &other.cache) + && self.doc.upgrade().zip(other.doc.upgrade()).is_some_and(|(a, b)| Arc::ptr_eq(&a, &b)) + } +} + +/// The issues found for one state of a document. +struct Found { + of: Checked, + issues: Arc>, + /// How long the check took. + #[cfg(not(target_arch = "wasm32"))] + took: Duration, + /// When the interface last asked for this state (`egui` input time, seconds). + #[cfg(not(target_arch = "wasm32"))] + asked_at: f64, +} + +#[derive(Default)] +pub(crate) struct State { + /// The issues last found for each of the documents checked last, oldest first. + found: Vec, + #[cfg(not(target_arch = "wasm32"))] + worker: Worker, + /// Checks run on the interface thread. + #[cfg(test)] + pub(crate) inline_checks: usize, +} + +impl State { + /// Keeps `found` in place of the issues found before for its document. + fn keep(&mut self, found: Found) { + self.found.retain(|f| f.of.uid != found.of.uid); + if self.found.len() >= MAX_DOCUMENTS { + self.found.remove(0); + } + self.found.push(found); + } +} + +/// The issues of the active document: those last found, which may be of an earlier state of it +/// while the worker checks the current one. `None` until the first check of the document ends. +pub(crate) fn issues(app: &mut DesignApp, ctx: &egui::Context) -> Option>> { + let now = ctx.input(|i| i.time); + issues_at(app, ctx, now) +} + +fn issues_at(app: &mut DesignApp, ctx: &egui::Context, now: f64) -> Option>> { + let (of, doc) = Checked::new(app)?; + let cache = Arc::clone(&app.session.cache); + let state = &mut app.preflight; + #[cfg(not(target_arch = "wasm32"))] + for mut done in state.worker.poll() { + done.asked_at = now; + state.keep(done); + } + if let Some(i) = state.found.iter().position(|f| f.of.same(&of)) { + // The active document's issues are the last to be dropped. + let shown = state.found.remove(i); + state.found.push(shown); + } + if let Some(found) = state.found.last_mut().filter(|f| f.of.same(&of)) { + let issues = Arc::clone(&found.issues); + #[cfg(not(target_arch = "wasm32"))] + if let Some(wait) = state.worker.retry_wait() { + if wait.is_zero() { + found.asked_at = now; + state.worker.ask(ctx, of, doc, &cache, true); + } else { + // Come back when a new worker may be tried. + ctx.request_repaint_after(wait); + } + } else if state.worker.enabled() { + let wait = refresh_after(found.took).as_secs_f64() - (now - found.asked_at); + if wait > 0.0 { + // Come back when the issues are due to be checked again, in case nothing else + // wakes the interface. + ctx.request_repaint_after(Duration::from_secs_f64(wait)); + } else { + found.asked_at = now; + state.worker.ask(ctx, of, doc, &cache, true); + } + } + return Some(issues); + } + #[cfg(not(target_arch = "wasm32"))] + if state.worker.ask(ctx, of.clone(), Arc::clone(&doc), &cache, false) { + return state.found.iter().find(|f| f.of.uid == of.uid).map(|f| Arc::clone(&f.issues)); + } + let _ = (ctx, now); + let issues = Arc::new(check_document(&doc, &cache, of.path.as_deref().map(std::path::Path::new), MIN_PPI)); + #[cfg(test)] + { + state.inline_checks += 1; + } + state.keep(Found { + of, + issues: Arc::clone(&issues), + #[cfg(not(target_arch = "wasm32"))] + took: Duration::ZERO, + #[cfg(not(target_arch = "wasm32"))] + asked_at: now, + }); + Some(issues) +} + +/// How long a check that took `took` stays current. +#[cfg(not(target_arch = "wasm32"))] +fn refresh_after(took: Duration) -> Duration { + took.clamp(REFRESH_MIN, REFRESH_MAX) +} + +#[cfg(not(target_arch = "wasm32"))] +struct Job { + of: Checked, + doc: Arc, + cache: Arc, +} + +#[cfg(not(target_arch = "wasm32"))] +type Channels = (std::sync::mpsc::SyncSender, std::sync::mpsc::Receiver); + +#[cfg(not(target_arch = "wasm32"))] +#[derive(Default)] +struct Worker { + channels: Option, + /// The state last asked for. + asked: Checked, + /// The job for that state while the worker's queue is full. A newer state replaces it, so at + /// most one job waits here, one in the queue and one is being checked. + waiting: Option, + /// The jobs queued whose results haven't arrived, oldest (the one being checked) first, each + /// with when it was queued. The worker answers each job in order, so there are at most two. + in_flight: std::collections::VecDeque<(Checked, Instant)>, + /// Worker threads alive, counting replaced ones still blocked. + live: Arc, + /// When the worker could not be started, or ended (a panic in a check). Checks run on the + /// interface thread until a new worker is tried, [`RETRY_AFTER`] later. + failed: Option, +} + +#[cfg(not(target_arch = "wasm32"))] +impl Worker { + /// Whether a worker runs or may be started. + fn enabled(&self) -> bool { + self.channels.is_some() || (background() && self.retry_due()) + } + + fn retry_due(&self) -> bool { + self.failed.is_none_or(|at| at.elapsed() >= RETRY_AFTER) + } + + /// How long until a new worker may be tried after one failed; `None` while one runs or when + /// none failed. + fn retry_wait(&self) -> Option { + if self.channels.is_some() { + return None; + } + self.failed.map(|at| RETRY_AFTER.saturating_sub(at.elapsed())) + } + + fn fail(&mut self) { + self.channels = None; + self.asked = Checked::default(); + self.waiting = None; + self.in_flight.clear(); + self.failed = Some(Instant::now()); + } + + /// Asks the worker for state `of` unless it was the last state asked for (`again` asks for it + /// anyway). False when there is no worker, so the caller checks on its own thread. + fn ask(&mut self, ctx: &egui::Context, of: Checked, doc: Arc, cache: &Arc, again: bool) -> bool { + if self.channels.is_none() { + if !background() || !self.retry_due() { + return false; + } + self.failed = None; + self.channels = spawn(ctx.clone(), &self.live); + if self.channels.is_none() { + self.fail(); + return false; + } + } + self.supersede_blocked(ctx, &of); + // A state already queued or being checked isn't asked for again. + let pending = self.in_flight.iter().any(|(job, _)| job.same(&of)) || self.waiting.as_ref().is_some_and(|job| job.of.same(&of)); + if (again && !pending) || !self.asked.same(&of) { + self.asked = of.clone(); + self.waiting = Some(Job { of, doc, cache: Arc::clone(cache) }); + } + self.send_waiting(); + self.channels.is_some() + } + + /// Replaces the worker when it is still on a job for another document queued more than + /// [`SUPERSEDE_AFTER`] ago, unless [`MAX_WORKERS`] are alive. The replaced thread ends when + /// its check returns; a job queued behind it is asked of the new worker. + fn supersede_blocked(&mut self, ctx: &egui::Context, of: &Checked) { + let Some(running) = self.in_flight.front().filter(|(job, _)| job.uid != of.uid).map(|(_, at)| at.elapsed()) else { return }; + if running < SUPERSEDE_AFTER { + // Come back when it has run that long, in case nothing else wakes the interface. + ctx.request_repaint_after(SUPERSEDE_AFTER - running); + return; + } + if self.live.load(std::sync::atomic::Ordering::Relaxed) >= MAX_WORKERS { + return; + } + if let Some(channels) = spawn(ctx.clone(), &self.live) { + self.channels = Some(channels); + self.in_flight.clear(); + self.asked = Checked::default(); + } + } + + /// Queues the waiting job if the worker's queue has room. + fn send_waiting(&mut self) { + let (Some(job), Some((tx, _))) = (self.waiting.take(), self.channels.as_ref()) else { return }; + let of = job.of.clone(); + match tx.try_send(job) { + Ok(()) => self.in_flight.push_back((of, Instant::now())), + Err(std::sync::mpsc::TrySendError::Full(job)) => self.waiting = Some(job), + Err(std::sync::mpsc::TrySendError::Disconnected(_)) => self.fail(), + } + } + + /// The results the worker sent since the last poll, oldest first. + fn poll(&mut self) -> Vec { + let Some((_, rx)) = self.channels.as_ref() else { return Vec::new() }; + let mut latest = Vec::new(); + loop { + match rx.try_recv() { + Ok(found) => { + self.in_flight.pop_front(); + latest.push(found); + } + Err(std::sync::mpsc::TryRecvError::Empty) => break, + Err(std::sync::mpsc::TryRecvError::Disconnected) => { + self.fail(); + break; + } + } + } + // The worker took a job and has room for the next. + self.send_waiting(); + latest + } + + /// Waits for the worker's next result. + #[cfg(test)] + fn wait(&mut self) -> Option { + let found = self.channels.as_ref()?.1.recv().ok()?; + self.in_flight.pop_front(); + self.send_waiting(); + Some(found) + } +} + +/// Whether checks run on the worker: not in tests (they can start one with [`start_worker`]) and +/// not with `DESIGNCRAFT_SYNC_RENDER` set. +#[cfg(not(target_arch = "wasm32"))] +fn background() -> bool { + !cfg!(test) && std::env::var_os("DESIGNCRAFT_SYNC_RENDER").is_none() +} + +/// Counts a worker thread as alive until it ends, however it ends. +#[cfg(not(target_arch = "wasm32"))] +struct Alive(Arc); + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for Alive { + fn drop(&mut self) { + self.0.fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn spawn(ctx: egui::Context, live: &Arc) -> Option { + let (tx, jobs) = std::sync::mpsc::sync_channel::(1); + let (done_tx, rx) = std::sync::mpsc::channel::(); + live.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let alive = Alive(Arc::clone(live)); + std::thread::Builder::new() + .name("designcraft-preflight".into()) + .spawn(move || { + let _alive = alive; + while let Ok(job) = jobs.recv() { + let started = Instant::now(); + let issues = check_document(&job.doc, &job.cache, job.of.path.as_deref().map(std::path::Path::new), MIN_PPI); + let found = Found { of: job.of, issues: Arc::new(issues), took: started.elapsed(), asked_at: 0.0 }; + // The checked state isn't kept alive by its check once the result is sent. + drop(job.doc); + if done_tx.send(found).is_err() { + break; + } + ctx.request_repaint(); + } + }) + .ok()?; + Some((tx, rx)) +} + +/// Starts the worker in a test, where checks otherwise run on the interface thread. +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) fn start_worker(app: &mut DesignApp, ctx: &egui::Context) { + app.preflight.worker.channels = spawn(ctx.clone(), &app.preflight.worker.live); +} + +/// Waits in a test for the worker's next result and keeps it, as a frame that polls would. +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) fn wait_for_worker(app: &mut DesignApp) { + if let Some(found) = app.preflight.worker.wait() { + app.preflight.keep(found); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/preflight_worker/tests.rs b/crates/ui-egui/src/preflight_worker/tests.rs new file mode 100644 index 000000000..f437a4174 --- /dev/null +++ b/crates/ui-egui/src/preflight_worker/tests.rs @@ -0,0 +1,259 @@ +use std::sync::Arc; + +use egui::vec2; +use serde_json::json; + +use super::Checked; +use crate::test_window; + +/// A document whose one text frame is too small for its text (one preflight error), with the +/// frame's id. +fn overset_app() -> (crate::DesignApp, u64) { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 3})).unwrap(); + let text = "Words that do not fit the frame. ".repeat(40); + let r = app.run("frame.create", json!({"rect": [72, 72, 200, 100], "content": "text", "text": text})).unwrap(); + app.run("edit.deselectAll", json!({})).unwrap(); + (app, r["id"].as_u64().unwrap()) +} + +/// The active document's current state. +fn current(app: &crate::DesignApp) -> Checked { + Checked::new(app).unwrap().0 +} + +/// The errors in the issues last found for the active document, and whether they are of its +/// current state. +fn found(app: &crate::DesignApp) -> Option<(usize, bool)> { + let now = current(app); + let f = app.preflight.found.iter().find(|f| f.of.uid == now.uid)?; + Some((f.issues.iter().filter(|i| i.severity == "error").count(), f.of.same(&now))) +} + +/// A worker whose thread never takes a job: the test reads the queue. +fn stalled_worker(app: &mut crate::DesignApp) -> (std::sync::mpsc::Receiver, std::sync::mpsc::Sender) { + let (tx, jobs) = std::sync::mpsc::sync_channel(1); + let (done, rx) = std::sync::mpsc::channel(); + app.preflight.worker.channels = Some((tx, rx)); + (jobs, done) +} + +/// Frames with the status bar and the Preflight panel showing check each state of the document +/// once, however many frames draw it. +#[test] +fn each_document_state_is_checked_once() { + let (mut app, id) = overset_app(); + app.ui.dock_tab = "properties".into(); + let mut h = test_window::open(app, vec2(1200.0, 700.0)); + h.state_mut().app.run("window.panel", json!({"panel": "preflight"})).unwrap(); + h.run_steps(20); + assert_eq!(h.state().app.preflight.inline_checks, 1); + assert_eq!(found(&h.state().app), Some((1, true))); + for k in 0..5 { + let dx = if k % 2 == 0 { 1.0 } else { -1.0 }; + h.state_mut().app.run("transform.move", json!({"ids": [id], "dx": dx, "dy": 0.0})).unwrap(); + h.run_steps(10); + } + assert_eq!(h.state().app.preflight.inline_checks, 6, "one check per edit"); + assert_eq!(found(&h.state().app), Some((1, true))); +} + +/// Saving under a new path changes where relative links resolve, and a font reload replaces the +/// compositions and bumps the revision: either way the document is checked again. +#[test] +fn a_new_save_path_or_font_reload_is_checked_again() { + let (mut app, _) = overset_app(); + let ctx = egui::Context::default(); + assert!(super::issues(&mut app, &ctx).is_some()); + assert!(super::issues(&mut app, &ctx).is_some()); + assert_eq!(app.preflight.inline_checks, 1); + let dir = tempfile::tempdir().unwrap(); + app.run("file.saveAs", json!({"path": dir.path().join("a.designcraft").to_string_lossy()})).unwrap(); + assert!(super::issues(&mut app, &ctx).is_some()); + assert_eq!(app.preflight.inline_checks, 2, "saved under a path"); + app.session.cache = Arc::new(designcraft_compose::Cache::new()); + assert!(super::issues(&mut app, &ctx).is_some()); + assert_eq!(app.preflight.inline_checks, 3, "new compositions"); + if let Some(st) = app.session.active_mut() { + st.bump_revision(); + } + assert!(super::issues(&mut app, &ctx).is_some()); + assert_eq!(app.preflight.inline_checks, 4, "a new revision"); + assert_eq!(found(&app), Some((1, true))); +} + +/// States asked for while the worker is busy don't queue up: one job waits in the worker's queue +/// and one beside it, the newest state, which replaces the one before. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_busy_worker_keeps_one_waiting_job() { + let (mut app, id) = overset_app(); + let ctx = egui::Context::default(); + let (jobs, _done) = stalled_worker(&mut app); + for k in 0..20 { + let dx = if k % 2 == 0 { 1.0 } else { -1.0 }; + app.run("transform.move", json!({"ids": [id], "dx": dx, "dy": 0.0})).unwrap(); + assert!(super::issues(&mut app, &ctx).is_none(), "nothing found yet"); + } + assert_eq!(app.preflight.inline_checks, 0); + let now = current(&app); + let waiting = app.preflight.worker.waiting.as_ref().expect("the newest state waits"); + assert!(waiting.of.same(&now)); + let queued = jobs.try_recv().expect("the first state is queued"); + assert!(!queued.of.same(&now)); + assert!(jobs.try_recv().is_err(), "nothing else is queued"); +} + +/// An unchanged document is checked again once its result is older than the refresh interval +/// (linked files can change outside the app), and not before. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn an_unchanged_document_is_checked_again_after_the_refresh_interval() { + let (mut app, _) = overset_app(); + let ctx = egui::Context::default(); + let (jobs, done) = stalled_worker(&mut app); + assert!(super::issues_at(&mut app, &ctx, 10.0).is_none()); + let job = jobs.try_recv().expect("the state is queued"); + done.send(super::Found { of: job.of, issues: Arc::new(vec![]), took: std::time::Duration::ZERO, asked_at: 0.0 }).unwrap(); + assert!(super::issues_at(&mut app, &ctx, 11.0).is_some(), "the worker's result"); + let refresh = super::REFRESH_MIN.as_secs_f64(); + assert!(super::issues_at(&mut app, &ctx, 11.0 + refresh - 0.5).is_some()); + assert!(jobs.try_recv().is_err(), "not checked again yet"); + assert!(super::issues_at(&mut app, &ctx, 11.0 + refresh).is_some(), "the last issues stay shown"); + assert!(jobs.try_recv().expect("checked again").of.same(¤t(&app))); + assert!(super::issues_at(&mut app, &ctx, 11.0 + refresh + 0.5).is_some()); + assert!(jobs.try_recv().is_err(), "asked once"); + // A check that outlasts the refresh interval isn't asked for again while it runs. + assert!(super::issues_at(&mut app, &ctx, 11.0 + 3.0 * refresh).is_some()); + assert!(jobs.try_recv().is_err(), "the check of this state is still running"); + assert_eq!(app.preflight.inline_checks, 0); +} + +/// Issues shown before they are due to be checked again ask for a frame at that time, so the check +/// runs even when nothing else wakes the interface. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn shown_issues_ask_for_a_frame_when_they_are_due_again() { + let (mut app, _) = overset_app(); + let ctx = egui::Context::default(); + let (jobs, done) = stalled_worker(&mut app); + assert!(super::issues_at(&mut app, &ctx, 10.0).is_none()); + let job = jobs.try_recv().expect("the state is queued"); + done.send(super::Found { of: job.of, issues: Arc::new(vec![]), took: std::time::Duration::ZERO, asked_at: 0.0 }).unwrap(); + for _ in 0..3 { + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); + } + assert!(!ctx.has_requested_repaint()); + assert!(super::issues_at(&mut app, &ctx, 11.0).is_some()); + assert!(ctx.has_requested_repaint()); +} + +/// A worker that ends leaves checks to the interface thread, and a new one is tried after +/// `RETRY_AFTER`. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_worker_that_ends_is_tried_again_later() { + let (mut app, _) = overset_app(); + let ctx = egui::Context::default(); + let (_jobs, done) = stalled_worker(&mut app); + drop(done); + assert_eq!(super::issues(&mut app, &ctx).map(|i| i.iter().filter(|i| i.severity == "error").count()), Some(1)); + assert_eq!(app.preflight.inline_checks, 1, "checked on the interface thread"); + assert!(app.preflight.worker.channels.is_none() && !app.preflight.worker.retry_due()); + // The shown issues ask for a frame when a new worker may be tried. + for _ in 0..3 { + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); + } + assert!(!ctx.has_requested_repaint()); + assert!(super::issues(&mut app, &ctx).is_some()); + assert!(ctx.has_requested_repaint()); + assert_eq!(app.preflight.inline_checks, 1); + let worker = &mut app.preflight.worker; + worker.failed = std::time::Instant::now().checked_sub(super::RETRY_AFTER); + assert!(worker.retry_due()); + assert_eq!(worker.retry_wait(), Some(std::time::Duration::ZERO)); +} + +/// A check of another document that has been running longer than `SUPERSEDE_AFTER` (a file +/// on a share that doesn't answer) doesn't hold up the active document: a fresh worker takes it. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_blocked_check_of_another_document_is_superseded() { + let (mut app, _) = overset_app(); + let ctx = egui::Context::default(); + let (jobs, _done) = stalled_worker(&mut app); + let mut other = current(&app); + other.uid += 1; + let long_ago = std::time::Instant::now().checked_sub(super::SUPERSEDE_AFTER * 2).unwrap(); + let in_flight = |app: &crate::DesignApp| app.preflight.worker.in_flight.iter().map(|(of, _)| of.same(¤t(app))).collect::>(); + // Asked while the other document's check had only just started: the active document's job is + // queued behind it. + app.preflight.worker.in_flight.push_back((other.clone(), std::time::Instant::now())); + for _ in 0..3 { + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); + } + assert!(!ctx.has_requested_repaint()); + assert!(super::issues(&mut app, &ctx).is_none()); + assert!(ctx.has_requested_repaint(), "a frame comes back to see whether it is blocked"); + assert!(jobs.try_recv().is_ok_and(|job| job.of.same(¤t(&app))), "queued behind the other document's check"); + assert_eq!(in_flight(&app), vec![false, true]); + // A later frame, once that check has been running too long, moves the job to a fresh worker. + app.preflight.worker.in_flight.front_mut().unwrap().1 = long_ago; + assert!(super::issues(&mut app, &ctx).is_none()); + assert!(jobs.try_recv().is_err(), "the blocked worker gets nothing more"); + assert_eq!(in_flight(&app), vec![true], "the fresh worker has the active document"); + // The same document's own earlier state waits for its worker instead. + let (jobs, _done) = stalled_worker(&mut app); + let mut earlier = current(&app); + earlier.revision += 1; + app.preflight.worker.in_flight = [(earlier, long_ago)].into(); + app.preflight.worker.asked = Checked::default(); + assert!(super::issues(&mut app, &ctx).is_none()); + assert!(jobs.try_recv().is_ok(), "queued on the same worker"); +} + +/// A result for another document keeps the active document's issues, and the issues of at most +/// `MAX_DOCUMENTS` documents are kept. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn another_documents_result_keeps_the_active_documents_issues() { + let (mut app, _) = overset_app(); + let ctx = egui::Context::default(); + let errors = |app: &mut crate::DesignApp| super::issues(app, &ctx).map(|i| i.iter().filter(|i| i.severity == "error").count()); + assert_eq!(errors(&mut app), Some(1)); + let (_jobs, done) = stalled_worker(&mut app); + for k in 1..=super::MAX_DOCUMENTS as u64 + 2 { + let mut other = current(&app); + other.uid += k; + done.send(super::Found { of: other, issues: Arc::new(vec![]), took: std::time::Duration::ZERO, asked_at: 0.0 }).unwrap(); + assert_eq!(errors(&mut app), Some(1), "the active document's issues"); + } + assert_eq!(app.preflight.found.len(), super::MAX_DOCUMENTS); + assert_eq!(app.preflight.inline_checks, 1); +} + +/// With the worker running, edits and the frames that draw them run no check on the interface +/// thread. The count last found stays shown until the worker has checked the current state. +#[test] +fn the_worker_checks_and_the_interface_thread_does_not() { + let (app, id) = overset_app(); + let mut h = test_window::open(app, vec2(1200.0, 700.0)); + let ctx = h.ctx.clone(); + assert_eq!(found(&h.state().app), Some((1, true)), "checked on the interface thread before the worker starts"); + super::start_worker(&mut h.state_mut().app, &ctx); + h.state_mut().app.preflight.inline_checks = 0; + for k in 0..20 { + let dx = if k % 2 == 0 { 1.0 } else { -1.0 }; + h.state_mut().app.run("transform.move", json!({"ids": [id], "dx": dx, "dy": 0.0})).unwrap(); + h.run_steps(1); + assert_eq!(found(&h.state().app).map(|f| f.0), Some(1), "the count last found stays shown"); + } + assert_eq!(h.state().app.preflight.inline_checks, 0, "no check ran on the interface thread"); + // The last frame handed the current state to the worker, whose last answer is for it. + while found(&h.state().app) != Some((1, true)) { + super::wait_for_worker(&mut h.state_mut().app); + } + let issues = super::issues(&mut h.state_mut().app, &ctx).unwrap(); + assert_eq!(issues.iter().filter(|i| i.severity == "error").count(), 1); + assert_eq!(h.state().app.preflight.inline_checks, 0, "the worker's answer is kept, not checked again"); +} From 0a8e9a5697e48394a07d19cc79c3e63a6127510b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 18:56:30 -0800 Subject: [PATCH 0933/1349] Canvas: moving an object with a drop shadow repaints only its area Damage treated any object with an effect as unbounded, so every drag step of a frame with a drop shadow, outer glow, feather or inner effect rendered the whole canvas again. An object's own effects are now bounded: the drop shadow and outer glow by the reach the renderer draws them with, the inner effects and feathers by the shape. Effects on items nested in a group still repaint everything. Strokes are drawn through the item's transform, so the stroke allowance now scales with it, and the strokes of a group's children count toward the group's area. --- crates/render/src/damage.rs | 135 +++++++++++++++++++++++++++-- crates/ui-egui/src/canvas/tests.rs | 28 ++++++ 2 files changed, 155 insertions(+), 8 deletions(-) diff --git a/crates/render/src/damage.rs b/crates/render/src/damage.rs index ff76e0ecb..bacd3864c 100644 --- a/crates/render/src/damage.rs +++ b/crates/render/src/damage.rs @@ -158,36 +158,52 @@ fn shows_other_text(d: &Document, s: &Story) -> bool { fn item_area(it: &Item) -> Option { let mut ok = true; it.walk(&mut |i| { - // Effects spill outside; text wrap reflows other frames. - if i.effects.any() || i.has_wrap() { + // Text wrap reflows other frames. A nested item's effects are drawn through its parents' + // transforms, which can scale how far they reach. + if i.has_wrap() || !std::ptr::eq(i, it) && i.effects.any() { ok = false; } }); if !ok { return None; } - let pad = it.stroke.extent().max(0.0) + 2.0 + if it.is_text_frame() { 24.0 } else { 0.0 }; - Some(painted_bounds(it).inflate(pad, pad)) + // The stroke is drawn through the item's transform. The item's own drop shadow and outer glow + // reach `fx::outset` past what it paints; its inner effects and feathers stay inside the shape. + let stroke = it.stroke.extent().max(0.0) * max_scale(it.xf)?; + let pad = stroke + 2.0 + if it.is_text_frame() { 24.0 } else { 0.0 } + crate::fx::outset(it); + Some(painted_bounds(it)?.inflate(pad, pad)) +} + +/// The largest factor `m` stretches a length by (its linear part's largest singular value), or +/// None when that is not finite. +fn max_scale(m: designcraft_geom::Affine) -> Option { + let [a, b, c, d, _, _] = m.as_coeffs(); + let s = a * a + b * b + c * c + d * d; + let det = a * d - b * c; + let v = ((s + (s * s - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt(); + v.is_finite().then_some(v) } /// An item's bounds, grown to its text: text is composed in the box around the frame's path in /// the frame's own coordinates, which a sheared then rotated frame turns past its path's bounds. -fn painted_bounds(it: &Item) -> Rect { +/// Its children's bounds include their strokes. None when a child's transform is not finite. +fn painted_bounds(it: &Item) -> Option { let mut b = it.bounds(); if it.is_text_frame() { b = b.union(it.xf.transform_rect_bbox(it.inner_bounds())); } for c in it.children() { - b = b.union(it.xf.transform_rect_bbox(painted_bounds(c))); + let stroke = c.stroke.extent().max(0.0) * max_scale(c.xf)?; + b = b.union(it.xf.transform_rect_bbox(painted_bounds(c)?.inflate(stroke, stroke))); } - b + Some(b) } /// A text frame's area: its spread and bounds with room for glyph overhang. fn frame_area(d: &Document, f: ItemId) -> Option<(SpreadRef, Rect)> { let loc = d.find(f)?; let it = d.item_at(&loc)?; - let b = d.parent_xf(&loc).transform_rect_bbox(painted_bounds(it)); + let b = d.parent_xf(&loc).transform_rect_bbox(painted_bounds(it)?); // Overhang of italics, swashes and big initials, and anchored objects pinned to lines. Some((loc.spread, b.inflate(24.0 + 0.1 * b.width().max(b.height()), 24.0))) } @@ -384,4 +400,107 @@ mod tests { let spreads: Vec = dmg.iter().map(|(r, _)| *r).collect(); assert!(spreads.contains(&SpreadRef::Doc(1)), "{dmg:?}"); } + + /// Moving an object with a drop shadow or an outer glow damages where its effect was and is, + /// and every pixel the move changes lies in that damage: the canvas repaints those regions, + /// not the whole view. + #[test] + fn moving_an_object_with_a_shadow_or_glow_damages_its_effect_area() { + for glow in [false, true] { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let lid = d.default_layer(); + let id = ItemId(d.alloc()); + let mut it = + Item::new(id, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 250.0, 200.0))); + it.fill = designcraft_doc::Fill::swatch(designcraft_color::swatch::BLACK); + if glow { + let g = &mut it.effects.outer_glow; + (g.on, g.color, g.opacity, g.size, g.spread) = (true, designcraft_color::swatch::BLACK.into(), 1.0, 30.0, 20.0); + } else { + let s = &mut it.effects.drop_shadow; + (s.on, s.color, s.opacity, s.size, s.distance, s.spread) = (true, designcraft_color::swatch::BLACK.into(), 1.0, 20.0, 25.0, 30.0); + } + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let old = d.clone(); + let it = d.item_mut(id).unwrap(); + it.path.transform(designcraft_geom::Affine::translate((60.0, 40.0))); + let changed = changed_pixels_in_damage(&old, &d); + assert!(changed.iter().any(|p| !Rect::new(98.0, 98.0, 312.0, 242.0).contains(*p)), "glow {glow}: the effect paints outside the object"); + } + // An effect on an object inside a group is drawn through the group's transform: unbounded. + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let lid = d.default_layer(); + let mut child = + Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 9.0, 9.0))); + child.effects.drop_shadow.on = true; + let gid = ItemId(d.alloc()); + let mut group = Item::new(gid, lid, designcraft_doc::Shape::Group, Default::default()); + group.content = designcraft_doc::Content::Group { items: vec![Arc::new(child)] }; + d.insert_item(SpreadRef::Doc(0), group, None).unwrap(); + let old = d.clone(); + d.item_mut(gid).unwrap().xf = designcraft_geom::Affine::scale(4.0); + assert!(damage(&old, &d).is_none()); + } + + /// A stroke is drawn through its item's transform: a frame scaled up paints its stroke that + /// much wider, and moving it damages all of it. + #[test] + fn moving_a_scaled_frame_damages_its_whole_stroke() { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let lid = d.default_layer(); + let id = ItemId(d.alloc()); + let mut it = Item::new(id, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(50.0, 50.0, 125.0, 100.0))); + it.xf = designcraft_geom::Affine::scale(2.0); + it.stroke.swatch = designcraft_color::swatch::BLACK.into(); + it.stroke.weight = 20.0; + it.stroke.align = designcraft_doc::StrokeAlign::Outside; + it.effects.outer_glow.on = true; + it.effects.outer_glow.size = 0.0; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let old = d.clone(); + let it = d.item_mut(id).unwrap(); + it.xf = designcraft_geom::Affine::translate((60.0, 40.0)) * it.xf; + // The stroke reaches 40 pt past the frame's 100..250 × 100..200 outline on the spread. + let changed = changed_pixels_in_damage(&old, &d); + assert!(changed.iter().any(|p| p.x < 70.0), "the stroke paints its scaled width"); + // The same frame inside a group with a gradient feather: the child's stroke counts too. + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let mut child = old.spreads[0].items[0].as_ref().clone(); + child.effects = Default::default(); + child.id = ItemId(d.alloc()); + let gid = ItemId(d.alloc()); + let outline = designcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 250.0, 200.0)); + let mut group = Item::new(gid, d.default_layer(), designcraft_doc::Shape::Group, outline); + group.content = designcraft_doc::Content::Group { items: vec![Arc::new(child)] }; + let gf = &mut group.effects.gradient_feather; + (gf.on, gf.start, gf.end) = (true, 1.0, 0.5); + d.insert_item(SpreadRef::Doc(0), group, None).unwrap(); + let old = d.clone(); + d.item_mut(gid).unwrap().xf = designcraft_geom::Affine::translate((60.0, 40.0)); + let changed = changed_pixels_in_damage(&old, &d); + assert!(changed.iter().any(|p| p.x < 70.0), "the child's stroke paints its scaled width"); + } + + /// The pixels a page render changes from `old` to `new`, each checked to lie in the damage. + fn changed_pixels_in_damage(old: &Document, new: &Document) -> Vec { + let dmg = damage(old, new).expect("bounded damage"); + let cache = designcraft_compose::Cache::new(); + let mut r = crate::Renderer::new(); + r.threads = 0; + let opts = crate::RenderOptions::default(); + let before = r.render_page(old, &cache, 0, 1.0, false, &opts).unwrap(); + let after = r.render_page(new, &cache, 0, 1.0, false, &opts).unwrap(); + let mut changed = Vec::new(); + for y in 0..before.height { + for x in 0..before.width { + if before.pixel(x, y) == after.pixel(x, y) { + continue; + } + let p = designcraft_geom::Point::new(f64::from(x) + 0.5, f64::from(y) + 0.5); + assert!(dmg.iter().any(|(_, r)| r.inflate(1.0, 1.0).contains(p)), "changed pixel {p:?} outside {dmg:?}"); + changed.push(p); + } + } + changed + } } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 62064ea79..685c1b205 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -2176,6 +2176,34 @@ fn edits_patch_the_canvas_only_at_full_resolution() { } } +/// Moving a frame with a drop shadow repaints the regions the frame and its shadow cover, as +/// moving one without a shadow does, instead of rendering the whole canvas again on every step. +#[test] +fn moving_a_frame_with_a_drop_shadow_patches_the_canvas() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let frame = |app: &mut DesignApp| { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 900.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + app.run("file.new", json!({})).unwrap(); + app.run("frame.create", json!({"rect": [72, 72, 200, 180], "content": "unassigned"})).unwrap(); + app.run("object.fill", json!({"swatch": "[Black]"})).unwrap(); + app.run("object.dropShadow", json!({"on": true})).unwrap(); + for _ in 0..3 { + frame(&mut app); + } + for step in 1..=3 { + app.run("transform.move", json!({"dx": 4, "dy": 2})).unwrap(); + frame(&mut app); + assert_eq!(app.canvas.patches, step, "drag step {step} repaints only what changed"); + } +} + /// The Type tool's caret at the end of a new text frame holding `text`, the app's first frames /// drawn; returns the story id. fn typing_app(app: &mut DesignApp, ctx: &egui::Context, text: &str) -> Value { From 18be5b76f5972905fdc4d4638ef1ab5f126fd143 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:06:29 -0800 Subject: [PATCH 0934/1349] Text: Text Frame Options in a footnote or table cell change the frame that shows it With the insertion point in footnote text or a table cell and no stored frame on the caret, Text Frame Options changed the last frame of the thread. They now change the frame the caret is drawn in: the frame that holds the placed footnote, or the cell's own occurrence (not a repeated header or footer), else the frame that shows the footnote reference or the table's anchor. --- crates/engine/src/cmd/object.rs | 96 +++++++++++++++++++++++++++++++-- docs/mcp.md | 3 +- 2 files changed, 94 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 67b1d21d4..50628d2bc 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -2807,11 +2807,24 @@ fn text_selection_frames(s: &Session, t: &TextSel) -> Vec { let Ok(st) = s.doc() else { return Vec::new() }; let Some(story) = st.doc.story(t.story) else { return Vec::new() }; let last = story.frames.last().copied(); - // In a table cell, `anchor` and `focus` index the cell's text: the frame the caret is shown in. - if t.cell.is_some() { - return t.frame.filter(|f| story.frames.contains(f)).or(last).into_iter().collect(); - } let cs = s.cache.get(&st.doc, t.story, None); + // In footnote text or a table cell, `anchor` and `focus` index that text: the frame the caret + // is drawn in (the placed footnote, or the cell's first non-repeated occurrence), else the + // frame that shows the footnote reference or the table's anchor character. + if let Some(c) = t.cell { + let (drawn, anchor) = match c.footnote_id() { + Some(id) => (designcraft_compose::find_note(&cs, id).map(|(fi, _)| fi), story.note_anchor(id)), + None => (designcraft_compose::find_cell(&cs, c.table, c.row, c.col).map(|(fi, ..)| fi), story.table_anchor(c.table)), + }; + return drawn + .or_else(|| anchor.and_then(|a| designcraft_compose::caret(&cs, a)).map(|(fi, ..)| fi)) + .and_then(|fi| cs.frames.get(fi)) + .map(|f| f.frame) + .or_else(|| t.frame.filter(|f| story.frames.contains(f))) + .or(last) + .into_iter() + .collect(); + } let r = t.range(); // The frame the caret at the start is drawn in; the caret's stored frame only when no line // holds it. @@ -5086,6 +5099,81 @@ mod type_tool_frame_options_tests { assert_eq!(s.execute("object.textFrameOptions", &fixed).unwrap()["changed"], 0); assert_eq!(undo_steps(&s), steps + 1, "the same Fixed Width options again add no undo step"); } + + /// A caret in footnote text changes the frame that shows the footnote, with or without a + /// stored frame on the caret. + #[test] + fn a_caret_in_a_footnote_changes_the_frame_that_shows_it() { + for (in_second, stored) in [(false, None), (true, None), (false, Some(true))] { + let mut s = Session::new(); + let (a, b, sid) = two_frame_thread(&mut s); + let r = shown(&s, sid, if in_second { b } else { a }); + s.execute("text.select", &json!({"story": sid.0, "anchor": r.start + 2})).unwrap(); + s.execute("footnote.insert", &json!({"text": "Note."})).unwrap(); + let mut t = s.doc().unwrap().selection.text.unwrap(); + assert!(t.cell.and_then(|c| c.footnote_id()).is_some(), "the caret is in the footnote: {t:?}"); + if let Some(second) = stored { + t.frame = Some(if second { b } else { a }); + s.doc_mut().unwrap().selection = Selection::text(t); + } + s.execute("object.textFrameOptions", &json!({"columns": 2})).unwrap(); + let want = if in_second { (1, 2) } else { (2, 1) }; + assert_eq!((options(&s, a).columns, options(&s, b).columns), want, "footnote in the second frame: {in_second}, stored frame: {stored:?}"); + } + } + + /// A caret in a table cell changes the frame that shows the cell, with or without a stored + /// frame on the caret. + #[test] + fn a_caret_in_a_table_cell_changes_the_frame_that_shows_it() { + for (in_second, stored) in [(false, None), (true, None), (false, Some(true))] { + let mut s = Session::new(); + let (a, b, sid) = two_frame_thread(&mut s); + let r = shown(&s, sid, if in_second { b } else { a }); + s.execute("text.select", &json!({"story": sid.0, "anchor": r.start + 2})).unwrap(); + s.execute("table.insert", &json!({"rows": 1, "cols": 1})).unwrap(); + let mut t = s.doc().unwrap().selection.text.unwrap(); + assert!(t.cell.is_some_and(|c| c.footnote_id().is_none()), "the caret is in the cell: {t:?}"); + if let Some(second) = stored { + t.frame = Some(if second { b } else { a }); + s.doc_mut().unwrap().selection = Selection::text(t); + } + s.execute("object.textFrameOptions", &json!({"columns": 2})).unwrap(); + let want = if in_second { (1, 2) } else { (2, 1) }; + assert_eq!((options(&s, a).columns, options(&s, b).columns), want, "table in the second frame: {in_second}, stored frame: {stored:?}"); + } + } + + /// A caret in a repeated footer row is drawn in the footer's own occurrence at the end of the + /// table: that frame changes, not the earlier frame that shows a repeat of the footer. + #[test] + fn a_caret_in_a_repeated_footer_changes_the_frame_with_the_footer_itself() { + let mut s = Session::new(); + let (a, b, sid) = two_frame_thread(&mut s); + let ra = shown(&s, sid, a); + s.execute("text.select", &json!({"story": sid.0, "anchor": ra.start + 2})).unwrap(); + s.execute("table.insert", &json!({"rows": 15, "cols": 1, "footerRows": 1})).unwrap(); + s.execute("table.options", &json!({"repeatFooter": true})).unwrap(); + let t = s.doc().unwrap().selection.text.unwrap(); + let table = t.cell.unwrap().table; + let footer = s.doc().unwrap().doc.story(sid).unwrap().tables.get(&table).unwrap().nrows() - 1; + let cs = designcraft_compose::compose_story(&s.doc().unwrap().doc, sid, &Default::default()); + let placed = |f: ItemId| { + cs.frame(f) + .unwrap() + .tables + .iter() + .filter(|tf| tf.table == table) + .filter_map(|tf| tf.cell(footer, 0)) + .map(|c| c.repeated) + .collect::>() + }; + assert_eq!((placed(a), placed(b)), (vec![true], vec![false]), "the footer repeats in the first frame and ends the table in the second"); + s.doc_mut().unwrap().selection = + Selection::text(TextSel { cell: Some(designcraft_doc::CellAddr { table, row: footer, col: 0 }), anchor: 0, focus: 0, frame: None, ..t }); + s.execute("object.textFrameOptions", &json!({"columns": 2})).unwrap(); + assert_eq!((options(&s, a).columns, options(&s, b).columns), (1, 2)); + } } #[cfg(test)] diff --git a/docs/mcp.md b/docs/mcp.md index 17c7e330b..d9a15256a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -228,7 +228,8 @@ With a text selection, this formats the selected paragraphs; with selected text `object.textFrameOptions` (columns, inset spacing, vertical justification and the rest of Text Frame Options) acts on the selected frames or on the `ids` the call passes. With the Type tool and no frame selected, it acts on the frame that shows the insertion point, or on every frame that holds part of the selected text, not on the other frames of the -thread. An empty `ids` is an error. Options a frame already has leave the document unchanged and add no undo step. +thread. With the insertion point in a footnote or a table cell, it acts on the frame that shows the footnote or the +cell. An empty `ids` is an error. Options a frame already has leave the document unchanged and add no undo step. ```text execute {"command": "object.textFrameOptions", "params": {"verticalJustification": "center", "inset": 6}} From e5010f363c8659b26da277fb14f2a2e8bcc78ee6 Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 03:07:11 +0000 Subject: [PATCH 0935/1349] Apply review fixes - crates/ui-egui/src/panels/pages.rs --- crates/ui-egui/src/panels/pages.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/panels/pages.rs b/crates/ui-egui/src/panels/pages.rs index ff8e2f3c7..8825a5bf2 100644 --- a/crates/ui-egui/src/panels/pages.rs +++ b/crates/ui-egui/src/panels/pages.rs @@ -83,6 +83,7 @@ fn thumb(app: &mut DesignApp, ctx: &egui::Context, of: ThumbOf, h: f32) -> Optio } if let Some((rev, t)) = map.get(&key) { if *rev == st.revision { + ctx.data_mut(|d| d.insert_temp(clock_id, clock)); return Some(t.clone()); } let wait = THUMB_QUIET_SECS - (now - clock.changed_at); From 7ba1f8b96f6f84874045294dc7d023b4af48f27d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:07:29 -0800 Subject: [PATCH 0936/1349] Place: test PNG and WebP resolution past 64 chunks Tests read a pHYs chunk behind 100 text chunks in a PNG, ignore a pHYs after the image data, and read an EXIF chunk stored after 100 frames of an animated WebP. --- crates/images/src/tests.rs | 50 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index f2fcf2bf0..1803b310a 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -626,6 +626,56 @@ fn png_phys_sets_natural_size() { assert_eq!(natural_size(&plain), Some((4.0, 4.0))); } +/// A pHYs chunk behind 100 text chunks is still read, and the scan stops at the first IDAT. +#[test] +fn png_phys_after_many_chunks_is_read() { + fn chunk(out: &mut Vec, kind: &[u8; 4], data: &[u8]) { + out.extend_from_slice(&(data.len() as u32).to_be_bytes()); + out.extend_from_slice(kind); + out.extend_from_slice(data); + out.extend_from_slice(&[0, 0, 0, 0]); + } + let mut phys = 11811u32.to_be_bytes().repeat(2); + phys.push(1); + let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); + chunk(&mut png, b"IHDR", &[0; 13]); + for _ in 0..100 { + chunk(&mut png, b"tEXt", b"Comment\x00x"); + } + let mut late = png.clone(); + chunk(&mut png, b"pHYs", &phys); + let (dx, dy) = raster_resolution(&png).unwrap(); + assert!((dx - 300.0).abs() < 0.05 && (dy - 300.0).abs() < 0.05, "{dx} x {dy}"); + // A pHYs after the image data is not read. + chunk(&mut late, b"IDAT", &[0; 4]); + chunk(&mut late, b"pHYs", &phys); + assert_eq!(raster_resolution(&late), None); +} + +/// An EXIF chunk stored after 100 animation frames of a WebP is still read. +#[test] +fn webp_exif_after_many_frames_is_read() { + fn chunk(out: &mut Vec, kind: &[u8; 4], data: &[u8]) { + out.extend_from_slice(kind); + out.extend_from_slice(&(data.len() as u32).to_le_bytes()); + out.extend_from_slice(data); + if data.len() % 2 == 1 { + out.push(0); + } + } + let mut body = b"WEBP".to_vec(); + chunk(&mut body, b"VP8X", &[0; 10]); + chunk(&mut body, b"ANIM", &[0; 6]); + for _ in 0..100 { + chunk(&mut body, b"ANMF", &[0; 17]); + } + chunk(&mut body, b"EXIF", &tiff_bytes((300, 1), (300, 1), Some(2))); + let mut webp = b"RIFF".to_vec(); + webp.extend_from_slice(&(body.len() as u32).to_le_bytes()); + webp.extend_from_slice(&body); + assert_eq!(raster_resolution(&webp), Some((300.0, 300.0))); +} + /// A real encoder-written BMP with the header pixels-per-meter patched (compression and image /// size stay zero, as the encoder writes them). fn bmp_with_ppm(ppm: i32) -> Vec { From 4b06bb219c04bd75ffd8931473e9553de622a1e4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:14:37 -0800 Subject: [PATCH 0937/1349] Render: keep drop shadow and outer glow images while an object moves The canvas drew and blurred every drop shadow and outer glow on every render, also when the object or the view had only moved. Each image is now kept per object, effect, page and ink pass, with the whole effect drawn once. While the object (apart from its position), the effect, the view's scale and rotation, the render options and the document's colours, styles, layers and images stay the same, a move by whole device pixels places the kept image again. Any other change draws it afresh. Only multithreaded renders (the canvas) keep images, and only for objects without text or nested items. Kept images are limited to 4 Mpx each and 128 MiB in all; the images used longest ago go first, and an image no render placed in 256 renders is dropped. --- crates/render/src/driver.rs | 5 +- crates/render/src/fx.rs | 417 ++++++++++++++++++++++++++++++++++-- crates/render/src/lib.rs | 2 + 3 files changed, 403 insertions(+), 21 deletions(-) diff --git a/crates/render/src/driver.rs b/crates/render/src/driver.rs index a5dd2b86b..b9568a595 100644 --- a/crates/render/src/driver.rs +++ b/crates/render/src/driver.rs @@ -15,6 +15,7 @@ impl Renderer { drawing_items: Vec::new(), cmyk_view: None, cmyk_ran: false, + kept: Default::default(), #[cfg(test)] cmyk_passes: 0, #[cfg(test)] @@ -26,11 +27,12 @@ impl Renderer { } } - /// Drop cached glyph paths and the CMYK viewport (rebuilt on demand). + /// Drop cached glyph paths, effect images and the CMYK viewport (rebuilt on demand). pub fn clear_caches(&mut self) { self.cmyk_view = None; self.glyphs.clear(); self.stories.clear(); + self.kept.clear(); } /// Number of text frames whose glyph paths are cached. @@ -88,6 +90,7 @@ impl Renderer { self.stats = FrameStats::default(); self.stories.clear(); self.glyphs.tick(); + self.kept.begin(doc); if let Some(bg) = opts.background { ctx.set_transform(Affine::IDENTITY); ctx.set_paint(peniko::Color::from_rgba8(bg[0], bg[1], bg[2], bg[3])); diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index 7c7c91fe1..44513c3ac 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -17,13 +17,16 @@ //! - Feather: the object is masked by its shape inset by half the width and blurred, so the //! edge fades from ~0 at the path to full strength `width` inside. -use designcraft_doc::Item; +use std::collections::HashMap; +use std::sync::Arc; + +use designcraft_doc::{Asset, AssetId, DocSettings, Document, InkManager, Item, ItemId, Layer, StrokeStyleDef}; use designcraft_geom::{Affine, BezPath, Rect, Shape, Vec2}; use vello_common::filter_effects::{EdgeMode, Filter, FilterPrimitive}; use vello_cpu::peniko::{self, BlendMode, Compose, Mix}; -use vello_cpu::{RenderContext, kurbo}; +use vello_cpu::{Pixmap, RenderContext, kurbo}; -use crate::{Frame, Renderer, color_of}; +use crate::{Frame, RenderOptions, Renderer, color_of}; use designcraft_compose::ShownOn; /// Shadow offset (spread units) for an InDesign angle (degrees, light direction) and distance. @@ -113,16 +116,25 @@ impl Renderer { let mut below = vec![]; if e.outer_glow.on { let g = &e.outer_glow; - below.push((Vec2::ZERO, g.size, g.spread, g.color.clone(), g.opacity, g.mode)); + below.push((Slot::OuterGlow, Vec2::ZERO, g.size, g.spread, g.color.clone(), g.opacity, g.mode)); } if e.drop_shadow.on { let d = &e.drop_shadow; - below.push((offset(doc.light_angle(d.angle, d.global_light), d.distance), d.size, d.spread, d.color.clone(), d.opacity, d.mode)); + below.push(( + Slot::DropShadow, + offset(doc.light_angle(d.angle, d.global_light), d.distance), + d.size, + d.spread, + d.color.clone(), + d.opacity, + d.mode, + )); } - for (off, size, pct, color, opacity, mode) in below { + for (slot, off, size, pct, color, opacity, mode) in below { let Some(c) = doc.resolve_color(&color, 1.0) else { continue }; let (sigma, grow) = split(size, pct); - let filter = shadow(sigma, color_of(&c, opacity.clamp(0.0, 1.0))); + let paint = color_of(&c, opacity.clamp(0.0, 1.0)); + let filter = shadow(sigma, paint); // The offset moves the geometry, not the filter: vello drops layer content that lies // entirely outside the viewport before filtering. let r = (reach + off).inflate(grow, grow); @@ -132,7 +144,8 @@ impl Renderer { ctx.set_transform(Affine::IDENTITY); ctx.push_layer(None, Some(BlendMode::new(mix, Compose::SrcOver)), None, None, None); } - self.with_filters(ctx, f, r, sigma, None, |me, c, fr| { + let look = Look { slot, off, sigma, grow, paint: paint.components }; + self.with_kept_filters(ctx, f, it, xf, page, look, r, |me, c, fr| { let moved = Frame { view: fr.view * Affine::translate(off), ..*fr }; c.set_transform(moved.view); c.push_layer(None, None, None, None, Some(filter)); @@ -448,23 +461,251 @@ impl Renderer { return; } let Some(o) = offscreen(f.view.transform_rect_bbox(reach), spread, ctx.width(), ctx.height()) else { return }; + // Clip where the result is at full resolution: offscreen unless that is reduced. + let (inner, outer) = if o.scale > 1.0 { (None, clip) } else { (clip, None) }; + let pm = self.draw_offscreen(f, &o, inner, draw); + push_clip(ctx, f, outer); + place(ctx, o.x0, o.y0, o.scale, Arc::new(pm)); + pop_clip(ctx, outer); + } + + /// `draw` into the single-threaded offscreen image `o`. + fn draw_offscreen( + &mut self, + f: &Frame, + o: &Offscreen, + clip: Option<(&BezPath, Affine)>, + draw: impl FnOnce(&mut Self, &mut RenderContext, &Frame), + ) -> Pixmap { let mut off = RenderContext::new_with(o.width, o.height, vello_cpu::RenderSettings { num_threads: 0, ..Default::default() }); let view = Affine::scale(1.0 / o.scale) * Affine::translate((-o.x0, -o.y0)) * f.view; let shifted = Frame { mt: false, view, px: f.px * o.scale, ..*f }; - // Clip where the result is at full resolution: offscreen unless that is reduced. - let (inner, outer) = if o.scale > 1.0 { (None, clip) } else { (clip, None) }; - push_clip(&mut off, &shifted, inner); + push_clip(&mut off, &shifted, clip); draw(self, &mut off, &shifted); - pop_clip(&mut off, inner); + pop_clip(&mut off, clip); off.flush(); - let mut pm = vello_cpu::Pixmap::new(o.width, o.height); + let mut pm = Pixmap::new(o.width, o.height); off.render(&mut pm, &mut self.resources); - push_clip(ctx, f, outer); - ctx.set_transform(Affine::translate((o.x0, o.y0)) * Affine::scale(o.scale)); - ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(std::sync::Arc::new(pm)), sampler: peniko::ImageSampler::default() }); - ctx.fill_rect(&Rect::new(0.0, 0.0, f64::from(o.width), f64::from(o.height))); - pop_clip(ctx, outer); - ctx.set_transform(Affine::IDENTITY); + pm + } + + /// [`Renderer::with_filters`] for a drop shadow or an outer glow of `it`, keeping its image + /// between renders. While the object, its effect, the view's scale and rotation, the render + /// options and the document's colours, styles and images stay the same, a move of the object + /// or of the view by whole device pixels places the kept image again instead of drawing and + /// blurring it. Only multithreaded contexts (the canvas) keep images, and only of objects + /// without text or nested items. + #[allow(clippy::too_many_arguments)] + fn with_kept_filters( + &mut self, + ctx: &mut RenderContext, + f: &Frame, + it: &Item, + xf: Affine, + page: ShownOn, + look: Look, + reach: Rect, + draw: impl FnOnce(&mut Self, &mut RenderContext, &Frame), + ) { + let keepable = f.mt && it.text_frame().is_none() && it.children().is_empty() && it.media.is_none(); + if !keepable { + self.with_filters(ctx, f, reach, look.sigma, None, draw); + return; + } + let [a, b, c, d, e, g] = (f.view * xf).as_coeffs(); + let (linear, anchor) = ([a, b, c, d], Vec2::new(e, g)); + let plate = crate::PLATE.with(std::cell::Cell::get); + let rich_black = crate::color::RICH_BLACK.with(std::cell::Cell::get); + let key = (it.id, page, look.slot, plate); + let tick = self.kept.tick; + if let Some(k) = self.kept.entries.get_mut(&key) + && k.look == look + && k.linear == linear + && k.px == f.px + && k.rich_black == rich_black + && k.opts == *f.opts + && (Item { xf: k.item.xf, ..it.clone() }) == k.item + { + let shift = anchor - k.anchor; + let (dx, dy) = (shift.x.round(), shift.y.round()); + if (shift.x - dx).abs() < 1e-3 && (shift.y - dy).abs() < 1e-3 { + k.used = tick; + let (x0, y0, scale, image) = (k.x0 + dx, k.y0 + dy, k.scale, k.image.clone()); + place(ctx, x0, y0, scale, image); + return; + } + } + // The whole effect, not only the part in view, so that it can be placed anywhere later. + let spread = bound(look.sigma).max(0.0) * 3.0 / f.px + 2.0; + let whole = f.view.transform_rect_bbox(reach).inflate(spread, spread); + let covers = |o: &Offscreen| f64::from(o.width) * o.scale >= whole.x1 - o.x0 && f64::from(o.height) * o.scale >= whole.y1 - o.y0; + let Some(o) = fit(whole, spread).filter(|o| usize::from(o.width) * usize::from(o.height) <= KEEP_MAX_PIXELS && covers(o)) else { + self.with_filters(ctx, f, reach, look.sigma, None, draw); + return; + }; + let image = Arc::new(self.draw_offscreen(f, &o, None, draw)); + #[cfg(test)] + { + self.kept.drawn += 1; + } + place(ctx, o.x0, o.y0, o.scale, image.clone()); + let kept = Kept { + item: it.clone(), + linear, + anchor, + look, + opts: f.opts.clone(), + px: f.px, + rich_black, + x0: o.x0, + y0: o.y0, + scale: o.scale, + image, + used: tick, + }; + self.kept.insert(f.doc, key, kept); + } +} + +/// Paint `image` with its top-left corner at device pixel (`x0`, `y0`), each of its pixels +/// covering `scale` device pixels. +fn place(ctx: &mut RenderContext, x0: f64, y0: f64, scale: f64, image: Arc) { + let (w, h) = (f64::from(image.width()), f64::from(image.height())); + ctx.set_transform(Affine::translate((x0, y0)) * Affine::scale(scale)); + ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(image), sampler: peniko::ImageSampler::default() }); + ctx.fill_rect(&Rect::new(0.0, 0.0, w, h)); + ctx.set_transform(Affine::IDENTITY); +} + +/// Pixels one kept effect image may have; a larger one is drawn each time. +const KEEP_MAX_PIXELS: usize = 4 << 20; +/// Pixels all kept effect images may have together (128 MiB). +const KEEP_BUDGET: usize = 32 << 20; +/// Renders an image no render has placed is kept for. +const KEEP_RENDERS: u64 = 256; + +/// The effect below an object a kept image is of. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) enum Slot { + OuterGlow, + DropShadow, +} + +/// What an effect image looks like apart from the object: its offset (spread space), blur, +/// growth and colour. +#[derive(Clone, Copy, PartialEq)] +struct Look { + slot: Slot, + off: Vec2, + sigma: f64, + grow: f64, + paint: [f32; 4], +} + +/// One kept effect image and what it was drawn from. +struct Kept { + /// The object, with the transform it had. + item: Item, + /// The linear part of the object's spread → device transform. + linear: [f64; 4], + /// The device position of the object's origin. + anchor: Vec2, + look: Look, + opts: RenderOptions, + px: f64, + rich_black: bool, + x0: f64, + y0: f64, + scale: f64, + image: Arc, + used: u64, +} + +/// What every kept image depends on besides its object. +struct Deps { + colors: designcraft_color::cms::ColorSettings, + swatches: Vec, + settings: DocSettings, + inks: InkManager, + stroke_styles: Vec, + layers: Vec, + /// Held, so that an asset changed in place or a new one at the same address is a new `Arc`. + assets: Vec<(AssetId, Arc)>, +} + +impl Deps { + fn of(doc: &Document) -> Self { + Deps { + colors: designcraft_color::cms::active_settings(), + swatches: doc.swatches.clone(), + settings: doc.settings.clone(), + inks: doc.inks.clone(), + stroke_styles: doc.stroke_styles.clone(), + layers: doc.layers.clone(), + assets: doc.assets.iter().map(|(id, a)| (*id, a.clone())).collect(), + } + } + fn same(&self, doc: &Document) -> bool { + self.colors == designcraft_color::cms::active_settings() + && self.swatches == doc.swatches + && self.settings == doc.settings + && self.inks == doc.inks + && self.stroke_styles == doc.stroke_styles + && self.layers == doc.layers + && self.assets.len() == doc.assets.len() + && self.assets.iter().zip(&doc.assets).all(|((a, p), (b, x))| a == b && Arc::ptr_eq(p, x)) + } +} + +/// Drop shadows and outer glows kept between renders ([`Renderer::with_kept_filters`]), at most +/// [`KEEP_BUDGET`] pixels; the images used longest ago go first, and an image no render placed +/// in [`KEEP_RENDERS`] renders goes too. +#[derive(Default)] +pub(crate) struct KeptEffects { + deps: Option, + entries: HashMap<(ItemId, ShownOn, Slot, Option), Kept>, + pixels: usize, + tick: u64, + /// Effect images drawn for keeping (tests). + #[cfg(test)] + pub(crate) drawn: usize, +} + +impl KeptEffects { + /// Start a render of `doc`: drop every image when what they depend on changed. + pub(crate) fn begin(&mut self, doc: &Document) { + self.tick += 1; + if !self.deps.as_ref().is_some_and(|d| d.same(doc)) { + self.clear(); + return; + } + let tick = self.tick; + let before = self.entries.len(); + self.entries.retain(|_, k| k.used + KEEP_RENDERS >= tick); + if self.entries.len() != before { + self.pixels = self.entries.values().map(|k| k.image.width() as usize * k.image.height() as usize).sum(); + } + } + pub(crate) fn clear(&mut self) { + self.entries.clear(); + self.pixels = 0; + self.deps = None; + } + fn insert(&mut self, doc: &Document, key: (ItemId, ShownOn, Slot, Option), kept: Kept) { + if self.deps.is_none() { + self.deps = Some(Deps::of(doc)); + } + let size = |k: &Kept| k.image.width() as usize * k.image.height() as usize; + self.pixels += size(&kept); + if let Some(old) = self.entries.insert(key, kept) { + self.pixels -= size(&old); + } + while self.pixels > KEEP_BUDGET { + let Some(oldest) = self.entries.iter().min_by_key(|(_, k)| k.used).map(|(key, _)| *key) else { break }; + if let Some(old) = self.entries.remove(&oldest) { + self.pixels -= size(&old); + } + } } } @@ -502,7 +743,15 @@ struct Offscreen { /// [`MAX_BLUR_SPREAD`], at most `MAX_SIDE` a side. `None` when none of it shows. fn offscreen(reach: Rect, spread: f64, width: u16, height: u16) -> Option { let screen = Rect::new(0.0, 0.0, f64::from(width), f64::from(height)).inflate(spread, spread); - let r = reach.inflate(spread, spread).intersect(screen); + fit(reach.inflate(spread, spread).intersect(screen), spread) +} + +/// The offscreen image covering `r` (device pixels) for a blur of `spread`, or `None` when it is +/// empty, not finite or more than `MAX_SIDE` a side. +fn fit(r: Rect, spread: f64) -> Option { + if !(r.x0.is_finite() && r.y0.is_finite() && r.x1.is_finite() && r.y1.is_finite()) { + return None; + } let (x0, y0) = (r.x0.floor(), r.y0.floor()); let scale = (spread / MAX_BLUR_SPREAD).max(1.0); let side = |len: f64| (len / scale).ceil().min(crate::MAX_SIDE as f64); @@ -607,4 +856,132 @@ mod tests { // The transparent half shows the page: no shadow painted there. assert!(lum(150) > 700, "nothing over the transparent part: {}", lum(150)); } + + /// A document with one image frame casting a drop shadow, and the frame's id. + fn shadowed_image() -> (designcraft_doc::Document, designcraft_doc::ItemId) { + use designcraft_doc::build::NewDocument; + use designcraft_doc::{Document, SpreadRef}; + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let img = image::RgbaImage::from_fn(64, 48, |x, y| image::Rgba([(x * 4) as u8, (y * 5) as u8, 128, 255])); + let mut png = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let aid = designcraft_doc::AssetId(d.alloc()); + d.assets.insert( + aid, + Arc::new(designcraft_doc::Asset { + id: aid, + name: "photo.png".into(), + mime: "image/png".into(), + data: Arc::new(png), + pixels: Some((64, 48)), + ..Default::default() + }), + ); + let id = designcraft_doc::ItemId(d.alloc()); + let mut it = Item::new(id, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 160.0, 120.0))); + it.xf = Affine::translate((100.0, 100.0)); + it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic { + layer_options: None, + asset: aid, + size: (160.0, 120.0), + xf: Affine::IDENTITY, + clip: None, + auto_fit: Default::default(), + fit_align: 4, + crop: [0.0; 4], + wrap: Default::default(), + fill: Default::default(), + }); + let s = &mut it.effects.drop_shadow; + (s.on, s.color, s.opacity, s.size, s.distance) = (true, "[Black]".into(), 0.75, 12.0, 9.0); + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + (d, id) + } + + /// Moving a shadowed frame, or the view, by whole pixels places the kept shadow again: the + /// shadow is drawn and blurred once, and every frame matches a render that draws it afresh. + /// A new effect setting, zoom, colour or a move by part of a pixel draws it again. + #[test] + fn a_moved_shadow_is_drawn_once_and_placed_again() { + use designcraft_doc::SpreadRef; + let (mut d, id) = shadowed_image(); + let cache = crate::Cache::new(); + let placed = [crate::Placed { spread: SpreadRef::Doc(0), xf: Affine::IDENTITY }]; + let opts = crate::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let mut kept = Renderer::new(); + kept.threads = 2; + let render = + |r: &mut Renderer, d: &designcraft_doc::Document, size: (u32, u32), view: Affine| r.render(d, &cache, &placed, size, view, &opts); + let fresh = |d: &designcraft_doc::Document, size: (u32, u32), view: Affine| { + let mut r = Renderer::new(); + r.threads = 2; + r.render(d, &crate::Cache::new(), &placed, size, view, &opts) + }; + let close = |a: &crate::Rendered, b: &crate::Rendered, what: &str| { + let worst = a.pixels.iter().zip(&b.pixels).map(|(x, y)| x.abs_diff(*y)).max().unwrap_or(0); + assert!(a.pixels.len() == b.pixels.len() && worst <= 1, "{what}: off by {worst}"); + }; + let view = Affine::scale(1.5); + close(&render(&mut kept, &d, (500, 450), view), &fresh(&d, (500, 450), view), "first render"); + assert_eq!(kept.kept.drawn, 1); + for step in 1..=4 { + let it = d.item_mut(id).unwrap(); + it.xf = Affine::translate((2.0, 4.0 / 3.0)) * it.xf; + close(&render(&mut kept, &d, (500, 450), view), &fresh(&d, (500, 450), view), "after a move"); + // A patch of the view, as the canvas repaints after an edit. + let patch = Affine::translate((-150.0, -140.0)) * view; + close(&render(&mut kept, &d, (120, 90), patch), &fresh(&d, (120, 90), patch), "a patch"); + assert_eq!(kept.kept.drawn, 1, "step {step}: placed again, not drawn"); + } + // Panning by whole pixels. + let panned = Affine::translate((-37.0, 11.0)) * view; + close(&render(&mut kept, &d, (500, 450), panned), &fresh(&d, (500, 450), panned), "panned"); + assert_eq!(kept.kept.drawn, 1); + // Part of a pixel, another zoom, another size, another colour: drawn again. + let it = d.item_mut(id).unwrap(); + it.xf = Affine::translate((0.25, 0.0)) * it.xf; + render(&mut kept, &d, (500, 450), view); + assert_eq!(kept.kept.drawn, 2); + render(&mut kept, &d, (500, 450), Affine::scale(2.0)); + assert_eq!(kept.kept.drawn, 3); + d.item_mut(id).unwrap().effects.drop_shadow.size = 20.0; + close(&render(&mut kept, &d, (500, 450), view), &fresh(&d, (500, 450), view), "a new size"); + assert_eq!(kept.kept.drawn, 4); + d.swatches.push(designcraft_color::Swatch::color("Extra", designcraft_color::Color::rgb8(1, 2, 3))); + render(&mut kept, &d, (500, 450), view); + assert_eq!(kept.kept.drawn, 5, "a swatch change drops kept images"); + // An image changed in place (its only document owner editing it). + let asset = d.assets.values_mut().next().unwrap(); + Arc::make_mut(asset).name = "edited.png".into(); + render(&mut kept, &d, (500, 450), view); + assert_eq!(kept.kept.drawn, 6, "an edited image drops kept images"); + // Single-threaded renders (exports) draw as before and keep nothing. + let mut single = Renderer::new(); + single.threads = 0; + render(&mut single, &d, (500, 450), view); + assert_eq!(single.kept.drawn, 0); + } + + /// In the CMYK blend space view the ink passes keep an image per plate, placed again on a move. + #[test] + fn the_ink_passes_keep_their_shadows() { + use designcraft_doc::SpreadRef; + let (mut d, id) = shadowed_image(); + d.settings.blend_space = designcraft_doc::BlendSpace::Cmyk; + let cache = crate::Cache::new(); + let placed = [crate::Placed { spread: SpreadRef::Doc(0), xf: Affine::IDENTITY }]; + let opts = crate::RenderOptions { blend_space_view: true, background: Some([255, 255, 255, 255]), ..Default::default() }; + let mut r = Renderer::new(); + r.threads = 2; + r.render(&d, &cache, &placed, (500, 450), Affine::IDENTITY, &opts); + // One for each ink pass, and one for the ordinary drawing around their area. + assert_eq!(r.kept.drawn, 3); + for _ in 0..3 { + let it = d.item_mut(id).unwrap(); + it.xf = Affine::translate((3.0, 1.0)) * it.xf; + r.render(&d, &cache, &placed, (500, 450), Affine::IDENTITY, &opts); + } + assert_eq!(r.kept.drawn, 3); + } } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 25207b248..973f1eb21 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -155,6 +155,8 @@ pub struct Renderer { cmyk_view: Option, /// Whether the last render ran the CMYK ink passes (only then is its view worth keeping). cmyk_ran: bool, + /// Drop shadow and outer glow images kept between renders. + kept: fx::KeptEffects, #[cfg(test)] cmyk_passes: usize, /// Pixels the last ink pass covered (tests). From 670ada58c22ffae76c16f53af212e89cdce0cade Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:20:11 -0800 Subject: [PATCH 0938/1349] Pages: test that a cached document is stored in the thumbnail clock The test switches to a document whose thumbnails are all current and checks that the clock names that document afterwards. --- crates/ui-egui/src/panels/pages/tests.rs | 28 ++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/crates/ui-egui/src/panels/pages/tests.rs b/crates/ui-egui/src/panels/pages/tests.rs index 62644227f..66d05fbb7 100644 --- a/crates/ui-egui/src/panels/pages/tests.rs +++ b/crates/ui-egui/src/panels/pages/tests.rs @@ -373,6 +373,34 @@ fn an_edit_redraws_only_thumbnails_in_view_one_per_frame() { assert!((2..60).all(|abs| !cached(abs)), "no thumbnail of a deleted page is kept"); } +/// Switching to a document whose thumbnails are all current stores that document in the clock, +/// so the next frames do not scan the whole cache again. +#[test] +fn switching_to_a_cached_document_stores_it_in_the_clock() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let frame = |app: &mut DesignApp| { + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(280.0, 520.0))), + time: Some(0.0), + ..Default::default() + }; + ctx.run_ui(raw, |ui| show(app, ui)).textures_delta.clear(); + }; + for _ in 0..2 { + app.run("file.new", json!({"pages": 2, "facingPages": false})).unwrap(); + frame(&mut app); + } + app.session.set_active(0); + let st = app.session.active().unwrap(); + let first = (st.uid, st.revision); + let before = THUMB_RENDERS.with(std::cell::Cell::get); + frame(&mut app); + assert_eq!(THUMB_RENDERS.with(std::cell::Cell::get), before, "the first document's thumbnails are current"); + let clock = ctx.data(|d| d.get_temp::(egui::Id::unique("pages_thumb_clock"))).unwrap(); + assert_eq!(clock.doc, first); +} + #[test] fn parents_are_added_duplicated_and_renamed_from_the_panel() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); From 5c6d45908d447f6e96599505c9225d31b612862f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:25:22 -0800 Subject: [PATCH 0939/1349] Compose: vertical justification keeps grid-aligned lines on the baseline grid With Align to Baseline Grid, Center and Bottom moved the lines by any amount, so they left the grid. They now move by whole grid steps: Bottom puts the last baseline on the lowest grid line above the bottom inset, and Center on the grid line nearest the centered position. With Justify the first line stays in place and the last baseline goes to the lowest grid line above the bottom inset; the lines between are spread evenly. --- crates/compose/src/lib.rs | 61 +++++++++++++++++++++++++++++++------ crates/compose/src/tests.rs | 53 +++++++++++++++++++++++++++++++- 2 files changed, 103 insertions(+), 11 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 72c0f69cb..f43caad84 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -2737,6 +2737,9 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C // and in split columns. let mut span_paras = vec![false; np]; let mut split_paras = vec![false; np]; + // Each paragraph's Align to Baseline Grid (vertical justification moves grid-aligned lines by + // whole grid steps). + let mut grid_paras = vec![GridAlign::None; np]; 'paras: while pi <= np { cur.pi = pi; cur.limits = Rc::clone(&limits); @@ -2896,6 +2899,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C // it, a paragraph moves on to the next sub-column. let split_cfg = SplitCfg::of(&pp); split_paras[pi] = split_cfg.is_some(); + grid_paras[pi] = pp.grid_align; if cur.split.is_some_and(|s| Some(s.cfg) != split_cfg) { cur.split = None; } @@ -3124,6 +3128,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C boxes: &boxes, span_paras: &span_paras, split_paras: &split_paras, + grid_paras: &grid_paras, styles_tab, }) } @@ -3138,11 +3143,12 @@ struct FinishInput<'a> { boxes: &'a [Option], span_paras: &'a [bool], split_paras: &'a [bool], + grid_paras: &'a [GridAlign], styles_tab: Vec, } fn finish_composition(input: FinishInput<'_>) -> ComposedStory { - let FinishInput { doc, story, frames, cols, notes, out, boxes, span_paras, split_paras, styles_tab } = input; + let FinishInput { doc, story, frames, cols, notes, out, boxes, span_paras, split_paras, grid_paras, styles_tab } = input; notes.finish(doc, story, frames, cols, out); // Ranges, content heights and vertical justification. for (fi, ft) in out.frames.iter_mut().enumerate() { @@ -3159,7 +3165,7 @@ fn finish_composition(input: FinishInput<'_>) -> ComposedStory { let before: Vec = ft.tables.iter().map(|t| ft.lines.get(t.line).map_or(0.0, |l| l.baseline)).collect(); let spanned = ft.columns.len() > 1 && ft.lines.iter().any(|l| span_paras.get(l.para) == Some(&true)) || ft.lines.iter().any(|l| split_paras.get(l.para) == Some(&true)); - vertical_justify(ft, f, spanned, &doc.footnote_options); + vertical_justify(ft, f, spanned, &doc.footnote_options, grid_paras); for (t, b) in ft.tables.iter_mut().zip(before) { let now = ft.lines.get(t.line).map_or(b, |l| l.baseline); t.shift(now - b); @@ -5484,8 +5490,9 @@ fn rule_decos(doc: &Document, r: &designcraft_doc::Rule, rect: Rect, (color, tin out } -/// `spanned`: a paragraph spans the frame's columns, so the lines move together. -fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &designcraft_doc::FootnoteOptions) { +/// `spanned`: a paragraph spans the frame's columns, so the lines move together. `grid_aligns`: +/// each paragraph's Align to Baseline Grid setting. +fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &designcraft_doc::FootnoteOptions, grid_aligns: &[GridAlign]) { if ft.lines.is_empty() || f.opts.vertical_justification == VerticalJustification::Top { return; } @@ -5563,10 +5570,13 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de let fits = |shift: &[f64]| { idx.iter().zip(&rows).all(|(&i, &k)| k == n || shift[k] <= 0.0 || ft.lines[i].baseline + ft.lines[i].descent + shift[k] <= limit + 1e-9) }; - // Every row moves no less as `space` grows, so the most room that fits is found by halving. - let mut shift = shifts(space); - if !fits(&shift) { - let (mut lo, mut hi) = (0.0, space); + // Every row moves no less as the room grows, so the most room that fits, up to `top`, is + // found by halving. + let most_room = |top: f64| -> f64 { + if fits(&shifts(top)) { + return top; + } + let (mut lo, mut hi) = (0.0, top); for _ in 0..60 { let mid = (lo + hi) / 2.0; if fits(&shifts(mid)) { @@ -5575,8 +5585,39 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de hi = mid; } } - shift = shifts(lo); - } + lo + }; + // Lines aligned to the baseline grid move by whole grid steps, so they stay on the grid. + // With Justify only the last row has to land on the grid (the first row doesn't move). + let on_grid = |i: usize| { + let line = &ft.lines[i]; + match grid_aligns.get(line.para) { + Some(GridAlign::AllLines) => true, + Some(GridAlign::FirstLineOnly) => line.first_in_para, + _ => false, + } + }; + let center = f.opts.vertical_justification == VerticalJustification::Center; + let step = f.grid.map(|(_, inc)| inc).filter(|inc| *inc > 0.0 && inc.is_finite()).filter(|_| match f.opts.vertical_justification { + VerticalJustification::Justify => idx.iter().zip(&rows).any(|(&i, &k)| k == n && on_grid(i)), + _ => idx.iter().any(|&i| on_grid(i)), + }); + let shift = match step { + None => shifts(most_room(space)), + Some(inc) => { + // The room one grid step takes: Center moves the lines by half the room. + let unit = if center { 2.0 * inc } else { inc }; + let room = most_room(if center { 2.0 * space } else { space }); + // The last baseline stays above the bottom of the text, and the rows above it fit. + let most = (space / inc + 1e-9).floor().min((room / unit + 1e-9).floor()).max(0.0); + // Bottom and Justify take the lowest grid line, Center the one nearest the middle. + let mut steps = if center { (space / 2.0 / inc).round().min(most) } else { most }; + if steps > 0.0 && !fits(&shifts(steps * unit)) { + steps -= 1.0; + } + shifts(steps * unit) + } + }; let before: Vec = idx.iter().map(|&i| ft.lines[i].baseline).collect(); for (&i, &k) in idx.iter().zip(&rows) { ft.lines[i].baseline += shift[k]; diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index b94d94000..0f7b54da2 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -2291,7 +2291,7 @@ fn vertical_justification_counts_table_fragment_bottoms() { let mut spec = frame_specs(&d, sid).remove(0); spec.opts.vertical_justification = mode; - vertical_justify(&mut ft, &spec, false, &d.footnote_options); + vertical_justify(&mut ft, &spec, false, &d.footnote_options, &[]); let moved = ft.lines[anchor].baseline - baseline; let limit = ft.notes[0].rect.y0 - d.footnote_options.space_before; @@ -2384,6 +2384,57 @@ fn vertical_justification_keeps_earlier_descenders_inside() { assert!((last - area.y1).abs() < 1e-6, "Justify: last baseline at {last}, text area at {}", area.y1); } +/// With Align to Baseline Grid, Center and Bottom move the lines by whole grid steps, so every +/// line stays on the grid: Bottom puts the last baseline on the lowest grid line above the bottom +/// inset, and Center on the grid line nearest the centered place. Justify keeps the first and last +/// lines on the grid and spreads the lines between them. +#[test] +fn vertical_justification_keeps_grid_aligned_lines_on_the_grid() { + use designcraft_doc::GridAlign; + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify, Top}; + let compose_with = |mode: VerticalJustification, align: GridAlign| { + let mut area = Rect::ZERO; + let (lines, grid) = grid_doc("One\nTwo\nThree", ParaAttrs { grid_align: Some(align), ..Default::default() }, |d, sid| { + let spec = frame_specs(d, sid).remove(0); + area = spec.area; + d.item_mut(spec.id).unwrap().text_frame_mut().unwrap().options.vertical_justification = mode; + }); + (area, lines.iter().map(|l| l.baseline).collect::>(), grid) + }; + let (area, top, grid) = compose_with(Top, GridAlign::AllLines); + let inc = grid.1; + assert_eq!(top.len(), 3); + assert!(top.iter().all(|&b| on_grid(b, grid)), "Top: {top:?}"); + assert!(!on_grid(area.y1, grid), "the bottom inset is between grid lines: {area:?}"); + + let (_, bottom, _) = compose_with(Bottom, GridAlign::AllLines); + assert!(bottom.iter().all(|&b| on_grid(b, grid)), "Bottom keeps every line on the grid: {bottom:?}"); + let last = bottom[2]; + assert!(last <= area.y1 + 1e-6 && last > area.y1 - inc, "Bottom: last baseline {last} on the lowest grid line above {}", area.y1); + assert!((bottom[1] - bottom[0] - (top[1] - top[0])).abs() < 1e-6, "Bottom keeps the leading"); + + let (_, center, _) = compose_with(Center, GridAlign::AllLines); + assert!(center.iter().all(|&b| on_grid(b, grid)), "Center keeps every line on the grid: {center:?}"); + let shift = center[0] - top[0]; + let ideal = (area.y1 - top[2]) / 2.0; + assert!(shift > 1.0 && (shift - ideal).abs() <= inc / 2.0 + 1e-6, "Center: moved {shift}, centered at {ideal}"); + assert!(center[2] <= area.y1 + 1e-6); + + let (_, justify, _) = compose_with(Justify, GridAlign::AllLines); + assert!((justify[0] - top[0]).abs() < 1e-6, "Justify keeps the first baseline: {justify:?}"); + assert!(on_grid(justify[2], grid), "Justify keeps the last line on the grid: {justify:?}"); + assert!(justify[2] <= area.y1 + 1e-6 && justify[2] > area.y1 - inc, "Justify: last baseline {} near {}", justify[2], area.y1); + assert!((justify[1] - justify[0] - (justify[2] - justify[1])).abs() < 1e-6, "Justify spreads the lines evenly: {justify:?}"); + + // First lines only: each paragraph here is one line, so Bottom keeps every line on the grid. + let (_, first_only, _) = compose_with(Bottom, GridAlign::FirstLineOnly); + assert!(first_only.iter().all(|&b| on_grid(b, grid)), "Bottom, first lines only: {first_only:?}"); + + // Without grid alignment the last baseline goes down to the bottom inset. + let (_, free, _) = compose_with(Bottom, GridAlign::None); + assert!((free[2] - area.y1).abs() < 1e-6, "Bottom without the grid: {free:?}"); +} + /// A corner radius leaves a Cap Height first line where it sits in a rectangular frame, with Top /// and with Center: a line's band above the text area isn't held to the frame's outline (#1999). /// Center puts the last baseline halfway between where Top sets it and the bottom inset, also in From 9f99420e32bbde7baab20d040344c3d99ac82785 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:40:54 -0800 Subject: [PATCH 0940/1349] Recovery: tests hold the background writer instead of sleeping The timer test now holds the recovery writer at the start of its write through a handshake (`recovery::testing`, behind the engine's `testing` feature), checks that frames and edits go on while the write is held, and fails when the write runs on the interface thread. The engine tests wait for the writer to go idle instead of polling with sleeps. `file.recovery.save` rejects a `background` that is not true or false. --- crates/engine/Cargo.toml | 4 + crates/engine/src/cmd/file/registry.rs | 6 +- crates/engine/src/recovery.rs | 118 ++++++++++++++++++++++++- crates/engine/src/recovery/tests.rs | 70 ++++++++++----- crates/ui-egui/Cargo.toml | 1 + crates/ui-egui/src/tests.rs | 28 ++++-- 6 files changed, 193 insertions(+), 34 deletions(-) diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index c1c0f1d33..6b6a43a87 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -8,6 +8,10 @@ description = "DesignCraft engine: session, documents, history, selection, comma [lints] workspace = true +[features] +# Recovery-writer handshakes for other crates' tests (`designcraft_engine::recovery::testing`). +testing = [] + [dependencies] craft-print = { workspace = true } craft-docpath = { workspace = true } diff --git a/crates/engine/src/cmd/file/registry.rs b/crates/engine/src/cmd/file/registry.rs index a9d14892c..df8709f10 100644 --- a/crates/engine/src/cmd/file/registry.rs +++ b/crates/engine/src/cmd/file/registry.rs @@ -70,8 +70,12 @@ pub fn specs() -> Vec { cmd!(noundo "file.recovery.save", "Save Recovery Data", [], None, "{dir?, background?} — write every unsaved document to the recovery folder (the app does this on a timer; `background` queues the writes and returns at once) → {saved} or {queued}", always, |s, p| { + let background = match p.get("background") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or_else(|| bad("file.recovery.save", "`background` must be true or false"))?, + }; let dir = recovery_dir(s, p, FolderAccess::Write)?; - if p.get("background").and_then(Value::as_bool).unwrap_or(false) { + if background { return Ok(json!({"queued": crate::recovery::start_tracked(s, &dir)?})); } Ok(json!({"saved": crate::recovery::save_tracked(s, &dir)?})) diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index a84034fb7..420d1795f 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -679,6 +679,8 @@ struct Written { /// document was saved, reverted or closed since the write started: its snapshot is then dropped /// instead of published, so a crash cannot offer back a copy older than the saved file. fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { + #[cfg(any(test, feature = "testing"))] + testing::gate(&entry.dir); let (doc, meta) = files(&entry.dir, entry.uid); let published = publish_recovery_written( &doc, @@ -812,7 +814,7 @@ pub(crate) fn finished(_s: &mut Session) -> Finished { mod worker { use std::collections::BTreeSet; use std::sync::mpsc::{Receiver, Sender}; - use std::sync::{Mutex, OnceLock}; + use std::sync::{Condvar, Mutex, OnceLock}; use super::{Path, PathBuf, Result, Snapshot, write_snapshot}; @@ -834,6 +836,8 @@ mod worker { /// A document saved, reverted or closed while its write was queued or running: the /// snapshot it is producing must not be published. cancelled: Mutex>, + /// Notified each time a write finishes and leaves `running`. + idle: Condvar, } static WRITER: OnceLock> = OnceLock::new(); @@ -851,6 +855,16 @@ mod worker { if let Ok(mut cancelled) = self.cancelled.lock() { cancelled.remove(&key); } + self.idle.notify_all(); + } + + /// Block until no write is queued or running. + #[cfg(any(test, feature = "testing"))] + pub(super) fn wait_until_idle(&self) { + let mut running = self.running.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + while !running.is_empty() { + running = self.idle.wait(running).unwrap_or_else(std::sync::PoisonError::into_inner); + } } /// Do not publish the snapshot being written for `dir`/`uid`: the document was saved, @@ -898,6 +912,7 @@ mod worker { done: Mutex::new(done_rx), running: Mutex::new(BTreeSet::new()), cancelled: Mutex::new(BTreeSet::new()), + idle: Condvar::new(), }) }) .as_ref() @@ -959,6 +974,107 @@ mod worker { } } +/// Handshakes for tests of the recovery writer, in this crate and, with the `testing` feature, in +/// the app's: hold a write at its start, and wait for the writer to finish. +#[cfg(any(test, feature = "testing"))] +pub mod testing { + use std::path::{Path, PathBuf}; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::mpsc::{Receiver, Sender}; + use std::sync::{Arc, Mutex, PoisonError}; + use std::thread::ThreadId; + + struct Gate { + dir: PathBuf, + holder: ThreadId, + entered: Sender<()>, + go: Receiver<()>, + ran_on_holder: Arc, + } + + static GATE: Mutex> = Mutex::new(None); + + /// The next recovery write into one folder, held at its start until this is released or + /// dropped. + pub struct HeldWrite { + entered: Receiver<()>, + go: Option>, + ran_on_holder: Arc, + } + + /// Hold the next recovery write into `dir`. A write on another thread waits before it writes + /// anything; a write on the calling thread does not wait, and [`HeldWrite::ran_here`] reports it. + pub fn hold_next_write(dir: &Path) -> HeldWrite { + let (entered_tx, entered) = std::sync::mpsc::channel(); + let (go, go_rx) = std::sync::mpsc::channel(); + let ran_on_holder = Arc::new(AtomicBool::new(false)); + let gate = Gate { + dir: dir.to_path_buf(), + holder: std::thread::current().id(), + entered: entered_tx, + go: go_rx, + ran_on_holder: ran_on_holder.clone(), + }; + *GATE.lock().unwrap_or_else(PoisonError::into_inner) = Some(gate); + HeldWrite { entered, go: Some(go), ran_on_holder } + } + + impl HeldWrite { + /// The held write ran on the thread that called [`hold_next_write`]. + pub fn ran_here(&self) -> bool { + self.ran_on_holder.load(Ordering::SeqCst) + } + + /// Block until the write has reached the gate. + pub fn wait_until_held(&self) { + let _ = self.entered.recv(); + } + + /// Let the held write go on. + pub fn release(mut self) { + if let Some(go) = self.go.take() { + let _ = go.send(()); + } + } + } + + impl Drop for HeldWrite { + fn drop(&mut self) { + // A gate no write reached is removed, so it cannot hold a later test's write. + let mut slot = GATE.lock().unwrap_or_else(PoisonError::into_inner); + if slot.as_ref().is_some_and(|gate| Arc::ptr_eq(&gate.ran_on_holder, &self.ran_on_holder)) { + *slot = None; + } + } + } + + /// Called at the start of every recovery write. + pub(super) fn gate(dir: &Path) { + let gate = { + let mut slot = GATE.lock().unwrap_or_else(PoisonError::into_inner); + if slot.as_ref().is_some_and(|gate| gate.dir == dir) { slot.take() } else { None } + }; + let Some(gate) = gate else { return }; + if std::thread::current().id() == gate.holder { + gate.ran_on_holder.store(true, Ordering::SeqCst); + let _ = gate.entered.send(()); + return; + } + let _ = gate.entered.send(()); + // A dropped `HeldWrite` closes the channel, which also lets the write go on. + let _ = gate.go.recv(); + } + + /// Block until the background writer has no write queued or running. + pub fn wait_until_idle() { + // Nothing is written in the background on the web. + #[cfg(not(target_arch = "wasm32"))] + if let Some(w) = super::worker::started() { + w.wait_until_idle(); + } + } +} + #[cfg(not(target_arch = "wasm32"))] fn secure_recovery_dir(dir: &Path) -> Result { match std::fs::symlink_metadata(dir) { diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index c1a742a31..3b7c2303d 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -135,20 +135,49 @@ fn background() -> std::sync::MutexGuard<'static, ()> { BACKGROUND.lock().unwrap_or_else(std::sync::PoisonError::into_inner) } -/// Poll `file.recovery.progress` until the background writer has nothing left, as the app does at -/// the end of a frame. +/// Wait for the background writer to have nothing left, then read `file.recovery.progress` as the +/// app does at the end of a frame. fn finished_writes(s: &mut Session) -> usize { - let mut written = 0; - for _ in 0..1200 { - let v = s.execute("file.recovery.progress", &json!({})).unwrap(); - assert_eq!(v["errors"], json!([]), "{v}"); - written += v["written"].as_u64().unwrap_or(0) as usize; - if !v["busy"].as_bool().unwrap_or(false) { - return written; - } - std::thread::sleep(std::time::Duration::from_millis(5)); - } - panic!("the background writer did not finish"); + testing::wait_until_idle(); + let v = s.execute("file.recovery.progress", &json!({})).unwrap(); + assert_eq!(v["errors"], json!([]), "{v}"); + assert_eq!(v["busy"], false, "{v}"); + v["written"].as_u64().unwrap_or(0) as usize +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_background_save_returns_while_its_write_is_held() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut s = dirty_session(); + s.recovery_dir = Some(dir.path().to_path_buf()); + let uid = s.docs[0].uid; + let (file, _) = files(dir.path(), uid); + let held = testing::hold_next_write(dir.path()); + let queued = s.execute("file.recovery.save", &json!({"background": true})).unwrap(); + assert!(!held.ran_here(), "the write ran on the calling thread"); + assert_eq!(queued["queued"], 1, "{queued}"); + // The writer thread is stopped at the start of the write, and the session goes on. + held.wait_until_held(); + let v = s.execute("file.recovery.progress", &json!({})).unwrap(); + assert_eq!(v["busy"], true, "{v}"); + s.execute("frame.create", &json!({"rect": [20, 20, 60, 60]})).unwrap(); + assert!(!file.exists(), "nothing is published while the write is held"); + held.release(); + assert_eq!(finished_writes(&mut s), 1); + assert!(file.exists()); + discard(dir.path(), uid); +} + +#[test] +fn a_background_save_rejects_a_background_that_is_not_true_or_false() { + let dir = tempfile::tempdir().unwrap(); + let mut s = dirty_session(); + s.recovery_dir = Some(dir.path().to_path_buf()); + let err = s.execute("file.recovery.save", &json!({"background": "yes"})).unwrap_err(); + assert!(err.to_string().contains("`background` must be true or false"), "{err}"); + assert!(list(dir.path()).is_empty(), "nothing was written"); } #[test] @@ -242,17 +271,10 @@ fn a_background_snapshot_whose_metadata_failed_is_still_the_documents_to_remove( std::fs::create_dir(&metadata).unwrap(); let queued = s.execute("file.recovery.save", &json!({"background": true})).unwrap(); assert_eq!(queued["queued"], 1, "{queued}"); - let mut reported = None; - for _ in 0..1200 { - let v = s.execute("file.recovery.progress", &json!({})).unwrap(); - if let Some(first) = v["errors"].as_array().and_then(|errors| errors.first()) { - reported = first.as_str().map(str::to_string); - } - if !v["busy"].as_bool().unwrap_or(false) { - break; - } - std::thread::sleep(std::time::Duration::from_millis(5)); - } + testing::wait_until_idle(); + let v = s.execute("file.recovery.progress", &json!({})).unwrap(); + assert_eq!(v["busy"], false, "{v}"); + let reported = v["errors"].as_array().and_then(|errors| errors.first()).and_then(Value::as_str).map(str::to_string); let reported = reported.expect("the metadata failure is reported"); assert!(reported.contains(&metadata.display().to_string()), "{reported}"); assert!(document.exists(), "the primary landed"); diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 6b08420a9..f7fe65d8e 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -44,6 +44,7 @@ zip = { workspace = true } # Headless (offscreen wgpu) rendering of the whole window for UI screenshots: `examples/ui_shot.rs`. egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] } designcraft-fonts = { workspace = true, features = ["testing"] } +designcraft-engine = { workspace = true, features = ["testing"] } [build-dependencies] serde_json = { workspace = true } diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 17cc20d28..8f2eef43d 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -151,18 +151,30 @@ fn the_recovery_timer_writes_off_the_interface_thread() { app.last_recovery = -1.0e9; let uid = app.session.documents()[0].uid; let entry = dir.path().join(format!("{uid}.designcraft")); - let mut written = false; - for _ in 0..600 { + // The writer stops at the start of the write until the test lets it go on, so a frame that + // waited for the write would never return. + let held = designcraft_engine::recovery::testing::hold_next_write(dir.path()); + // egui discards a pass that needs another layout; the timer runs in the first pass it keeps. + for _ in 0..10 { shot_frame(&mut app, &ctx, egui::vec2(1400.0, 900.0)); - // The timer fired and the write finished: the file is there and nothing is still queued. - if entry.exists() && !app.recovery_writing { - written = true; + if app.last_recovery > 0.0 { break; } - std::thread::sleep(std::time::Duration::from_millis(5)); } - assert!(written, "the timer's background write published the document"); - assert!(app.last_recovery > 0.0, "the timer restarted its interval"); + assert!(app.last_recovery > 0.0, "the timer fired and restarted its interval"); + assert!(!held.ran_here(), "the timer wrote the recovery data on the interface thread"); + assert!(app.recovery_writing, "the timer queued the write"); + held.wait_until_held(); + // While the write is held, the interface keeps drawing frames and taking edits. + app.run("frame.create", json!({"rect": [20, 20, 80, 80]})).unwrap(); + shot_frame(&mut app, &ctx, egui::vec2(1400.0, 900.0)); + assert!(app.recovery_writing, "the write is still held"); + assert!(!entry.exists(), "nothing is published while the write is held"); + held.release(); + designcraft_engine::recovery::testing::wait_until_idle(); + shot_frame(&mut app, &ctx, egui::vec2(1400.0, 900.0)); + assert!(!app.recovery_writing, "the frame after the write took its result"); + assert!(entry.exists(), "the timer's background write published the document"); // The checkpoint is the document's: saving it removes the recovery entry. let saved = dir.path().join("saved.designcraft"); app.run("file.saveAs", json!({"path": saved.to_string_lossy()})).unwrap(); From ee69d5ac390f024afdd68995ba660ed514fbc9d5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:42:03 -0800 Subject: [PATCH 0941/1349] Preflight: the worker keeps its compositions out of the interface thread's cache The worker checks the document state it was given, which is often one edit behind the interface. It composed that older state into the shared composition cache, replacing the interface thread's composition of the current state, so the next frame composed the edited story again (about 14 ms per edit for a 10-page story). Cache::over makes a cache that uses another cache's compositions of the same state and keeps whatever it composes to itself. The worker checks with one over the interface thread's cache, keeps it for the next check of the same document, and drops it after a minute without jobs. With no active document, the job waiting for a busy worker is dropped, so it no longer keeps a closed document in memory until another document opens. --- crates/compose/src/cache.rs | 35 ++++++++++++ crates/compose/src/tests.rs | 19 +++++++ crates/ui-egui/src/preflight_worker.rs | 56 +++++++++++++++++--- crates/ui-egui/src/preflight_worker/tests.rs | 47 ++++++++++++++++ 4 files changed, 149 insertions(+), 8 deletions(-) diff --git a/crates/compose/src/cache.rs b/crates/compose/src/cache.rs index 5e4cb0911..9cf96e497 100644 --- a/crates/compose/src/cache.rs +++ b/crates/compose/src/cache.rs @@ -62,6 +62,9 @@ pub struct Cache { /// The composition each story (page-independent key) had before its latest recomposition, /// with the story revision it was composed from (repaint only the frames an edit changed). previous: Mutex, Arc)>>, + /// A cache this one reads without writing to: a composition or index found there for the same + /// inputs is used, and anything composed is kept here only. + base: Option>, } /// A signature's hash, standing in for it in another story's signature. @@ -104,6 +107,18 @@ impl Cache { Self::default() } + /// An empty cache that also uses what `base` holds for the same inputs, and never changes + /// `base`. A reader of an older state of the document composes that state here instead of + /// replacing the compositions of the current state in `base`. + pub fn over(base: Arc) -> Self { + Cache { base: Some(base), ..Self::default() } + } + + /// The cache given to [`Cache::over`]. + pub fn base(&self) -> Option<&Arc> { + self.base.as_ref() + } + /// The composed story, from cache or freshly composed. `page` is the absolute page a /// parent-page item is shown on (its page number markers and variables are that page's), or /// `None` for a story's own frames. Pages are identified by index, not name: names repeat when @@ -255,6 +270,14 @@ impl Cache { return e.out.clone(); } } + if let Some(base) = &self.base { + let g = base.map.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(e) = g.0.get(&key) + && e.sig == sig + { + return e.out.clone(); + } + } // Parent-page items are composed per page: markers show its name, variables need its index. let page = page.filter(|_| with_vars); let running = running.then(|| self.running_index(doc)); @@ -368,6 +391,12 @@ impl Cache { { return r.clone(); } + if let Some(base) = &self.base + && let Some((s, r)) = &*base.xrefs.lock().unwrap_or_else(PoisonError::into_inner) + && *s == sig + { + return r.clone(); + } let r = Arc::new(crate::xref::XrefIndex::build(doc, &|sid| self.get(doc, sid, None))); *self.xrefs.lock().unwrap_or_else(PoisonError::into_inner) = Some((sig, r.clone())); r @@ -381,6 +410,12 @@ impl Cache { { return r.clone(); } + if let Some(base) = &self.base + && let Some((s, r)) = &*base.running.lock().unwrap_or_else(PoisonError::into_inner) + && *s == sig + { + return r.clone(); + } let r = Arc::new(RunningIndex::build(doc, &|sid| self.get(doc, sid, None))); *self.running.lock().unwrap_or_else(PoisonError::into_inner) = Some((sig, r.clone())); r diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index f15f1e33d..900bced97 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -8156,6 +8156,25 @@ fn cache_recomposes_when_the_baseline_grid_changes() { assert!((la.baseline - lb.baseline).abs() > 1.0, "{} {}", la.baseline, lb.baseline); } +/// A cache over another uses its compositions of the same state, and composes an older state +/// without replacing the other cache's composition of the current one. +#[test] +fn a_cache_over_another_reads_it_without_writing_to_it() { + let (old, sid, _) = doc_with(LOREM, Rect::new(0.0, 0.0, 200.0, 600.0), ParaAttrs::default()); + let mut new = old.clone(); + new.story_mut(sid).unwrap().rev += 1; + let base = Arc::new(Cache::new()); + let current = base.get(&new, sid, None); + let reader = Cache::over(Arc::clone(&base)); + assert!(reader.base().is_some_and(|b| Arc::ptr_eq(b, &base))); + assert!(Arc::ptr_eq(&reader.get(&new, sid, None), ¤t), "the base's composition is used"); + let earlier = reader.get(&old, sid, None); + assert!(!Arc::ptr_eq(&earlier, ¤t)); + assert!(Arc::ptr_eq(&reader.get(&old, sid, None), &earlier), "kept in the reader"); + assert!(Arc::ptr_eq(&base.get(&new, sid, None), ¤t), "the base keeps the current state's composition"); + assert!(base.composed_for(&old, sid).is_none(), "the base holds nothing of the older state"); +} + /// Two single pages 618 pt tall, top margins 36 and 48, each with an overset 11/13 story aligned /// to a baseline grid (start 0, increment 13) and a frame filling its margin box (bottom 582). fn grid_margin_doc(relative_to: designcraft_doc::GridRelative) -> (Document, [StoryId; 2]) { diff --git a/crates/ui-egui/src/preflight_worker.rs b/crates/ui-egui/src/preflight_worker.rs index 6abb67e0c..ddcdffe68 100644 --- a/crates/ui-egui/src/preflight_worker.rs +++ b/crates/ui-egui/src/preflight_worker.rs @@ -40,6 +40,10 @@ const MAX_WORKERS: usize = 4; // this long. #[cfg(not(target_arch = "wasm32"))] const RETRY_AFTER: Duration = Duration::from_secs(30); +// A worker given no job for this long drops its own compositions, which keep the document they +// were made from alive after it closes. +#[cfg(not(target_arch = "wasm32"))] +const FORGET_AFTER: Duration = Duration::from_secs(60); /// A state of a document as a check sees it: which document, which state of it with which /// compositions (a font reload replaces the cache and bumps the revision), and where it is saved @@ -118,7 +122,17 @@ pub(crate) fn issues(app: &mut DesignApp, ctx: &egui::Context) -> Option Option>> { - let (of, doc) = Checked::new(app)?; + let Some((of, doc)) = Checked::new(app) else { + // A job waiting for the worker would keep a closed document alive. + #[cfg(not(target_arch = "wasm32"))] + { + app.preflight.worker.waiting = None; + for done in app.preflight.worker.poll() { + app.preflight.keep(done); + } + } + return None; + }; let cache = Arc::clone(&app.session.cache); let state = &mut app.preflight; #[cfg(not(target_arch = "wasm32"))] @@ -355,13 +369,17 @@ fn spawn(ctx: egui::Context, live: &Arc) -> Opti .name("designcraft-preflight".into()) .spawn(move || { let _alive = alive; - while let Ok(job) = jobs.recv() { - let started = Instant::now(); - let issues = check_document(&job.doc, &job.cache, job.of.path.as_deref().map(std::path::Path::new), MIN_PPI); - let found = Found { of: job.of, issues: Arc::new(issues), took: started.elapsed(), asked_at: 0.0 }; - // The checked state isn't kept alive by its check once the result is sent. - drop(job.doc); - if done_tx.send(found).is_err() { + let mut own = None; + loop { + let job = match jobs.recv_timeout(FORGET_AFTER) { + Ok(job) => job, + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { + own = None; + continue; + } + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, + }; + if done_tx.send(check(&mut own, job)).is_err() { break; } ctx.request_repaint(); @@ -371,6 +389,28 @@ fn spawn(ctx: egui::Context, live: &Arc) -> Opti Some((tx, rx)) } +/// Checks `job` with the worker's own compositions, `own`. +#[cfg(not(target_arch = "wasm32"))] +fn check(own: &mut Option<(u64, Cache)>, job: Job) -> Found { + let started = Instant::now(); + let issues = check_document(&job.doc, reader(own, &job), job.of.path.as_deref().map(std::path::Path::new), MIN_PPI); + // The checked state isn't kept alive by its check once the result is sent. + drop(job.doc); + Found { of: job.of, issues: Arc::new(issues), took: started.elapsed(), asked_at: 0.0 } +} + +/// The cache a worker checks `job` with: a cache over the interface thread's cache, which the +/// worker reads and never writes. The worker keeps it for the next job of the same document over +/// the same cache. +#[cfg(not(target_arch = "wasm32"))] +fn reader<'a>(own: &'a mut Option<(u64, Cache)>, job: &Job) -> &'a Cache { + let reuse = own.as_ref().is_some_and(|(uid, c)| *uid == job.of.uid && c.base().is_some_and(|b| Arc::ptr_eq(b, &job.cache))); + if !reuse { + *own = None; + } + &own.get_or_insert_with(|| (job.of.uid, Cache::over(Arc::clone(&job.cache)))).1 +} + /// Starts the worker in a test, where checks otherwise run on the interface thread. #[cfg(all(test, not(target_arch = "wasm32")))] pub(crate) fn start_worker(app: &mut DesignApp, ctx: &egui::Context) { diff --git a/crates/ui-egui/src/preflight_worker/tests.rs b/crates/ui-egui/src/preflight_worker/tests.rs index f437a4174..9cc9a394b 100644 --- a/crates/ui-egui/src/preflight_worker/tests.rs +++ b/crates/ui-egui/src/preflight_worker/tests.rs @@ -212,6 +212,53 @@ fn a_blocked_check_of_another_document_is_superseded() { assert!(jobs.try_recv().is_ok(), "queued on the same worker"); } +/// A worker checking an older state of the document leaves the interface thread's composition of +/// the current state in its cache. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_check_of_an_older_state_keeps_the_current_compositions() { + let (mut app, id) = overset_app(); + let (older, _) = Checked::new(&app).unwrap(); + let older_doc = Arc::clone(&app.session.active().unwrap().doc); + app.run("transform.move", json!({"ids": [id], "dx": 1.0, "dy": 0.0})).unwrap(); + let doc = Arc::clone(&app.session.active().unwrap().doc); + let sid = *doc.stories.keys().next().unwrap(); + let cache = Arc::clone(&app.session.cache); + let current = cache.get(&doc, sid, None); + let mut own = None; + let found = super::check(&mut own, super::Job { of: older, doc: Arc::clone(&older_doc), cache: Arc::clone(&cache) }); + assert_eq!(found.issues.iter().filter(|i| i.severity == "error").count(), 1); + assert!(Arc::ptr_eq(&cache.get(&doc, sid, None), ¤t), "the current state's composition is kept"); + // The worker keeps its compositions for the next check of the document over the same cache. + let earlier = own.as_ref().unwrap().1.get(&older_doc, sid, None); + let (of, doc) = Checked::new(&app).unwrap(); + super::check(&mut own, super::Job { of, doc, cache: Arc::clone(&cache) }); + assert!(Arc::ptr_eq(&own.as_ref().unwrap().1.get(&older_doc, sid, None), &earlier), "kept for the next check"); + let reloaded = Arc::new(designcraft_compose::Cache::new()); + let (of, doc) = Checked::new(&app).unwrap(); + super::check(&mut own, super::Job { of, doc, cache: Arc::clone(&reloaded) }); + assert!(own.as_ref().unwrap().1.base().is_some_and(|b| Arc::ptr_eq(b, &reloaded)), "a new cache after a font reload"); +} + +/// Closing the last document drops the job waiting for a busy worker, which holds that document. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn closing_the_last_document_drops_the_waiting_job() { + let (mut app, id) = overset_app(); + let ctx = egui::Context::default(); + let (_jobs, _done) = stalled_worker(&mut app); + for dx in [1.0, -1.0] { + app.run("transform.move", json!({"ids": [id], "dx": dx, "dy": 0.0})).unwrap(); + assert!(super::issues(&mut app, &ctx).is_none()); + } + assert!(app.preflight.worker.waiting.is_some()); + app.run("file.close", json!({})).unwrap(); + assert!(app.session.active().is_none()); + assert!(super::issues(&mut app, &ctx).is_none()); + assert!(app.preflight.worker.waiting.is_none(), "the waiting job is dropped"); + assert!(app.preflight.found.is_empty()); +} + /// A result for another document keeps the active document's issues, and the issues of at most /// `MAX_DOCUMENTS` documents are kept. #[cfg(not(target_arch = "wasm32"))] From 9c4c3730ab5425eed3177e900cb4cb871d65a776 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:42:30 -0800 Subject: [PATCH 0942/1349] CMYK view: convert the blended inks to screen colours on the render threads In the CMYK blend space view (Proof Colors off) every render converted each pixel of the ink passes' area from the blended inks to a screen colour on the calling thread, through a 16-entry lookup per pixel. With render threads it now converts bands of rows on that many threads at once, at least 32 rows a band. The colours are the same; the Wasm build and single-threaded renders convert on one thread as before. --- crates/render/src/blendspace.rs | 93 +++++++++++++++++++++++++++++---- crates/render/src/driver.rs | 2 + crates/render/src/lib.rs | 3 ++ 3 files changed, 88 insertions(+), 10 deletions(-) diff --git a/crates/render/src/blendspace.rs b/crates/render/src/blendspace.rs index 449410c59..1d992c6fd 100644 --- a/crates/render/src/blendspace.rs +++ b/crates/render/src/blendspace.rs @@ -12,6 +12,7 @@ use crate::{Frame, Placed, RenderOptions, Rendered, Renderer}; use designcraft_color::BlendMode as DcBlend; use designcraft_doc::{Document, Item, SpreadRef}; use designcraft_geom::{Affine, Rect, Shape}; +use vello_cpu::color::PremulRgba8; use vello_cpu::{RenderContext, peniko}; /// At most one viewport, capped at 64 MiB. The snapshot shares the document's large Arcs; @@ -284,6 +285,58 @@ fn srgb_in(table: &[[f32; 3]], cmyk: [f32; 4]) -> [f32; 3] { out } +/// Rows of the ink passes' area one conversion thread takes at least. +const MIN_BAND_ROWS: usize = 32; + +/// The blended inks, the C/M/Y complements in `cmy` and the K complement in `black` (`width` +/// pixels a row), converted to screen colours in `cmy`. With render threads, bands of rows are +/// converted on that many threads at once. Returns the number of bands. +fn inks_to_screen(cmy: &mut [PremulRgba8], black: &[PremulRgba8], width: usize, rich_black: bool, threads: u16) -> usize { + let table = srgb_table(); + let convert = |cmy: &mut [PremulRgba8], black: &[PremulRgba8]| { + for (c, k) in cmy.iter_mut().zip(black) { + if c.a == 0 { + continue; + } + let a = c.a as f32; + let inks = [1.0 - c.r as f32 / a, 1.0 - c.g as f32 / a, 1.0 - c.b as f32 / a, 1.0 - k.r as f32 / a]; + let rgb = if rich_black && inks[0..3].iter().all(|v| *v <= 1e-3) && inks[3] >= 0.999 { [0.0; 3] } else { srgb_in(&table, inks) }; + let [r, g, b] = rgb.map(|v| (v.clamp(0.0, 1.0) * a).round() as u8); + (c.r, c.g, c.b) = (r, g, b); + } + }; + let rows = cmy.len().checked_div(width).unwrap_or(0); + let bands = usize::from(threads).min(rows / MIN_BAND_ROWS).max(1); + if cfg!(target_arch = "wasm32") || bands == 1 { + convert(cmy, black); + return 1; + } + let chunk = rows.div_ceil(bands) * width; + let mut parts: Vec<(&mut [PremulRgba8], &[PremulRgba8])> = cmy.chunks_mut(chunk).zip(black.chunks(chunk)).collect(); + let convert = &convert; + let mut failed = Vec::new(); + std::thread::scope(|s| { + let mut each = parts.iter_mut().enumerate(); + let first = each.next(); + for (i, (c, k)) in each { + if let Err(e) = std::thread::Builder::new().spawn_scoped(s, move || convert(c, k)) { + log::warn!("CMYK view: a conversion thread did not start ({e})"); + failed.push(i); + } + } + if let Some((_, (c, k))) = first { + convert(c, k); + } + }); + // A band whose thread did not start is converted here. + for i in failed { + if let Some((c, k)) = parts.get_mut(i) { + convert(c, k); + } + } + bands +} + impl Renderer { /// The view pixels the spread's transparency can change: the union of its transparent /// objects (opacity, blend, effects, knockout, also nested or anchored) with their effects' @@ -413,16 +466,10 @@ impl Renderer { crate::PLATE.with(|p| p.set(f.opts.plate)); self.stats.items = (self.stats.items - stats.items) / 2 + stats.items; self.stats.glyphs = (self.stats.glyphs - stats.glyphs) / 2 + stats.glyphs; - let table = srgb_table(); - for (c, k) in cmy.data_mut().iter_mut().zip(black.data()) { - if c.a == 0 { - continue; - } - let a = c.a as f32; - let inks = [1.0 - c.r as f32 / a, 1.0 - c.g as f32 / a, 1.0 - c.b as f32 / a, 1.0 - k.r as f32 / a]; - let rgb = if f.opts.rich_black && inks[0..3].iter().all(|v| *v <= 1e-3) && inks[3] >= 0.999 { [0.0; 3] } else { srgb_in(&table, inks) }; - let [r, g, b] = rgb.map(|v| (v.clamp(0.0, 1.0) * a).round() as u8); - (c.r, c.g, c.b) = (r, g, b); + let _bands = inks_to_screen(cmy.data_mut(), black.data(), usize::from(aw), f.opts.rich_black, threads); + #[cfg(test)] + { + self.cmyk_convert_bands = _bands; } ctx.set_transform(Affine::translate((area.x0, area.y0))); ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(std::sync::Arc::new(cmy)), sampler: peniko::ImageSampler::default() }); @@ -669,6 +716,32 @@ mod tests { } } + /// With render threads, the ink passes' colours are converted in that many bands of rows at + /// once, each band by its own thread, and the result is the same as converting on one thread. + #[test] + fn ink_colours_convert_in_a_band_per_render_thread() { + let mut doc = document(); + rectangle(&mut doc, SpreadRef::Doc(0), Rect::new(-20.0, -5.0, 180.0, 125.0), "C=100 M=0 Y=0 K=0", DcBlend::Multiply); + let render = |threads: u16| { + let mut renderer = Renderer::new(); + renderer.threads = threads; + let image = renderer.render( + &doc, + &Cache::new(), + &[Placed { spread: SpreadRef::Doc(0), xf: Affine::IDENTITY }], + (400, 300), + Affine::scale(2.0) * Affine::translate((30.0, 10.0)), + &RenderOptions { blend_space_view: true, background: Some([180, 180, 180, 255]), ..Default::default() }, + ); + (image, renderer.cmyk_convert_bands) + }; + let (one, bands) = render(0); + assert_eq!(bands, 1); + let (four, bands) = render(4); + assert_eq!(bands, 4, "a band per render thread"); + assert_eq!(four.pixels, one.pixels); + } + #[test] fn cmyk_nonseparable_modes_use_the_existing_rgb_approximation() { let mut doc = document(); diff --git a/crates/render/src/driver.rs b/crates/render/src/driver.rs index a5dd2b86b..7230644a6 100644 --- a/crates/render/src/driver.rs +++ b/crates/render/src/driver.rs @@ -21,6 +21,8 @@ impl Renderer { cmyk_pass_pixels: 0, #[cfg(test)] cmyk_pass_items: 0, + #[cfg(test)] + cmyk_convert_bands: 0, threads: default_threads(), stats: FrameStats::default(), } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 25207b248..9f790c9f4 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -163,6 +163,9 @@ pub struct Renderer { /// Items the last ink pass drew (tests). #[cfg(test)] cmyk_pass_items: usize, + /// Bands of rows the last ink passes' colours were converted in (tests). + #[cfg(test)] + cmyk_convert_bands: usize, pub threads: u16, pub stats: FrameStats, } From 229abafbe60e07574b37b9bf826b98670c765ccf Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 03:43:53 +0000 Subject: [PATCH 0943/1349] Apply review fixes - crates/render/src/driver.rs - crates/render/src/fx.rs --- crates/render/src/driver.rs | 2 +- crates/render/src/fx.rs | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/render/src/driver.rs b/crates/render/src/driver.rs index b9568a595..cee99590c 100644 --- a/crates/render/src/driver.rs +++ b/crates/render/src/driver.rs @@ -46,6 +46,7 @@ impl Renderer { let (width, height) = size; RICH_BLACK.with(|r| r.set(opts.rich_black)); PLATE.with(|p| p.set(opts.plate)); + self.kept.begin(doc); if let Some(hit) = self.cmyk_view.as_ref().filter(|entry| entry.matches(doc, spreads, width, height, view, opts, self.threads)) { let image = hit.image(); self.stats = hit.stats(); @@ -90,7 +91,6 @@ impl Renderer { self.stats = FrameStats::default(); self.stories.clear(); self.glyphs.tick(); - self.kept.begin(doc); if let Some(bg) = opts.background { ctx.set_transform(Affine::IDENTITY); ctx.set_paint(peniko::Color::from_rgba8(bg[0], bg[1], bg[2], bg[3])); diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index 44513c3ac..5248bf9ba 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -513,7 +513,8 @@ impl Renderer { return; } let [a, b, c, d, e, g] = (f.view * xf).as_coeffs(); - let (linear, anchor) = ([a, b, c, d], Vec2::new(e, g)); + let [va, vb, vc, vd, _, _] = f.view.as_coeffs(); + let (linear, anchor) = ([a, b, c, d, va, vb, vc, vd], Vec2::new(e, g)); let plate = crate::PLATE.with(std::cell::Cell::get); let rich_black = crate::color::RICH_BLACK.with(std::cell::Cell::get); let key = (it.id, page, look.slot, plate); @@ -606,8 +607,8 @@ struct Look { struct Kept { /// The object, with the transform it had. item: Item, - /// The linear part of the object's spread → device transform. - linear: [f64; 4], + /// The linear parts of the object's spread → device transform and of the view (the effect offset turns with the view). + linear: [f64; 8], /// The device position of the object's origin. anchor: Vec2, look: Look, From 27963d6d055133820ba7d6326d171822cd811dc0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:45:30 -0800 Subject: [PATCH 0944/1349] Justification: the dialog sets Auto Leading and Single Word Justification Type > Justification and Paragraph Style Options > Justification now show Auto Leading (0% to 500% of the type size) and Single Word Justification (Align Left, Align Center, Align Right, Full Justify). Both fields show the selected paragraphs' values, or blank where they differ, and OK writes autoLeading and singleWordJustify only when they were edited. An Auto Leading outside 0% to 500% keeps the dialog open with the reason. --- crates/ui-egui/src/dialogs.rs | 49 ++++++++++++- crates/ui-egui/src/dialogs/tests.rs | 107 ++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/ar.rs | 3 + crates/ui-egui/src/i18n/cs.rs | 3 + crates/ui-egui/src/i18n/de.rs | 2 + crates/ui-egui/src/i18n/hu.rs | 3 + crates/ui-egui/src/i18n/it.rs | 3 + crates/ui-egui/src/i18n/ja.rs | 2 + crates/ui-egui/src/i18n/ka.rs | 2 + crates/ui-egui/src/i18n/pl.rs | 3 + crates/ui-egui/src/i18n/pt_br.rs | 2 + crates/ui-egui/src/i18n/ru.rs | 3 + crates/ui-egui/src/i18n/sv.rs | 2 + crates/ui-egui/src/i18n/table.rs | 5 ++ crates/ui-egui/src/i18n/uk.rs | 3 + docs/typography-parity.md | 2 +- 16 files changed, 191 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a6400054d..6664fc349 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -7689,7 +7689,7 @@ fn shown_rule(d: &Dialog, prefix: &str, which: &str, current: &Value) -> Value { } /// The paragraph attributes of the Justification controls. -pub const JUSTIFY_ATTRS: [&str; 12] = [ +pub const JUSTIFY_ATTRS: [&str; 14] = [ "wordSpaceMin", "wordSpaceDesired", "wordSpaceMax", @@ -7699,6 +7699,8 @@ pub const JUSTIFY_ATTRS: [&str; 12] = [ "glyphScaleMin", "glyphScaleDesired", "glyphScaleMax", + "autoLeading", + "singleWordJustify", "composer", "kashidas", "koreanCharBreaks", @@ -7711,9 +7713,29 @@ const JUSTIFY_ROWS: [(&str, &str, (f64, f64)); 3] = [ ("Glyph Scaling", "glyphScale", (50.0, 200.0)), ]; +/// The allowed Auto Leading, in percent of the type size. +const AUTO_LEADING_RANGE: (f64, f64) = (0.0, 500.0); + +/// The Single Word Justification choices: (attribute value, label). +const SINGLE_WORD_CHOICES: [(&str, &str); 4] = + [("left", "Align Left"), ("center", "Align Center"), ("right", "Align Right"), ("fullyJustified", "Full Justify")]; + /// Checks the edited spacing values: each within its range, and minimum ≤ desired ≤ maximum -/// (values left mixed are not compared). +/// (values left mixed are not compared); an edited Auto Leading within its range, and an edited +/// Single Word Justification one of its choices. fn check_justification(d: &Dialog, prefix: &str, current: &Value) -> Result<(), String> { + if let Some(v) = d.fields.get(&format!("{prefix}autoLeading")) { + let (lo, hi) = AUTO_LEADING_RANGE; + let pct = v.as_f64().map(|x| x * 100.0).filter(|x| x.is_finite()).ok_or("Justification: Auto Leading is not a number")?; + if !(lo..=hi).contains(&pct) { + return Err(format!("Justification: Auto Leading must be between {lo}% and {hi}%")); + } + } + if let Some(v) = d.fields.get(&format!("{prefix}singleWordJustify")) + && !SINGLE_WORD_CHOICES.iter().any(|(k, _)| v.as_str() == Some(k)) + { + return Err(format!("Justification: Single Word Justification cannot be {v}")); + } for (label, stem, (lo, hi)) in JUSTIFY_ROWS { let mut edited = false; let mut known = Vec::new(); @@ -7916,6 +7938,29 @@ fn justification(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, prefix: &str, cu } ui.end_row(); } + crate::rtl::label(ui, crate::i18n::tr(lang, "Auto Leading:")); + let auto = cur(d, "autoLeading").as_f64().map(|x| x * 100.0); + if let Some(n) = ui.scope(|ui| crate::widgets::number(ui, &format!("ps{prefix}autoLeading"), auto, "%", 60.0, 0)).inner { + d.fields.insert(format!("{prefix}autoLeading"), json!(n / 100.0)); + } + ui.end_row(); + let single_label = crate::rtl::label(ui, crate::i18n::tr(lang, "Single Word Justification:")); + let single = cur(d, "singleWordJustify"); + // Mixed (null) shows blank until a choice is made. + let shown = SINGLE_WORD_CHOICES.iter().find(|(k, _)| single.as_str() == Some(k)).map_or("", |(_, label)| label); + craft_ui::ComboBox::from_id_salt(("singleWordJustify", prefix)) + .selected_text(crate::rtl::widget(ui, crate::i18n::tr(lang, shown))) + .width(130.0) + .show_ui(ui, |ui| { + for (v, label) in SINGLE_WORD_CHOICES { + if ui.selectable_label(single.as_str() == Some(v), crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() { + d.fields.insert(format!("{prefix}singleWordJustify"), json!(v)); + } + } + }) + .response + .labelled_by(single_label.id); + ui.end_row(); crate::rtl::label(ui, crate::i18n::tr(lang, "Composer:")); let composer = cur(d, "composer"); // Mixed (null) selects neither; a Japanese composer keeps its kind. diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 272165b08..1343b30d7 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1130,6 +1130,113 @@ fn justification_dialog_leaves_mixed_fields_alone_and_refuses_bad_values() { } } +/// The Justification dialog shows Auto Leading and Single Word Justification, OK sets them on the +/// selected paragraph as one undo step, bad values keep the dialog open, and both values survive +/// saving and opening the native file and an IDML export. +#[test] +fn justification_dialog_sets_auto_leading_and_single_word_justification() { + use egui_kittest::{Harness, kittest::Queryable}; + let (mut app, story) = two_paragraphs(); + app.run("app.justificationDialog", json!({})).unwrap(); + let d = app.ui.dialog.clone().unwrap(); + let current = d.fields["current"].clone(); + assert_eq!((current["autoLeading"].clone(), current["singleWordJustify"].clone()), (json!(1.2), json!("fullyJustified"))); + let mut h = Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let key = egui::Id::unique("justification_single_word_fonts"); + if ui.data(|d| d.get_temp::(key)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(key, true)); + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(3); + assert!(h.query_by_label("Auto Leading:").is_some()); + assert!(h.query_by_label("Single Word Justification:").is_some()); + // The dropdown shows the paragraph's Full Justify; pick Align Center. + h.get_by(|n| n.role() == egui::accesskit::Role::ComboBox && n.value().as_deref() == Some("Full Justify")).click(); + h.run_steps(3); + h.get_by_label("Align Center").click(); + h.run_steps(3); + let mut app = std::mem::replace(h.state_mut(), DesignApp::new(designcraft_engine::Session::new(), crate::Services::default())); + drop(h); + let ctx = egui::Context::default(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["singleWordJustify"], "center", "the choice is the edit"); + + // Out of range or not a choice: an error, the dialog stays open, nothing changes. + let d = app.ui.dialog.clone().unwrap(); + let before = undo_steps(&app); + let bad = [ + ("autoLeading", json!(5.004)), + ("autoLeading", json!(-0.004)), + ("autoLeading", json!(f64::NAN)), + ("singleWordJustify", json!("leftJustified")), + ]; + for (key, v) in bad { + app.ui.dialog = Some(d.clone()); + app.ui.dialog.as_mut().unwrap().fields.insert(key.into(), v.clone()); + assert!(confirm(&mut app).is_err(), "{key} = {v}"); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.fields.contains_key("justifyError")), "{key}: the dialog shows why"); + } + assert_eq!(undo_steps(&app), before); + + app.ui.dialog = Some(d); + app.ui.dialog.as_mut().unwrap().fields.insert("autoLeading".into(), json!(1.5)); + draw(&mut app, &ctx); + confirm(&mut app).unwrap(); + assert_eq!(undo_steps(&app), before + 1, "one undo step"); + let both = |app: &mut DesignApp, story: &Value, at| (para_attr(app, story, at, "autoLeading"), para_attr(app, story, at, "singleWordJustify")); + assert_eq!(both(&mut app, &story, 0), (json!(1.5), json!("center"))); + assert_eq!(both(&mut app, &story, 4), (json!(1.2), json!("fullyJustified")), "only the selected paragraph"); + + // Both paragraphs selected: the fields that differ show blank, and OK with no edit adds no undo step. + app.run("text.select", json!({"story": story, "anchor": 0, "focus": 7})).unwrap(); + app.run("app.justificationDialog", json!({})).unwrap(); + draw(&mut app, &ctx); + let current = app.ui.dialog.as_ref().unwrap().fields["current"].clone(); + assert_eq!((current["autoLeading"].clone(), current["singleWordJustify"].clone()), (Value::Null, Value::Null)); + let before = undo_steps(&app); + confirm(&mut app).unwrap(); + assert_eq!(undo_steps(&app), before); + + // Saved and opened again, natively and through IDML. + let native = app.run("file.serialize", json!({})).unwrap(); + app.run("file.openBytes", json!({"name": "justify.designcraft", "base64": native["base64"]})).unwrap(); + assert_eq!(both(&mut app, &story, 0), (json!(1.5), json!("center"))); + let idml = app.run("file.exportIdml", json!({})).unwrap(); + app.run("file.openBytes", json!({"name": "justify.idml", "base64": idml["base64"]})).unwrap(); + let doc = &app.session.doc().unwrap().doc; + let sid = doc.stories.iter().find(|(_, s)| s.text == "One\nTwo").map(|(id, _)| *id).expect("the story comes back"); + let story = serde_json::to_value(sid).unwrap(); + assert_eq!(both(&mut app, &story, 0), (json!(1.5), json!("center"))); + assert_eq!(both(&mut app, &story, 4), (json!(1.2), json!("fullyJustified"))); +} + +/// Paragraph Style Options › Justification sets Auto Leading and Single Word Justification on the +/// style, and refuses an Auto Leading out of range. +#[test] +fn paragraph_style_options_justification_sets_auto_leading_and_single_word_justification() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("style.paragraph.create", json!({"name": "Headline"})).unwrap(); + let ctx = egui::Context::default(); + app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Headline", "section": "justify"}))); + draw(&mut app, &ctx); + app.ui.dialog.as_mut().unwrap().fields.insert("p.autoLeading".into(), json!(6.0)); + assert!(confirm(&mut app).unwrap_err().contains("Auto Leading")); + let style = |app: &DesignApp| app.session.doc().unwrap().doc.styles.para("Headline").unwrap().para.clone(); + assert_eq!(style(&app).auto_leading, None, "nothing saved"); + app.ui.dialog.as_mut().unwrap().fields.insert("p.autoLeading".into(), json!(1.0)); + app.ui.dialog.as_mut().unwrap().fields.insert("p.singleWordJustify".into(), json!("right")); + draw(&mut app, &ctx); + confirm(&mut app).unwrap(); + let para = style(&app); + assert_eq!((para.auto_leading, para.single_word_justify), (Some(1.0), Some(designcraft_doc::Align::Right))); +} + fn command_app(id: &str, fields: Value) -> DesignApp { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); app.ui.dialog = Some(Dialog::new(&format!("cmd:{id}"), fields)); diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index adf22f4fb..1a75534a5 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -611,6 +611,9 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("In justified Arabic text", "في النص العربي المضبوط"), ("Korean Line Breaks:", "فواصل الأسطر الكورية:"), ("Between syllables (not only at spaces)", "بين المقاطع (وليس عند المسافات فقط)"), + ("Auto Leading:", "التباعد التلقائي بين الأسطر:"), + ("Single Word Justification:", "ضبط الكلمة المفردة:"), + ("Full Justify", "ضبط كامل"), ("Minimum Space Before First Footnote:", "أقل مسافة قبل الحاشية الأولى:"), ("Space Between Footnotes:", "المسافة بين الحواشي:"), ("Offset:", "الإزاحة:"), diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index 5310e8d12..31fb1876c 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -1185,6 +1185,9 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("In justified Arabic text", "V arabském textu zarovnaném do bloku"), ("Korean Line Breaks:", "Zalomení řádků v korejštině:"), ("Between syllables (not only at spaces)", "Mezi slabikami (nejen u mezer)"), + ("Auto Leading:", "Automatický proklad:"), + ("Single Word Justification:", "Zarovnání jednoho slova:"), + ("Full Justify", "Plné zarovnání"), ("Binding:", "Vazba:"), ("Ruby:", "Ruby:"), ("Set over the selected text; empty removes it.", "Umístí se nad vybraný text; prázdné pole ho odstraní."), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 2e9920126..ce333f489 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1155,6 +1155,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("In justified Arabic text", "Im arabischen Blocksatz"), ("Korean Line Breaks:", "Koreanische Zeilenumbrüche:"), ("Between syllables (not only at spaces)", "Zwischen Silben (nicht nur an Leerzeichen)"), + ("Auto Leading:", "Automatischer Zeilenabstand:"), + ("Single Word Justification:", "Ausrichtung einzelner Wörter:"), ("Binding:", "Bindung:"), ("Ruby:", "Ruby:"), ("Set over the selected text; empty removes it.", "Wird über den ausgewählten Text gesetzt; leer entfernt es."), diff --git a/crates/ui-egui/src/i18n/hu.rs b/crates/ui-egui/src/i18n/hu.rs index ab30bce8d..1a63f3fad 100644 --- a/crates/ui-egui/src/i18n/hu.rs +++ b/crates/ui-egui/src/i18n/hu.rs @@ -156,6 +156,9 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Before", "Előtte"), ("Before Last:", "Az utolsó előtt:"), ("Between syllables (not only at spaces)", "Szótagok között (nem csak szóközöknél)"), + ("Auto Leading:", "Automatikus sorköz:"), + ("Single Word Justification:", "Egyetlen szó igazítása:"), + ("Full Justify", "Teljes sorkizárás"), ("Bevel", "Levágott sarok"), ("Bevel and Emboss", "Domborítás"), ("Beveled Rectangle", "Levágott sarkú téglalap"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 131875d46..de768d8e9 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1329,6 +1329,9 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("In justified Arabic text", "Nel testo arabo giustificato"), ("Korean Line Breaks:", "Interruzioni di riga coreane:"), ("Between syllables (not only at spaces)", "Tra le sillabe (non solo agli spazi)"), + ("Auto Leading:", "Interlinea automatica:"), + ("Single Word Justification:", "Giustificazione parola singola:"), + ("Full Justify", "Giustifica tutto"), ("Binding:", "Rilegatura:"), ("Ruby:", "Ruby:"), ("Set over the selected text; empty removes it.", "Applicato sopra il testo selezionato; se vuoto viene rimosso."), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index ae2dd653f..e4f436171 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1351,6 +1351,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("In justified Arabic text", "両端揃えのアラビア語テキストで使用"), ("Korean Line Breaks:", "韓国語の改行:"), ("Between syllables (not only at spaces)", "音節間で改行 (スペース以外も可)"), + ("Auto Leading:", "自動行送り:"), + ("Single Word Justification:", "単語のみの行の揃え:"), ("Binding:", "綴じ方向:"), ("Ruby:", "ルビ:"), ("Set over the selected text; empty removes it.", "選択したテキストの上にルビを付けます。空欄にすると削除します。"), diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index 1ba9a61a9..c9db1eab0 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -1254,6 +1254,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("In justified Arabic text", "ორმხრივად სწორებულ არაბულ ტექსტში"), ("Korean Line Breaks:", "კორეული სტრიქონების წყვეტა:"), ("Between syllables (not only at spaces)", "მარცვლებს შორის (არა მხოლოდ ჰარებთან)"), + ("Auto Leading:", "ავტომატური სტრიქონთაშორისი:"), + ("Single Word Justification:", "ერთი სიტყვის სწორება:"), ("Binding:", "აკინძვა:"), ("Ruby:", "რუბი:"), ("Set over the selected text; empty removes it.", "დაისმება მონიშნული ტექსტის თავზე; ცარიელი წაშლის მას."), diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index 7aac5d74b..e0b10e9cd 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -1198,6 +1198,9 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("In justified Arabic text", "W justowanym tekście arabskim"), ("Korean Line Breaks:", "Podział wierszy w koreańskim:"), ("Between syllables (not only at spaces)", "Między sylabami (nie tylko na spacjach)"), + ("Auto Leading:", "Interlinia automatyczna:"), + ("Single Word Justification:", "Justowanie pojedynczego słowa:"), + ("Full Justify", "Pełne justowanie"), ("Binding:", "Oprawa:"), ("Ruby:", "Ruby:"), ("Set over the selected text; empty removes it.", "Nad zaznaczonym tekstem; puste usuwa."), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 147947dbd..2bc5fc935 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1962,6 +1962,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Utilities", "Utilitários"), ("Korean Line Breaks:", "Quebras de linha em coreano:"), ("Between syllables (not only at spaces)", "Entre sílabas (não apenas nos espaços)"), + ("Auto Leading:", "Entrelinha automática:"), + ("Single Word Justification:", "Justificação de palavra única:"), ("Show Font Names in English", "Mostrar nomes de fontes em inglês"), ("Missing Glyphs", "Glifos ausentes"), ("Draw Missing Glyphs from Fallback Fonts", "Desenhar glifos ausentes com fontes substitutas"), diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 178cc9bc3..e6c223d9d 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -1175,6 +1175,9 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("In justified Arabic text", "В арабском тексте, выровненном по ширине"), ("Korean Line Breaks:", "Переносы корейского текста:"), ("Between syllables (not only at spaces)", "Между слогами (а не только на пробелах)"), + ("Auto Leading:", "Автоинтерлиньяж:"), + ("Single Word Justification:", "Выключка одного слова:"), + ("Full Justify", "Полная выключка"), ("Binding:", "Переплет:"), ("Ruby:", "Руби:"), ("Set over the selected text; empty removes it.", "Размещается над выделенным текстом; пустое значение удаляет подпись."), diff --git a/crates/ui-egui/src/i18n/sv.rs b/crates/ui-egui/src/i18n/sv.rs index 766ba32da..485dffa5f 100644 --- a/crates/ui-egui/src/i18n/sv.rs +++ b/crates/ui-egui/src/i18n/sv.rs @@ -409,6 +409,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("In justified Arabic text", "I marginaljusterad arabisk text"), ("Korean Line Breaks:", "Koreanska radbrytningar:"), ("Between syllables (not only at spaces)", "Mellan stavelser (inte bara vid blanksteg)"), + ("Auto Leading:", "Automatiskt radavstånd:"), + ("Single Word Justification:", "Justering av enstaka ord:"), ("Minimum Space Before First Footnote:", "Minsta avstånd före första fotnoten:"), ("Space Between Footnotes:", "Avstånd mellan fotnoter:"), ("Offset:", "Förskjutning:"), diff --git a/crates/ui-egui/src/i18n/table.rs b/crates/ui-egui/src/i18n/table.rs index ebde2b629..c216d6b97 100644 --- a/crates/ui-egui/src/i18n/table.rs +++ b/crates/ui-egui/src/i18n/table.rs @@ -3480,6 +3480,11 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[ "在音节之间(不仅在空格处)", ], ), + ("Auto Leading:", ["Automatischer Zeilenabstand:", "Interlignage automatique :", "Interlineado automático:", "自動行送り:", "自动行距:"]), + ( + "Single Word Justification:", + ["Ausrichtung einzelner Wörter:", "Justification des mots isolés :", "Justificación de palabra única:", "単語のみの行の揃え:", "单字齐行:"], + ), ("Binding:", ["Binding:", "Reliure :", "Binding:", "Binding:", "装订方向:"]), ("Ruby:", ["Ruby:", "Ruby :", "Ruby:", "Ruby:", "旁注:"]), ( diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 4b2853eae..65dace8a5 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -1326,6 +1326,9 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("In justified Arabic text", "В арабському тексті, вирівняному за шириною"), ("Korean Line Breaks:", "Переноси корейського тексту:"), ("Between syllables (not only at spaces)", "Між складами (а не лише на пробілах)"), + ("Auto Leading:", "Автоінтерліньяж:"), + ("Single Word Justification:", "Вирівнювання одного слова:"), + ("Full Justify", "Повне вирівнювання"), ("Binding:", "Напрямок палітурки:"), ("Ruby:", "Фонетичні підписи:"), ("Set over the selected text; empty removes it.", "Розміщується над виділеним текстом; порожнє значення вилучає підпис."), diff --git a/docs/typography-parity.md b/docs/typography-parity.md index 8e17cd2a9..1064ef823 100644 --- a/docs/typography-parity.md +++ b/docs/typography-parity.md @@ -35,7 +35,7 @@ Fidelity: **unmeasured** unless stated. | Paragraph Composer | Adobe's multi-line composer | Knuth–Plass total fit, fitness classes, hyphen penalties | ~ | same family of algorithm, Adobe's weights unknown; breaks will differ on some paragraphs | | Single-line Composer | greedy | greedy with the same ranges | ✓ | | | World-Ready composers | Paragraph / Single-line World-Ready | RTL, Arabic and bidi in the main composer | ~ | Indic scripts (Devanagari etc.) shape through harfrust but are untested | -| Justification | word/letter spacing, glyph scaling min/desired/max, single-word, last line | all of these | ✓ | a justified line with a tab justifies after the tab (#284); set per paragraph in Type › Justification… and the Paragraph panel menu (#531) | +| Justification | word/letter spacing, glyph scaling min/desired/max, single-word, last line | all of these | ✓ | a justified line with a tab justifies after the tab (#284); set per paragraph in Type › Justification… and the Paragraph panel menu (#531); Auto Leading (0% to 500%) and Single Word Justification are set there and in Paragraph Style Options › Justification | | Hyphenation | per-language dictionaries (~40), zone, limits, capitalized, last word, across columns | Liang patterns: English (trained from the public-domain Moby list), Spanish (Bezos), Portuguese (hyph-pt), Norwegian (hyph-no), Danish (hyph-da), Greek (hyph-el-monoton), German 2006 (hyph-de-1996), French (hyph-fr), Italian (hyph-it) and Dutch (Tutelaers); zone, limits, exceptions in the user dictionary; Hyphenate Across Column off keeps automatic hyphens off the last line of a column or frame; discretionary U+00AD breaks with both composers regardless of automatic hyphenation and replaces pattern points within its word (#1955) | ~ | other languages don't hyphenate (#87 reported "doesn't work") | | Spelling | per-language dictionaries | English (Moby) + document/user dictionary | ~ | | | Kerning | Metrics, Optical, manual, none | Metrics, Optical (outline-based: pairs pulled towards the font's stem gap, `crates/compose/src/optical.rs`), manual, none | ~ | Optical is an approximation of Adobe's algorithm (#181), not a match: imported display text can still break differently | From 3473b8d96ef9d9c0c01398919f3e0b9a0404bab2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:46:20 -0800 Subject: [PATCH 0945/1349] Text: Text Frame Options refuse an ids that is not a list of object ids A call with an `ids` or `id` that is not an object id used to fall back to the selected frame or the caret's frame. It now fails and leaves the document unchanged. The Properties panel's Text Frame section shows the frame Text Frame Options change: with the Type tool, the frame the caret is drawn in. --- crates/engine/src/cmd/object.rs | 32 +++++++++++++++++-- crates/ui-egui/src/panels/properties/tests.rs | 20 ++++++++++++ crates/ui-egui/src/panels/properties/text.rs | 16 +++++++--- docs/mcp.md | 2 +- 4 files changed, 62 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 50628d2bc..e8b3267bc 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -2592,9 +2592,16 @@ fn has_selection_or_text(s: &Session) -> std::result::Result<(), String> { fn text_frame_options(s: &mut Session, p: &Value) -> Result { const ID: &str = "object.textFrameOptions"; let st = s.doc()?; - // A call that names its objects acts on those; an empty `ids` names nothing. - let named = p.get("ids").is_some() || p.get("id").is_some(); - let ids = if named { targets(s, p)? } else { text_frame_options_frames(s) }; + // A call that names its objects acts on those; an empty `ids` names nothing. `ids`, when + // given, wins over `id`, and a value that is not an object id is an error. + let ids = match (p.get("ids"), p.get("id")) { + (Some(v), _) => v + .as_array() + .and_then(|a| a.iter().map(|x| x.as_u64().map(ItemId)).collect::>>()) + .ok_or_else(|| bad(ID, format!("ids must be a list of object ids, not {v}")))?, + (None, Some(v)) => vec![v.as_u64().map(ItemId).ok_or_else(|| bad(ID, format!("id must be an object id, not {v}")))?], + (None, None) => text_frame_options_frames(s), + }; // With a text caret the command runs before named objects are checked. if let Some(gone) = ids.iter().find(|i| st.doc.item(**i).is_none()) { return Err(bad(ID, format!("no object with id {}", gone.0))); @@ -5075,6 +5082,25 @@ mod type_tool_frame_options_tests { assert_eq!((options(&s, a).columns, options(&s, b).columns), (1, 1)); } + /// An `ids` that is not a list of object ids is refused, not read as the selected frame or the + /// caret's frame. + #[test] + fn malformed_ids_are_an_error() { + let mut s = Session::new(); + let (a, b, sid) = two_frame_thread(&mut s); + s.execute("selection.set", &json!({"ids": [b.0]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + for p in [json!({"ids": "bad", "columns": 2}), json!({"ids": [b.0, "x"], "columns": 2}), json!({"ids": null, "columns": 2})] { + let e = s.execute("object.textFrameOptions", &p).unwrap_err().to_string(); + assert!(e.contains("ids must be a list of object ids"), "{p}: {e}"); + } + s.execute("text.select", &json!({"story": sid.0, "anchor": 2})).unwrap(); + let e = s.execute("object.textFrameOptions", &json!({"ids": "bad", "columns": 2})).unwrap_err().to_string(); + assert!(e.contains("ids must be a list of object ids"), "with a caret: {e}"); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "nothing changed"); + assert_eq!((options(&s, a).columns, options(&s, b).columns), (1, 1)); + } + /// Options the frame already has change nothing and add no undo step. #[test] fn unchanged_options_add_no_undo_step() { diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 1e7c40c8a..59e0cbd1e 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1277,3 +1277,23 @@ fn transform_flips_and_rotates_from_properties() { // The angle and scale fields are there. assert!(h.query_by(|n| n.role() == egui::accesskit::Role::TextInput && n.value().as_deref() == Some("90°")).is_some()); } + +/// With the Type tool, the Text Frame section shows the frame Text Frame Options change: the frame +/// the caret is drawn in, not the caret's stored frame. +#[test] +fn text_frame_section_shows_the_frame_that_shows_the_caret() { + use designcraft_doc::{ItemId, Selection, StoryId, TextSel}; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let text = (0..40).map(|i| format!("Line {i} of the threaded story.")).collect::>().join(" "); + let a = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": text})).unwrap(); + let b = app.run("frame.create", json!({"rect": [36, 200, 300, 700], "content": "text", "text": "", "caret": false})).unwrap(); + let (a, b, sid) = (a["id"].as_u64().unwrap(), b["id"].as_u64().unwrap(), a["story"].as_u64().unwrap()); + app.run("text.thread", json!({"from": a, "to": b})).unwrap(); + app.run("object.textFrameOptions", json!({"ids": [b], "columns": 3})).unwrap(); + // The end of the story is drawn in the second frame; the caret's stored frame is the first. + app.session.doc_mut().unwrap().selection = + Selection::text(TextSel { story: StoryId(sid), anchor: text.len(), focus: text.len(), frame: Some(ItemId(a)), cell: None }); + let shown = super::text::text_frame_target(&app).map(|(id, o)| (id, o.columns)); + assert_eq!(shown, Some((ItemId(b), 3))); +} diff --git a/crates/ui-egui/src/panels/properties/text.rs b/crates/ui-egui/src/panels/properties/text.rs index 36c23c195..f444d6ba2 100644 --- a/crates/ui-egui/src/panels/properties/text.rs +++ b/crates/ui-egui/src/panels/properties/text.rs @@ -516,13 +516,21 @@ pub(super) fn quick_actions_text(app: &mut DesignApp, ui: &mut Ui) { } } -/// Text Frame section: columns, gutter, [Options]. +/// The text frame the Text Frame section shows, as Text Frame Options shows it: the first selected +/// frame, the frame that shows the caret, or the first frame holding selected text. Its id and its +/// options. +pub(super) fn text_frame_target(app: &DesignApp) -> Option<(designcraft_doc::ItemId, designcraft_doc::TextFrameOptions)> { + let st = app.session.active()?; + let fid = designcraft_engine::cmd::text_frame_options_frames(&app.session).first().copied()?; + Some((fid, st.doc.item(fid)?.text_frame()?.options.clone())) +} + +/// Text Frame section: columns, gutter, [Options]. With the Type tool it changes the frame that +/// shows the caret, or every frame that holds part of the selected text. pub(super) fn text_frame_section(app: &mut DesignApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let u = units(app); - let Some(st) = app.session.active() else { return }; - let fid = st.selection.items.first().copied().or_else(|| st.selection.text.and_then(|t| t.frame)); - let Some(opts) = fid.and_then(|f| st.doc.item(f)).and_then(|i| i.text_frame()).map(|t| t.options.clone()) else { return }; + let Some((_, opts)) = text_frame_target(app) else { return }; let b = block(ui, FIELD_H); icons::paint(ui.painter(), sub(b, 0.0, 1.0, 19.0, 19.0), "text-columns", t.icon); if let Some(v) = place(ui, sub(b, 22.0, 0.0, 54.0, FIELD_H), |ui| { diff --git a/docs/mcp.md b/docs/mcp.md index d9a15256a..255f282a4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -229,7 +229,7 @@ With a text selection, this formats the selected paragraphs; with selected text the selected frames or on the `ids` the call passes. With the Type tool and no frame selected, it acts on the frame that shows the insertion point, or on every frame that holds part of the selected text, not on the other frames of the thread. With the insertion point in a footnote or a table cell, it acts on the frame that shows the footnote or the -cell. An empty `ids` is an error. Options a frame already has leave the document unchanged and add no undo step. +cell. An empty `ids`, or an `ids` that is not a list of object ids, is an error. Options a frame already has leave the document unchanged and add no undo step. ```text execute {"command": "object.textFrameOptions", "params": {"verticalJustification": "center", "inset": 6}} From 43088a87c0214ecb475c8b31fe1c30c2502563cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:51:54 -0800 Subject: [PATCH 0946/1349] Recovery: a cancel cannot race the rename, and results go to their session A save, revert or close that cancels a background write now waits for a rename already under way, and a later rename sees the cancel, so a stale snapshot or its metadata cannot be published after the cleanup. The writer's results go back to the session that queued them: another session's poll no longer removes their snapshots, and results for a session that has been dropped are not kept. --- crates/engine/src/lib.rs | 4 ++ crates/engine/src/recovery.rs | 97 ++++++++++++++++++++++++----- crates/engine/src/recovery/tests.rs | 59 ++++++++++++++++++ 3 files changed, 145 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3d43a80e0..bb67875b4 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -412,6 +412,9 @@ pub struct Session { pub clipboard_origin: f64, /// Crash-recovery folder (the app sets it; saving or closing a document removes its entry). pub recovery_dir: Option, + /// This session's number for the background recovery writer, which returns each result to + /// the session that queued it. + pub(crate) recovery_owner: recovery::Owner, /// Copied text with its formatting (a frameless story slice), its plain text, and what pasting /// it needs from its document: a copy holding only the stories its anchored text frames show /// (and theirs) and the graphics the text and those stories place. @@ -477,6 +480,7 @@ impl Session { clipboard: None, clipboard_origin: 0.0, recovery_dir: None, + recovery_owner: recovery::Owner::new(), text_clipboard: None, link_checks: Default::default(), ui_requests: vec![], diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index 420d1795f..dc7d63ed7 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -649,6 +649,32 @@ struct Snapshot { own: bool, /// The folder's canonical key, for recording that a shared entry is this run's now. key: PathBuf, + /// The session that queued a background write ([`Session::recovery_owner`]), which takes its + /// result. + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + owner: u64, +} + +/// A number for each session, so background results go back to the session that queued them. +/// Dropping it retires the number: results still queued for it are then dropped. +pub(crate) struct Owner(pub(crate) u64); + +/// The numbers of the sessions that exist. +static LIVE_OWNERS: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeSet::new()); + +impl Owner { + pub(crate) fn new() -> Self { + static NEXT_OWNER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + let id = NEXT_OWNER.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + LIVE_OWNERS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(id); + Owner(id) + } +} + +impl Drop for Owner { + fn drop(&mut self) { + LIVE_OWNERS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).remove(&self.0); + } } impl Snapshot { @@ -662,6 +688,7 @@ impl Snapshot { // An entry this run did not write is never replaced, even one made since it checked. own: access.owns(d.uid), key: access.key.clone(), + owner: 0, } } } @@ -700,7 +727,16 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert((entry.key.clone(), entry.uid)); } let metadata = json!({"path": entry.path, "title": entry.title, "saved": designcraft_doc::vars::now()}); - Written { published: true, error: publish_recovery_file(&meta, metadata.to_string().as_bytes(), entry.own).err() } + // A cancel after the primary landed removes it; the metadata must not be left without it. + let bytes = metadata.to_string(); + let error = publish_recovery_written( + &meta, + entry.own, + |out| out.write_all(bytes.as_bytes()).map_err(|e| EngineError::Other(format!("{}: {e}", meta.display()))), + &cancelled, + ) + .err(); + Written { published: true, error } } /// Write recovery entries for dirty documents on a background thread and drop clean checkpoints @@ -729,7 +765,8 @@ pub(crate) fn start_tracked(s: &mut Session, dir: &Path) -> Result { continue; } let Some(document) = s.docs.get(index) else { continue }; - let entry = Snapshot::of(&access, dir, document); + let mut entry = Snapshot::of(&access, dir, document); + entry.owner = s.recovery_owner.0; // A write still running for this document already holds a snapshot of it; the next // timer tick catches up with the edits made since. match worker::submit(entry) { @@ -787,8 +824,20 @@ pub(crate) fn finished(s: &mut Session) -> Finished { let Some(w) = worker::started() else { return out }; // Before draining: the worker sends a result before it clears the document as running, so a writer idle now has every result in the channel already. let busy = w.busy(); - let done = w.done.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - while let Ok(d) = done.try_recv() { + // Results go to the session that queued them: another session has none of those documents, + // and would remove their snapshots as if they had been closed. + let mine: Vec = { + let done = w.done.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut others = w.undelivered.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut all = std::mem::take(&mut *others); + all.extend(done.try_iter()); + let (mine, rest): (Vec<_>, Vec<_>) = all.into_iter().partition(|d| d.owner == s.recovery_owner.0); + // A session that is gone takes nothing: its results are dropped rather than kept for ever. + let live = LIVE_OWNERS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + *others = rest.into_iter().filter(|d| live.contains(&d.owner)).collect(); + mine + }; + for d in mine { // A primary that landed belongs to this run even if its optional metadata failed: record // it, so Save and Close remove the snapshot instead of leaving it in the folder for ever. if d.published && record_checkpoint(s, d.dir, d.uid) { @@ -826,11 +875,15 @@ mod worker { /// The primary document reached the folder (its optional metadata may have failed): the /// checkpoint must still be recorded, or Save and Close could not remove it. pub(super) published: bool, + /// The session that queued the write. + pub(super) owner: u64, } pub(super) struct Writer { jobs: Sender, pub(super) done: Mutex>, + /// Results taken from `done` by a session that did not queue them, kept for their own. + pub(super) undelivered: Mutex>, /// Documents queued or being written: a second write of one still holds nothing newer. running: Mutex>, /// A document saved, reverted or closed while its write was queued or running: the @@ -872,6 +925,9 @@ mod worker { /// as small as the work in flight. fn cancel(&self, dir: &Path, uid: u64) { let key = (dir.to_path_buf(), uid); + // A rename under way finishes first, so the caller's cleanup comes after it; a later + // one sees the mark. + let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); if !self.running.lock().is_ok_and(|running| running.contains(&key)) { return; } @@ -894,11 +950,11 @@ mod worker { let spawned = std::thread::Builder::new().name("designcraft-recovery".into()).spawn(move || { while let Ok(job) = job_rx.recv() { let (published, error) = guarded_write(&job); - let (dir, uid) = (job.dir, job.uid); + let (dir, uid, owner) = (job.dir, job.uid, job.owner); // The result before the document reads as idle: a writer that is not busy // has already delivered it, so the interface never stops polling with an // answer still on its way. - let sent = done_tx.send(Done { dir: dir.clone(), uid, error, published }).is_ok(); + let sent = done_tx.send(Done { dir: dir.clone(), uid, error, published, owner }).is_ok(); if let Some(w) = WRITER.get().and_then(Option::as_ref) { w.finish(&dir, uid); } @@ -910,6 +966,7 @@ mod worker { spawned.ok().map(|_| Writer { jobs, done: Mutex::new(done_rx), + undelivered: Mutex::new(Vec::new()), running: Mutex::new(BTreeSet::new()), cancelled: Mutex::new(BTreeSet::new()), idle: Condvar::new(), @@ -1124,6 +1181,11 @@ fn publish_recovery_file(path: &Path, bytes: &[u8], replace: bool) -> Result<()> .map(|_| ()) } +/// Serializes the last check for a cancelled write with the rename that publishes it, and with +/// [`worker::cancel`]. +#[cfg(not(target_arch = "wasm32"))] +static PUBLISH: std::sync::Mutex<()> = std::sync::Mutex::new(()); + /// [`publish_recovery_file`], with `write` filling the temporary file: a large document is written /// straight to disk instead of being built in memory first. Returns whether it was published; /// `cancelled` is asked after the bytes are written and before the rename, so a document saved or @@ -1155,16 +1217,21 @@ fn publish_recovery_written( out.flush().map_err(|e| EngineError::Other(format!("{}: {e}", path.display())))?; } tmp.as_file_mut().sync_all().map_err(|e| EngineError::Other(format!("{}: {e}", path.display())))?; - // Last moment: the document was saved, reverted or closed while the bytes were written. The - // temporary file is dropped, so nothing of the stale snapshot stays. - if cancelled() { - return Ok(false); + { + // Held from the check to the rename: a cancel waits for a rename already under way (the + // cleanup after it then removes the file), and a rename after a cancel sees it. + let _publishing = PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + // Last moment: the document was saved, reverted or closed while the bytes were written. + // The temporary file is dropped, so nothing of the stale snapshot stays. + if cancelled() { + return Ok(false); + } + // Validate the non-followed leaf again immediately before renaming the randomized + // temporary file to its fixed sibling destination. + validate_recovery_dir(dir)?; + let published = if replace { tmp.persist(path) } else { tmp.persist_noclobber(path) }; + published.map_err(|e| EngineError::Other(format!("{}: {}", path.display(), e.error)))?; } - // Validate the non-followed leaf again immediately before renaming the randomized temporary - // file to its fixed sibling destination. - validate_recovery_dir(dir)?; - let published = if replace { tmp.persist(path) } else { tmp.persist_noclobber(path) }; - published.map_err(|e| EngineError::Other(format!("{}: {}", path.display(), e.error)))?; sync_recovery_dir(dir)?; Ok(true) } diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index 3b7c2303d..79644ca3d 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -170,6 +170,65 @@ fn a_background_save_returns_while_its_write_is_held() { discard(dir.path(), uid); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_document_saved_while_its_write_is_held_leaves_no_snapshot() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut s = dirty_session(); + s.recovery_dir = Some(dir.path().to_path_buf()); + let uid = s.docs[0].uid; + let held = testing::hold_next_write(dir.path()); + s.execute("file.recovery.save", &json!({"background": true})).unwrap(); + held.wait_until_held(); + let saved = dir.path().join("saved.designcraft"); + s.execute("file.saveAs", &json!({"path": saved.to_string_lossy()})).unwrap(); + held.release(); + assert_eq!(finished_writes(&mut s), 0); + assert!(!files(dir.path(), uid).0.exists(), "the stale snapshot was not published"); + assert!(!files(dir.path(), uid).1.exists(), "nor its metadata"); + assert!(list(dir.path()).is_empty()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_background_result_goes_to_the_session_that_queued_it() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut queued_by = dirty_session(); + queued_by.recovery_dir = Some(dir.path().to_path_buf()); + let uid = queued_by.docs[0].uid; + let mut other = dirty_session(); + queued_by.execute("file.recovery.save", &json!({"background": true})).unwrap(); + testing::wait_until_idle(); + // Another session has none of these documents: it must neither take the result nor remove + // the snapshot as if its document had been closed. + let v = other.execute("file.recovery.progress", &json!({})).unwrap(); + assert_eq!(v["written"], 0, "{v}"); + assert!(files(dir.path(), uid).0.exists(), "the snapshot is still there"); + assert_eq!(finished_writes(&mut queued_by), 1); + assert!(queued_by.docs[0].recovery_entries.iter().any(|(d, u)| *u == uid && same_directory(d, dir.path())), "the checkpoint is recorded"); + discard(dir.path(), uid); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn results_for_a_session_that_is_gone_are_not_kept() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut gone = dirty_session(); + gone.recovery_dir = Some(dir.path().to_path_buf()); + let owner = gone.recovery_owner.0; + gone.execute("file.recovery.save", &json!({"background": true})).unwrap(); + testing::wait_until_idle(); + drop(gone); + let mut other = dirty_session(); + other.execute("file.recovery.progress", &json!({})).unwrap(); + let writer = worker::started().unwrap(); + let kept = writer.undelivered.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert!(!kept.iter().any(|d| d.owner == owner), "a result nobody can take was kept"); +} + #[test] fn a_background_save_rejects_a_background_that_is_not_true_or_false() { let dir = tempfile::tempdir().unwrap(); From 29f259bf077d42798cc5072fba5cc65bc59a742b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:54:23 -0800 Subject: [PATCH 0947/1349] Render: test that a turned view and snapshot renders handle kept shadows A view turned 90 degrees with the frame turned back draws the shadow again and matches a fresh render. Renders served from the CMYK viewport snapshot drop kept images unused for 256 renders. --- crates/render/src/fx.rs | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index 5248bf9ba..c6cbd532e 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -984,5 +984,41 @@ mod tests { r.render(&d, &cache, &placed, (500, 450), Affine::IDENTITY, &opts); } assert_eq!(r.kept.drawn, 3); + // Renders served from the CMYK viewport snapshot count towards the expiry too. + assert!(!r.kept.entries.is_empty()); + for _ in 0..=KEEP_RENDERS { + r.render(&d, &cache, &placed, (500, 450), Affine::IDENTITY, &opts); + } + assert_eq!(r.kept.drawn, 3, "the snapshot served every render"); + assert!(r.kept.entries.is_empty(), "images unused for {KEEP_RENDERS} renders are dropped"); + } + + /// A view turned 90° with the frame turned back by 90° leaves the frame where it was on the + /// device, but turns the shadow's offset: the shadow is drawn again. + #[test] + fn a_turned_view_draws_the_shadow_again() { + use designcraft_doc::SpreadRef; + let (mut d, id) = shadowed_image(); + let cache = crate::Cache::new(); + let placed = [crate::Placed { spread: SpreadRef::Doc(0), xf: Affine::IDENTITY }]; + let opts = crate::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let mut kept = Renderer::new(); + kept.threads = 2; + let view = Affine::scale(1.5); + kept.render(&d, &cache, &placed, (500, 450), view, &opts); + assert_eq!(kept.kept.drawn, 1); + // Exact quarter turns, so that the frame's spread → device transform stays the same. + let (turn, back) = (Affine::new([0.0, 1.0, -1.0, 0.0, 0.0, 0.0]), Affine::new([0.0, -1.0, 1.0, 0.0, 0.0, 0.0])); + let it = d.item_mut(id).unwrap(); + it.xf = back * it.xf; + assert_eq!((view * turn * it.xf).as_coeffs(), (view * Affine::translate((100.0, 100.0))).as_coeffs()); + let turned = view * turn; + let image = kept.render(&d, &cache, &placed, (500, 450), turned, &opts); + let mut r = Renderer::new(); + r.threads = 2; + let fresh = r.render(&d, &crate::Cache::new(), &placed, (500, 450), turned, &opts); + let worst = image.pixels.iter().zip(&fresh.pixels).map(|(x, y)| x.abs_diff(*y)).max().unwrap_or(0); + assert!(worst <= 1, "off by {worst}"); + assert_eq!(kept.kept.drawn, 2); } } From 5d9fbb4d4eb892a51f3563574c11c20530badcfd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:02:54 -0800 Subject: [PATCH 0948/1349] Docs: vertical justification moves grid-aligned lines by whole grid steps --- docs/typography-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/typography-parity.md b/docs/typography-parity.md index 8e17cd2a9..7987b9632 100644 --- a/docs/typography-parity.md +++ b/docs/typography-parity.md @@ -47,7 +47,7 @@ Fidelity: **unmeasured** unless stated. | First baseline | ascent, cap height, x-height, leading, fixed, min | ✓ | ✓ | | | Frame fit / overset | baseline of the last line must fit | descenders must fit | ~ | **differs** (#180): frames go overset where InDesign fits | | Baseline grid | document grid relative to the top of the page or each page's top margin; frame grids relative to the top of the page, top margin, top of frame or top inset | ✓ | ✓ | | -| Vertical justification | top, centre, bottom, justify, paragraph spacing limit | ✓ | ✓ | | +| Vertical justification | top, centre, bottom, justify, paragraph spacing limit | ✓ | ✓ | with Center and Bottom, lines aligned to the baseline grid move by whole grid steps; with Justify only the first and last lines stay on the grid | | Text in shaped frames | lines follow oval, polygon and freeform frame outlines, one inset from the outline | ✓ | ~ | concave shapes set one slot per line (the widest); vertical justification and paragraph shading use the frame's rectangle (#646) | | Columns, span / split columns | ✓ | ✓ | ✓ | split columns within a column (#295); text after a span flows below it (#276) | | Column rules | ✓ | ✓ (screen, PDF, IDML) | ~ | no stroke types or overprint (#274) | From 5b89a13c2e979bb8f66211a62d503779910ebb61 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:04:50 -0800 Subject: [PATCH 0949/1349] Text wrap: anchored images keep their Alpha Channel outline Outlines are traced for images anchored in text as well as for those on the spreads, so an anchored image's Alpha Channel contour follows its visible pixels instead of falling back to the frame. Tracing reads the pixels once: a coarser grid, used when the outline has too many edges, is made from the finer grid's mask when each side halves, and the cell of each pixel is counted along the row instead of divided. --- crates/engine/src/cmd/alpha_wrap.rs | 145 +++++++++++++++++++++++----- 1 file changed, 123 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs index 8a94ae818..cd6a1d00b 100644 --- a/crates/engine/src/cmd/alpha_wrap.rs +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -5,7 +5,7 @@ //! current transform, so it follows the image when it is moved, scaled or refitted. use std::sync::Arc; -use designcraft_doc::{AlphaOutline, AssetId, ContourType, Document, WrapMode}; +use designcraft_doc::{AlphaOutline, AssetId, ContourType, Document, Item, WrapMode}; use designcraft_geom::{BezPath, PathData, Point}; /// Images larger than this many pixels aren't traced (their contour follows the frame). @@ -19,18 +19,26 @@ const MAX_EDGES: usize = 1 << 16; /// nothing changed: tracing happens only for an image and threshold not seen before. pub(crate) fn sync(doc: &mut Document) { let mut wanted: Vec<(AssetId, u8)> = Vec::new(); + // Every frame, in groups and Paste Into containers too, with the wrap set on the frame or on + // its placed graphic (Direct Selection sets the graphic's). + let mut want = |it: &Item| { + let Some(g) = it.graphic() else { return }; + for w in [&it.wrap, &g.wrap] { + if w.mode == WrapMode::Contour && w.contour == ContourType::AlphaChannel && !wanted.contains(&(g.asset, w.alpha_threshold)) { + wanted.push((g.asset, w.alpha_threshold)); + } + } + }; for sp in doc.spreads.iter().chain(doc.parents.iter()) { - // Every frame, in groups and Paste Into containers too, with the wrap set on the frame or - // on its placed graphic (Direct Selection sets the graphic's). for top in &sp.items { - top.walk(&mut |it| { - let Some(g) = it.graphic() else { return }; - for w in [&it.wrap, &g.wrap] { - if w.mode == WrapMode::Contour && w.contour == ContourType::AlphaChannel && !wanted.contains(&(g.asset, w.alpha_threshold)) { - wanted.push((g.asset, w.alpha_threshold)); - } - } - }); + top.walk(&mut want); + } + } + // Objects anchored in text wrap the lines after their anchor; anchored_items lists their + // children too. + if doc.has_anchored_items() { + for (_, it) in doc.anchored_items() { + want(it); } } if wanted.is_empty() && doc.alpha_outlines.is_empty() { @@ -69,12 +77,20 @@ pub(crate) fn trace(data: &Arc>, asset: AssetId, threshold: u8) -> Optio return None; } let mut grid = MAX_GRID; + // The previous grid's mask: a grid half as fine is made from it without reading the pixels again. + let mut finer: Option<(Vec, u32, u32)> = None; while grid >= 16 { let (cols, rows) = (w.min(grid), h.min(grid)); - let (mask, transparent) = occupancy(img.as_raw(), w, h, cols, rows, threshold); - if !transparent { - return None; - } + let mask = match finer.as_ref().and_then(|(m, fc, fr)| coarsen(m, *fc, *fr, cols, rows)) { + Some(m) => m, + None => { + let (mask, transparent) = occupancy(img.as_raw(), w, h, cols, rows, threshold); + if !transparent { + return None; + } + mask + } + }; if let Some((outer, holes)) = rings(&mask, cols as usize, rows as usize) { let (sx, sy) = (f64::from(w) / f64::from(cols), f64::from(h) / f64::from(rows)); let path = |rings: &[Vec<(i32, i32)>]| { @@ -93,24 +109,55 @@ pub(crate) fn trace(data: &Arc>, asset: AssetId, threshold: u8) -> Optio let source = Arc::downgrade(data); return Some(AlphaOutline { asset, threshold, width: w, height: h, outer: path(&outer), holes: path(&holes), source }); } + finer = Some((mask, cols, rows)); grid /= 2; } None } +/// The `cols` × `rows` mask made from a `fc` × `fr` one, when each side has the same number of +/// cells or twice as many (a pixel's coarse cell is then its fine cell, or half of it). None +/// otherwise: the pixels are read again. +fn coarsen(mask: &[bool], fc: u32, fr: u32, cols: u32, rows: u32) -> Option> { + let step = |fine: u32, coarse: u32| match fine { + f if f == coarse => Some(1), + f if u64::from(f) == 2 * u64::from(coarse) => Some(2), + _ => None, + }; + let (sx, sy) = (step(fc, cols)?, step(fr, rows)?); + let (fc, cols) = (fc as usize, cols as usize); + let mut out = vec![false; cols * rows as usize]; + for (i, _) in mask.iter().enumerate().filter(|(_, v)| **v) { + let (x, y) = (i % fc, i / fc); + if let Some(c) = out.get_mut(y / sy * cols + x / sx) { + *c = true; + } + } + Some(out) +} + /// Which cells of a `cols` × `rows` grid hold a pixel of the `w` × `h` RGBA image `rgba` more /// opaque than `threshold` (a cell is visible when any of its pixels is), and whether the image /// has any transparency. fn occupancy(rgba: &[u8], w: u32, h: u32, cols: u32, rows: u32, threshold: u8) -> (Vec, bool) { let mut mask = vec![false; (cols as usize) * (rows as usize)]; let mut transparent = false; - for (i, px) in rgba.as_chunks::<4>().0.iter().enumerate() { - let alpha = px[3]; - transparent |= alpha < 255; - if alpha > threshold { - let (x, y) = ((i as u64) % u64::from(w), (i as u64) / u64::from(w)); - let (gx, gy) = (x * u64::from(cols) / u64::from(w), y * u64::from(rows) / u64::from(h)); - if let Some(c) = mask.get_mut((gy * u64::from(cols) + gx) as usize) { + // A pixel's cell is (x * cols / w, y * rows / h). Along a row the column is counted up as x + // passes each cell's edge (cols <= w, so at most one edge per pixel) instead of divided out. + for (y, row) in rgba.chunks_exact(w as usize * 4).take(h as usize).enumerate() { + let base = (y as u64 * u64::from(rows) / u64::from(h)) as usize * cols as usize; + let (mut gx, mut acc, mut edge) = (0usize, 0u64, u64::from(w)); + for px in row.as_chunks::<4>().0 { + if acc >= edge { + gx += 1; + edge += u64::from(w); + } + acc += u64::from(cols); + let alpha = px[3]; + transparent |= alpha < 255; + if alpha > threshold + && let Some(c) = mask.get_mut(base + gx) + { *c = true; } } @@ -218,6 +265,39 @@ mod tests { assert!(trace(&Arc::new(png(|_, _| true)), AssetId(1), 25).is_none()); } + /// The cell masks match a pixel-by-pixel count (cell = x * cols / w, y * rows / h), and a + /// mask half as fine made from the finer one matches the mask read from the pixels. + #[test] + fn cell_masks_match_the_pixels_and_coarser_masks_match_the_finer_ones() { + let (w, h) = (600u32, 300u32); + // An irregular pattern: visible where a small hash says so. + let on = |x: u32, y: u32| (x.wrapping_mul(2_654_435_761) ^ y.wrapping_mul(40_503)).rotate_left(7).is_multiple_of(7); + let mut rgba = vec![0u8; (w * h * 4) as usize]; + for y in 0..h { + for x in 0..w { + rgba[((y * w + x) * 4 + 3) as usize] = if on(x, y) { 255 } else { 0 }; + } + } + for (cols, rows) in [(256, 256), (128, 128), (100, 37), (600, 300)] { + let mut expect = vec![false; (cols * rows) as usize]; + for y in 0..h { + for x in 0..w { + if on(x, y) { + expect[((y * rows / h) * cols + x * cols / w) as usize] = true; + } + } + } + assert_eq!(occupancy(&rgba, w, h, cols, rows, 25), (expect, true), "{cols} x {rows}"); + } + let (fine, _) = occupancy(&rgba, w, h, 256, 256, 25); + assert_eq!(coarsen(&fine, 256, 256, 128, 128), Some(occupancy(&rgba, w, h, 128, 128, 25).0)); + // Same count on one side, twice on the other. + let (fine, _) = occupancy(&rgba, w, h, 128, 256, 25); + assert_eq!(coarsen(&fine, 128, 256, 128, 128), Some(occupancy(&rgba, w, h, 128, 128, 25).0)); + // Any other ratio is read from the pixels. + assert_eq!(coarsen(&fine, 128, 256, 100, 128), None); + } + #[test] fn an_alpha_channel_contour_is_traced_when_set_and_kept_out_of_the_saved_file() { let mut s = Session::new(); @@ -314,6 +394,27 @@ mod tests { assert_eq!((b.x0, b.x1), (24.0, 40.0), "the new image's outline"); } + /// An image anchored in text keeps its outline: anchored objects wrap the lines after their + /// anchor, and they are kept in the story, not on the spread. + #[test] + fn an_anchored_image_keeps_its_outline() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let data = png(|x, _| (16..48).contains(&x)); + let image = s + .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": 100, "y": 100, "width": 128})) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("object.textWrap", &json!({"ids": [image], "mode": "contour", "contour": "alphaChannel"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.alpha_outlines.len(), 1); + let t = s.execute("frame.create", &json!({"rect": [36, 300, 400, 500], "content": "text", "text": "Before after."})).unwrap(); + s.execute("anchored.insert", &json!({"ids": [image], "story": t["story"], "pos": 7})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.anchored_item(designcraft_doc::ItemId(image)).is_some(), "the image is in the text"); + assert_eq!(d.alpha_outlines.len(), 1, "the anchored image keeps its outline"); + } + /// An image placed 128 pt wide at (100, 100) (2 pt per pixel), its wrap a contour with no /// offset, and a caption frame at `caption` with 8 pt "Hi". fn page(data: &[u8], caption: [f64; 4]) -> (Session, Value, u64) { From c69db898623c0efebf920a30c33c9f4e98707cb6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:06:28 -0800 Subject: [PATCH 0950/1349] Justification: Auto Leading stores the shown percent, and the current choice is no edit The Auto Leading field shows whole percents, and it now stores the whole percent it shows, so a typed 500.4% (shown as 500%) is accepted as 500% instead of being refused. Picking the Single Word Justification the paragraphs already have is no longer an edit, so OK adds no undo step for it. --- crates/ui-egui/src/dialogs.rs | 16 ++++++++++++++-- crates/ui-egui/src/dialogs/tests.rs | 24 ++++++++++++++++++++---- 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6664fc349..1ad599bbd 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -7716,6 +7716,12 @@ const JUSTIFY_ROWS: [(&str, &str, (f64, f64)); 3] = [ /// The allowed Auto Leading, in percent of the type size. const AUTO_LEADING_RANGE: (f64, f64) = (0.0, 500.0); +/// The Auto Leading stored for a percent typed into its field: the whole percent the field shows. +fn auto_leading_typed(pct: f64) -> f64 { + // Adding 0.0 turns a rounded -0 into 0. + (pct.round() + 0.0) / 100.0 +} + /// The Single Word Justification choices: (attribute value, label). const SINGLE_WORD_CHOICES: [(&str, &str); 4] = [("left", "Align Left"), ("center", "Align Center"), ("right", "Align Right"), ("fullyJustified", "Full Justify")]; @@ -7941,7 +7947,7 @@ fn justification(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, prefix: &str, cu crate::rtl::label(ui, crate::i18n::tr(lang, "Auto Leading:")); let auto = cur(d, "autoLeading").as_f64().map(|x| x * 100.0); if let Some(n) = ui.scope(|ui| crate::widgets::number(ui, &format!("ps{prefix}autoLeading"), auto, "%", 60.0, 0)).inner { - d.fields.insert(format!("{prefix}autoLeading"), json!(n / 100.0)); + d.fields.insert(format!("{prefix}autoLeading"), json!(auto_leading_typed(n))); } ui.end_row(); let single_label = crate::rtl::label(ui, crate::i18n::tr(lang, "Single Word Justification:")); @@ -7954,7 +7960,13 @@ fn justification(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, prefix: &str, cu .show_ui(ui, |ui| { for (v, label) in SINGLE_WORD_CHOICES { if ui.selectable_label(single.as_str() == Some(v), crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() { - d.fields.insert(format!("{prefix}singleWordJustify"), json!(v)); + // The paragraphs' own choice is no edit, so OK adds no undo step for it. + let key = format!("{prefix}singleWordJustify"); + if current["singleWordJustify"].as_str() == Some(v) { + d.fields.remove(&key); + } else { + d.fields.insert(key, json!(v)); + } } } }) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 1343b30d7..2e3cd162a 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1156,8 +1156,15 @@ fn justification_dialog_sets_auto_leading_and_single_word_justification() { h.run_steps(3); assert!(h.query_by_label("Auto Leading:").is_some()); assert!(h.query_by_label("Single Word Justification:").is_some()); - // The dropdown shows the paragraph's Full Justify; pick Align Center. - h.get_by(|n| n.role() == egui::accesskit::Role::ComboBox && n.value().as_deref() == Some("Full Justify")).click(); + use egui::accesskit::Role; + // The dropdown shows the paragraph's Full Justify. Picking Full Justify again is no edit. + h.get_by(|n| n.role() == Role::ComboBox && n.value().as_deref() == Some("Full Justify")).click(); + h.run_steps(3); + h.get_by(|n| n.role() != Role::ComboBox && n.label().as_deref() == Some("Full Justify")).click(); + h.run_steps(3); + assert!(!h.state().ui.dialog.as_ref().unwrap().fields.contains_key("singleWordJustify"), "the paragraph's own choice is no edit"); + // Pick Align Center. + h.get_by(|n| n.role() == Role::ComboBox && n.value().as_deref() == Some("Full Justify")).click(); h.run_steps(3); h.get_by_label("Align Center").click(); h.run_steps(3); @@ -1170,8 +1177,8 @@ fn justification_dialog_sets_auto_leading_and_single_word_justification() { let d = app.ui.dialog.clone().unwrap(); let before = undo_steps(&app); let bad = [ - ("autoLeading", json!(5.004)), - ("autoLeading", json!(-0.004)), + ("autoLeading", json!(5.01)), + ("autoLeading", json!(-0.01)), ("autoLeading", json!(f64::NAN)), ("singleWordJustify", json!("leftJustified")), ]; @@ -1183,6 +1190,15 @@ fn justification_dialog_sets_auto_leading_and_single_word_justification() { } assert_eq!(undo_steps(&app), before); + // A typed percent is stored as the whole percent the field shows, so 500.4% (shown as 500%) + // and -0.4% (shown as 0%) are accepted. + for (typed, stored) in [(500.4, 5.0), (-0.4, 0.0), (149.6, 1.5)] { + assert_eq!(auto_leading_typed(typed), stored, "{typed}%"); + let mut probe = d.clone(); + probe.fields.insert("autoLeading".into(), json!(auto_leading_typed(typed))); + assert_eq!(check_justification(&probe, "", ¤t), Ok(()), "{typed}%"); + } + app.ui.dialog = Some(d); app.ui.dialog.as_mut().unwrap().fields.insert("autoLeading".into(), json!(1.5)); draw(&mut app, &ctx); From 9fcab8e66baca0cce1406b783c05f418d74ce216 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:13:21 -0800 Subject: [PATCH 0951/1349] Text wrap: Alpha Channel outlines fit composition, and an empty one wraps nothing An outline with more path elements than composition follows is traced on a coarser grid, so a fragmented image keeps an Alpha Channel contour instead of falling back to the frame. An image with no pixel more opaque than the threshold leaves the text alone. --- crates/compose/src/lib.rs | 38 +++++++++++++++++++----- crates/engine/src/cmd/alpha_wrap.rs | 46 +++++++++++++++++++++++++---- 2 files changed, 71 insertions(+), 13 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 47798d7a3..f0451f938 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -386,7 +386,7 @@ pub struct Contour { } /// Points a contour outline may have; a larger outline wraps around its bounding box. -const MAX_CONTOUR_POINTS: usize = 8192; +pub const MAX_CONTOUR_POINTS: usize = 8192; impl Contour { /// The outline of `path` (after `to_inner`), flattened; None if it is empty or too detailed. @@ -587,7 +587,8 @@ pub fn exclusion(doc: &Document, other: &Item, xf: Affine, inv: Affine, left_pag let group = other.shape == designcraft_doc::Shape::Group; let b = if group { (xf * other.xf.inverse()).transform_rect_bbox(other.bounds()) } else { other.path.transformed(xf).bounds().unwrap_or(Rect::ZERO) }; - wrap_exclusion(&other.wrap, b, || (!group).then(|| contour_path(doc, other, &other.wrap)), xf, inv, left_page) + let e = wrap_exclusion(&other.wrap, b, || (!group).then(|| contour_path(doc, other, &other.wrap)), xf, inv, left_page); + nothing_visible_wraps_nothing(doc, other, &other.wrap, e) } /// The wrap exclusion of the graphic placed in frame `it` (arguments as for [`exclusion`]): around @@ -595,7 +596,26 @@ pub fn exclusion(doc: &Document, other: &Item, xf: Affine, inv: Affine, left_pag pub fn graphic_exclusion(doc: &Document, it: &Item, xf: Affine, inv: Affine, left_page: bool) -> Option { let g = it.graphic()?; let shown = g.shown_bounds(it.inner_bounds())?; - Some(wrap_exclusion(&g.wrap, xf.transform_rect_bbox(shown), || Some(contour_path(doc, it, &g.wrap)), xf, inv, left_page)) + let e = wrap_exclusion(&g.wrap, xf.transform_rect_bbox(shown), || Some(contour_path(doc, it, &g.wrap)), xf, inv, left_page); + Some(nothing_visible_wraps_nothing(doc, it, &g.wrap, e)) +} + +/// An Alpha Channel contour around an image with no pixel more opaque than the threshold leaves +/// the text alone (the exclusion's mode becomes None). +fn nothing_visible_wraps_nothing(doc: &Document, it: &Item, wrap: &designcraft_doc::TextWrap, mut e: Exclusion) -> Exclusion { + if wrap.mode == WrapMode::Contour + && wrap.contour == designcraft_doc::ContourType::AlphaChannel + && wrap.path.is_none() + && let Some(g) = it.graphic() + && let Some(o) = doc.alpha_outline(g.asset, wrap.alpha_threshold) + && o.width > 0 + && o.height > 0 + && o.outer.subpaths.is_empty() + { + e.mode = WrapMode::None; + e.contour = None; + } + e } /// The exclusion of `wrap` around an object with spread-space bounds `b`; `outline` gives its @@ -637,8 +657,9 @@ fn wrap_exclusion( /// The outline a contour wrap of `kind` around frame `it` follows, in the frame's inner space, and /// for an outline taken from the placed graphic, the frame path that clips it. Bounding Box /// follows the part of the placed graphic the frame shows; Same As Clipping follows the graphic's -/// clipping path when it has one; detected edges, alpha channels and image paths need the image, -/// so they follow the frame's path (as other frames do). +/// clipping path when it has one; Alpha Channel follows the image's traced outline when the +/// engine has traced one; detected edges and image paths follow the frame's path (as other +/// frames do). fn contour_path(doc: &Document, it: &Item, wrap: &designcraft_doc::TextWrap) -> (designcraft_geom::BezPath, Option) { let frame = designcraft_geom::corners::apply(&it.path, &it.corners); let kind = wrap.contour; @@ -765,11 +786,14 @@ fn wrap_obstacles( } let xf = parent * it.xf; let left = || left_page(parent.transform_rect_bbox(it.bounds()).center().x); + // An exclusion whose mode came back None (nothing visible to wrap) is left out. if it.wrap.mode != WrapMode::None { - out.push(exclusion(doc, it, xf, inv, left())); + out.extend(Some(exclusion(doc, it, xf, inv, left())).filter(|e| e.mode != WrapMode::None)); } match &it.content { - Content::Graphic(g) if g.wrap.mode != WrapMode::None => out.extend(graphic_exclusion(doc, it, xf, inv, left())), + Content::Graphic(g) if g.wrap.mode != WrapMode::None => { + out.extend(graphic_exclusion(doc, it, xf, inv, left()).filter(|e| e.mode != WrapMode::None)) + } Content::Group { .. } => { for c in it.shown_children() { wrap_obstacles(doc, c, xf, inv, skip, left_page, depth + 1, out); diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs index cd6a1d00b..b4009de1d 100644 --- a/crates/engine/src/cmd/alpha_wrap.rs +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -91,7 +91,12 @@ pub(crate) fn trace(data: &Arc>, asset: AssetId, threshold: u8) -> Optio mask } }; - if let Some((outer, holes)) = rings(&mask, cols as usize, rows as usize) { + // Composition follows an outline of at most MAX_CONTOUR_POINTS path elements (holes + // included, for Include Inside Edges): a ring of k points is k + 1 elements with its close. + let fits = |outer: &[Vec<(i32, i32)>], holes: &[Vec<(i32, i32)>]| { + outer.iter().chain(holes).map(|r| r.len() + 1).sum::() <= designcraft_compose::MAX_CONTOUR_POINTS + }; + if let Some((outer, holes)) = rings(&mask, cols as usize, rows as usize).filter(|(o, h)| fits(o, h)) { let (sx, sy) = (f64::from(w) / f64::from(cols), f64::from(h) / f64::from(rows)); let path = |rings: &[Vec<(i32, i32)>]| { let mut p = BezPath::new(); @@ -240,15 +245,44 @@ mod tests { /// A 64 × 64 PNG: visible where `on(x, y)`. fn png(on: impl Fn(usize, usize) -> bool) -> Vec { - let mut pixels = vec![0; 64 * 64 * 4]; - for y in 0..64 { - for x in 0..64 { - let i = (y * 64 + x) * 4; + png_sized(64, on) + } + + /// A `size` × `size` PNG: visible where `on(x, y)`. + fn png_sized(size: usize, on: impl Fn(usize, usize) -> bool) -> Vec { + let mut pixels = vec![0; size * size * 4]; + for y in 0..size { + for x in 0..size { + let i = (y * size + x) * 4; pixels[i] = 120; pixels[i + 3] = if on(x, y) { 255 } else { 0 }; } } - designcraft_render::Rendered { width: 64, height: 64, pixels }.to_png() + designcraft_render::Rendered { width: size as u32, height: size as u32, pixels }.to_png() + } + + /// An outline too detailed for composition (here 4,096 separate dots, 20,480 path elements + /// on the finest grid) is traced on a coarser grid until composition can follow it. + #[test] + fn a_fragmented_outline_is_traced_coarser_until_composition_can_follow_it() { + let dots = png_sized(256, |x, y| x % 4 == 0 && y % 4 == 0); + let o = trace(&Arc::new(dots), AssetId(1), 25).unwrap(); + let elements = o.outer.to_bezpath().elements().len() + o.holes.to_bezpath().elements().len(); + assert!(elements > 0 && elements <= designcraft_compose::MAX_CONTOUR_POINTS, "{elements} path elements"); + } + + /// An image with no pixel more opaque than the threshold leaves the text alone: with the + /// frame's contour the caption over it is overset, with Alpha Channel it is set. + #[test] + fn an_image_with_nothing_visible_wraps_no_text() { + let (mut s, image, story) = page(&png(|_, _| false), [150.0, 150.0, 178.0, 178.0]); + assert!(overset(&s, story), "the frame's contour covers the caption"); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(!overset(&s, story), "nothing visible: nothing wraps"); + // The same for the wrap set on the placed graphic. + s.execute("object.textWrap", &json!({"ids": [image], "mode": "none"})).unwrap(); + s.execute("object.textWrap", &json!({"ids": [image], "content": true, "mode": "contour", "contour": "alphaChannel"})).unwrap(); + assert!(!overset(&s, story)); } #[test] From 97ed25093f03ff03b9fc7c73466e8df64ad8581d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:23:59 -0800 Subject: [PATCH 0952/1349] Text wrap: a vertical open path keeps its offset, and previewed images are traced A contour's zero-width spans (a vertical open path) are kept until the wrap offset widens them, so text no longer crosses such a path. A record previewed into an image placeholder gets the image's Alpha Channel outline, as an edit would. --- crates/compose/src/lib.rs | 10 ++++++--- crates/compose/src/tests.rs | 15 +++++++++++++ crates/engine/src/cmd/datamerge.rs | 2 ++ crates/engine/src/cmd/datamerge/tests.rs | 27 ++++++++++++++++++++++++ 4 files changed, 51 insertions(+), 3 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index f0451f938..62e319f36 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -451,8 +451,10 @@ impl Contour { let mut cut = Vec::new(); let (mut i, mut j) = (0, 0); while let (Some(&(a, b)), Some(&(c, d))) = (spans.get(i), clip.get(j)) { - if a.max(c) < b.min(d) { - cut.push((a.max(c), b.min(d))); + let (lo, hi) = (a.max(c), b.min(d)); + // A zero-width span (a vertical open path) is kept where the clip covers it. + if lo < hi || (a == b && lo == hi) { + cut.push((lo, hi)); } if b < d { i += 1; @@ -466,8 +468,10 @@ impl Contour { } } +/// Sorted, overlapping spans joined. Zero-width spans (a vertical edge of an open path) are kept: +/// the wrap offset widens them, and without one they still split the line there. fn merge_spans(mut spans: Vec<(f64, f64)>) -> Vec<(f64, f64)> { - spans.retain(|(a, b)| a.is_finite() && b.is_finite() && b - a > 1e-9); + spans.retain(|(a, b)| a.is_finite() && b.is_finite() && b >= a); spans.sort_by(|a, b| a.0.total_cmp(&b.0)); let mut out: Vec<(f64, f64)> = Vec::new(); for (a, b) in spans { diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index e96e33cf4..3df861733 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -8464,6 +8464,21 @@ fn contour_intervals_cover_the_whole_slanted_line_band() { assert_eq!(c.band_spans(0.0, 10.0), vec![(0.0, 12.0)]); } +/// A vertical open path blocks the offset on both sides of it, and splits the line with no +/// offset; clipped to a frame that holds it, it still does. +#[test] +fn a_vertical_open_path_keeps_its_offset() { + let mut path = designcraft_geom::BezPath::new(); + path.move_to((10.0, 0.0)); + path.line_to((10.0, 100.0)); + let c = Contour::of(&path, designcraft_geom::Affine::IDENTITY, 3.0).unwrap(); + assert_eq!(c.band_spans(40.0, 50.0), vec![(7.0, 13.0)]); + let frame = designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 100.0)).to_bezpath(); + assert_eq!(c.within(&frame, designcraft_geom::Affine::IDENTITY).band_spans(40.0, 50.0), vec![(7.0, 13.0)]); + let c = Contour::of(&path, designcraft_geom::Affine::IDENTITY, 0.0).unwrap(); + assert_eq!(c.band_spans(40.0, 50.0), vec![(10.0, 10.0)]); +} + /// Rule Above's offset runs from the first line's baseline up to the rule's bottom edge, as in /// InDesign: a rule set clear of the cap height sits between the rows, not across the row above /// (an INDD project list whose rules crossed the previous paragraph's text). diff --git a/crates/engine/src/cmd/datamerge.rs b/crates/engine/src/cmd/datamerge.rs index 7cb332fd3..aad5b72f3 100644 --- a/crates/engine/src/cmd/datamerge.rs +++ b/crates/engine/src/cmd/datamerge.rs @@ -210,6 +210,8 @@ fn preview_cmd(s: &mut Session, p: &Value) -> Result { let images = ImageCache::default(); let sources = Sources { options: &options, data_dir: data_dir.as_deref(), doc_dir: doc_dir.as_deref(), images: &images }; fill_row(&mut doc, &source.fields, &row, record as u32, &maps, &sources); + // An image the record placed gets its Alpha Channel outline, as an edit's would. + crate::cmd::alpha_wrap::sync(&mut doc); st.doc = Arc::new(doc); st.preview_record = Some(record as u32); st.bump_revision(); diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index 4793aac17..dad43af66 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -1310,3 +1310,30 @@ fn merged_records_give_anchored_objects_their_own_ids() { doc.check().unwrap(); designcraft_format::load(&designcraft_format::save(doc).unwrap()).unwrap(); } + +/// A record previewed into an image placeholder whose frame wraps with an Alpha Channel contour +/// gets the image's outline, as an edit would. +#[test] +fn a_previewed_image_gets_its_alpha_channel_outline() { + let dir = scratch("alpha-preview"); + let mut pixels = vec![0u8; 64 * 64 * 4]; + for y in 0..64 { + for x in 16..48 { + pixels[(y * 64 + x) * 4 + 3] = 255; + } + } + std::fs::write(dir.join("cut.png"), designcraft_render::Rendered { width: 64, height: 64, pixels }.to_png()).unwrap(); + write(&dir.join("pics.csv"), "Photo\ncut.png\n"); + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": dir.join("pics.csv")})); + let frame = exec(&mut s, "frame.create", json!({"rect": [0.0, 0.0, 200.0, 100.0], "content": "graphic"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "role": "image", "item": frame["id"]})); + exec(&mut s, "object.textWrap", json!({"ids": [frame["id"]], "mode": "contour", "contour": "alphaChannel"})); + assert!(s.doc().unwrap().doc.alpha_outlines.is_empty(), "no image placed yet"); + exec(&mut s, "data.preview", json!({"record": 1})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.alpha_outlines.len(), 1, "the previewed image is traced"); + assert!(d.alpha_outlines[0].width > 0 && !d.alpha_outlines[0].outer.subpaths.is_empty()); + let _ = std::fs::remove_dir_all(&dir); +} From 7b91cad608f2c47f626a2d4818710a98ab9f5f6c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:24:55 -0800 Subject: [PATCH 0953/1349] Recovery: Save cancels a document's writes to any folder Save, Revert and Close now cancel the document's background writes to every folder, including one named with `file.recovery.save {dir}` that is not in its entries yet, and remove a snapshot such a write already published even when its result has not been taken. A cancel that comes after the write published retires its result, so the removed snapshot is not recorded as a checkpoint after a later edit. Cancels apply only to writes the same session queued. The test that closes a run's lock and expects it free no longer runs while a test starts its child process, which held a copy of the lock until the child ran its program. --- crates/engine/src/recovery.rs | 64 ++++++++++++++++--- crates/engine/src/recovery/tests.rs | 96 ++++++++++++++++++++++++++--- 2 files changed, 146 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index dc7d63ed7..6d2eac44d 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -514,6 +514,15 @@ pub(crate) fn discard_document(s: &mut Session, index: usize, default_dir: Optio { entries.push((dir.to_path_buf(), uid)); } + // Background writes still queued or running for it, in any folder (one named by + // `file.recovery.save {dir}` is not in its entries until the write's result is taken): none + // may publish after this point, and what one already published is removed below. + #[cfg(not(target_arch = "wasm32"))] + for dir in worker::cancel_document(uid, s.recovery_owner.0) { + if !entries.iter().any(|(entry_dir, entry_uid)| *entry_uid == uid && same_directory(entry_dir, &dir)) { + entries.push((dir, uid)); + } + } for (dir, uid) in entries { // Session ownership governs deletion as well as writes: never consume another live // document's only source merely because its old uid matches this unrelated document. @@ -861,7 +870,7 @@ pub(crate) fn finished(_s: &mut Session) -> Finished { /// gigabytes of placed files is written without stopping the interface. #[cfg(not(target_arch = "wasm32"))] mod worker { - use std::collections::BTreeSet; + use std::collections::{BTreeMap, BTreeSet}; use std::sync::mpsc::{Receiver, Sender}; use std::sync::{Condvar, Mutex, OnceLock}; @@ -884,8 +893,9 @@ mod worker { pub(super) done: Mutex>, /// Results taken from `done` by a session that did not queue them, kept for their own. pub(super) undelivered: Mutex>, - /// Documents queued or being written: a second write of one still holds nothing newer. - running: Mutex>, + /// Documents queued or being written, with the session that queued each: a second write + /// of one still holds nothing newer. + running: Mutex>, /// A document saved, reverted or closed while its write was queued or running: the /// snapshot it is producing must not be published. cancelled: Mutex>, @@ -928,7 +938,7 @@ mod worker { // A rename under way finishes first, so the caller's cleanup comes after it; a later // one sees the mark. let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if !self.running.lock().is_ok_and(|running| running.contains(&key)) { + if !self.running.lock().is_ok_and(|running| running.contains_key(&key)) { return; } if let Ok(mut cancelled) = self.cancelled.lock() { @@ -936,6 +946,35 @@ mod worker { } } + /// [`Writer::cancel`] for every folder a write of `uid` queued by session `owner` is queued + /// or running for. Returns those folders, and the folders of its finished writes whose + /// results nobody has taken. + fn cancel_document(&self, uid: u64, owner: u64) -> Vec { + // Held while results are read: the writer checks for a cancel and sends its result + // under it, so a result sent after this sees the cancel. + let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let keys: Vec<(PathBuf, u64)> = self + .running + .lock() + .map(|running| running.iter().filter(|((_, u), o)| *u == uid && **o == owner).map(|(key, _)| key.clone()).collect()) + .unwrap_or_default(); + if let Ok(mut cancelled) = self.cancelled.lock() { + cancelled.extend(keys.iter().cloned()); + } + let mut dirs: Vec = keys.into_iter().map(|(dir, _)| dir).collect(); + // Results stay queued for their session; only their folders are read here. + let done = self.done.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut undelivered = self.undelivered.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + undelivered.extend(done.try_iter()); + for d in undelivered.iter_mut().filter(|d| d.uid == uid && d.owner == owner && d.published) { + dirs.push(d.dir.clone()); + // The caller removes that snapshot: its result must not record it as a checkpoint + // once the document has changed again. + d.published = false; + } + dirs + } + fn cancelled(&self, dir: &Path, uid: u64) -> bool { self.cancelled.lock().is_ok_and(|cancelled| cancelled.contains(&(dir.to_path_buf(), uid))) } @@ -954,7 +993,12 @@ mod worker { // The result before the document reads as idle: a writer that is not busy // has already delivered it, so the interface never stops polling with an // answer still on its way. - let sent = done_tx.send(Done { dir: dir.clone(), uid, error, published, owner }).is_ok(); + let sent = { + let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + // Cancelled after it was published: the canceller removes the snapshot. + let published = published && !cancelled(&dir, uid); + done_tx.send(Done { dir: dir.clone(), uid, error, published, owner }).is_ok() + }; if let Some(w) = WRITER.get().and_then(Option::as_ref) { w.finish(&dir, uid); } @@ -967,7 +1011,7 @@ mod worker { jobs, done: Mutex::new(done_rx), undelivered: Mutex::new(Vec::new()), - running: Mutex::new(BTreeSet::new()), + running: Mutex::new(BTreeMap::new()), cancelled: Mutex::new(BTreeSet::new()), idle: Condvar::new(), }) @@ -987,6 +1031,11 @@ mod worker { } } + /// Do not publish any write of `uid` in flight (see [`Writer::cancel_document`]). + pub(super) fn cancel_document(uid: u64, owner: u64) -> Vec { + started().map(|w| w.cancel_document(uid, owner)).unwrap_or_default() + } + /// Whether that write is already marked as cancelled (see [`Writer::cancelled`]). pub(super) fn cancelled(dir: &Path, uid: u64) -> bool { started().is_some_and(|w| w.cancelled(dir, uid)) @@ -1016,9 +1065,10 @@ mod worker { let w = writer()?; let mut running = w.running.lock().ok()?; let key = (entry.dir.clone(), entry.uid); - if !running.insert(key.clone()) { + if running.contains_key(&key) { return Some(false); } + running.insert(key.clone(), entry.owner); // A write is wanted again: whatever cancelled the last one does not apply to this one. if let Ok(mut cancelled) = w.cancelled.lock() { cancelled.remove(&key); diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index 79644ca3d..2d6cc8861 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -184,12 +184,57 @@ fn a_document_saved_while_its_write_is_held_leaves_no_snapshot() { let saved = dir.path().join("saved.designcraft"); s.execute("file.saveAs", &json!({"path": saved.to_string_lossy()})).unwrap(); held.release(); - assert_eq!(finished_writes(&mut s), 0); + // Before the session takes the result: a crash now must not find the stale snapshot. + testing::wait_until_idle(); assert!(!files(dir.path(), uid).0.exists(), "the stale snapshot was not published"); assert!(!files(dir.path(), uid).1.exists(), "nor its metadata"); + assert_eq!(finished_writes(&mut s), 0); assert!(list(dir.path()).is_empty()); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_document_saved_while_its_write_to_a_named_folder_is_held_leaves_no_snapshot() { + // A folder given to `file.recovery.save` is not the session's, and is not in the document's + // entries until the write's result is taken. + let _turn = background(); + let named = tempfile::tempdir().unwrap(); + let mut s = dirty_session(); + let uid = s.docs[0].uid; + let held = testing::hold_next_write(named.path()); + let queued = s.execute("file.recovery.save", &json!({"background": true, "dir": named.path().to_string_lossy()})).unwrap(); + assert_eq!(queued["queued"], 1, "{queued}"); + held.wait_until_held(); + let saved = named.path().join("saved.designcraft"); + s.execute("file.saveAs", &json!({"path": saved.to_string_lossy()})).unwrap(); + held.release(); + // Before the session takes the result: a crash now must not find the stale snapshot. + testing::wait_until_idle(); + assert!(!files(named.path(), uid).0.exists(), "the stale snapshot was not published"); + assert_eq!(finished_writes(&mut s), 0); + assert!(list(named.path()).is_empty()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn saving_removes_a_finished_write_to_a_named_folder_whose_result_was_not_taken() { + let _turn = background(); + let named = tempfile::tempdir().unwrap(); + let mut s = dirty_session(); + let uid = s.docs[0].uid; + s.execute("file.recovery.save", &json!({"background": true, "dir": named.path().to_string_lossy()})).unwrap(); + testing::wait_until_idle(); + assert!(files(named.path(), uid).0.exists(), "the write finished"); + let saved = named.path().join("saved.designcraft"); + s.execute("file.saveAs", &json!({"path": saved.to_string_lossy()})).unwrap(); + assert!(!files(named.path(), uid).0.exists(), "Save removed the snapshot before its result was taken"); + // Edited again before the result is taken: the removed snapshot is not its checkpoint. + s.execute("frame.create", &json!({"rect": [20, 20, 60, 60]})).unwrap(); + assert_eq!(finished_writes(&mut s), 0); + assert!(!s.docs[0].recovery_entries.iter().any(|(d, _)| same_directory(d, named.path())), "no checkpoint for a removed snapshot"); + assert!(list(named.path()).is_empty()); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn a_background_result_goes_to_the_session_that_queued_it() { @@ -211,6 +256,28 @@ fn a_background_result_goes_to_the_session_that_queued_it() { discard(dir.path(), uid); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn saving_in_one_session_leaves_another_sessions_write_alone() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut queued_by = dirty_session(); + queued_by.recovery_dir = Some(dir.path().to_path_buf()); + let uid = queued_by.docs[0].uid; + // The same uid in another session (recovered documents keep the uids of their entries). + let mut other = dirty_session(); + other.docs[0].uid = uid; + let held = testing::hold_next_write(dir.path()); + queued_by.execute("file.recovery.save", &json!({"background": true})).unwrap(); + held.wait_until_held(); + let elsewhere = tempfile::tempdir().unwrap(); + other.execute("file.saveAs", &json!({"path": elsewhere.path().join("other.designcraft").to_string_lossy()})).unwrap(); + held.release(); + assert_eq!(finished_writes(&mut queued_by), 1); + assert!(files(dir.path(), uid).0.exists(), "the other session's save did not cancel this write"); + discard(dir.path(), uid); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn results_for_a_session_that_is_gone_are_not_kept() { @@ -709,6 +776,11 @@ fn restart_recovery_child() { } } +/// A child process starts with a copy of every open file of this one until it runs its program, so +/// a lock file closed meanwhile stays locked: a test that closes a lock and expects it free does +/// not run while a child is started. +static SPAWN: std::sync::Mutex<()> = std::sync::Mutex::new(()); + fn run_restart_case(mode: &str) { let source = restart_fixture(); if mode == "max_uid" { @@ -717,12 +789,20 @@ fn run_restart_case(mode: &str) { std::fs::rename(doc, max_doc).unwrap(); std::fs::rename(meta, max_meta).unwrap(); } - let output = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", "recovery::tests::restart_recovery_child", "--ignored", "--nocapture"]) - .env("DESIGNCRAFT_TEST_RECOVERY_SOURCE", source.path()) - .env("DESIGNCRAFT_TEST_RECOVERY_MODE", mode) - .output() - .unwrap(); + // `spawn` returns once the child runs its program, and its copies of this process's files + // are closed by then. + let child = { + let _spawning = SPAWN.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "recovery::tests::restart_recovery_child", "--ignored", "--nocapture"]) + .env("DESIGNCRAFT_TEST_RECOVERY_SOURCE", source.path()) + .env("DESIGNCRAFT_TEST_RECOVERY_MODE", mode) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + }; + let output = child.wait_with_output().unwrap(); assert!(output.status.success(), "fresh child failed: {}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); let child_stdout = String::from_utf8_lossy(&output.stdout); assert!(child_stdout.contains("test result: ok. 1 passed; 0 failed;"), "the fresh-process helper did not run exactly once: {child_stdout}"); @@ -953,6 +1033,8 @@ fn documents_of_two_apps_that_ended_are_both_recovered() { fn a_running_apps_recovery_data_is_left_alone() { let root = tempfile::tempdir().unwrap(); let running = run_left(root.path(), "run-7-0", "still open", 1); + // No child starts while the lock is open, so closing it frees it (see `SPAWN`). + let _no_spawn = SPAWN.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let lock = std::fs::File::open(running.join(LOCK)).unwrap(); lock.try_lock().unwrap(); let own = run_dir(root.path()).unwrap(); From f27e2c380bac9221e1234fc17423b2c35573f3bb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:30:25 -0800 Subject: [PATCH 0954/1349] Data merge: overset count composes with the merged images' Alpha Channel outlines --- crates/engine/src/cmd/datamerge.rs | 2 ++ crates/engine/src/cmd/datamerge/tests.rs | 27 ++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/crates/engine/src/cmd/datamerge.rs b/crates/engine/src/cmd/datamerge.rs index aad5b72f3..84e8b65e3 100644 --- a/crates/engine/src/cmd/datamerge.rs +++ b/crates/engine/src/cmd/datamerge.rs @@ -263,6 +263,8 @@ fn merge_cmd(s: &mut Session, p: &Value) -> Result { merged.data_merge.placeholders.clear(); merged.title = format!("{} merged", src.title); let pages = merged.page_count(); + // The merged images' Alpha Channel outlines first: the overset count composes with them. + crate::cmd::alpha_wrap::sync(&mut merged); let overset = overset_count(&merged); let records = selected.len(); let missing_json: Vec = missing.iter().map(|m| json!({"record": m.record, "field": m.field, "path": m.path})).collect(); diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index dad43af66..062ff9483 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -1337,3 +1337,30 @@ fn a_previewed_image_gets_its_alpha_channel_outline() { assert!(d.alpha_outlines[0].width > 0 && !d.alpha_outlines[0].outer.subpaths.is_empty()); let _ = std::fs::remove_dir_all(&dir); } + +/// The overset count data merge reports is composed with the merged images' Alpha Channel +/// outlines: a caption over the image's transparent part is set, not counted as overset. +#[test] +fn a_merge_counts_overset_text_with_the_merged_images_outlines() { + let dir = scratch("alpha-merge"); + // Visible only in the left quarter. + let mut pixels = vec![0u8; 64 * 64 * 4]; + for y in 0..64 { + for x in 0..16 { + pixels[(y * 64 + x) * 4 + 3] = 255; + } + } + std::fs::write(dir.join("cut.png"), designcraft_render::Rendered { width: 64, height: 64, pixels }.to_png()).unwrap(); + write(&dir.join("pics.csv"), "Photo\ncut.png\n"); + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": dir.join("pics.csv")})); + let frame = exec(&mut s, "frame.create", json!({"rect": [100.0, 100.0, 300.0, 300.0], "content": "graphic"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "role": "image", "item": frame["id"]})); + exec(&mut s, "data.options", json!({"fitting": "fitContentToFrame"})); + exec(&mut s, "object.textWrap", json!({"ids": [frame["id"]], "mode": "contour", "contour": "alphaChannel", "offset": 0})); + text_frame(&mut s, [220.0, 180.0, 290.0, 220.0], "Hi", None); + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["oversetStories"], 0, "the caption sits beside the image's visible pixels: {r}"); + let _ = std::fs::remove_dir_all(&dir); +} From b73c21db37acf667461d99007be84ee7c2a8099b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:36:39 -0800 Subject: [PATCH 0955/1349] Data merge: a file that is not an image does not hide a later image candidate The image search stopped at the first file that could be read and checked whether it decodes afterwards. A non-image file at an earlier candidate (the drive root, or beside the data file) then hid a valid image beside the data file or the document, and the field was reported missing. The decode check now runs inside the search, so only an image ends it. --- crates/engine/src/cmd/datamerge/fill.rs | 11 ++++++----- crates/engine/src/cmd/datamerge/tests.rs | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/datamerge/fill.rs b/crates/engine/src/cmd/datamerge/fill.rs index caea4d67e..ebe950fb6 100644 --- a/crates/engine/src/cmd/datamerge/fill.rs +++ b/crates/engine/src/cmd/datamerge/fill.rs @@ -464,7 +464,7 @@ struct LoadedImage { fn load_image(cell: &str, sources: &Sources) -> Option { let Sources { data_dir, doc_dir, images, .. } = *sources; let cands = image_candidates(cell, data_dir, doc_dir); - let (path, bytes) = cands.iter().find_map(|p| { + cands.iter().find_map(|p| { // Read once per merge: many records naming one file is the normal case, and reading it // per record is the amplification (#1595). let bytes = images.get_or_read(p, || { @@ -475,10 +475,11 @@ fn load_image(cell: &str, sources: &Sources) -> Option { } crate::io::read_file(p).ok().filter(|b| !b.is_empty()) })?; - Some((p.clone(), bytes)) - })?; - let (pixels, natural) = designcraft_render::image_size(&bytes).zip(designcraft_render::natural_size(&bytes, 0))?; - Some(LoadedImage { path, bytes, pixels, natural }) + // A file that does not decode leaves the search going, so a valid image at a later + // candidate is still found. + let (pixels, natural) = designcraft_render::image_size(&bytes).zip(designcraft_render::natural_size(&bytes, 0))?; + Some(LoadedImage { path: p.clone(), bytes, pixels, natural }) + }) } fn report_missing(report: &mut FillReport, record: u32, field: &str, cell: &str) { diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index 39b1988e2..5480a5686 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -914,6 +914,28 @@ fn an_image_path_with_a_leading_separator_is_found_beside_the_data_file() { assert_eq!(r["missingImages"].as_array().map(Vec::len), Some(0), "{r}"); } +/// A file at an earlier candidate that is not an image does not hide a valid image at a later +/// one: the search goes on past it. +#[test] +fn a_non_image_file_beside_the_data_does_not_hide_the_image_beside_the_document() { + let dir = scratch("undecodable-image"); + let (data, docs) = (dir.join("data"), dir.join("docs")); + write(&data.join("pics").join("a.png"), "not an image"); + write_png_sized(&docs.join("pics").join("a.png"), 12, 12); + write(&data.join("cards.csv"), "@Photo\npics/a.png\n"); + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": data.join("cards.csv")})); + exec(&mut s, "file.save", json!({"path": docs.join("layout.designcraft")})); + let frame = exec(&mut s, "frame.create", json!({"rect": [36.0, 36.0, 80.0, 80.0], "content": "graphic"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "item": frame["id"]})); + exec(&mut s, "data.options", json!({"linkImages": true})); + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["missingImages"].as_array().map(Vec::len), Some(0), "{r}"); + let link = graphic_link(&s).unwrap_or_default(); + assert!(link.contains("docs"), "{link}"); +} + #[test] fn single_record_merge_copies_pages_and_leaves_the_template() { let mut s = Session::new(); From 1455093812ee039a3e67acd495821b098f368791 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:37:03 -0800 Subject: [PATCH 0956/1349] Text wrap: the alpha threshold default is described as DesignCraft's own --- crates/doc/src/item/text_frame.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/doc/src/item/text_frame.rs b/crates/doc/src/item/text_frame.rs index c87b74e0a..62f12eb24 100644 --- a/crates/doc/src/item/text_frame.rs +++ b/crates/doc/src/item/text_frame.rs @@ -306,7 +306,7 @@ pub struct TextWrap { pub alpha_threshold: u8, } -/// InDesign's default alpha threshold for contour wraps. +/// DesignCraft's default alpha threshold for Alpha Channel contour wraps. pub const DEFAULT_ALPHA_THRESHOLD: u8 = 25; impl Default for TextWrap { From 04fac58d9b9b229805e0fb165763b2fe0463afcc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:43:12 -0800 Subject: [PATCH 0957/1349] Recovery: writes are keyed by the folder's canonical path A synchronous recovery write now cancels a background write to the same folder named another way, and a cancel also matches the folder as the session named it. Background writes whose results have not been taken count toward the per-document checkpoint limit, cancelled ones excluded. Save, Revert and Close clean up a cancelled write's folder under the name the session used for it. --- crates/engine/src/recovery.rs | 103 ++++++++++++++++++++++------ crates/engine/src/recovery/tests.rs | 57 +++++++++++++++ 2 files changed, 138 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index 6d2eac44d..f5bafd316 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -636,7 +636,21 @@ pub(crate) fn save_tracked(s: &mut Session, dir: &Path) -> Result { /// Reject a complete batch before writing rather than silently losing old ownership records. fn reject_overfull_checkpoints(s: &Session, dir: &Path) -> Result<()> { for document in &s.docs { - if document.is_dirty() && !has_checkpoint(document, dir) && document.recovery_entries.len() >= MAX_RECOVERY_ENTRIES { + if !document.is_dirty() || has_checkpoint(document, dir) { + continue; + } + // Background writes whose results are not taken yet hold checkpoints the entries do not. + #[cfg(not(target_arch = "wasm32"))] + let pending = worker::pending_folders(document.uid, s.recovery_owner.0) + .into_iter() + .map(|pending| directory_key(&pending).unwrap_or(pending)) + .collect::>() + .iter() + .filter(|pending| !same_directory(pending, dir) && !has_checkpoint(document, pending)) + .count(); + #[cfg(target_arch = "wasm32")] + let pending = 0; + if document.recovery_entries.len() + pending >= MAX_RECOVERY_ENTRIES { return Err(EngineError::Other( "too many recovery checkpoints; save or close the document before choosing another recovery folder".into(), )); @@ -895,7 +909,7 @@ mod worker { pub(super) undelivered: Mutex>, /// Documents queued or being written, with the session that queued each: a second write /// of one still holds nothing newer. - running: Mutex>, + running: Mutex>, /// A document saved, reverted or closed while its write was queued or running: the /// snapshot it is producing must not be published. cancelled: Mutex>, @@ -903,15 +917,27 @@ mod worker { idle: Condvar, } + /// A write in flight: the session that queued it, and its folder as that session named it. + struct Queued { + owner: u64, + dir: PathBuf, + } + static WRITER: OnceLock> = OnceLock::new(); + /// A write's key: the folder's canonical path, so two spellings of one folder are one write. + fn key(dir: &Path, uid: u64) -> (PathBuf, u64) { + (super::directory_key(dir).unwrap_or_else(|_| dir.to_path_buf()), uid) + } + impl Writer { pub(super) fn busy(&self) -> bool { self.running.lock().is_ok_and(|running| !running.is_empty()) } - fn finish(&self, dir: &Path, uid: u64) { - let key = (dir.to_path_buf(), uid); + /// `key` is the job's ([`Snapshot::key`], uid). + fn finish(&self, key: &(PathBuf, u64)) { + let key = key.clone(); if let Ok(mut running) = self.running.lock() { running.remove(&key); } @@ -934,15 +960,19 @@ mod worker { /// reverted or closed. Only a write that is queued or running is marked, so the set stays /// as small as the work in flight. fn cancel(&self, dir: &Path, uid: u64) { - let key = (dir.to_path_buf(), uid); + let canonical = key(dir, uid); // A rename under way finishes first, so the caller's cleanup comes after it; a later // one sees the mark. let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if !self.running.lock().is_ok_and(|running| running.contains_key(&key)) { - return; - } + // The folder's canonical path, or its name as given: a link in the path may lead + // elsewhere now than when the write was queued. + let keys: Vec<(PathBuf, u64)> = self + .running + .lock() + .map(|running| running.iter().filter(|(k, q)| **k == canonical || (k.1 == uid && q.dir == dir)).map(|(k, _)| k.clone()).collect()) + .unwrap_or_default(); if let Ok(mut cancelled) = self.cancelled.lock() { - cancelled.insert(key); + cancelled.extend(keys); } } @@ -953,15 +983,18 @@ mod worker { // Held while results are read: the writer checks for a cancel and sends its result // under it, so a result sent after this sees the cancel. let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let keys: Vec<(PathBuf, u64)> = self + // The canonical keys to mark, and the folders as the session named them, which is how + // the cleanup finds this run's folder. + let (keys, mut dirs): (Vec<(PathBuf, u64)>, Vec) = self .running .lock() - .map(|running| running.iter().filter(|((_, u), o)| *u == uid && **o == owner).map(|(key, _)| key.clone()).collect()) + .map(|running| { + running.iter().filter(|((_, u), q)| *u == uid && q.owner == owner).map(|(key, q)| (key.clone(), q.dir.clone())).unzip() + }) .unwrap_or_default(); if let Ok(mut cancelled) = self.cancelled.lock() { - cancelled.extend(keys.iter().cloned()); + cancelled.extend(keys); } - let mut dirs: Vec = keys.into_iter().map(|(dir, _)| dir).collect(); // Results stay queued for their session; only their folders are read here. let done = self.done.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let mut undelivered = self.undelivered.lock().unwrap_or_else(std::sync::PoisonError::into_inner); @@ -975,8 +1008,26 @@ mod worker { dirs } - fn cancelled(&self, dir: &Path, uid: u64) -> bool { - self.cancelled.lock().is_ok_and(|cancelled| cancelled.contains(&(dir.to_path_buf(), uid))) + /// The folders of writes of `uid` queued by session `owner` that are in flight, or finished + /// and published with their results not taken yet: checkpoints its entries do not hold yet. + fn pending_folders(&self, uid: u64, owner: u64) -> Vec { + let keys: Vec<(PathBuf, u64)> = self + .running + .lock() + .map(|running| running.iter().filter(|((_, u), q)| *u == uid && q.owner == owner).map(|(key, _)| key.clone()).collect()) + .unwrap_or_default(); + // A cancelled write publishes nothing. + let mut dirs: Vec = keys.into_iter().filter(|key| !self.cancelled(key)).map(|(dir, _)| dir).collect(); + let done = self.done.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut undelivered = self.undelivered.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + undelivered.extend(done.try_iter()); + dirs.extend(undelivered.iter().filter(|d| d.uid == uid && d.owner == owner && d.published).map(|d| d.dir.clone())); + dirs + } + + /// `key` as in [`Writer::finish`]. + fn cancelled(&self, key: &(PathBuf, u64)) -> bool { + self.cancelled.lock().is_ok_and(|cancelled| cancelled.contains(key)) } } @@ -989,6 +1040,7 @@ mod worker { let spawned = std::thread::Builder::new().name("designcraft-recovery".into()).spawn(move || { while let Ok(job) = job_rx.recv() { let (published, error) = guarded_write(&job); + let key = (job.key.clone(), job.uid); let (dir, uid, owner) = (job.dir, job.uid, job.owner); // The result before the document reads as idle: a writer that is not busy // has already delivered it, so the interface never stops polling with an @@ -996,11 +1048,11 @@ mod worker { let sent = { let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); // Cancelled after it was published: the canceller removes the snapshot. - let published = published && !cancelled(&dir, uid); - done_tx.send(Done { dir: dir.clone(), uid, error, published, owner }).is_ok() + let published = published && !started().is_some_and(|w| w.cancelled(&key)); + done_tx.send(Done { dir, uid, error, published, owner }).is_ok() }; if let Some(w) = WRITER.get().and_then(Option::as_ref) { - w.finish(&dir, uid); + w.finish(&key); } if !sent { break; @@ -1031,21 +1083,28 @@ mod worker { } } + /// See [`Writer::pending_folders`]. + pub(super) fn pending_folders(uid: u64, owner: u64) -> Vec { + started().map(|w| w.pending_folders(uid, owner)).unwrap_or_default() + } + /// Do not publish any write of `uid` in flight (see [`Writer::cancel_document`]). pub(super) fn cancel_document(uid: u64, owner: u64) -> Vec { started().map(|w| w.cancel_document(uid, owner)).unwrap_or_default() } /// Whether that write is already marked as cancelled (see [`Writer::cancelled`]). + #[cfg(test)] pub(super) fn cancelled(dir: &Path, uid: u64) -> bool { - started().is_some_and(|w| w.cancelled(dir, uid)) + started().is_some_and(|w| w.cancelled(&key(dir, uid))) } /// Write one snapshot, turning a panic into its error: a panic that ended this thread would /// leave the document marked as running for ever (so it is never written again) and the /// interface asking for frames for ever. A safety net: a writer still must not panic. fn guarded_write(job: &Snapshot) -> (bool, Option) { - match guarded(|| Ok(write_snapshot(job, || cancelled(&job.dir, job.uid)))) { + let key = (job.key.clone(), job.uid); + match guarded(|| Ok(write_snapshot(job, || started().is_some_and(|w| w.cancelled(&key))))) { // A primary that landed is this run's to remove, even if its metadata failed. Ok(written) => (written.published, written.error.map(|e| e.to_string())), Err(e) => (false, Some(e.to_string())), @@ -1064,11 +1123,11 @@ mod worker { pub(super) fn submit(entry: Snapshot) -> Option { let w = writer()?; let mut running = w.running.lock().ok()?; - let key = (entry.dir.clone(), entry.uid); + let key = (entry.key.clone(), entry.uid); if running.contains_key(&key) { return Some(false); } - running.insert(key.clone(), entry.owner); + running.insert(key.clone(), Queued { owner: entry.owner, dir: entry.dir.clone() }); // A write is wanted again: whatever cancelled the last one does not apply to this one. if let Ok(mut cancelled) = w.cancelled.lock() { cancelled.remove(&key); diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index 2d6cc8861..2353e476d 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -278,6 +278,63 @@ fn saving_in_one_session_leaves_another_sessions_write_alone() { discard(dir.path(), uid); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_write_now_cancels_a_background_write_to_the_same_folder_spelled_another_way() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join("sub")).unwrap(); + let spelled = dir.path().join("sub").join(".."); + let mut s = dirty_session(); + s.recovery_dir = Some(spelled.clone()); + let uid = s.docs[0].uid; + let held = testing::hold_next_write(&spelled); + s.execute("file.recovery.save", &json!({"background": true})).unwrap(); + held.wait_until_held(); + // The newer state, written now under the folder's plain name. + s.execute("frame.create", &json!({"rect": [20, 20, 60, 60]})).unwrap(); + s.execute("file.recovery.save", &json!({"dir": dir.path().to_string_lossy()})).unwrap(); + assert!(worker::cancelled(&spelled, uid), "the older write is cancelled"); + held.release(); + testing::wait_until_idle(); + let _ = s.execute("file.recovery.progress", &json!({})).unwrap(); + let mut reopened = Session::new(); + assert_eq!(open(&mut reopened, dir.path()).unwrap().len(), 1); + assert_eq!(reopened.doc().unwrap().doc.spreads[0].items.len(), 2, "the newer snapshot was kept"); + discard(dir.path(), reopened.doc().unwrap().uid); + discard(dir.path(), uid); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn queued_background_writes_count_toward_the_checkpoint_limit() { + let _turn = background(); + let mut s = dirty_session(); + let folders: Vec = (0..=MAX_RECOVERY_ENTRIES).map(|_| tempfile::tempdir().unwrap()).collect(); + // The first write is held, so every later one is still queued when the next is asked for. + let held = testing::hold_next_write(folders[0].path()); + for folder in &folders[..MAX_RECOVERY_ENTRIES] { + let queued = s.execute("file.recovery.save", &json!({"background": true, "dir": folder.path().to_string_lossy()})).unwrap(); + assert_eq!(queued["queued"], 1, "{queued}"); + } + let over = folders[MAX_RECOVERY_ENTRIES].path(); + let err = s.execute("file.recovery.save", &json!({"background": true, "dir": over.to_string_lossy()})).unwrap_err(); + assert!(err.to_string().contains("too many recovery checkpoints"), "{err}"); + // Saving cancels the queued writes: they no longer count once the document changes again. + let saved = folders[0].path().join("saved.designcraft"); + s.execute("file.saveAs", &json!({"path": saved.to_string_lossy()})).unwrap(); + s.execute("frame.create", &json!({"rect": [20, 20, 60, 60]})).unwrap(); + let queued = s.execute("file.recovery.save", &json!({"background": true, "dir": over.to_string_lossy()})).unwrap(); + assert_eq!(queued["queued"], 1, "{queued}"); + held.release(); + assert_eq!(finished_writes(&mut s), 1, "only the write queued after the save is a checkpoint"); + assert_eq!(list(over).len(), 1); + let uid = s.docs[0].uid; + for folder in &folders { + discard(folder.path(), uid); + } +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn results_for_a_session_that_is_gone_are_not_kept() { From 9cea62b2380e447342fbddc0a5ecd29b87f6be55 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:48:43 -0800 Subject: [PATCH 0958/1349] Type: a repeated alignment records no undo step; menu-bar inserts stop with the window's shortcuts - Align Left, Center, Right, Justify Left, Justify All Lines and type.align leave the document and the undo list alone when every target paragraph already has that alignment as its own value. - On the Mac, Em Space, En Space and Current Page Number from the menu bar also do nothing while Quick Apply or a dialog is open, an input method is composing or a canvas context menu is open, the cases that stop the window's own shortcuts. - Tests for both, and for Justify All Lines across threaded frames, over a paragraph style, through IDML export and import, and with parameters it does not take. --- ROADMAP.md | 3 +- crates/engine/src/cmd/text.rs | 174 ++++++++++++++++++++++++++--- crates/ui-egui/src/menus/invoke.rs | 8 +- crates/ui-egui/src/menus/keys.rs | 2 +- crates/ui-egui/src/menus/tests.rs | 27 ++++- 5 files changed, 187 insertions(+), 27 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index b5967dd01..8dc79c909 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -387,6 +387,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log +- **2026-11-12** · Type shortcuts: Justify All Lines ⇧⌘F, Insert White Space › Em Space ⇧⌘M and En Space ⇧⌘N (shown in the menu, enabled at an insertion point), Paragraph Rules… ⌥⌘J (shown in the Paragraph panel menu). On the Mac a menu-bar insert (Em/En Space, Current Page Number) no longer types into the document while a text field has focus, a dialog or Quick Apply is open, or an input method is composing. An alignment the paragraphs already have records no undo step (#1138). No readiness percentage change. - **2026-11-04** · Striped strokes retain out-and-back cubic segments whose second control point is away from the coincident endpoints and first control point. A geometry regression checks the offset extent and both stripe bands. No readiness percentage change. - **2026-11-04** · Esperanto is a text language (Character › Language, `type.char {language: "Esperanto"}`, IDML `$ID/Esperanto`): tag `eo`, English-style quotes; not hyphenated yet (#1201). No readiness percentage change. @@ -860,5 +861,3 @@ The shared craft-installer UI preserves this revision's install options and prov - **2026-10-15** · Windows recovery folders validate the identity of the live locked file without reading it through a second handle. Missing or replaced locks disable writes and cleanup; regression tests cover retained exclusive locking and replacement-file protection. No readiness percentage change. - PDF reader infrastructure: pinned shared parsing/rasterization, transformed page-box geometry and explicit failures for known incomplete layered-PDF exports. Application ownership and parity targets are unchanged. - -- **2026-10-16** · InDesign's type shortcuts: Justify All Lines ⇧⌘F, Insert White Space › Em Space ⇧⌘M and En Space ⇧⌘N (shown in the menu, enabled at an insertion point), Paragraph Rules… ⌥⌘J (shown in the Paragraph panel menu). On the Mac a menu-bar insert (Em/En Space, Current Page Number) no longer types into the document while a text field has focus. No readiness percentage change. diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index eb6e3e0b5..7f8def96c 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -2,7 +2,7 @@ use designcraft_compose as compose; use designcraft_doc::story::floor_char_boundary; -use designcraft_doc::{CellAddr, CharAttrs, Content, ItemId, ParaAttrs, Selection, StoryId, TextSel}; +use designcraft_doc::{Align, CellAddr, CharAttrs, Content, ItemId, ParaAttrs, Selection, StoryId, TextSel}; use designcraft_geom::Point; use serde_json::{Value, json}; @@ -240,21 +240,19 @@ pub fn specs() -> Vec { ), cmd!("type.align", "Align", [], None, "{align: left|center|right|leftJustified|…|null} (required)", has_text_or_frames, |s, p| { let align = p.get("align").cloned().ok_or_else(|| bad("type.align", "`align` required"))?; - format_paras(s, &json!({ "align": align })) + // A value that isn't an alignment goes to `format_paras`, which names the error. + match serde_json::from_value::>(align.clone()) { + Ok(a) => align_paras(s, a), + Err(_) => format_paras(s, &json!({ "align": align })), + } }), - cmd!("type.alignLeft", "Align Left", [], Some("Cmd+Shift+L"), "{}", has_text_or_frames, |s, _| format_paras(s, &json!({"align": "left"}))), - cmd!("type.alignCenter", "Align Center", [], Some("Cmd+Shift+C"), "{}", has_text_or_frames, |s, _| format_paras( + cmd!("type.alignLeft", "Align Left", [], Some("Cmd+Shift+L"), "{}", has_text_or_frames, |s, _| align_paras(s, Some(Align::Left))), + cmd!("type.alignCenter", "Align Center", [], Some("Cmd+Shift+C"), "{}", has_text_or_frames, |s, _| align_paras(s, Some(Align::Center))), + cmd!("type.alignRight", "Align Right", [], Some("Cmd+Shift+R"), "{}", has_text_or_frames, |s, _| align_paras(s, Some(Align::Right))), + cmd!("type.justify", "Justify Left", [], Some("Cmd+Shift+J"), "{}", has_text_or_frames, |s, _| align_paras(s, Some(Align::LeftJustified))), + cmd!("type.justifyAll", "Justify all lines", [], Some("Cmd+Shift+F"), "{}", has_text_or_frames, |s, _| align_paras( s, - &json!({"align": "center"}) - )), - cmd!("type.alignRight", "Align Right", [], Some("Cmd+Shift+R"), "{}", has_text_or_frames, |s, _| format_paras(s, &json!({"align": "right"}))), - cmd!("type.justify", "Justify Left", [], Some("Cmd+Shift+J"), "{}", has_text_or_frames, |s, _| format_paras( - s, - &json!({"align": "leftJustified"}) - )), - cmd!("type.justifyAll", "Justify all lines", [], Some("Cmd+Shift+F"), "{}", has_text_or_frames, |s, _| format_paras( - s, - &json!({"align": "fullyJustified"}) + Some(Align::FullyJustified) )), cmd!( "type.bold", @@ -448,24 +446,164 @@ pub fn specs() -> Vec { ] } +/// Sets the alignment of the paragraphs a formatting command targets (`None` removes the +/// override, back to the style's value). When each of them already carries that value as its +/// own, or there is no paragraph to change, the document is left as it is and no undo step is +/// recorded. +fn align_paras(s: &mut Session, align: Option) -> Result { + let targets = format_targets(s); + let doc = &s.doc()?.doc; + let unchanged = targets.iter().all(|t| { + doc.text_story(t.story, t.cell).is_none_or(|st| { + let (a, b) = (st.para_at(t.range.start), st.para_at(t.range.end.max(t.range.start))); + st.paras.get(a..=b).is_none_or(|paras| paras.iter().all(|p| p.para.align == align)) + }) + }); + if unchanged { + return ok(); + } + format_paras(s, &json!({ "align": align })) +} + #[cfg(test)] mod alignment_shortcut_tests { - use serde_json::json; + use designcraft_doc::{Align, Document}; + use serde_json::{Value, json}; use crate::Session; - /// InDesign's Justify All Lines is ⇧⌘F (Shift+Ctrl+F), next to Justify Left ⇧⌘J. + fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() + } + + fn selection_align(s: &mut Session) -> Value { + s.execute("type.selectionAttrs", &json!({})).unwrap()["para"]["align"].clone() + } + + /// The resolved alignment of every paragraph of the story whose text starts with `start`. + fn story_aligns(d: &Document, start: &str) -> Vec { + let st = d.stories.values().find(|st| st.text.starts_with(start)).unwrap(); + st.paras.iter().map(|p| d.styles.resolve_para(p).0.align).collect() + } + + /// Justify All Lines is ⇧⌘F (Shift+Ctrl+F), next to Justify Left ⇧⌘J. #[test] - fn justify_all_lines_has_indesigns_shortcut_and_justifies_the_last_line_too() { + fn justify_all_lines_has_its_shortcut_and_justifies_the_last_line_too() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Spring issue"})).unwrap(); s.execute("text.select", &json!({"story": r["story"], "anchor": 3, "focus": 3})).unwrap(); - // From Justify Left, so the result is not a default or a neighbouring justification. + // From Justify Left, so the result is not a default or a neighboring justification. s.execute("type.justify", &json!({})).unwrap(); assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["para"]["align"], "leftJustified"); s.execute("type.justifyAll", &json!({})).unwrap(); assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["para"]["align"], "fullyJustified"); assert_eq!(crate::find_command("type.justifyAll").and_then(|c| c.shortcut), Some("Cmd+Shift+F")); } + + /// A second press of an alignment shortcut, or `type.align` with the value the paragraphs + /// already have, leaves the document and the undo list alone. + #[test] + fn an_alignment_the_paragraphs_already_have_records_no_undo_step() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "One\nTwo"})).unwrap(); + s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 5})).unwrap(); + for (id, params, align) in [ + ("type.justifyAll", json!({}), "fullyJustified"), + ("type.align", json!({"align": "center"}), "center"), + ("type.alignLeft", json!({}), "left"), + ("type.alignCenter", json!({}), "center"), + ("type.alignRight", json!({}), "right"), + ("type.justify", json!({}), "leftJustified"), + ] { + let before = undo_steps(&s); + s.execute(id, ¶ms).unwrap(); + assert_eq!(selection_align(&mut s), align, "{id}"); + assert_eq!(undo_steps(&s), before + 1, "{id}: one step"); + let rev = s.doc().unwrap().doc.clone(); + s.execute(id, ¶ms).unwrap(); + assert_eq!(undo_steps(&s), before + 1, "{id} again: no step"); + assert!(std::sync::Arc::ptr_eq(&rev, &s.doc().unwrap().doc), "{id} again: the document is unchanged"); + } + // Removing the override: once it is gone, a second removal does nothing. + s.execute("type.align", &json!({"align": null})).unwrap(); + let before = undo_steps(&s); + s.execute("type.align", &json!({"align": null})).unwrap(); + assert_eq!(undo_steps(&s), before); + // One paragraph that differs is enough to apply it, to both. + s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap(); + s.execute("type.justifyAll", &json!({})).unwrap(); + s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 5})).unwrap(); + let before = undo_steps(&s); + s.execute("type.justifyAll", &json!({})).unwrap(); + assert_eq!(undo_steps(&s), before + 1); + assert_eq!(story_aligns(&s.doc().unwrap().doc, "One"), [Align::FullyJustified; 2]); + } + + /// The shortcut commands take no parameters: a misspelled call is refused and changes nothing. + #[test] + fn justify_all_lines_refuses_parameters() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Spring"})).unwrap(); + s.execute("text.select", &json!({"story": r["story"], "anchor": 1, "focus": 1})).unwrap(); + let before = undo_steps(&s); + assert!(s.execute("type.justifyAll", &json!({"align": "left"})).is_err()); + assert_eq!(selection_align(&mut s), "left"); + assert_eq!(undo_steps(&s), before); + } + + /// With text frames selected, every paragraph of their stories, across threaded frames; + /// other selected frames are skipped, and a selection with no text frame is refused. + #[test] + fn justify_all_lines_on_frames_reaches_threaded_text_and_skips_other_frames() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let a = s.execute("frame.create", &json!({"rect": [36, 36, 300, 60], "content": "text", "text": "Alpha\nBeta\nGamma\nDelta"})).unwrap(); + let b = s.execute("frame.create", &json!({"rect": [36, 300, 300, 500], "content": "text"})).unwrap(); + s.execute("text.thread", &json!({"from": a["id"], "to": b["id"]})).unwrap(); + let rect = s.execute("frame.create", &json!({"rect": [400, 36, 500, 136]})).unwrap(); + s.execute("selection.set", &json!({"ids": [rect["id"]]})).unwrap(); + let before = undo_steps(&s); + assert!(s.execute("type.justifyAll", &json!({})).is_err(), "no text frame selected"); + assert_eq!(undo_steps(&s), before); + // The second frame of the thread and the rectangle. + s.execute("selection.set", &json!({"ids": [b["id"], rect["id"]]})).unwrap(); + s.execute("type.justifyAll", &json!({})).unwrap(); + assert_eq!(undo_steps(&s), before + 1); + assert_eq!(story_aligns(&s.doc().unwrap().doc, "Alpha"), [Align::FullyJustified; 4]); + } + + /// Over a paragraph style's alignment, Justify All Lines is a local override: the style keeps + /// its value, and removing the override goes back to it. + #[test] + fn justify_all_lines_overrides_the_paragraph_style() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Spring issue"})).unwrap(); + s.execute("text.select", &json!({"story": r["story"], "anchor": 2, "focus": 2})).unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Caption", "para": {"align": "right"}})).unwrap(); + s.execute("style.paragraph.apply", &json!({"name": "Caption"})).unwrap(); + assert_eq!(selection_align(&mut s), "right"); + s.execute("type.justifyAll", &json!({})).unwrap(); + assert_eq!(selection_align(&mut s), "fullyJustified"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.styles.resolve_para_style("Caption").0.align, Align::Right); + s.execute("type.align", &json!({"align": null})).unwrap(); + assert_eq!(selection_align(&mut s), "right"); + } + + /// IDML writes the paragraph's Justification as FullyJustified and reads it back. + #[test] + fn justify_all_lines_survives_idml_export_and_import() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Spring\nissue"})).unwrap(); + s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap(); + s.execute("type.justifyAll", &json!({})).unwrap(); + let bytes = designcraft_idml::export_idml(&s.doc().unwrap().doc); + s.execute("file.openIdml", &json!({"base64": crate::cmd::base64_encode(&bytes), "name": "in.idml"})).unwrap(); + assert_eq!(story_aligns(&s.doc().unwrap().doc, "Spring"), [Align::FullyJustified, Align::Left]); + } } diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 33096849d..492cdc7e2 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -146,9 +146,11 @@ pub fn activate_native(app: &mut DesignApp, ctx: &egui::Context, id: &str, param if params.is_null() && ctx.text_edit_focused() && forward_to_text_edit(app, ctx, id) { return; } - // The menu bar takes ⇧⌘M before the window: with a field focused (Story Editor, Find/Change) - // or a dialog open, the character would land at the canvas caret behind it. - if params.is_null() && (ctx.text_edit_focused() || app.ui.dialog.is_some()) && TEXT_INSERTS.contains(&id) { + // The menu bar takes ⇧⌘M before the window: with a field focused (Story Editor, Find/Change), + // a dialog or Quick Apply open, an input method composing or a context menu open, the + // character would land at the canvas caret behind it. The window's shortcuts stop for the + // same cases. + if params.is_null() && (ctx.text_edit_focused() || super::keys::keys_taken(app, ctx)) && TEXT_INSERTS.contains(&id) { return; } // The canvas text editor is not an egui TextEdit, so its clipboard events must pass through diff --git a/crates/ui-egui/src/menus/keys.rs b/crates/ui-egui/src/menus/keys.rs index 8b2179469..a4cf59eed 100644 --- a/crates/ui-egui/src/menus/keys.rs +++ b/crates/ui-egui/src/menus/keys.rs @@ -66,7 +66,7 @@ pub fn forwarded_shortcuts(app: &mut DesignApp, ctx: &egui::Context, events: Vec /// Whether something other than the shortcuts has the keyboard: a dialog or Quick Apply, an input /// method composing at the text caret, an open canvas context menu (Escape closes it, as a /// native menu would) or the menu search. -fn keys_taken(app: &DesignApp, ctx: &egui::Context) -> bool { +pub(super) fn keys_taken(app: &DesignApp, ctx: &egui::Context) -> bool { app.ui.dialog.is_some() || app.ui.palette.is_some() || app.session.tool_composing() diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 5958bcd4d..24ccb02a0 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -2499,14 +2499,14 @@ fn story_text(app: &crate::DesignApp, story: &Value) -> String { } #[test] -fn indesigns_type_shortcuts_insert_spaces_justify_all_lines_and_open_paragraph_rules() { +fn type_shortcuts_insert_spaces_justify_all_lines_and_open_paragraph_rules() { use egui::{Key, Modifiers}; let ctx = egui::Context::default(); let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({})).unwrap(); let frame = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text", "text": "ab"})).unwrap(); let story = frame["story"].clone(); - // A selected frame and no insertion point: the spaces have nowhere to go, as in InDesign. + // A selected frame and no insertion point: the spaces have nowhere to go. app.run("selection.set", json!({"ids": [frame["id"]]})).unwrap(); assert!(app.session.doc().unwrap().selection.text.is_none()); assert!(!menu_enabled(&app, "app.insertEmSpace") && !menu_enabled(&app, "app.insertEnSpace")); @@ -2521,7 +2521,7 @@ fn indesigns_type_shortcuts_insert_spaces_justify_all_lines_and_open_paragraph_r app.run("type.justify", json!({})).unwrap(); press(&mut app, &ctx, Key::F, Modifiers::COMMAND | Modifiers::SHIFT); assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["align"], "fullyJustified", "⇧⌘F justifies all lines"); - // Guard: ⌥⇧⌘J is another chord (InDesign's Justification…); the rules want Shift up. + // Guard: ⌥⇧⌘J is another chord (Justification…); the rules want Shift up. press(&mut app, &ctx, Key::J, Modifiers::COMMAND | Modifiers::ALT | Modifiers::SHIFT); assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("justification"), "⌥⇧⌘J opens Justification"); app.ui.dialog = None; @@ -2581,6 +2581,27 @@ fn native_insert_shortcuts_leave_the_document_alone_while_a_field_has_focus() { assert_eq!(app.ui.palette.as_deref(), Some("x")); } +#[test] +fn native_insert_shortcuts_leave_the_document_alone_while_a_dialog_or_quick_apply_is_open() { + // The same cases stop the window's shortcuts. In the first frame nothing has keyboard focus + // yet, so only the open dialog or Quick Apply keeps the character out of the story. + for open in ["", "dialog", "palette"] { + let ctx = egui::Context::default(); + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let story = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text", "text": "ab"})).unwrap()["story"].clone(); + app.run("text.select", json!({"story": story, "anchor": 1, "focus": 1})).unwrap(); + match open { + "dialog" => app.ui.dialog = Some(crate::dialogs::Dialog::new("paragraphRules", json!({}))), + "palette" => app.ui.palette = Some(String::new()), + _ => {} + } + native_frame(&mut app, &ctx, vec![], Some("app.insertEmSpace")); + let want = if open.is_empty() { "a\u{2003}b" } else { "ab" }; + assert_eq!(story_text(&app, &story), want, "{open:?}"); + } +} + #[test] fn custom_workspaces_save_apply_and_delete() { let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); From 630b5dfc43d32b15181afaee13a2bf6b95dd7cd0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:50:24 -0800 Subject: [PATCH 0959/1349] Paste: images on the system clipboard paste as embedded images (#2204) Paste ignored a bitmap on the system clipboard: a screenshot or an image copied in a browser had to be saved and placed. Paste now places it. - edit.pasteImage {base64, name?, spread?, at?} embeds the image in the selected empty frame, or in a new frame centered on `at` at its stored resolution (72 ppi when none) and at most 60% of the page width, as File > Place sizes it. Save and reopen and IDML export keep the pixels. Images over 64 million pixels and names without an image extension are refused. - Ctrl/Cmd+V pastes the image egui delivers with no text, and Edit > Paste reads the clipboard's bitmap, or the first image file of a copied file list, when there is no text or the text is only an address. - The menu read waits at most 1.5 s on its own thread, with one read in flight at a time. - With a native menu, objects copied here still paste as objects until the pasteboard's change count shows a newer copy. - ui.paste takes {image} for the control channel. --- apps/designcraft/Cargo.toml | 8 +- apps/designcraft/src/clipboard_image.rs | 135 +++++++++++++ apps/designcraft/src/main.rs | 4 + crates/engine/src/cmd.rs | 3 + crates/engine/src/cmd/paste_image.rs | 251 ++++++++++++++++++++++++ crates/images/src/lib.rs | 9 + crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/app/clipboard.rs | 89 ++++++++- crates/ui-egui/src/app/commands.rs | 12 +- crates/ui-egui/src/canvas/input.rs | 16 +- crates/ui-egui/src/canvas/tests.rs | 121 ++++++++++++ crates/ui-egui/src/control.rs | 21 +- crates/ui-egui/src/lib.rs | 8 +- crates/ui-egui/src/services.rs | 33 ++++ docs/control-protocol.md | 2 +- 15 files changed, 694 insertions(+), 19 deletions(-) create mode 100644 apps/designcraft/src/clipboard_image.rs create mode 100644 crates/engine/src/cmd/paste_image.rs diff --git a/apps/designcraft/Cargo.toml b/apps/designcraft/Cargo.toml index b17258acd..b66041a04 100644 --- a/apps/designcraft/Cargo.toml +++ b/apps/designcraft/Cargo.toml @@ -27,7 +27,8 @@ winresource = "0.1" # Not called here: craft-dialogs shows the dialogs. rfd's default features keep its Wayland # support on, so portal dialogs get the window as their parent. rfd = { workspace = true } -arboard = { workspace = true } +# `image-data`: Edit › Paste reads bitmaps from the clipboard (src/clipboard_image.rs). +arboard = { workspace = true, features = ["image-data"] } [target.'cfg(all(unix, not(target_os = "macos")))'.dependencies] # The same winit eframe uses: to pick the X11 backend (file drag-and-drop) in main.rs. @@ -46,9 +47,10 @@ winsafe = { version = "0.0.29", default-features = false, features = ["user"] } winit = { version = "0.30", default-features = false } muda = { version = "0.21", default-features = false } # The input context, to drop the IME's marked text when the Type tool ends a composition. The -# versions muda uses, through safe methods. +# versions muda uses, through safe methods. `NSPasteboard`: the pasteboard's change count, which +# tells Paste whether anything was copied since an object Copy (src/clipboard_image.rs). objc2 = "0.6" -objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSEvent", "NSResponder", "NSScreen", "NSTextInputContext"] } +objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSEvent", "NSPasteboard", "NSResponder", "NSScreen", "NSTextInputContext"] } # Files dragged in from the Finder: the pointer's place on the screen (src/pointer.rs). objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSGeometry"] } # The window's `movable` flag follows the application bar's controls. diff --git a/apps/designcraft/src/clipboard_image.rs b/apps/designcraft/src/clipboard_image.rs new file mode 100644 index 000000000..0e8339ff4 --- /dev/null +++ b/apps/designcraft/src/clipboard_image.rs @@ -0,0 +1,135 @@ +//! The system clipboard's image for Edit › Paste (`Services::clipboard_image`): a bitmap +//! (Windows `CF_DIBV5` or `PNG`, the macOS pasteboard's TIFF or PNG, `image/png` on X11), else the +//! first image file of files copied in a file manager. The read runs on its own thread, and Paste +//! waits for it at most [`WAIT`], so an application that is slow to hand over the clipboard does +//! not freeze the window. While a read that timed out is still waiting, Paste starts no other. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc; +use std::time::Duration; + +use designcraft_ui_egui::ClipboardImage; + +/// How long Paste waits for the clipboard's image. +const WAIT: Duration = Duration::from_millis(1500); + +/// The largest image file Paste reads from a copied file list, in bytes. +const MAX_FILE_BYTES: u64 = 256 << 20; + +/// A clipboard read is running. +static READING: AtomicBool = AtomicBool::new(false); + +/// The clipboard's image, or `None` when it holds none or does not answer within [`WAIT`]. +pub fn read() -> Option { + within(&READING, WAIT, read_now) +} + +/// Clears the in-flight flag when the read's thread ends. +struct Reading(&'static AtomicBool); + +impl Drop for Reading { + fn drop(&mut self) { + self.0.store(false, Ordering::Release); + } +} + +/// `read`'s result when it arrives within `wait`. A read that takes longer finishes on its own +/// thread and is dropped; until it does, `busy` stays set and no other read starts. +fn within(busy: &'static AtomicBool, wait: Duration, read: impl FnOnce() -> Option + Send + 'static) -> Option { + if busy.swap(true, Ordering::AcqRel) { + log::warn!("clipboard image: the previous read has not finished"); + return None; + } + let (tx, rx) = mpsc::channel(); + let spawned = std::thread::Builder::new().name("clipboard image".into()).spawn(move || { + let _reading = Reading(busy); + let _ = tx.send(read()); + }); + if let Err(e) = spawned { + busy.store(false, Ordering::Release); + log::warn!("clipboard image: no thread to read it: {e}"); + return None; + } + match rx.recv_timeout(wait) { + Ok(image) => image, + Err(mpsc::RecvTimeoutError::Timeout) => { + log::warn!("clipboard image: the clipboard did not answer within {} ms", wait.as_millis()); + None + } + Err(mpsc::RecvTimeoutError::Disconnected) => None, + } +} + +/// The general pasteboard's change count, which AppKit raises with every copy. +#[cfg(target_os = "macos")] +pub fn change_count() -> Option { + i64::try_from(objc2_app_kit::NSPasteboard::generalPasteboard().changeCount()).ok() +} + +fn read_now() -> Option { + let mut clipboard = arboard::Clipboard::new().ok()?; + if let Ok(image) = clipboard.get_image() { + let width = u32::try_from(image.width).ok()?; + let height = u32::try_from(image.height).ok()?; + return Some(ClipboardImage::Pixels { width, height, rgba: image.bytes.into_owned() }); + } + first_image_file(&clipboard.get().file_list().ok()?) +} + +/// The first of `paths` that is an image file no larger than [`MAX_FILE_BYTES`], with its name. +fn first_image_file(paths: &[PathBuf]) -> Option { + paths.iter().find_map(|path| { + let ext = path.extension()?.to_str()?.to_ascii_lowercase(); + if !designcraft_engine::cmd::IMAGE_EXTENSIONS.contains(&ext.as_str()) || std::fs::metadata(path).ok()?.len() > MAX_FILE_BYTES { + return None; + } + // At most one byte past the limit is read, should the file grow after the size check. + let bytes = designcraft_engine::io::read_capped(path, MAX_FILE_BYTES).ok().filter(|b| b.len() as u64 <= MAX_FILE_BYTES)?; + Some(ClipboardImage::File { name: file_name(path), bytes }) + }) +} + +fn file_name(path: &Path) -> String { + path.file_name().map_or_else(|| path.to_string_lossy().into_owned(), |n| n.to_string_lossy().into_owned()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_read_that_does_not_answer_is_given_up_and_no_second_one_starts_meanwhile() { + static BUSY: AtomicBool = AtomicBool::new(false); + let (release, blocked) = mpsc::channel::<()>(); + // The read waits for a message that is only sent after Paste has given up on it. + assert_eq!(within(&BUSY, Duration::ZERO, move || blocked.recv().ok().map(|()| 1)), None); + let (started, ran) = mpsc::channel::<()>(); + let second = within(&BUSY, Duration::from_secs(60), move || started.send(()).ok().map(|()| 2)); + assert_eq!(second, None, "refused while the first read waits"); + assert!(ran.try_recv().is_err(), "the second read never ran"); + let _ = release.send(()); + while BUSY.load(Ordering::Acquire) { + std::thread::yield_now(); + } + assert_eq!(within(&BUSY, Duration::from_secs(60), || Some(3)), Some(3), "an answer is taken as soon as it comes"); + } + + #[test] + fn a_copied_file_list_pastes_its_first_image_file() { + let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let dir = std::env::temp_dir().join(format!("designcraft-clipboard-files-{}-{stamp}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + let (text, missing, png) = (dir.join("notes.txt"), dir.join("gone.png"), dir.join("Photo.PNG")); + std::fs::write(&text, b"text").unwrap(); + std::fs::write(&png, b"png bytes").unwrap(); + let picked = first_image_file(&[text, missing, png.clone()]); + let none = first_image_file(&[dir.join("a.txt")]); + let _ = std::fs::remove_dir_all(&dir); + match picked { + Some(ClipboardImage::File { name, bytes }) => assert_eq!((name.as_str(), bytes.as_slice()), ("Photo.PNG", b"png bytes".as_slice())), + _ => panic!("the image file is picked"), + } + assert!(none.is_none()); + } +} diff --git a/apps/designcraft/src/main.rs b/apps/designcraft/src/main.rs index ab6970332..5f465e46d 100644 --- a/apps/designcraft/src/main.rs +++ b/apps/designcraft/src/main.rs @@ -15,6 +15,7 @@ #[cfg(target_os = "macos")] mod apple_events; +mod clipboard_image; mod control_server; mod gpu; mod gpu_limits; @@ -227,6 +228,9 @@ fn services() -> Services { read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))), write: Some(Box::new(|p: &str, b: &[u8]| designcraft_engine::atomic::write_atomic(std::path::Path::new(p), b).map_err(|e| e.to_string()))), clipboard_text: Some(Box::new(|| arboard::Clipboard::new().and_then(|mut c| c.get_text()).ok())), + clipboard_image: Some(Box::new(clipboard_image::read)), + #[cfg(target_os = "macos")] + clipboard_change: Some(Box::new(clipboard_image::change_count)), #[cfg(target_os = "macos")] pointer: Some(Box::new(pointer::screen_position)), ..Default::default() diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index dc1acaf15..20260a5ad 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -44,6 +44,7 @@ mod object; mod overrides; mod package; pub mod params; +mod paste_image; mod paste_svg; mod path_type; mod paths; @@ -179,6 +180,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(export::specs()); v.extend(export_batch::specs()); v.extend(edit::specs()); + v.extend(paste_image::specs()); v.extend(paste_svg::specs()); v.extend(endnotes::specs()); v.extend(editorial::specs()); @@ -376,5 +378,6 @@ pub use file::{ DOCUMENT_SNIFF_BYTES, RecentPreview, base64_decode, base64_encode, from_bytes, is_document, recent_preview, to_bytes, with_document_extension, }; pub use layout::chapter_numbering; +pub use paste_image::{IMAGE_EXTENSIONS, MAX_PASTED_PIXELS, PASTED_IMAGE_NAME, check_pasted_size, pasted_pixels, pasted_png}; pub use paste_svg::is_svg_markup; pub(crate) use place_text::autoflow as place_text_autoflow; diff --git a/crates/engine/src/cmd/paste_image.rs b/crates/engine/src/cmd/paste_image.rs new file mode 100644 index 000000000..d5197a90c --- /dev/null +++ b/crates/engine/src/cmd/paste_image.rs @@ -0,0 +1,251 @@ +//! Paste a bitmap from the system clipboard (a screenshot, an image copied in a web browser or an +//! image editor, an image file copied in a file manager) as a placed image. The pixels are +//! embedded in the document, so a save and reopen or an IDML export keeps them. + +use designcraft_doc::Content; +use designcraft_geom::Point; +use serde_json::{Value, json}; + +use super::{CommandSpec, Result, Session, bad, cmd, has_doc, spread_param}; + +const ID: &str = "edit.pasteImage"; + +/// The most pixels a pasted image may have (8,000 × 8,000). +pub const MAX_PASTED_PIXELS: u64 = 64_000_000; + +/// The largest pasted image file, in bytes. +const MAX_PASTED_BYTES: usize = 256 << 20; + +/// The extensions a pasted image's name may end in. +pub const IMAGE_EXTENSIONS: [&str; 8] = ["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp"]; + +/// The name a pasted bitmap gets in the Links panel when it comes with none. +pub const PASTED_IMAGE_NAME: &str = "Pasted image.png"; + +pub fn specs() -> Vec { + vec![cmd!( + "edit.pasteImage", + "Paste Image", + [], + None, + "{base64: an image file (PNG/JPEG/GIF/WebP/TIFF/BMP) as base64, name?: its name in the Links panel ending in an image extension (default \"Pasted image.png\"), spread?, at?: [x, y] (spread coords of the image's center; default the first page's center)} → {id, asset} — embedded; a selected empty frame takes the image, otherwise a new frame holds it at its stored resolution (72 ppi when none) and at most 60% of the page width", + has_doc, + paste_image + )] +} + +/// Whether a `width × height` bitmap is small enough to paste; the error says why not. +pub fn check_pasted_size(width: u32, height: u32) -> std::result::Result<(), String> { + if width == 0 || height == 0 { + return Err("the image on the clipboard has no pixels".into()); + } + if u64::from(width) * u64::from(height) > MAX_PASTED_PIXELS { + return Err(format!( + "the image on the clipboard is {width} × {height} pixels; images of up to 64 million pixels can be pasted (save it and use File › Place)" + )); + } + Ok(()) +} + +/// Unpremultiplied RGBA pixels from the clipboard, rows top to bottom, as a PNG file for +/// [`edit.pasteImage`](specs). +pub fn pasted_png(width: u32, height: u32, rgba: Vec) -> std::result::Result, String> { + check_pasted_size(width, height)?; + if (rgba.len() as u64) != u64::from(width) * u64::from(height) * 4 { + return Err("the image on the clipboard has the wrong number of pixels".into()); + } + designcraft_images::png_from_rgba(width, height, rgba).ok_or_else(|| "the image on the clipboard can't be stored".to_string()) +} + +/// An image file's pixels: (width, height, unpremultiplied RGBA). `None` when it is not a raster +/// DesignCraft reads or has more pixels than [`MAX_PASTED_PIXELS`]. +pub fn pasted_pixels(bytes: &[u8]) -> Option<(u32, u32, Vec)> { + let (w, h) = raster_size(bytes)?; + check_pasted_size(w, h).ok()?; + let img = designcraft_images::decode_rgba(bytes)?; + Some((img.width(), img.height(), img.into_raw())) +} + +/// A raster's pixel size; `None` for vector formats (PDF, SVG, EPS) and unreadable data. +fn raster_size(bytes: &[u8]) -> Option<(u32, u32)> { + if designcraft_images::is_pdf(bytes) || designcraft_images::is_svg(bytes) || designcraft_images::is_eps(bytes) { + return None; + } + designcraft_images::pixel_size(bytes) +} + +fn paste_image(s: &mut Session, p: &Value) -> Result { + let b64 = match p.get("base64") { + Some(Value::String(b)) if !b.is_empty() => b, + Some(_) => return Err(bad(ID, "`base64` must be a non-empty string")), + None => return Err(bad(ID, "missing base64")), + }; + if b64.len() / 4 * 3 > MAX_PASTED_BYTES { + return Err(bad(ID, format!("the image is larger than {} MB", MAX_PASTED_BYTES >> 20))); + } + let name = match p.get("name") { + None | Some(Value::Null) => PASTED_IMAGE_NAME, + Some(Value::String(n)) if !n.trim().is_empty() => n.as_str(), + Some(_) => return Err(bad(ID, "`name` must be a non-empty string")), + }; + // File › Place picks text and layout import by the name's extension: keep it an image's. + let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default(); + if !IMAGE_EXTENSIONS.contains(&ext.as_str()) { + return Err(bad(ID, format!("`name` must end in an image extension ({})", IMAGE_EXTENSIONS.join(", ")))); + } + let bytes = super::base64_decode(b64); + let (pw, ph) = raster_size(&bytes).ok_or_else(|| bad(ID, "the clipboard doesn't hold an image DesignCraft can read"))?; + check_pasted_size(pw, ph).map_err(|e| bad(ID, e))?; + let sr = spread_param(p, ID)?; + let at = match p.get("at") { + None | Some(Value::Null) => None, + Some(_) => { + let at = super::point_param(p, "at").ok_or_else(|| bad(ID, "`at` must be [x, y]"))?; + if !(at.x.is_finite() && at.y.is_finite()) { + return Err(bad(ID, "`at` must be finite")); + } + Some(at) + } + }; + // A selected empty frame takes the image, as File › Place fills it. + let st = s.doc()?; + let empty_frame = match st.selection.items.as_slice() { + [only] if st.doc.item(*only).is_some_and(|it| !it.locked && it.path.encloses_area() && matches!(it.content, Content::Unassigned)) => { + Some(only.0) + } + _ => None, + }; + if let Some(frame) = empty_frame { + return s.execute("file.place", &json!({"base64": b64, "name": name, "frame": frame})); + } + let d = &s.doc()?.doc; + let sp = d.spread(sr).ok_or_else(|| bad(ID, "no such spread"))?; + let center = match at { + Some(at) => at, + None => sp.pages.first().map_or(Point::ZERO, |pg| pg.bounds().center()), + }; + // The size File › Place gives it: the stored resolution (72 ppi when none), at most 60% of + // the page width. + let (nw, nh) = designcraft_render::natural_size(&bytes, 0).unwrap_or((f64::from(pw), f64::from(ph))); + let w = nw.min(d.settings.page_width * 0.6); + let h = nh * w / nw; + let spread = p.get("spread").cloned().unwrap_or(Value::Null); + s.execute("file.place", &json!({"base64": b64, "name": name, "spread": spread, "x": center.x - w / 2.0, "y": center.y - h / 2.0})) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::cmd::{base64_decode, base64_encode}; + use designcraft_doc::{ItemId, SpreadRef}; + + /// A `w × h` PNG whose pixels count up, so a changed pixel shows. + fn png(w: u32, h: u32) -> Vec { + let rgba: Vec = (0..w * h * 4).map(|i| (i % 251) as u8).collect(); + pasted_png(w, h, rgba).unwrap() + } + + fn doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s + } + + fn placed_png(s: &Session, id: ItemId) -> Vec { + let d = &s.doc().unwrap().doc; + let Content::Graphic(g) = &d.item(id).unwrap().content else { panic!("not a graphic") }; + let a = &d.assets[&g.asset]; + assert_eq!(a.link, None, "embedded, not linked"); + a.data.to_vec() + } + + #[test] + fn a_pasted_bitmap_is_embedded_at_the_center_and_kept_by_save_and_idml() { + let mut s = doc(); + let png = png(40, 30); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute(ID, &json!({"base64": base64_encode(&png), "at": [300, 400]})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + let id = ItemId(r["id"].as_u64().unwrap()); + let st = s.doc().unwrap(); + assert_eq!(st.selection.items, [id], "the pasted image is selected"); + let b = st.doc.item(id).unwrap().bounds(); + assert!( + (b.x0 - 280.0).abs() < 1e-9 && (b.y0 - 385.0).abs() < 1e-9 && (b.width() - 40.0).abs() < 1e-9 && (b.height() - 30.0).abs() < 1e-9, + "{b:?}" + ); + assert_eq!(placed_png(&s, id), png); + assert_eq!(s.doc().unwrap().doc.assets[&designcraft_doc::AssetId(r["asset"].as_u64().unwrap())].name, PASTED_IMAGE_NAME); + + let saved = s.execute("file.serialize", &json!({})).unwrap(); + let mut t = Session::new(); + t.execute("file.openBytes", &json!({"name": "a.designcraft", "base64": saved["base64"]})).unwrap(); + assert_eq!(placed_png(&t, id), png, "saved with the document"); + + let idml = s.execute("file.exportIdml", &json!({})).unwrap(); + let imported = designcraft_idml::import_idml(&base64_decode(idml["base64"].as_str().unwrap())).unwrap(); + assert!(imported.assets.values().any(|a| *a.data == png), "the IDML package carries the pixels"); + } + + #[test] + fn without_a_point_the_image_lands_in_the_middle_of_the_first_page_and_shrinks_to_the_page() { + let mut s = doc(); + let r = s.execute(ID, &json!({"base64": base64_encode(&png(1000, 10))})).unwrap(); + let d = &s.doc().unwrap().doc; + let b = d.item(ItemId(r["id"].as_u64().unwrap())).unwrap().bounds(); + let page = d.spread(SpreadRef::Doc(0)).unwrap().pages[0].bounds(); + let w = d.settings.page_width * 0.6; + assert!((b.width() - w).abs() < 1e-9 && (b.height() - w / 100.0).abs() < 1e-9, "{b:?}"); + assert!((b.center().x - page.center().x).abs() < 1e-9 && (b.center().y - page.center().y).abs() < 1e-9, "{b:?}"); + } + + #[test] + fn a_selected_empty_frame_takes_the_image() { + let mut s = doc(); + let frame = s.execute("frame.create", &json!({"rect": [100, 100, 200, 300]})).unwrap()["id"].as_u64().unwrap(); + s.execute("selection.set", &json!({"ids": [frame]})).unwrap(); + let items = s.doc().unwrap().doc.spreads[0].items.len(); + let r = s.execute(ID, &json!({"base64": base64_encode(&png(10, 10)), "at": [500, 500]})).unwrap(); + assert_eq!(r["id"].as_u64(), Some(frame)); + assert_eq!(s.doc().unwrap().doc.spreads[0].items.len(), items, "no new frame"); + // A frame that already holds a graphic gets a new frame beside it instead. + let r = s.execute(ID, &json!({"base64": base64_encode(&png(10, 10)), "at": [500, 500]})).unwrap(); + assert_ne!(r["id"].as_u64(), Some(frame)); + assert_eq!(s.doc().unwrap().doc.spreads[0].items.len(), items + 1); + } + + #[test] + fn bad_input_is_refused_and_leaves_no_undo_step() { + let mut s = doc(); + let ok = base64_encode(&png(2, 2)); + let undo = s.doc().unwrap().history.undo.len(); + for (p, want) in [ + (json!({}), "missing base64"), + (json!({"base64": 5}), "`base64` must be a non-empty string"), + (json!({"base64": ""}), "`base64` must be a non-empty string"), + (json!({"base64": base64_encode(b"just text")}), "doesn't hold an image"), + (json!({"base64": base64_encode(b"")}), "doesn't hold an image"), + (json!({"base64": ok, "name": ""}), "`name` must be a non-empty string"), + (json!({"base64": ok, "name": 3}), "`name` must be a non-empty string"), + (json!({"base64": ok, "name": "notes.txt"}), "`name` must end in an image extension"), + (json!({"base64": ok, "name": "page.idml"}), "`name` must end in an image extension"), + (json!({"base64": ok, "name": "png"}), "`name` must end in an image extension"), + (json!({"base64": ok, "at": [1]}), "`at` must be [x, y]"), + (json!({"base64": ok, "spread": 9}), "no such spread"), + ] { + let e = s.execute(ID, &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + } + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed"); + } + + #[test] + fn images_beyond_the_pixel_limit_are_refused_before_they_are_encoded() { + let e = pasted_png(9000, 8000, Vec::new()).unwrap_err(); + assert!(e.contains("9000 × 8000 pixels") && e.contains("64 million"), "{e}"); + assert!(pasted_png(0, 5, Vec::new()).is_err()); + assert!(pasted_png(2, 2, vec![0; 15]).unwrap_err().contains("wrong number of pixels")); + assert_eq!(pasted_pixels(&png(3, 2)).map(|(w, h, px)| (w, h, px.len())), Some((3, 2, 24))); + assert_eq!(pasted_pixels(b"%PDF-1.4"), None, "vector files are not pasted as pixels"); + } +} diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 83c540e6e..02f978b6a 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -373,6 +373,15 @@ pub fn natural_size(bytes: &[u8]) -> Option<(f64, f64)> { Some((w as f64, h as f64)) } +/// Unpremultiplied RGBA pixels, rows top to bottom, as a PNG file with no resolution stored. +/// `None` when `rgba` doesn't hold exactly `width × height` pixels. +pub fn png_from_rgba(width: u32, height: u32, rgba: Vec) -> Option> { + let img = image::RgbaImage::from_raw(width, height, rgba)?; + let mut png = Vec::new(); + image::DynamicImage::ImageRgba8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + Some(png) +} + /// Pixel dimensions of a raster. pub fn pixel_size(bytes: &[u8]) -> Option<(u32, u32)> { if let Some(p) = palette_tiff(bytes) { diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 88bd48c58..8355e236f 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -113,6 +113,7 @@ impl DesignApp { egui_ctx: None, in_control: false, object_clip_text: None, + object_clip_change: None, ime_marked: None, ime_discard: false, canvas_ime: false, diff --git a/crates/ui-egui/src/app/clipboard.rs b/crates/ui-egui/src/app/clipboard.rs index 4b813dd5c..bff5156f7 100644 --- a/crates/ui-egui/src/app/clipboard.rs +++ b/crates/ui-egui/src/app/clipboard.rs @@ -1,13 +1,35 @@ use super::{DesignApp, Value, canvas, json}; +use crate::services::ClipboardImage; + +/// What Paste takes from the system clipboard. +pub(super) enum Pasted { + /// The command's params, with the clipboard's text when it has some. + Params(Value), + /// An image, pasted as a placed image instead. + Image(ClipboardImage), +} + +/// Text that is only the address of a file or a web page: what a browser puts beside a copied +/// image. Paste prefers the image to such text. +fn is_bare_address(text: &str) -> bool { + let t = text.trim(); + !t.is_empty() + && !t.contains(char::is_whitespace) + && ["http://", "https://", "file://", "data:image/"] + .iter() + .any(|scheme| t.get(..scheme.len()).is_some_and(|s| s.eq_ignore_ascii_case(scheme))) +} impl DesignApp { /// Paste without the clipboard's text (a menu, not the paste keys): read it here. With no /// insertion point, text that doesn't stand for copied objects becomes a new text frame - /// centred in the view. - pub(super) fn with_system_clipboard(&mut self, id: &str, mut params: Value) -> Value { + /// centered in the view, and an image on the clipboard (when there is no text, or the text is + /// only an address) becomes a placed image, unless nothing was copied to the clipboard since + /// objects were last copied here. + pub(super) fn with_system_clipboard(&mut self, id: &str, mut params: Value) -> Pasted { let typing = self.session.active().is_some_and(|d| d.selection.text.is_some()); if !matches!(id, "edit.paste" | "edit.pasteWithoutFormatting") || !(typing || id == "edit.paste") { - return params; + return Pasted::Params(params); } if params.get("text").is_none() && let Some(text) = self.services.clipboard_text.as_mut().and_then(|f| f()) @@ -15,14 +37,33 @@ impl DesignApp { { o.insert("text".into(), Value::String(text)); } + // Nothing was copied to the clipboard since objects were copied here (native menu, where + // the system raises a change count with every copy). + let unchanged = match self.object_clip_change { + Some(at_copy) => self.services.clipboard_change.as_mut().and_then(|f| f()) == Some(at_copy), + None => true, + }; // Still what an object copy put there: paste those objects, not the placeholder text. let norm = |t: &str| t.replace("\r\n", "\n"); - if let Some(copied) = &self.object_clip_text - && params.get("text").and_then(Value::as_str).is_some_and(|t| norm(t) == norm(copied)) - && let Some(o) = params.as_object_mut() - { + let ours = unchanged + && self + .object_clip_text + .as_ref() + .is_some_and(|copied| params.get("text").and_then(Value::as_str).is_some_and(|t| norm(t) == norm(copied))); + if ours && let Some(o) = params.as_object_mut() { o.remove("text"); } + let text = params.get("text").and_then(Value::as_str); + let copied_here = + text.is_none() && self.session.clipboard.is_some() && self.object_clip_text.is_none() && self.object_clip_change.is_some() && unchanged; + if !typing + && !ours + && !copied_here + && text.is_none_or(is_bare_address) + && let Some(image) = self.services.clipboard_image.as_mut().and_then(|f| f()) + { + return Pasted::Image(image); + } if !typing && params.get("text").and_then(Value::as_str).is_some_and(|t| !t.is_empty()) && let Some((spread, at)) = canvas::view_centre(self) @@ -32,7 +73,39 @@ impl DesignApp { o.entry("spread").or_insert(spread); o.entry("at").or_insert(json!([at.x, at.y])); } - params + Pasted::Params(params) + } + + /// Paste an image from the system clipboard as a placed image (`edit.pasteImage`), centered + /// in the view or in the selected empty frame. Text being edited takes no image. + pub(crate) fn paste_clipboard_image(&mut self, image: ClipboardImage) -> Result { + let typing = self.session.active().is_some_and(|d| d.selection.text.is_some()); + let file = if typing { + Err("To paste the image, stop editing the text first (Esc).".to_string()) + } else { + match image { + ClipboardImage::Pixels { width, height, rgba } => { + designcraft_engine::cmd::pasted_png(width, height, rgba).map(|png| (png, designcraft_engine::cmd::PASTED_IMAGE_NAME.to_string())) + } + ClipboardImage::File { name, bytes } => Ok((bytes, name)), + } + }; + let (bytes, name) = match file { + Ok(file) => file, + Err(e) => { + self.status(e.clone()); + return Err(e); + } + }; + let mut params = json!({"base64": designcraft_engine::cmd::base64_encode(&bytes), "name": name}); + if let Some((spread, at)) = canvas::view_centre(self) + && let Ok(spread) = serde_json::to_value(spread) + && let Some(o) = params.as_object_mut() + { + o.insert("spread".into(), spread); + o.insert("at".into(), json!([at.x, at.y])); + } + self.run("edit.pasteImage", params) } /// Keep widget clipboard output private while a queued control event is running. diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index bb75c102e..dc0326172 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -8,7 +8,14 @@ impl DesignApp { } // Only user-initiated runs touch the system clipboard, never the control channel's. let system_clipboard = !self.in_control && !self.control_input_frame.load(std::sync::atomic::Ordering::Relaxed); - let mut params = if system_clipboard { self.with_system_clipboard(id, params) } else { params }; + let mut params = if system_clipboard { + match self.with_system_clipboard(id, params) { + super::clipboard::Pasted::Params(params) => params, + super::clipboard::Pasted::Image(image) => return self.paste_clipboard_image(image), + } + } else { + params + }; // Vector art copied in another app (Illustrator, VectorCraft, Figma) is SVG markup on the // system clipboard: with no insertion point it pastes as editable paths where text would go. let typing = self.session.active().is_some_and(|d| d.selection.text.is_some()); @@ -37,14 +44,17 @@ impl DesignApp { let text = match v.get("text").and_then(Value::as_str) { Some(t) => { self.object_clip_text = None; + self.object_clip_change = None; Some(t.to_string()) } None if !self.native_menu => { self.object_clip_text = Some(designcraft_engine::cmd::copied_objects_text(&self.session)); + self.object_clip_change = None; self.object_clip_text.clone() } None => { self.object_clip_text = self.services.clipboard_text.as_mut().and_then(|f| f()); + self.object_clip_change = self.services.clipboard_change.as_mut().and_then(|f| f()); None } }; diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 590b0f8c6..d9102e266 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -435,7 +435,13 @@ pub(super) fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui:: let _ = app.run("text.insert", json!({"text": t})); } // The IME owns the keyboard until it commits: no typing, clipboard or editing keys. - egui::Event::Text(_) | egui::Event::Paste(_) | egui::Event::Copy | egui::Event::Cut | egui::Event::Key { .. } if composing => {} + egui::Event::Text(_) + | egui::Event::Paste(_) + | egui::Event::PasteImage(_) + | egui::Event::Copy + | egui::Event::Cut + | egui::Event::Key { .. } + if composing => {} egui::Event::Paste(t) if wants_text => { // Formatted when the system clipboard still holds what was copied here; // Shift (⇧⌘V) pastes without formatting. @@ -443,6 +449,10 @@ pub(super) fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui:: let id = if plain { "edit.pasteWithoutFormatting" } else { "edit.paste" }; let _ = app.run(id, json!({"text": t})); } + // A clipboard image with no text (a screenshot, an image copied in a browser). + egui::Event::PasteImage(image) => { + let _ = app.paste_clipboard_image(crate::ClipboardImage::from_color_image(&image)); + } egui::Event::Copy | egui::Event::Cut if wants_text => { // `run` puts the copied text on the system clipboard. let id = if matches!(e, egui::Event::Cut) { "edit.cut" } else { "edit.copy" }; @@ -525,6 +535,10 @@ pub(crate) fn forwarded_keys(app: &mut DesignApp, events: Vec, modi (egui::Event::Copy, _) if !app.native_menu => ("edit.copy", serde_json::Value::Null), (egui::Event::Cut, _) if !app.native_menu => ("edit.cut", serde_json::Value::Null), (egui::Event::Paste(t), _) if !app.native_menu => ("edit.paste", json!({"text": t})), + (egui::Event::PasteImage(image), _) => { + let _ = app.paste_clipboard_image(crate::ClipboardImage::from_color_image(&image)); + continue; + } (egui::Event::Key { key, pressed: true, modifiers, .. }, _) => { tool_key(app, key, modifiers, vi); continue; diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 62064ea79..0937904d9 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1051,6 +1051,127 @@ fn edit_paste_from_the_menu_pastes_svg_on_the_system_clipboard_as_paths() { assert_eq!(app.session.doc().unwrap().doc.spreads[0].items.len(), items, "no paths added"); } +/// A fake system clipboard: its text, a bitmap of a given size and the change count that every +/// copy raises. +#[derive(Default)] +struct FakeClip { + text: Option, + image: Option<(u32, u32)>, + change: i64, +} + +type FakeClipboard = std::rc::Rc>; + +/// Another application copies `text` and an image of `image` pixels. +fn copy_elsewhere(clip: &FakeClipboard, text: Option<&str>, image: Option<(u32, u32)>) { + let mut c = clip.borrow_mut(); + (c.text, c.image, c.change) = (text.map(str::to_string), image, c.change + 1); +} + +fn fake_clipboard(text: Option<&str>, image: Option<(u32, u32)>) -> (FakeClipboard, crate::Services) { + let clip = FakeClipboard::default(); + copy_elsewhere(&clip, text, image); + let (t, i, c) = (clip.clone(), clip.clone(), clip.clone()); + let services = crate::Services { + clipboard_text: Some(Box::new(move || t.borrow().text.clone())), + clipboard_image: Some(Box::new(move || { + let (width, height) = i.borrow().image?; + // Sizes past the paste limit are refused before their pixels are read. + let len = if u64::from(width) * u64::from(height) > designcraft_engine::cmd::MAX_PASTED_PIXELS { 0 } else { width * height * 4 }; + Some(crate::ClipboardImage::Pixels { width, height, rgba: vec![90; len as usize] }) + })), + clipboard_change: Some(Box::new(move || Some(c.borrow().change))), + ..Default::default() + }; + (clip, services) +} + +/// The embedded image the selected frame shows: its pixel size and the asset's name. +fn pasted_image(app: &DesignApp) -> Option<((u32, u32), String)> { + let st = app.session.doc().unwrap(); + let id = *st.selection.items.first()?; + let designcraft_doc::Content::Graphic(g) = &st.doc.item(id)?.content else { return None }; + let asset = &st.doc.assets[&g.asset]; + assert_eq!(asset.link, None, "embedded"); + Some((asset.pixels?, asset.name.clone())) +} + +#[test] +fn edit_paste_from_the_menu_places_the_clipboard_image() { + let (clip, services) = fake_clipboard(None, Some((40, 30))); + let mut app = DesignApp::new(designcraft_engine::Session::new(), services); + app.native_menu = true; + app.run("file.new", json!({})).unwrap(); + crate::menus::activate(&mut app, "edit.paste", &Value::Null); + assert_eq!(pasted_image(&app), Some(((40, 30), designcraft_engine::cmd::PASTED_IMAGE_NAME.to_string()))); + // A browser puts the image's address beside it: the image wins. + copy_elsewhere(&clip, Some("https://example.com/cat.png"), Some((8, 6))); + crate::menus::activate(&mut app, "edit.paste", &Value::Null); + assert_eq!(pasted_image(&app).map(|(px, _)| px), Some((8, 6))); + // Other text wins over a picture of it. + copy_elsewhere(&clip, Some("Some words"), Some((8, 6))); + crate::menus::activate(&mut app, "edit.paste", &Value::Null); + assert_eq!(pasted_image(&app), None); + assert!(app.session.doc().unwrap().selection.text.is_none(), "a text frame, selected as an object"); + // Too many pixels: refused with a message, and nothing is added. + copy_elsewhere(&clip, None, Some((9000, 8000))); + let items = app.session.doc().unwrap().doc.spreads[0].items.len(); + crate::menus::activate(&mut app, "edit.paste", &Value::Null); + assert_eq!(app.session.doc().unwrap().doc.spreads[0].items.len(), items); + assert!(app.ui.status.contains("64 million"), "{}", app.ui.status); +} + +#[test] +fn objects_copied_here_still_paste_as_objects_until_another_image_is_copied() { + // A native menu: Copy leaves the system clipboard (here an older image) alone. + let (clip, services) = fake_clipboard(None, Some((40, 30))); + let mut app = DesignApp::new(designcraft_engine::Session::new(), services); + app.native_menu = true; + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [100, 100, 200, 200], "content": "text"})).unwrap()["id"].clone(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + crate::menus::activate(&mut app, "edit.copy", &Value::Null); + crate::menus::activate(&mut app, "edit.paste", &Value::Null); + assert_eq!(pasted_image(&app), None, "the copied text frame"); + assert_ne!(app.session.doc().unwrap().selection.items.first().map(|i| i.0), id.as_u64()); + // The same image copied again in another application is a new copy. + copy_elsewhere(&clip, None, Some((40, 30))); + crate::menus::activate(&mut app, "edit.paste", &Value::Null); + assert_eq!(pasted_image(&app).map(|(px, _)| px), Some((40, 30)), "an image copied since then"); + // The same goes for an image whose address was on the clipboard at the copy. + let url = "https://example.com/cat.png"; + copy_elsewhere(&clip, Some(url), Some((5, 5))); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + crate::menus::activate(&mut app, "edit.copy", &Value::Null); + crate::menus::activate(&mut app, "edit.paste", &Value::Null); + assert_eq!(pasted_image(&app), None, "the copied text frame again"); + copy_elsewhere(&clip, Some(url), Some((5, 5))); + crate::menus::activate(&mut app, "edit.paste", &Value::Null); + assert_eq!(pasted_image(&app).map(|(px, _)| px), Some((5, 5)), "the image copied again with the same address"); +} + +#[test] +fn the_paste_keys_place_an_image_in_the_selected_empty_frame_but_not_in_text() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let frame = app.run("frame.create", json!({"rect": [100, 100, 300, 250]})).unwrap()["id"].as_u64().unwrap(); + app.run("selection.set", json!({"ids": [frame]})).unwrap(); + let mut h = harness(app); + let image = || egui::Event::PasteImage(std::sync::Arc::new(egui::ColorImage::filled([20, 10], egui::Color32::RED))); + h.input_mut().events.push(image()); + h.run_steps(2); + assert_eq!(h.state().session.doc().unwrap().selection.items.first().map(|i| i.0), Some(frame), "the frame took it"); + assert_eq!(pasted_image(h.state()).map(|(px, _)| px), Some((20, 10))); + // While text is edited, the image is not pasted and the status bar says why. + let story = h.state_mut().run("frame.create", json!({"rect": [10, 400, 300, 600], "content": "text"})).unwrap()["story"].clone(); + h.state_mut().run("text.select", json!({"story": story, "anchor": 0, "focus": 0})).unwrap(); + let items = h.state().session.doc().unwrap().doc.spreads[0].items.len(); + h.input_mut().events.push(image()); + h.run_steps(2); + assert_eq!(h.state().session.doc().unwrap().doc.spreads[0].items.len(), items); + assert!(h.state().ui.status.contains("stop editing the text"), "{}", h.state().ui.status); +} + #[test] fn selected_merged_owners_paint_the_same_row_and_column_targets() { for column in [true, false] { diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index d70a79695..9a8e23900 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -272,11 +272,24 @@ fn handle_request(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest ctx.request_repaint(); ok(Value::Null) } - // What Ctrl/Cmd+V delivers from the system clipboard: text, or SVG markup copied in an - // illustration app (pasted as editable paths when no text is being edited). + // What Ctrl/Cmd+V delivers from the system clipboard: text, SVG markup copied in an + // illustration app (pasted as editable paths when no text is being edited), or an image + // (`image`: an image file as base64, pasted as a placed image). "ui.paste" => { - let Some(text) = s("text") else { return err("missing `text`") }; - app.control_synthetic.push(egui::Event::Paste(text.to_string())); + let event = match (s("text"), s("image")) { + (Some(text), None) => egui::Event::Paste(text.to_string()), + (None, Some(image)) => { + let bytes = designcraft_engine::cmd::base64_decode(image); + let Some((w, h, rgba)) = designcraft_engine::cmd::pasted_pixels(&bytes) else { + return err("`image` is not an image file that can be pasted"); + }; + let size = [w, h].map(|n| usize::try_from(n).unwrap_or(0)); + egui::Event::PasteImage(std::sync::Arc::new(egui::ColorImage::from_rgba_unmultiplied(size, &rgba))) + } + (Some(_), Some(_)) => return err("give `text` or `image`, not both"), + (None, None) => return err("missing `text` or `image`"), + }; + app.control_synthetic.push(event); ctx.request_repaint(); ok(Value::Null) } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 40bdfbcb3..f441e2f1d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -74,7 +74,10 @@ use app::browser_import_tests; pub use app::opens_as_document; pub use clock::now_ms; pub use key_names::{drop_key_name_text, is_key_name}; -pub use services::{ClipboardFn, DownloadFn, Inbox, OpenAsyncFn, PointerFn, ReadFn, Services, WindowFrameFn, WriteFn}; +pub use services::{ + ClipboardChangeFn, ClipboardFn, ClipboardImage, ClipboardImageFn, DownloadFn, Inbox, OpenAsyncFn, PointerFn, ReadFn, Services, WindowFrameFn, + WriteFn, +}; pub(crate) use state::second_window_viewport; pub use state::{CanvasCache, HiddenPanels, ImportRequest, ImportedFile, PdfExportSettings, Perf, SavedWorkspace, ScreenMode, Shown, UiState, View}; @@ -257,6 +260,9 @@ pub struct DesignApp { /// (no native menu: without it the paste keys produce no paste event), or what it held then /// (native menu). It is never pasted as text: Paste with it pastes the copied objects. object_clip_text: Option, + /// The clipboard's change count at the last object copy (native menu). While it is unchanged, + /// Paste pastes the copied objects rather than an image the clipboard held before the copy. + object_clip_change: Option, /// The marked text the system IME last sent (`None` once it commits or clears). When the /// composition ends some other way (a click, a tool switch), the IME is told to drop it. pub(crate) ime_marked: Option, diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 384a75b4b..fd529ac42 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -11,6 +11,32 @@ pub type DownloadFn = Box Result<(), String>>; pub type ClipboardFn = Box Option>; +/// An image on the system clipboard. +pub enum ClipboardImage { + /// A bitmap (a screenshot, an image copied in a browser): unpremultiplied RGBA, rows top to + /// bottom. + Pixels { width: u32, height: u32, rgba: Vec }, + /// An image file copied in a file manager: its name and contents. + File { name: String, bytes: Vec }, +} + +impl ClipboardImage { + /// An image egui delivered with Ctrl/Cmd+V (`Event::PasteImage`). + pub fn from_color_image(image: &egui::ColorImage) -> Self { + let rgba = image.pixels.iter().flat_map(|c| c.to_srgba_unmultiplied()).collect(); + let [w, h] = image.size.map(|n| u32::try_from(n).unwrap_or(u32::MAX)); + ClipboardImage::Pixels { width: w, height: h, rgba } + } +} + +/// The system clipboard's image, for Paste chosen from a menu. It returns within a short bound +/// even when the application that owns the clipboard is slow to answer (`None` then). +pub type ClipboardImageFn = Box Option>; + +/// A number the system raises with every copy to the clipboard (the macOS pasteboard's change +/// count), read without waiting for the clipboard's owner. +pub type ClipboardChangeFn = Box Option>; + /// Keeps the window's frame as the app needs it; called once per frame, before it is laid out. pub type WindowFrameFn = Box; @@ -40,6 +66,13 @@ pub struct Services { /// The system clipboard's text, for Paste chosen from a menu (egui only delivers it with the /// paste keys, which a native menu bar takes first). pub clipboard_text: Option, + /// The system clipboard's image (a bitmap, else the first image file of a copied file list), + /// for Paste chosen from a menu when the clipboard holds no text or only an image's address. + pub clipboard_image: Option, + /// The clipboard's change count, so Paste can tell an image copied after an object Copy from + /// one that was there before it. Needed where Copy leaves the system clipboard alone (a + /// native menu bar); `None` elsewhere. + pub clipboard_change: Option, /// Keeps the undecorated window borderless, so the content and the pointer stay aligned /// (Windows custom title bar, #1295). `None` when the window is decorated or the platform /// needs no fixing. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index e886c07ab..706c1fc43 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -42,7 +42,7 @@ so only enable it while you use it. Transport: `apps/designcraft/src/control_ser | `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick, x, y, space?: "screen"\|"canvas", clicks?}], mods?}` | Drive the active tool through the same code path as the mouse; `clicks` on a `down` is the press count (3 = triple click); returns the selection, the tool and its cursor at the last event (e.g. `LoadedText`, `ThreadLink`, `Unthread`) | | `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | Synthetic keyboard input (typing into a text frame) | | `ui.ime` | `{preedit?, active?: [start, end], commit?}` | Input method events as the system IME sends them: marked text (shown in place, `active` is the clause being converted, in characters) and the committed text (typed as one `text.insert`) | -| `ui.paste` | `{text}` | What Ctrl/Cmd+V delivers from the system clipboard: text into the text being edited, or SVG markup (vector art copied in Illustrator, VectorCraft or Figma) as editable paths in the middle of the view | +| `ui.paste` | `{text}` or `{image}` | What Ctrl/Cmd+V delivers from the system clipboard: text into the text being edited, SVG markup (vector art copied in Illustrator, VectorCraft or Figma) as editable paths in the middle of the view, or an image (`image`: an image file as base64) as an embedded image in the selected empty frame or in the middle of the view (`edit.pasteImage`) | | `ui.move` / `ui.click` / `ui.drag` | screen points, `button?: left\|right\|middle`, `count?: 1–255` (click/drag, default 1), `steps?: positive integer` (drag, default 8) | Real egui pointer input — reaches every widget, menu and panel | | `ui.set` | `{brightness?, panel?, rulers?, guides?, frameEdges?, baselineGrid?, documentGrid?, textThreads?, screenMode?, zoom?, page?, fit?}` | UI state | | `ui.dialog.open` | `{id, fields?}` | Open a dialog by id (e.g. `paragraphStyleOptions` or `characterStyleOptions` with `{name, section}`, or `{new: true}` for a new style) | From eff8865f86c42218f8aba795c722b5607b16e802 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:50:31 -0800 Subject: [PATCH 0960/1349] Recovery: an edit after a save is written once the cancelled write stops A recovery write queued while a cancelled write of the same document and folder is still running now follows it instead of being refused until the next timer tick. A write in a folder that is not the run's own is recorded as the run's in the same step as its rename, so a save right after it can remove it. --- crates/engine/src/recovery.rs | 161 ++++++++++++++++++---------- crates/engine/src/recovery/tests.rs | 27 +++++ 2 files changed, 133 insertions(+), 55 deletions(-) diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index f5bafd316..e2e09a42b 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -737,6 +737,14 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { entry.own, |out| designcraft_format::write(out, &entry.doc, None).map_err(|e| EngineError::Other(e.to_string())), &cancelled, + // Written: in a folder that is not this run's own, the entry is now this run's to replace + // and remove (Save and Close must clean up the snapshot they wrote). Recorded with the + // rename, so a cleanup after it can remove the entry. + || { + if !entry.own { + WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert((entry.key.clone(), entry.uid)); + } + }, ); match published { Ok(true) => {} @@ -744,11 +752,6 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { Ok(false) => return Written { published: false, error: None }, Err(e) => return Written { published: false, error: Some(e) }, } - // Written: in a folder that is not this run's own, the entry is now this run's to replace and - // remove (Save and Close must clean up the snapshot they wrote). - if !entry.own { - WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert((entry.key.clone(), entry.uid)); - } let metadata = json!({"path": entry.path, "title": entry.title, "saved": designcraft_doc::vars::now()}); // A cancel after the primary landed removes it; the metadata must not be left without it. let bytes = metadata.to_string(); @@ -757,6 +760,7 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { entry.own, |out| out.write_all(bytes.as_bytes()).map_err(|e| EngineError::Other(format!("{}: {e}", meta.display()))), &cancelled, + || {}, ) .err(); Written { published: true, error } @@ -921,6 +925,9 @@ mod worker { struct Queued { owner: u64, dir: PathBuf, + /// A newer write of the same document and folder, queued after this one was cancelled: + /// it is written as soon as this one stops. + next: Option, } static WRITER: OnceLock> = OnceLock::new(); @@ -935,16 +942,30 @@ mod worker { self.running.lock().is_ok_and(|running| !running.is_empty()) } - /// `key` is the job's ([`Snapshot::key`], uid). - fn finish(&self, key: &(PathBuf, u64)) { - let key = key.clone(); - if let Ok(mut running) = self.running.lock() { - running.remove(&key); - } - if let Ok(mut cancelled) = self.cancelled.lock() { - cancelled.remove(&key); - } + /// `key` is the job's ([`Snapshot::key`], uid). Returns the write queued to follow it. + fn finish(&self, key: &(PathBuf, u64)) -> Option { + let next = match self.running.lock() { + Ok(mut running) => { + let next = running.get_mut(key).and_then(|q| q.next.take()); + match (&next, running.get_mut(key)) { + (Some(n), Some(q)) => { + q.owner = n.owner; + q.dir = n.dir.clone(); + } + _ => { + running.remove(key); + } + } + // The mark was for the write that stopped, not the one that follows it. + if let Ok(mut cancelled) = self.cancelled.lock() { + cancelled.remove(key); + } + next + } + Err(_) => None, + }; self.idle.notify_all(); + next } /// Block until no write is queued or running. @@ -966,11 +987,15 @@ mod worker { let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); // The folder's canonical path, or its name as given: a link in the path may lead // elsewhere now than when the write was queued. - let keys: Vec<(PathBuf, u64)> = self - .running - .lock() - .map(|running| running.iter().filter(|(k, q)| **k == canonical || (k.1 == uid && q.dir == dir)).map(|(k, _)| k.clone()).collect()) - .unwrap_or_default(); + let Ok(mut running) = self.running.lock() else { return }; + let keys: Vec<(PathBuf, u64)> = + running.iter().filter(|(k, q)| **k == canonical || (k.1 == uid && q.dir == dir)).map(|(k, _)| k.clone()).collect(); + // A write queued to follow it is older than what the caller has now, too. + for k in &keys { + if let Some(q) = running.get_mut(k) { + q.next = None; + } + } if let Ok(mut cancelled) = self.cancelled.lock() { cancelled.extend(keys); } @@ -985,15 +1010,17 @@ mod worker { let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); // The canonical keys to mark, and the folders as the session named them, which is how // the cleanup finds this run's folder. - let (keys, mut dirs): (Vec<(PathBuf, u64)>, Vec) = self - .running - .lock() - .map(|running| { - running.iter().filter(|((_, u), q)| *u == uid && q.owner == owner).map(|(key, q)| (key.clone(), q.dir.clone())).unzip() - }) - .unwrap_or_default(); - if let Ok(mut cancelled) = self.cancelled.lock() { - cancelled.extend(keys); + let mut dirs = Vec::new(); + if let Ok(mut running) = self.running.lock() { + let mut keys = Vec::new(); + for (key, q) in running.iter_mut().filter(|((_, u), q)| *u == uid && q.owner == owner) { + keys.push(key.clone()); + dirs.push(q.dir.clone()); + q.next = None; + } + if let Ok(mut cancelled) = self.cancelled.lock() { + cancelled.extend(keys); + } } // Results stay queued for their session; only their folders are read here. let done = self.done.lock().unwrap_or_else(std::sync::PoisonError::into_inner); @@ -1011,13 +1038,20 @@ mod worker { /// The folders of writes of `uid` queued by session `owner` that are in flight, or finished /// and published with their results not taken yet: checkpoints its entries do not hold yet. fn pending_folders(&self, uid: u64, owner: u64) -> Vec { - let keys: Vec<(PathBuf, u64)> = self + // A cancelled write publishes nothing; a write queued to follow it does. + let mut dirs: Vec = self .running .lock() - .map(|running| running.iter().filter(|((_, u), q)| *u == uid && q.owner == owner).map(|(key, _)| key.clone()).collect()) + .map(|running| { + running + .iter() + .filter(|(key, q)| { + key.1 == uid && ((q.owner == owner && !self.cancelled(key)) || q.next.as_ref().is_some_and(|n| n.owner == owner)) + }) + .map(|((dir, _), _)| dir.clone()) + .collect() + }) .unwrap_or_default(); - // A cancelled write publishes nothing. - let mut dirs: Vec = keys.into_iter().filter(|key| !self.cancelled(key)).map(|(dir, _)| dir).collect(); let done = self.done.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let mut undelivered = self.undelivered.lock().unwrap_or_else(std::sync::PoisonError::into_inner); undelivered.extend(done.try_iter()); @@ -1038,24 +1072,25 @@ mod worker { let (jobs, job_rx) = std::sync::mpsc::channel::(); let (done_tx, done_rx) = std::sync::mpsc::channel::(); let spawned = std::thread::Builder::new().name("designcraft-recovery".into()).spawn(move || { - while let Ok(job) = job_rx.recv() { - let (published, error) = guarded_write(&job); - let key = (job.key.clone(), job.uid); - let (dir, uid, owner) = (job.dir, job.uid, job.owner); - // The result before the document reads as idle: a writer that is not busy - // has already delivered it, so the interface never stops polling with an - // answer still on its way. - let sent = { - let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - // Cancelled after it was published: the canceller removes the snapshot. - let published = published && !started().is_some_and(|w| w.cancelled(&key)); - done_tx.send(Done { dir, uid, error, published, owner }).is_ok() - }; - if let Some(w) = WRITER.get().and_then(Option::as_ref) { - w.finish(&key); - } - if !sent { - break; + while let Ok(first) = job_rx.recv() { + let mut queued = Some(first); + while let Some(job) = queued.take() { + let (published, error) = guarded_write(&job); + let key = (job.key.clone(), job.uid); + let (dir, uid, owner) = (job.dir, job.uid, job.owner); + // The result before the document reads as idle: a writer that is not + // busy has already delivered it, so the interface never stops polling + // with an answer still on its way. + let sent = { + let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + // Cancelled after it was published: the canceller removes the snapshot. + let published = published && !started().is_some_and(|w| w.cancelled(&key)); + done_tx.send(Done { dir, uid, error, published, owner }).is_ok() + }; + queued = WRITER.get().and_then(Option::as_ref).and_then(|w| w.finish(&key)); + if !sent { + return; + } } } }); @@ -1124,10 +1159,16 @@ mod worker { let w = writer()?; let mut running = w.running.lock().ok()?; let key = (entry.key.clone(), entry.uid); - if running.contains_key(&key) { + if let Some(q) = running.get_mut(&key) { + // The write in flight was cancelled (the document was saved since), so it holds + // nothing to recover: this one follows it, in place of any that was waiting. + if w.cancelled.lock().is_ok_and(|cancelled| cancelled.contains(&key)) { + q.next = Some(entry); + return Some(true); + } return Some(false); } - running.insert(key.clone(), Queued { owner: entry.owner, dir: entry.dir.clone() }); + running.insert(key.clone(), Queued { owner: entry.owner, dir: entry.dir.clone(), next: None }); // A write is wanted again: whatever cancelled the last one does not apply to this one. if let Ok(mut cancelled) = w.cancelled.lock() { cancelled.remove(&key); @@ -1286,8 +1327,14 @@ fn secure_recovery_dir(_dir: &Path) -> Result { #[cfg(not(target_arch = "wasm32"))] fn publish_recovery_file(path: &Path, bytes: &[u8], replace: bool) -> Result<()> { - publish_recovery_written(path, replace, |out| out.write_all(bytes).map_err(|e| EngineError::Other(format!("{}: {e}", path.display()))), || false) - .map(|_| ()) + publish_recovery_written( + path, + replace, + |out| out.write_all(bytes).map_err(|e| EngineError::Other(format!("{}: {e}", path.display()))), + || false, + || {}, + ) + .map(|_| ()) } /// Serializes the last check for a cancelled write with the rename that publishes it, and with @@ -1298,13 +1345,15 @@ static PUBLISH: std::sync::Mutex<()> = std::sync::Mutex::new(()); /// [`publish_recovery_file`], with `write` filling the temporary file: a large document is written /// straight to disk instead of being built in memory first. Returns whether it was published; /// `cancelled` is asked after the bytes are written and before the rename, so a document saved or -/// closed meanwhile leaves nothing behind. +/// closed meanwhile leaves nothing behind. `on_publish` runs right after the rename, before a +/// cancel can. #[cfg(not(target_arch = "wasm32"))] fn publish_recovery_written( path: &Path, replace: bool, write: impl FnOnce(&mut std::io::BufWriter<&mut std::fs::File>) -> Result<()>, cancelled: impl Fn() -> bool, + on_publish: impl FnOnce(), ) -> Result { let Some(dir) = path.parent() else { return Err(EngineError::Other(format!("{} has no parent folder", path.display()))); @@ -1340,6 +1389,7 @@ fn publish_recovery_written( validate_recovery_dir(dir)?; let published = if replace { tmp.persist(path) } else { tmp.persist_noclobber(path) }; published.map_err(|e| EngineError::Other(format!("{}: {}", path.display(), e.error)))?; + on_publish(); } sync_recovery_dir(dir)?; Ok(true) @@ -1406,6 +1456,7 @@ fn publish_recovery_written( _replace: bool, _write: impl FnOnce(&mut std::io::BufWriter<&mut std::fs::File>) -> Result<()>, _cancelled: impl Fn() -> bool, + _on_publish: impl FnOnce(), ) -> Result { Err(EngineError::Other("recovery files are unavailable on the web".into())) } diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index 2353e476d..c59c5ee76 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -235,6 +235,33 @@ fn saving_removes_a_finished_write_to_a_named_folder_whose_result_was_not_taken( assert!(list(named.path()).is_empty()); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn an_edit_after_a_save_is_written_after_the_cancelled_write_stops() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut s = dirty_session(); + s.recovery_dir = Some(dir.path().to_path_buf()); + let uid = s.docs[0].uid; + let held = testing::hold_next_write(dir.path()); + s.execute("file.recovery.save", &json!({"background": true})).unwrap(); + held.wait_until_held(); + let saved = tempfile::tempdir().unwrap(); + s.execute("file.saveAs", &json!({"path": saved.path().join("saved.designcraft").to_string_lossy()})).unwrap(); + s.execute("frame.create", &json!({"rect": [20, 20, 60, 60]})).unwrap(); + // The held write was cancelled: the new edit is queued behind it instead of waiting for the + // next timer tick. + let queued = s.execute("file.recovery.save", &json!({"background": true})).unwrap(); + assert_eq!(queued["queued"], 1, "{queued}"); + held.release(); + assert_eq!(finished_writes(&mut s), 1); + let mut reopened = Session::new(); + assert_eq!(open(&mut reopened, dir.path()).unwrap().len(), 1); + assert_eq!(reopened.doc().unwrap().doc.spreads[0].items.len(), 2, "the snapshot after the edit was written"); + discard(dir.path(), reopened.doc().unwrap().uid); + discard(dir.path(), uid); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn a_background_result_goes_to_the_session_that_queued_it() { From 6fff5328eb59a5fdff5d91df44034212cc07e670 Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Wed, 11 Nov 2026 20:52:41 -0800 Subject: [PATCH 0961/1349] Tests: type.align refusal cases name the check that refuses each (#2662) Follows #2645. Its test said a misspelled key used to apply Align Left. Only empty params and a bare string did; the parameter check already refused a misspelled key, and the value parser refused an unknown value. Each case now asserts the refusal message it gets. --- crates/engine/src/cmd/text/format.rs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/text/format.rs b/crates/engine/src/cmd/text/format.rs index 10bce4841..64f3c17c7 100644 --- a/crates/engine/src/cmd/text/format.rs +++ b/crates/engine/src/cmd/text/format.rs @@ -1080,8 +1080,9 @@ mod align_param_tests { use crate::Session; - /// `type.align` with no `align` applied Align Left, so a script that misspelled the key - /// (`{"alignment": "center"}`) changed the paragraph to the opposite of what it asked for. + /// `type.align` with empty params (`{}`) or a bare value (`"center"`) applied Align Left. + /// A misspelled key and an unknown value were already refused, and each case checks which + /// check refuses it. #[test] fn type_align_without_a_value_is_refused_and_changes_nothing() { let mut s = Session::new(); @@ -1092,8 +1093,16 @@ mod align_param_tests { let align = |s: &mut Session| s.execute("type.selectionAttrs", &json!({})).unwrap()["para"]["align"].clone(); assert_eq!(align(&mut s), json!("right")); let steps = s.doc().unwrap().history.undo.len(); - for params in [json!({}), json!({"alignment": "center"}), json!("center"), json!({"align": "middle"})] { - assert!(s.execute("type.align", ¶ms).is_err(), "{params}"); + // `{}` and `"center"` reach the command without `align`. The parameter check refuses + // `{"alignment": …}` and the value parser refuses `"middle"`. + for (params, refusal) in [ + (json!({}), "`align` required"), + (json!("center"), "`align` required"), + (json!({"alignment": "center"}), "unknown parameter `alignment`"), + (json!({"align": "middle"}), "middle"), + ] { + let err = s.execute("type.align", ¶ms).unwrap_err().to_string(); + assert!(err.contains(refusal), "{params}: {err}"); assert_eq!(align(&mut s), json!("right"), "{params}"); assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{params}: no undo step"); } From f47acd5dfd90ae2ae9bd7900f24a52dab8fa71aa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:54:37 -0800 Subject: [PATCH 0962/1349] Object styles: Text Frame General Options set only the General page - An object style's text frame options set the columns, insets, vertical justification, paragraph spacing limit and Ignore Text Wrap. A frame keeps its auto-size, baseline, column rule and Type on a Path settings, and follows an edit of the style while its General options match the style's. - textFrame refuses keys outside the General options, takes one number for all four insets, and checks the values the call gives. - Applying a style that changes nothing records no undo step. - The dialog's Paragraph Spacing Limit reaches the style. - IDML import: a style's Text Frame General Options take the settings its TextFramePreference leaves out from the styles it is based on (by id or bare name), skipping styles that turn the category off. - i18n: Hungarian and Swedish rows for the object style dialog; the duplicate Brazilian Portuguese rows are removed. --- crates/doc/src/item/text_frame.rs | 43 ++++++++++++++ crates/doc/src/styles.rs | 5 +- crates/engine/src/cmd/style.rs | 6 +- crates/engine/src/cmd/style/object.rs | 42 ++++++++++--- crates/engine/src/tests.rs | 72 +++++++++++++++++++++++ crates/idml/src/import/styles.rs | 44 +++++++++----- crates/idml/src/tests/object_styles.rs | 37 ++++++++++++ crates/ui-egui/src/i18n/hu.rs | 13 ++++ crates/ui-egui/src/i18n/pt_br.rs | 2 - crates/ui-egui/src/i18n/sv.rs | 12 ++++ crates/ui-egui/src/object_style_dialog.rs | 39 +++++++++++- 11 files changed, 285 insertions(+), 30 deletions(-) diff --git a/crates/doc/src/item/text_frame.rs b/crates/doc/src/item/text_frame.rs index d8f7f29e3..5c01bb21b 100644 --- a/crates/doc/src/item/text_frame.rs +++ b/crates/doc/src/item/text_frame.rs @@ -240,6 +240,49 @@ impl Default for TextFrameOptions { } } +impl TextFrameOptions { + /// The JSON keys of the General options: columns, inset spacing, vertical justification and + /// Ignore Text Wrap. An object style's Text Frame General Options category sets these only. + pub const GENERAL_KEYS: [&str; 9] = [ + "columns", + "columnsKind", + "gutter", + "columnWidth", + "balanceColumns", + "inset", + "verticalJustification", + "vjParagraphSpacingLimit", + "ignoreWrap", + ]; + + /// Whether the General options (see [`Self::GENERAL_KEYS`]) of `self` and `other` are the same. + pub fn general_eq(&self, other: &TextFrameOptions) -> bool { + self.columns == other.columns + && self.columns_kind == other.columns_kind + && self.gutter == other.gutter + && self.column_width == other.column_width + && self.balance_columns == other.balance_columns + && self.inset == other.inset + && self.vertical_justification == other.vertical_justification + && self.vj_paragraph_spacing_limit == other.vj_paragraph_spacing_limit + && self.ignore_wrap == other.ignore_wrap + } + + /// Copies the General options of `from` (see [`Self::GENERAL_KEYS`]). Baseline, auto-size, + /// column rule and Type on a Path settings stay as they are. + pub fn set_general(&mut self, from: &TextFrameOptions) { + self.columns = from.columns; + self.columns_kind = from.columns_kind; + self.gutter = from.gutter; + self.column_width = from.column_width; + self.balance_columns = from.balance_columns; + self.inset = from.inset; + self.vertical_justification = from.vertical_justification; + self.vj_paragraph_spacing_limit = from.vj_paragraph_spacing_limit; + self.ignore_wrap = from.ignore_wrap; + } +} + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum WrapMode { diff --git a/crates/doc/src/styles.rs b/crates/doc/src/styles.rs index 1ba59ef25..98923762c 100644 --- a/crates/doc/src/styles.rs +++ b/crates/doc/src/styles.rs @@ -72,7 +72,8 @@ pub struct ObjectStyle { } impl ObjectStyle { - /// Gives `it` the fill, stroke, corners, effects and text frame options this style sets. + /// Gives `it` the fill, stroke, corners, effects and text frame General options this style + /// sets. A text frame keeps its baseline, auto-size, column rule and Type on a Path settings. pub fn apply_to(&self, it: &mut Item) { if let Some(c) = self.corners { it.corners = c.named_to_path(&it.path); @@ -87,7 +88,7 @@ impl ObjectStyle { it.effects = e.clone(); } if let (Some(tf), Some(o)) = (it.text_frame_mut(), &self.text_frame) { - tf.options = o.clone(); + tf.options.set_general(o); } } diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 64cc8f6f3..5b1ac047d 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -173,7 +173,7 @@ pub fn specs() -> Vec { "Apply Object Style", [], None, - "{name, ids?} — sets the style's fill, stroke, effects and text frame options on the items", + "{name, ids?} — sets the style's fill, stroke, corners, effects and text frame General options on the items, and its paragraph styles on their text; records nothing when the items already have them", super::has_selection, apply_object ), @@ -182,7 +182,7 @@ pub fn specs() -> Vec { "New Object Style…", [], None, - "{name, fromSelection?: true (fill, stroke, corners, effects and text frame options of the first selected item), fill?: swatch | {swatch?, tint?}, stroke?: {swatch?, weight?, tint?, type?, …}, corners?: {shape?, size?} | {corners: [{shape, size}] ×4}, paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns?, columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right], verticalJustification?, ignoreWrap?, …} | null (the options of `document.inspect` text frames; null: the style sets none), effects?: {dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?}, dropShadow?: {on?, color?, opacity? (0–1), angle?, globalLight?, distance?, size?, spread?}, feather?: width, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} → {name} (made unique)", + "{name, fromSelection?: true (fill, stroke, corners, effects and text frame options of the first selected item), fill?: swatch | {swatch?, tint?}, stroke?: {swatch?, weight?, tint?, type?, …}, corners?: {shape?, size?} | {corners: [{shape, size}] ×4}, paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns? (1–40), columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right] | one number for all four, verticalJustification?: top|center|bottom|justify, vjParagraphSpacingLimit?, ignoreWrap?} | null (Text Frame General Options, named as `document.inspect` names text frame options; lengths 0–15552 pt; other keys are refused; a frame keeps its baseline, auto-size and column rule settings; null: the style sets none), effects?: {dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?}, dropShadow?: {on?, color?, opacity? (0–1), angle?, globalLight?, distance?, size?, spread?}, feather?: width, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} → {name} (made unique)", has_doc, create_object ), @@ -191,7 +191,7 @@ pub fn specs() -> Vec { "Object Style Options…", [], None, - "{name, rename?: new name (every use follows), fill?: swatch | {swatch?, tint?} | null, stroke?: {swatch?, weight?, tint?, type?, …} | null, corners?: {shape?: none|rounded|inverseRounded|inset|bevel|fancy, size?} | {corners: [{shape, size}] ×4} | null (null: the style no longer sets it; items keep theirs), paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns?, columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right], verticalJustification?, ignoreWrap?, …} | null (the options of `document.inspect` text frames; null: the style sets none), effects?: {…} | null (the style no longer sets effects), dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} — effect objects merge field by field into the style's effects (fields as in `document.inspect` item effects); values that aren't finite numbers are refused, the others clamped (opacities 0–1, sizes and distances ≥ 0); items using the style whose effects (fill, stroke, corners) match the style's (an item's defaults, when the style set none) take the new ones, items with their own keep them → {name, updated}", + "{name, rename?: new name (every use follows), fill?: swatch | {swatch?, tint?} | null, stroke?: {swatch?, weight?, tint?, type?, …} | null, corners?: {shape?: none|rounded|inverseRounded|inset|bevel|fancy, size?} | {corners: [{shape, size}] ×4} | null (null: the style no longer sets it; items keep theirs), paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns? (1–40), columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right] | one number for all four, verticalJustification?: top|center|bottom|justify, vjParagraphSpacingLimit?, ignoreWrap?} | null (Text Frame General Options, named as `document.inspect` names text frame options; lengths 0–15552 pt; other keys are refused; a frame keeps its baseline, auto-size and column rule settings; null: the style sets none), effects?: {…} | null (the style no longer sets effects), dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} — effect objects merge field by field into the style's effects (fields as in `document.inspect` item effects); values that aren't finite numbers are refused, the others clamped (opacities 0–1, sizes and distances ≥ 0); items using the style whose effects (fill, stroke, corners) match the style's (an item's defaults, when the style set none) take the new ones, items with their own keep them; the text of frames still in the old paragraph styles takes the new ones → {name, updated, restyled}", has_doc, edit_object ), diff --git a/crates/engine/src/cmd/style/object.rs b/crates/engine/src/cmd/style/object.rs index fb2467e5f..6c7455099 100644 --- a/crates/engine/src/cmd/style/object.rs +++ b/crates/engine/src/cmd/style/object.rs @@ -4,6 +4,18 @@ pub(super) fn apply_object(s: &mut Session, p: &Value) -> Result { let name = str_param(p, "name").ok_or_else(|| bad("style.object.apply", "missing name"))?.to_string(); let os = s.doc()?.doc.styles.object_style(&name).cloned().ok_or_else(|| bad("style.object.apply", format!("no object style `{name}`")))?; let ids = crate::cmd::targets(s, p)?; + // Nothing to record when every target already has the style and its attributes, and its text + // the style's paragraph styles. + let d = &s.doc()?.doc; + let unchanged = ids.iter().filter_map(|id| d.item(*id)).all(|it| { + let mut next = it.clone(); + next.object_style = name.clone(); + os.apply_to(&mut next); + next == *it && it.text_frame().and_then(|tf| d.story(tf.story)).is_none_or(|st| os.story_follows(&d.styles, st)) + }); + if unchanged { + return Ok(Value::Null); + } s.edit(|d, _| { let mut stories = Vec::new(); for id in &ids { @@ -170,19 +182,33 @@ fn paragraph_style_param(cmd: &str, s: &Session, p: &Value) -> Result, ) -> Result>> { - let tf = group_param(cmd, p, "textFrame", base.unwrap_or(&designcraft_doc::TextFrameOptions::default()))?; + let general = designcraft_doc::TextFrameOptions::GENERAL_KEYS; + let mut p = p.clone(); + if let Some(Value::Object(o)) = p.get_mut("textFrame") { + if let Some(k) = o.keys().find(|k| !general.contains(&k.as_str())) { + return Err(bad(cmd, format!("textFrame.{k} is not a General option ({})", general.join(", ")))); + } + if let Some(n) = o.get("inset").filter(|v| v.is_number()).cloned() { + o.insert("inset".into(), json!([n, n, n, n])); + } + } + let tf = group_param(cmd, &p, "textFrame", base.unwrap_or(&designcraft_doc::TextFrameOptions::default()))?; if let Some(Some(o)) = &tf { - if !(1..=40).contains(&o.columns) { + // Only the values given in this call are checked. + let given = |k: &str| p.get("textFrame").is_some_and(|t| t.get(k).is_some()); + if given("columns") && !(1..=40).contains(&o.columns) { return Err(bad(cmd, "text frame columns must be 1–40")); } - let mut lengths = [o.gutter, o.column_width, o.vj_paragraph_spacing_limit, o.first_baseline_min].into_iter().chain(o.inset); + let lengths = [("gutter", o.gutter), ("columnWidth", o.column_width), ("vjParagraphSpacingLimit", o.vj_paragraph_spacing_limit)]; + let mut lengths = lengths.into_iter().filter(|(k, _)| given(k)).map(|(_, v)| v).chain(o.inset.into_iter().filter(|_| given("inset"))); if !lengths.all(|v| v.is_finite() && (0.0..=15552.0).contains(&v)) { return Err(bad(cmd, "a text frame's gutter, widths and insets must be 0–15552 pt")); } @@ -360,7 +386,7 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { || fill.as_ref().is_some_and(|(o, _)| it.fill == *o) || stroke.as_ref().is_some_and(|(o, _)| it.stroke == *o) || corners.as_ref().is_some_and(|(o, _)| it.corners == o.named_to_path(&it.path)) - || frame.as_ref().is_some_and(|(o, _)| it.text_frame().is_some_and(|t| t.options == *o)) + || frame.as_ref().is_some_and(|(o, _)| it.text_frame().is_some_and(|t| t.options.general_eq(o))) }; let updated = d.update_items( |it| it.object_style == new.name && follows(it), @@ -387,9 +413,9 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { } if let Some((o, n)) = &frame && let Some(tf) = it.text_frame_mut() - && tf.options == *o + && tf.options.general_eq(o) { - tf.options = n.clone(); + tf.options.set_general(n); } }, ); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index fad29a1d7..48cb02446 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -882,6 +882,78 @@ fn object_styles_carry_a_paragraph_style_and_text_frame_options() { assert_eq!((styles_of(&s, a), options(&s, a).columns), (vec!["Box Body Text".to_string(); 3], 2)); } +/// An object style's Text Frame General Options set the columns, insets, vertical justification +/// and Ignore Text Wrap only: a frame keeps its auto-size and column rule, follows an edit of the +/// style while its General options are the style's, and keeps the settings through save and open. +/// Applying a style that changes nothing records no undo step, threaded frames share one Next +/// Style chain, and keys outside the General options are refused. +#[test] +fn object_style_text_frame_general_options_leave_the_other_frame_settings() { + use designcraft_doc::{AutoSize, ItemId, VerticalJustification}; + let mut s = session(); + s.execute("style.paragraph.create", &json!({"name": "Body"})).unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Lead", "nextStyle": "Body"})).unwrap(); + let name = "Callout"; + s.execute( + "style.object.create", + &json!({"name": name, "fromSelection": false, "paragraphStyle": "Lead", "applyNextStyle": true, + "textFrame": {"inset": 6, "verticalJustification": "center"}}), + ) + .unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 36, 156, 200], "content": "text", "text": "One\nTwo", "caret": false})).unwrap(); + let a = r["id"].as_u64().unwrap(); + let b = s.execute("frame.create", &json!({"rect": [200, 36, 320, 200], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.textFrameOptions", &json!({"ids": [a], "autoSize": "heightOnly", "columnRule": true})).unwrap(); + s.execute("style.object.apply", &json!({"name": name, "ids": [a]})).unwrap(); + let options = |s: &Session, id: u64| s.doc().unwrap().doc.item(ItemId(id)).unwrap().text_frame().unwrap().options.clone(); + let o = options(&s, a); + assert_eq!((o.inset, o.vertical_justification), ([6.0; 4], VerticalJustification::Center)); + assert_eq!((o.auto_size, o.column_rule), (AutoSize::HeightOnly, true), "the frame's own auto-size and column rule stay"); + + // Applying it again changes nothing and records no undo step. + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = undo(&s); + s.execute("style.object.apply", &json!({"name": name, "ids": [a]})).unwrap(); + assert_eq!(undo(&s), before, "no undo step when nothing changes"); + + // The frame differs from the style's options only in auto-size, so it follows the edit. + let r = s.execute("style.object.edit", &json!({"name": name, "textFrame": {"inset": [1, 2, 3, 4], "ignoreWrap": true}})).unwrap(); + assert_eq!(r["updated"], 1); + let o = options(&s, a); + assert_eq!((o.inset, o.ignore_wrap, o.auto_size), ([1.0, 2.0, 3.0, 4.0], true, AutoSize::HeightOnly)); + + // Threaded frames: the story's paragraphs take one Next Style chain across both frames. + s.execute("text.thread", &json!({"from": a, "to": b})).unwrap(); + s.execute("style.object.apply", &json!({"name": name, "ids": [a, b]})).unwrap(); + let d = &s.doc().unwrap().doc; + let sid = d.item(ItemId(a)).unwrap().text_frame().unwrap().story; + assert_eq!(d.item(ItemId(b)).unwrap().text_frame().unwrap().story, sid); + assert_eq!(d.story(sid).unwrap().paras.iter().map(|p| p.style.as_str()).collect::>(), ["Lead", "Body"]); + + // Save and open keep the style's General options and Apply Next Style. + let bytes = s.execute("file.serialize", &json!({})).unwrap(); + let mut back = Session::new(); + back.execute("file.openBytes", &json!({"name": "copy", "base64": bytes["base64"]})).unwrap(); + let os = back.doc().unwrap().doc.styles.object_style(name).cloned().unwrap(); + assert!(os.apply_next_style); + assert_eq!(os.text_frame.map(|t| (t.inset, t.ignore_wrap)), Some(([1.0, 2.0, 3.0, 4.0], true))); + + // Keys outside the General options, a misspelled key and a word for the inset are refused. + for bad in [json!({"autoSize": "heightOnly"}), json!({"insets": 4}), json!({"inset": "wide"}), json!({"verticalJustification": "middle"})] { + let p = json!({"name": name, "textFrame": bad}); + assert!(s.execute("style.object.edit", &p).is_err(), "{bad}"); + } + // A style that already holds 60 columns (as a file can give it) takes other edits, and 60 + // given again is refused. + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let st = d.styles_mut().object.iter_mut().find(|o| o.name == name).unwrap(); + st.text_frame.as_mut().unwrap().columns = 60; + } + s.execute("style.object.edit", &json!({"name": name, "textFrame": {"inset": 2}})).unwrap(); + assert!(s.execute("style.object.edit", &json!({"name": name, "textFrame": {"columns": 60}})).is_err()); +} + #[test] fn object_style_effects_reach_grouped_and_anchored_items() { use designcraft_doc::ItemId; diff --git a/crates/idml/src/import/styles.rs b/crates/idml/src/import/styles.rs index 5fa1aa87e..e82d8fc0b 100644 --- a/crates/idml/src/import/styles.rs +++ b/crates/idml/src/import/styles.rs @@ -197,8 +197,16 @@ impl<'r> Importer<'r> { let paragraph_style = enabled("EnableParagraphStyle", "AppliedParagraphStyle") .then(|| e.get("AppliedParagraphStyle").map(|r| self.para_style_ref(r))) .flatten(); + let levels = based_on_levels(e, &objects_by_self); + // Text Frame General Options: each attribute from the nearest style whose + // `TextFramePreference` sets it, among the styles that don't turn the category off. let text_frame = if e.get("EnableTextFrameGeneralOptions") == Some("true") { - e.find("TextFramePreference").map(|t| self.frame_options(&[t])) + let prefs: Vec<&El> = levels + .iter() + .filter(|l| l.get("EnableTextFrameGeneralOptions") != Some("false")) + .filter_map(|l| l.find("TextFramePreference")) + .collect(); + (!prefs.is_empty()).then(|| self.frame_options(&prefs)) } else { None }; @@ -207,19 +215,7 @@ impl<'r> Importer<'r> { // that sets some corners takes the others from the styles it is based on, as the style // holds all four. let corners = (e.get("EnableStrokeAndCornerOptions") != Some("false") && corners(e, "").is_some()) - .then(|| { - let mut levels = vec![e]; - let mut next = e.prop("BasedOn"); - while let Some(b) = next.take() - && levels.len() < 16 - && let Some(s) = objects_by_self.get(b.trim()).copied() - && !levels.iter().any(|l| std::ptr::eq(*l, s)) - { - levels.push(s); - next = s.prop("BasedOn"); - } - corners_in(&levels, "") - }) + .then(|| corners_in(&levels, "")) .flatten() .map(|c| CornerOptions { corners: c }); let apply_next_style = paragraph_style.is_some() && e.get("ApplyNextParagraphStyle") == Some("true"); @@ -421,3 +417,23 @@ impl<'r> Importer<'r> { } } } + +/// Object style `e`, then the styles it is based on, nearest first (cycle-safe, at most 16). A +/// `BasedOn` may name a style by its `Self` id or by its bare name. +fn based_on_levels<'e>(e: &'e El, objects_by_self: &HashMap<&str, &'e El>) -> Vec<&'e El> { + let id = |b: String| { + let b = b.trim(); + if b.starts_with("ObjectStyle/") { b.to_string() } else { format!("ObjectStyle/{}", names::escape_id(b)) } + }; + let mut levels = vec![e]; + let mut next = e.prop("BasedOn").map(id); + while let Some(b) = next.take() + && levels.len() < 16 + && let Some(s) = objects_by_self.get(b.as_str()).copied() + && !levels.iter().any(|l| std::ptr::eq(*l, s)) + { + levels.push(s); + next = s.prop("BasedOn").map(id); + } + levels +} diff --git a/crates/idml/src/tests/object_styles.rs b/crates/idml/src/tests/object_styles.rs index faaef4f32..52605d7a0 100644 --- a/crates/idml/src/tests/object_styles.rs +++ b/crates/idml/src/tests/object_styles.rs @@ -177,6 +177,43 @@ fn object_style_apply_next_style_round_trips() { } } +/// A style's Text Frame General Options take each setting its own `TextFramePreference` leaves out +/// from the style it is based on (named by its id or bare name, and only when that style doesn't +/// turn the category off), and export and import keep the merged options. +#[test] +fn object_style_text_frame_options_inherit_from_the_based_on_style() { + let styles = r#" + $ID/[None] + + + + ObjectStyle/Box + + + + Box + + + + $ID/[None] + + + + ObjectStyle/Off + + "#; + let d = fixture(styles, &[]); + let tf = d.styles.object_style("Inset").and_then(|s| s.text_frame.clone()).expect("Inset sets text frame options"); + assert_eq!((tf.inset, tf.columns, tf.vertical_justification), ([9.0; 4], 2, designcraft_doc::VerticalJustification::Center)); + let bare = d.styles.object_style("Bare").and_then(|s| s.text_frame.clone()).expect("Bare sets text frame options"); + assert_eq!((bare.inset, bare.columns), ([3.0; 4], 2), "a BasedOn given as a bare name"); + let on_off = d.styles.object_style("OnOff").and_then(|s| s.text_frame.clone()).expect("OnOff sets text frame options"); + assert_eq!((on_off.inset, on_off.columns), ([1.0; 4], 1), "a based-on style with the category off gives nothing"); + let back = import_idml(&export_idml(&d)).unwrap(); + let again = back.styles.object_style("Inset").and_then(|s| s.text_frame.clone()).expect("after a round trip"); + assert!(again.general_eq(&tf), "{again:?}"); +} + #[test] fn exported_frames_keep_their_own_values_over_their_object_style() { let mut d = small_doc(); diff --git a/crates/ui-egui/src/i18n/hu.rs b/crates/ui-egui/src/i18n/hu.rs index ab30bce8d..bbf3a6ed3 100644 --- a/crates/ui-egui/src/i18n/hu.rs +++ b/crates/ui-egui/src/i18n/hu.rs @@ -1979,6 +1979,19 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Measure Tool", "Mérőeszköz"), ("Hand Tool", "Kéz eszköz"), ("Zoom Tool", "Nagyító eszköz"), + ("Apply Next Style", "Következő stílus alkalmazása"), + ("Text Frame General Options", "Szövegkeret általános beállításai"), + ("New Object Style", "Új objektumstílus"), + ("Object Style Options", "Objektumstílus beállításai"), + ("Object Style Options…", "Objektumstílus beállításai…"), + ("Basic Attributes", "Alapattribútumok"), + ("Stroke & Corner Options", "Körvonal- és sarokbeállítások"), + ("Effects for:", "Hatások ehhez:"), + ("Create New Style", "Új stílus létrehozása"), + ("Clear Overrides", "Felülírások törlése"), + ("Shape:", "Alakzat:"), + ("(no attributes)", "(nincsenek attribútumok)"), + ("Enter a style name.", "Adjon meg egy stílusnevet."), ]; pub(super) const CONTEXT: &[(&str, &str, &str)] = diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index f3b0e7df0..2c5f6d356 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -41,7 +41,6 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Text Frame General Options", "Opções gerais do quadro de texto"), ("New Object Style", "Novo estilo de objeto"), ("Object Style Options", "Opções de estilo de objeto"), - ("Object Style Options…", "Opções de estilo de objeto…"), ("Basic Attributes", "Atributos básicos"), ("Stroke & Corner Options", "Opções de traçado e canto"), ("Effects for:", "Efeitos para:"), @@ -50,7 +49,6 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Shape:", "Forma:"), ("(no attributes)", "(sem atributos)"), ("Enter a style name.", "Digite um nome de estilo."), - ("Corner Options", "Opções de canto"), ("Keep In Frame", "Manter no quadro"), ("New Paragraph Style", "Novo estilo de parágrafo"), ("New Character Style", "Novo estilo de caractere"), diff --git a/crates/ui-egui/src/i18n/sv.rs b/crates/ui-egui/src/i18n/sv.rs index 766ba32da..fe85de091 100644 --- a/crates/ui-egui/src/i18n/sv.rs +++ b/crates/ui-egui/src/i18n/sv.rs @@ -2968,6 +2968,18 @@ pub(super) const TABLE: &[(&str, &str)] = &[ "Links and Images: {found} linked, {modified} changed, {missing} not found", "Länkar och bilder: {found} länkade, {modified} ändrade, {missing} hittades inte", ), + ("Apply Next Style", "Använd nästa stil"), + ("Text Frame General Options", "Allmänna alternativ för textram"), + ("New Object Style", "Ny objektstil"), + ("Object Style Options", "Alternativ för objektstil"), + ("Basic Attributes", "Grundläggande attribut"), + ("Stroke & Corner Options", "Kontur- och hörnalternativ"), + ("Effects for:", "Effekter för:"), + ("Create New Style", "Skapa ny stil"), + ("Clear Overrides", "Rensa lokala ändringar"), + ("Shape:", "Form:"), + ("(no attributes)", "(inga attribut)"), + ("Enter a style name.", "Ange ett stilnamn."), ]; pub(super) const CONTEXT: &[(&str, &str, &str)] = &[ diff --git a/crates/ui-egui/src/object_style_dialog.rs b/crates/ui-egui/src/object_style_dialog.rs index 5ce0d56a5..bdac19645 100644 --- a/crates/ui-egui/src/object_style_dialog.rs +++ b/crates/ui-egui/src/object_style_dialog.rs @@ -153,10 +153,22 @@ fn frame_options(d: &Dialog) -> Result *side = measure(key).ok_or_else(|| bad("an inset is not a measure"))?; } o.vertical_justification = serde_json::from_value(json!(d.s("verticalJustification"))).unwrap_or(o.vertical_justification); + if o.vertical_justification == designcraft_doc::VerticalJustification::Justify { + o.vj_paragraph_spacing_limit = measure("paragraphSpacingLimit").ok_or_else(|| bad("the paragraph spacing limit is not a measure"))?; + } o.ignore_wrap = d.b("ignoreWrap"); Ok(Some(o)) } +/// The General options of `o` as the `textFrame` parameter of `style.object.create` and `edit`. +fn general_json(o: &designcraft_doc::TextFrameOptions) -> Value { + let mut v = serde_json::to_value(o).unwrap_or_default(); + if let Value::Object(m) = &mut v { + m.retain(|k, _| designcraft_doc::TextFrameOptions::GENERAL_KEYS.contains(&k.as_str())); + } + v +} + /// OK: the new style (applied to the selection when asked), or the edited one. pub fn confirm(app: &mut DesignApp, d: &Dialog) -> Result { let name = d.s("name").trim().to_string(); @@ -164,7 +176,7 @@ pub fn confirm(app: &mut DesignApp, d: &Dialog) -> Result { return Err(crate::i18n::tr(&app.ui.language, "Enter a style name.").to_string()); } let mut p = attrs(d); - p.insert("textFrame".into(), frame_options(d)?.map_or(Value::Null, |o| serde_json::to_value(o).unwrap_or_default())); + p.insert("textFrame".into(), frame_options(d)?.map_or(Value::Null, |o| general_json(&o))); if d.b("new") { p.insert("name".into(), json!(name)); p.insert("fromSelection".into(), json!(false)); @@ -694,6 +706,31 @@ mod tests { assert_eq!(os.text_frame.map(|t| t.columns), Some(2), "2.5 columns changed nothing"); } + /// Text Frame General Options › Vertical Justification: Justify with a Paragraph Spacing Limit + /// sets both on the style and its frame, and the frame keeps its auto-size setting. + #[test] + fn the_general_options_page_sets_the_paragraph_spacing_limit() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let r = app.run("frame.create", json!({"rect": [36, 36, 336, 336], "content": "text", "caret": false})).unwrap(); + let id = r["id"].as_u64().unwrap(); + app.run("object.textFrameOptions", json!({"ids": [id], "autoSize": "heightOnly"})).unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + open_new(&mut app); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("name".into(), json!("Justified")); + d.fields.insert("verticalJustification".into(), json!("justify")); + d.fields.insert("paragraphSpacingLimit".into(), json!("6 pt")); + } + crate::dialogs::confirm(&mut app).unwrap(); + let doc = app.session.active().unwrap().doc.clone(); + let tf = doc.styles.object_style("Justified").and_then(|s| s.text_frame.clone()).unwrap(); + assert_eq!((tf.vertical_justification, tf.vj_paragraph_spacing_limit), (designcraft_doc::VerticalJustification::Justify, 6.0)); + app.run("style.object.apply", json!({"name": "Justified", "ids": [id]})).unwrap(); + let o = app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().text_frame().unwrap().options.clone(); + assert_eq!((o.vj_paragraph_spacing_limit, o.auto_size), (6.0, designcraft_doc::AutoSize::HeightOnly)); + } + /// `objectStyle.dialog` with a style the document lacks, or `[None]`, is an error and opens /// nothing; without a name it opens New Object Style. #[test] From 966c8a587cce0d2853f1977cb73889ea4d8446d1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:01:47 -0800 Subject: [PATCH 0963/1349] Recovery: a cancel stops a background write at its next chunk A save, revert or close during a background recovery write now stops the write at its next piece of output (at most 1 MiB) instead of after the whole package, and a stopped write is not reported as a failure. --- crates/engine/src/lib.rs | 1 + crates/engine/src/recovery.rs | 41 ++++++++++++++++++++++++++--- crates/engine/src/recovery/tests.rs | 20 ++++++++++++++ 3 files changed, 59 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index bb67875b4..363f4e9cd 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -414,6 +414,7 @@ pub struct Session { pub recovery_dir: Option, /// This session's number for the background recovery writer, which returns each result to /// the session that queued it. + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] pub(crate) recovery_owner: recovery::Owner, /// Copied text with its formatting (a frameless story slice), its plain text, and what pasting /// it needs from its document: a copy holding only the stories its anchored text frames show diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index e2e09a42b..3b4060763 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -725,6 +725,36 @@ struct Written { error: Option, } +/// A writer that fails once `cancelled` says so, checked before each write of at most +/// [`STOP_CHECK_BYTES`]. +struct StopWhen<'a, W, C> { + out: &'a mut W, + cancelled: &'a C, +} + +/// The most [`StopWhen`] writes between two checks for a cancel. +const STOP_CHECK_BYTES: usize = 1 << 20; + +impl bool> std::io::Write for StopWhen<'_, W, C> { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if (self.cancelled)() { + return Err(std::io::Error::other("recovery write cancelled")); + } + // A large placed file is written in pieces, so a cancel does not wait for all of it. + self.out.write(&buf[..buf.len().min(STOP_CHECK_BYTES)]) + } + + fn flush(&mut self) -> std::io::Result<()> { + self.out.flush() + } +} + +impl std::io::Seek for StopWhen<'_, W, C> { + fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result { + self.out.seek(pos) + } +} + /// Publish a document's recovery entry before its optional metadata. `cancelled` says whether the /// document was saved, reverted or closed since the write started: its snapshot is then dropped /// instead of published, so a crash cannot offer back a copy older than the saved file. @@ -735,7 +765,10 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { let published = publish_recovery_written( &doc, entry.own, - |out| designcraft_format::write(out, &entry.doc, None).map_err(|e| EngineError::Other(e.to_string())), + // A cancel stops the write at its next chunk instead of after the whole package. + |out| { + designcraft_format::write(&mut StopWhen { out, cancelled: &cancelled }, &entry.doc, None).map_err(|e| EngineError::Other(e.to_string())) + }, &cancelled, // Written: in a folder that is not this run's own, the entry is now this run's to replace // and remove (Save and Close must clean up the snapshot they wrote). Recorded with the @@ -748,8 +781,10 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { ); match published { Ok(true) => {} - // Cancelled while writing: no snapshot and no metadata for it. + // Cancelled while writing: no snapshot and no metadata for it. A write stopped part way + // reports an error, which is the cancel's and not a failure. Ok(false) => return Written { published: false, error: None }, + Err(_) if cancelled() => return Written { published: false, error: None }, Err(e) => return Written { published: false, error: Some(e) }, } let metadata = json!({"path": entry.path, "title": entry.title, "saved": designcraft_doc::vars::now()}); @@ -758,7 +793,7 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { let error = publish_recovery_written( &meta, entry.own, - |out| out.write_all(bytes.as_bytes()).map_err(|e| EngineError::Other(format!("{}: {e}", meta.display()))), + |out| std::io::Write::write_all(out, bytes.as_bytes()).map_err(|e| EngineError::Other(format!("{}: {e}", meta.display()))), &cancelled, || {}, ) diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index c59c5ee76..4534c3c37 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -514,6 +514,26 @@ fn a_write_cancelled_midway_publishes_nothing() { ); } +#[test] +fn a_cancel_stops_a_write_before_the_package_is_finished() { + let dir = tempfile::tempdir().unwrap(); + let s = dirty_session(); + let entry = Snapshot::of(&prepare_save(&s, dir.path()).unwrap(), dir.path(), &s.docs[0]); + // Cancelled once the write has started: the first check passes, every later one fails. + let checks = std::cell::Cell::new(0); + let written = write_snapshot(&entry, || { + checks.set(checks.get() + 1); + checks.get() > 1 + }); + assert!(!written.published && written.error.is_none(), "a stopped write is not an error"); + assert!(checks.get() >= 2, "the write checked again before it finished"); + assert!(!files(dir.path(), entry.uid).0.exists(), "nothing was published"); + assert!( + std::fs::read_dir(dir.path()).unwrap().all(|e| e.is_ok_and(|e| !e.file_name().to_string_lossy().starts_with(".designcraft-recovery-"))), + "no temporary file is left" + ); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn only_a_queued_write_is_cancelled() { From 16d60dc03a54695731c770911ac222ce251074d0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:04:28 -0800 Subject: [PATCH 0964/1349] Object styles: options follow one by one; corner sizes are checked - Editing a style's Text Frame General Options updates each option a frame still shares with the style, so a frame's own inset stays while a new column count reaches it. - style.object.create and edit refuse corner sizes outside 0-10000 pt instead of clamping them. - IDML import: a style that turns Stroke & Corner Options on without corner attributes of its own takes all four corners from the styles it is based on. --- crates/doc/src/item/text_frame.rs | 16 ++++++++++++++++ crates/engine/src/cmd/style/object.rs | 15 +++++++-------- crates/engine/src/tests.rs | 11 +++++++++++ crates/idml/src/import/styles.rs | 23 ++++++++++++++++------- crates/idml/src/tests/object_styles.rs | 12 ++++++++++++ 5 files changed, 62 insertions(+), 15 deletions(-) diff --git a/crates/doc/src/item/text_frame.rs b/crates/doc/src/item/text_frame.rs index 5c01bb21b..cb437e149 100644 --- a/crates/doc/src/item/text_frame.rs +++ b/crates/doc/src/item/text_frame.rs @@ -268,6 +268,22 @@ impl TextFrameOptions { && self.ignore_wrap == other.ignore_wrap } + /// Each General option that is `old`'s here takes `new`'s; the others stay. `true` when one + /// changed. + pub fn follow_general(&mut self, old: &TextFrameOptions, new: &TextFrameOptions) -> bool { + let mut changed = false; + macro_rules! follow { + ($($f:ident),*) => {$( + if self.$f == old.$f && self.$f != new.$f { + self.$f = new.$f; + changed = true; + } + )*}; + } + follow!(columns, columns_kind, gutter, column_width, balance_columns, inset, vertical_justification, vj_paragraph_spacing_limit, ignore_wrap); + changed + } + /// Copies the General options of `from` (see [`Self::GENERAL_KEYS`]). Baseline, auto-size, /// column rule and Type on a Path settings stay as they are. pub fn set_general(&mut self, from: &TextFrameOptions) { diff --git a/crates/engine/src/cmd/style/object.rs b/crates/engine/src/cmd/style/object.rs index 6c7455099..50f38e835 100644 --- a/crates/engine/src/cmd/style/object.rs +++ b/crates/engine/src/cmd/style/object.rs @@ -293,11 +293,9 @@ fn corners_param( let size = sz.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(cmd, "corner size must be a number"))?; c.corners.iter_mut().for_each(|k| k.size = size); } - for k in &mut c.corners { - if !k.size.is_finite() { - return Err(bad(cmd, "corner sizes must be finite")); - } - k.size = k.size.clamp(0.0, 10_000.0); + // Sizes given in this call must be 0–10000 pt. + if (o.contains_key("corners") || o.contains_key("size")) && !c.corners.iter().all(|k| k.size.is_finite() && (0.0..=10_000.0).contains(&k.size)) { + return Err(bad(cmd, "corner sizes must be 0–10000 pt")); } Ok(Some(Some(c))) } @@ -386,7 +384,7 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { || fill.as_ref().is_some_and(|(o, _)| it.fill == *o) || stroke.as_ref().is_some_and(|(o, _)| it.stroke == *o) || corners.as_ref().is_some_and(|(o, _)| it.corners == o.named_to_path(&it.path)) - || frame.as_ref().is_some_and(|(o, _)| it.text_frame().is_some_and(|t| t.options.general_eq(o))) + || frame.as_ref().is_some_and(|(o, n)| it.text_frame().is_some_and(|t| t.options.clone().follow_general(o, n))) }; let updated = d.update_items( |it| it.object_style == new.name && follows(it), @@ -411,11 +409,12 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { { it.corners = n.named_to_path(&it.path); } + // Each General option follows on its own, so a frame's own inset stays while a + // new column count reaches it. if let Some((o, n)) = &frame && let Some(tf) = it.text_frame_mut() - && tf.options.general_eq(o) { - tf.options.set_general(n); + tf.options.follow_general(o, n); } }, ); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 48cb02446..d559fd7d2 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -792,6 +792,12 @@ fn object_styles_carry_corners_and_their_stroke_and_corners_can_be_edited() { assert!(s.execute("style.object.edit", &json!({"name": "Framed", "rename": "[Basic Text Frame]"})).is_err()); assert!(s.execute("style.object.edit", &json!({"name": "[Basic Graphics Frame]", "rename": "Mine"})).is_err()); assert!(s.execute("style.object.edit", &json!({"name": "Framed", "corners": {"size": "big"}})).is_err()); + // A size outside 0–10000 pt is refused, not changed. + for size in [-1.0, 10_001.0] { + assert!(s.execute("style.object.edit", &json!({"name": "Framed", "corners": {"size": size}})).is_err(), "{size}"); + let c = json!({"shape": "rounded", "size": size}); + assert!(s.execute("style.object.create", &json!({"name": "Odd", "corners": {"corners": [c, c, c, c]}})).is_err(), "{size}"); + } // A negative stroke weight is refused when creating a style as when editing one. let styles = s.doc().unwrap().doc.styles.object.len(); for cmd in ["style.object.create", "style.object.edit"] { @@ -921,6 +927,11 @@ fn object_style_text_frame_general_options_leave_the_other_frame_settings() { assert_eq!(r["updated"], 1); let o = options(&s, a); assert_eq!((o.inset, o.ignore_wrap, o.auto_size), ([1.0, 2.0, 3.0, 4.0], true, AutoSize::HeightOnly)); + // Each option follows on its own: the frame's own inset stays and the new column count arrives. + s.execute("object.textFrameOptions", &json!({"ids": [a], "inset": 9})).unwrap(); + s.execute("style.object.edit", &json!({"name": name, "textFrame": {"columns": 3}})).unwrap(); + let o = options(&s, a); + assert_eq!((o.columns, o.inset), (3, [9.0; 4])); // Threaded frames: the story's paragraphs take one Next Style chain across both frames. s.execute("text.thread", &json!({"from": a, "to": b})).unwrap(); diff --git a/crates/idml/src/import/styles.rs b/crates/idml/src/import/styles.rs index e82d8fc0b..e2e11e979 100644 --- a/crates/idml/src/import/styles.rs +++ b/crates/idml/src/import/styles.rs @@ -211,13 +211,7 @@ impl<'r> Importer<'r> { None }; let effects = self.style_effects(e); - // Corner options, when the style sets them (Stroke & Corner Options), by name. A style - // that sets some corners takes the others from the styles it is based on, as the style - // holds all four. - let corners = (e.get("EnableStrokeAndCornerOptions") != Some("false") && corners(e, "").is_some()) - .then(|| corners_in(&levels, "")) - .flatten() - .map(|c| CornerOptions { corners: c }); + let corners = style_corners(e, &levels); let apply_next_style = paragraph_style.is_some() && e.get("ApplyNextParagraphStyle") == Some("true"); let s = ObjectStyle { name: name.clone(), based_on, fill, stroke, paragraph_style, apply_next_style, text_frame, effects, corners }; match self.styles.object.iter_mut().find(|o| o.name == name) { @@ -418,6 +412,21 @@ impl<'r> Importer<'r> { } } +/// Object style `e`'s corner options (Stroke & Corner Options), by name, when it sets them. A style +/// that sets some corners, or turns the category on, takes the others from the styles in `levels` +/// (`e` and the styles it is based on) that don't turn the category off. +fn style_corners(e: &El, levels: &[&El]) -> Option { + match e.get("EnableStrokeAndCornerOptions") { + Some("false") => return None, + Some("true") => {} + _ => { + corners(e, "")?; + } + } + let on: Vec<&El> = levels.iter().copied().filter(|l| l.get("EnableStrokeAndCornerOptions") != Some("false")).collect(); + corners_in(&on, "").map(|c| CornerOptions { corners: c }) +} + /// Object style `e`, then the styles it is based on, nearest first (cycle-safe, at most 16). A /// `BasedOn` may name a style by its `Self` id or by its bare name. fn based_on_levels<'e>(e: &'e El, objects_by_self: &HashMap<&str, &'e El>) -> Vec<&'e El> { diff --git a/crates/idml/src/tests/object_styles.rs b/crates/idml/src/tests/object_styles.rs index 52605d7a0..4ff0fa6bf 100644 --- a/crates/idml/src/tests/object_styles.rs +++ b/crates/idml/src/tests/object_styles.rs @@ -314,6 +314,18 @@ fn a_style_setting_one_corner_inherits_the_others_and_names_them() { assert_eq!(it.corners.corners.map(|c| c.shape), [CornerShape::Rounded, CornerShape::Rounded, CornerShape::Rounded, CornerShape::Bevel]); } +/// A style that turns Stroke & Corner Options on without corner attributes of its own takes all +/// four corners from the style it is based on. +#[test] +fn a_style_turning_corners_on_inherits_all_four() { + let child = r#" + ObjectStyle/Round + "#; + let d = fixture(&format!("{ROUND}{child}"), &[]); + let c = d.styles.object.iter().find(|s| s.name == "Plain").and_then(|s| s.corners).expect("inherited corners").corners; + assert_eq!((c.map(|c| c.shape), c.map(|c| c.size)), ([CornerShape::Rounded; 4], [17.0; 4])); +} + /// An object style giving its corners only with the legacy all-corners `CornerOption` and /// `CornerRadius` keeps them, so applying it to another frame rounds it. #[test] From 4973d11569d99ea0b2ad9e6ca7944895218ff4cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:15:03 -0800 Subject: [PATCH 0965/1349] Object styles: unknown swatches and settings are refused - style.object.create and edit refuse a fill, stroke or gap swatch the document lacks, and a fill or stroke key that is not a setting of it (a misspelled "wieght" no longer succeeds without a change). - fromSelection must be true or false. --- crates/engine/src/cmd/style.rs | 4 +-- crates/engine/src/cmd/style/object.rs | 46 ++++++++++++++++++++++----- crates/engine/src/tests.rs | 15 +++++++++ 3 files changed, 55 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 5b1ac047d..7e55e0529 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -182,7 +182,7 @@ pub fn specs() -> Vec { "New Object Style…", [], None, - "{name, fromSelection?: true (fill, stroke, corners, effects and text frame options of the first selected item), fill?: swatch | {swatch?, tint?}, stroke?: {swatch?, weight?, tint?, type?, …}, corners?: {shape?, size?} | {corners: [{shape, size}] ×4}, paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns? (1–40), columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right] | one number for all four, verticalJustification?: top|center|bottom|justify, vjParagraphSpacingLimit?, ignoreWrap?} | null (Text Frame General Options, named as `document.inspect` names text frame options; lengths 0–15552 pt; other keys are refused; a frame keeps its baseline, auto-size and column rule settings; null: the style sets none), effects?: {dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?}, dropShadow?: {on?, color?, opacity? (0–1), angle?, globalLight?, distance?, size?, spread?}, feather?: width, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} → {name} (made unique)", + "{name, fromSelection?: true (fill, stroke, corners, effects and text frame options of the first selected item), fill?: swatch | {swatch?, tint?}, stroke?: {swatch?, weight?, tint?, type?, …} (swatches must exist; unknown fill and stroke keys are refused), corners?: {shape?, size?} | {corners: [{shape, size}] ×4}, paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns? (1–40), columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right] | one number for all four, verticalJustification?: top|center|bottom|justify, vjParagraphSpacingLimit?, ignoreWrap?} | null (Text Frame General Options, named as `document.inspect` names text frame options; lengths 0–15552 pt; other keys are refused; a frame keeps its baseline, auto-size and column rule settings; null: the style sets none), effects?: {dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?}, dropShadow?: {on?, color?, opacity? (0–1), angle?, globalLight?, distance?, size?, spread?}, feather?: width, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} → {name} (made unique)", has_doc, create_object ), @@ -191,7 +191,7 @@ pub fn specs() -> Vec { "Object Style Options…", [], None, - "{name, rename?: new name (every use follows), fill?: swatch | {swatch?, tint?} | null, stroke?: {swatch?, weight?, tint?, type?, …} | null, corners?: {shape?: none|rounded|inverseRounded|inset|bevel|fancy, size?} | {corners: [{shape, size}] ×4} | null (null: the style no longer sets it; items keep theirs), paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns? (1–40), columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right] | one number for all four, verticalJustification?: top|center|bottom|justify, vjParagraphSpacingLimit?, ignoreWrap?} | null (Text Frame General Options, named as `document.inspect` names text frame options; lengths 0–15552 pt; other keys are refused; a frame keeps its baseline, auto-size and column rule settings; null: the style sets none), effects?: {…} | null (the style no longer sets effects), dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} — effect objects merge field by field into the style's effects (fields as in `document.inspect` item effects); values that aren't finite numbers are refused, the others clamped (opacities 0–1, sizes and distances ≥ 0); items using the style whose effects (fill, stroke, corners) match the style's (an item's defaults, when the style set none) take the new ones, items with their own keep them; the text of frames still in the old paragraph styles takes the new ones → {name, updated, restyled}", + "{name, rename?: new name (every use follows), fill?: swatch | {swatch?, tint?} | null, stroke?: {swatch?, weight?, tint?, type?, …} | null (swatches must exist; unknown fill and stroke keys are refused), corners?: {shape?: none|rounded|inverseRounded|inset|bevel|fancy, size?} | {corners: [{shape, size}] ×4} | null (null: the style no longer sets it; items keep theirs), paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns? (1–40), columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right] | one number for all four, verticalJustification?: top|center|bottom|justify, vjParagraphSpacingLimit?, ignoreWrap?} | null (Text Frame General Options, named as `document.inspect` names text frame options; lengths 0–15552 pt; other keys are refused; a frame keeps its baseline, auto-size and column rule settings; null: the style sets none), effects?: {…} | null (the style no longer sets effects), dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} — effect objects merge field by field into the style's effects (fields as in `document.inspect` item effects); values that aren't finite numbers are refused, the others clamped (opacities 0–1, sizes and distances ≥ 0); items using the style whose effects (fill, stroke, corners) match the style's (an item's defaults, when the style set none) take the new ones, items with their own keep them; the text of frames still in the old paragraph styles takes the new ones → {name, updated, restyled}", has_doc, edit_object ), diff --git a/crates/engine/src/cmd/style/object.rs b/crates/engine/src/cmd/style/object.rs index 50f38e835..2a8ec7dd3 100644 --- a/crates/engine/src/cmd/style/object.rs +++ b/crates/engine/src/cmd/style/object.rs @@ -131,7 +131,9 @@ fn merge_json(base: &mut Value, top: Value, depth: usize) { pub(super) fn create_object(s: &mut Session, p: &Value) -> Result { let base = str_param(p, "name").unwrap_or("Object Style 1").to_string(); - let from_sel = p.get("fromSelection").and_then(Value::as_bool).unwrap_or(true); + const CREATE: &str = "style.object.create"; + check_swatches(CREATE, s, p)?; + let from_sel = bool_param(CREATE, p, "fromSelection")?.unwrap_or(true); let src = if from_sel { s.doc()?.selection.items.first().and_then(|i| s.doc().ok()?.doc.item(*i).cloned()) } else { None }; let mut os = ObjectStyle::default(); if let Some(it) = &src { @@ -141,7 +143,6 @@ pub(super) fn create_object(s: &mut Session, p: &Value) -> Result { os.text_frame = it.text_frame().map(|t| t.options.clone()); os.effects = Some(it.effects.clone()); } - const CREATE: &str = "style.object.create"; if let Some(f) = fill_param(CREATE, p, os.fill.as_ref())? { os.fill = f; } @@ -171,6 +172,23 @@ pub(super) fn create_object(s: &mut Session, p: &Value) -> Result { }) } +/// The swatches this call gives (`fill` as a name or `fill.swatch`, `stroke.swatch` and +/// `stroke.gapSwatch`) must be swatches of the document. +fn check_swatches(cmd: &str, s: &Session, p: &Value) -> Result<()> { + let doc = &s.doc()?.doc; + let given = [ + ("fill", p.get("fill").and_then(|f| f.as_str().or_else(|| f.get("swatch").and_then(Value::as_str)))), + ("stroke", p.get("stroke").and_then(|f| f.get("swatch")).and_then(Value::as_str)), + ("stroke gap", p.get("stroke").and_then(|f| f.get("gapSwatch")).and_then(Value::as_str)), + ]; + for (key, name) in given { + if let Some(name) = name { + crate::cmd::object::known_swatch(doc, name, cmd, key)?; + } + } + Ok(()) +} + /// `paragraphStyle`: a paragraph style's name, or null (the object style sets none). fn paragraph_style_param(cmd: &str, s: &Session, p: &Value) -> Result>> { match p.get("paragraphStyle") { @@ -200,7 +218,7 @@ fn text_frame_param( o.insert("inset".into(), json!([n, n, n, n])); } } - let tf = group_param(cmd, &p, "textFrame", base.unwrap_or(&designcraft_doc::TextFrameOptions::default()))?; + let tf = group_param(cmd, &p, "textFrame", base.unwrap_or(&designcraft_doc::TextFrameOptions::default()), &[])?; if let Some(Some(o)) = &tf { // Only the values given in this call are checked. let given = |k: &str| p.get("textFrame").is_some_and(|t| t.get(k).is_some()); @@ -228,7 +246,8 @@ fn bool_param(cmd: &str, p: &Value, key: &str) -> Result> { /// `p.stroke` merged over `base` (as [`group_param`]), refused when the weight isn't a number ≥ 0 /// or the tint isn't 0–1. fn stroke_param(cmd: &str, p: &Value, base: Option<&designcraft_doc::Stroke>) -> Result>> { - let st = group_param(cmd, p, "stroke", base.unwrap_or(&designcraft_doc::Stroke::default()))?; + let optional = ["gapOverprint", "gradientAngle", "gradientVector"]; + let st = group_param(cmd, p, "stroke", base.unwrap_or(&designcraft_doc::Stroke::default()), &optional)?; if let Some(Some(st)) = &st { if !(st.weight.is_finite() && st.weight >= 0.0) { return Err(bad(cmd, "stroke weight must be a number ≥ 0")); @@ -241,13 +260,23 @@ fn stroke_param(cmd: &str, p: &Value, base: Option<&designcraft_doc::Stroke>) -> } /// `p[key]`, an attribute group of a style, merged field by field over `base`: `None` when not -/// given, `Some(None)` for null (the style no longer sets it). -fn group_param(cmd: &str, p: &Value, key: &str, base: &T) -> Result>> { +/// given, `Some(None)` for null (the style no longer sets it). A field `base` doesn't write and +/// `optional` doesn't name is refused. +fn group_param( + cmd: &str, + p: &Value, + key: &str, + base: &T, + optional: &[&str], +) -> Result>> { match p.get(key) { None => Ok(None), Some(Value::Null) => Ok(Some(None)), - Some(v @ Value::Object(_)) => { + Some(v @ Value::Object(given)) => { let mut cur = serde_json::to_value(base).map_err(|e| bad(cmd, e.to_string()))?; + if let Some(k) = given.keys().find(|k| cur.get(k.as_str()).is_none() && !optional.contains(&k.as_str())) { + return Err(bad(cmd, format!("{key}.{k} is not a {key} setting"))); + } merge_json(&mut cur, v.clone(), 0); serde_json::from_value(cur).map(|t| Some(Some(t))).map_err(|e| bad(cmd, format!("{key}: {e}"))) } @@ -260,7 +289,7 @@ fn fill_param(cmd: &str, p: &Value, base: Option<&designcraft_doc::Fill>) -> Res if let Some(sw) = p.get("fill").and_then(Value::as_str) { return Ok(Some(Some(designcraft_doc::Fill::swatch(sw)))); } - let fill = group_param(cmd, p, "fill", base.unwrap_or(&designcraft_doc::Fill::default()))?; + let fill = group_param(cmd, p, "fill", base.unwrap_or(&designcraft_doc::Fill::default()), &["gradientAngle", "gradientVector"])?; if let Some(Some(f)) = &fill && !(f.tint.is_finite() && (0.0..=1.0).contains(&f.tint)) { @@ -307,6 +336,7 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { return Err(bad(CMD, format!("`{name}` can't be edited"))); } let old = s.doc()?.doc.styles.object_style(&name).cloned().ok_or_else(|| bad(CMD, format!("no object style `{name}`")))?; + check_swatches(CMD, s, p)?; let mut new = old.clone(); if p.get("effects").is_some_and(Value::is_null) { if EFFECT_KEYS.iter().any(|k| p.get(k).is_some()) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d559fd7d2..526f421a8 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -792,6 +792,21 @@ fn object_styles_carry_corners_and_their_stroke_and_corners_can_be_edited() { assert!(s.execute("style.object.edit", &json!({"name": "Framed", "rename": "[Basic Text Frame]"})).is_err()); assert!(s.execute("style.object.edit", &json!({"name": "[Basic Graphics Frame]", "rename": "Mine"})).is_err()); assert!(s.execute("style.object.edit", &json!({"name": "Framed", "corners": {"size": "big"}})).is_err()); + // An unknown swatch, a misspelled setting and a word for a switch are refused. + for bad in [ + json!({"fill": "Nope"}), + json!({"fill": {"swatch": "Nope"}}), + json!({"stroke": {"swatch": "Nope"}}), + json!({"stroke": {"wieght": 5}}), + json!({"fill": {"tnt": 0.5}}), + ] { + let mut p = bad.clone(); + p["name"] = json!("Framed"); + assert!(s.execute("style.object.edit", &p).is_err(), "{bad}"); + p["name"] = json!("Other"); + assert!(s.execute("style.object.create", &p).is_err(), "{bad}"); + } + assert!(s.execute("style.object.create", &json!({"name": "Other", "fromSelection": "yes"})).is_err()); // A size outside 0–10000 pt is refused, not changed. for size in [-1.0, 10_001.0] { assert!(s.execute("style.object.edit", &json!({"name": "Framed", "corners": {"size": size}})).is_err(), "{size}"); From 4282f30cf9b85b888898a5a581b0842efc5ca5c3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:23:48 -0800 Subject: [PATCH 0966/1349] Object styles: a stroke added to a style reaches shapes with the default stroke When a style that set no stroke gains one, its frames with no stroke and its drawn shapes still carrying the default 1 pt black stroke take it. A text or graphic frame with its own stroke keeps it. --- crates/engine/src/cmd/style/object.rs | 18 ++++++++++++------ crates/engine/src/tests.rs | 22 ++++++++++++++++++++++ 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/style/object.rs b/crates/engine/src/cmd/style/object.rs index 2a8ec7dd3..dc5f81643 100644 --- a/crates/engine/src/cmd/style/object.rs +++ b/crates/engine/src/cmd/style/object.rs @@ -402,17 +402,23 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { // most frames). An attribute the style no longer sets stays as it is on the items. let effects = (new.effects != old.effects).then_some(new.effects.clone()).flatten().map(|e| (old.effects.clone().unwrap_or_default(), e)); let fill = (new.fill != old.fill).then_some(new.fill.clone()).flatten().map(|f| (old.fill.clone().unwrap_or_default(), f)); - let stroke = (new.stroke != old.stroke) - .then_some(new.stroke.clone()) - .flatten() - .map(|f| (old.stroke.clone().unwrap_or_else(designcraft_doc::Stroke::none), f)); + let stroke = (new.stroke != old.stroke).then_some(new.stroke.clone()).flatten().map(|f| (old.stroke.clone(), f)); + // With no stroke in the style before, an item with no stroke (a frame's default) or a + // 1 pt black one (a drawn shape's default) follows. + let stroke_follows = |it: &Item, old: &Option| match old { + Some(o) => it.stroke == *o, + None => { + it.stroke == designcraft_doc::Stroke::none() + || (matches!(it.content, designcraft_doc::Content::Unassigned) && it.stroke == designcraft_doc::Stroke::default()) + } + }; let corners = (new.corners != old.corners).then_some(new.corners).flatten().map(|c| (old.corners.unwrap_or_default(), c)); let frame = (new.text_frame != old.text_frame).then_some(new.text_frame.clone()).flatten().map(|t| (old.text_frame.clone().unwrap_or_default(), t)); let follows = |it: &Item| { effects.as_ref().is_some_and(|(o, _)| it.effects == *o) || fill.as_ref().is_some_and(|(o, _)| it.fill == *o) - || stroke.as_ref().is_some_and(|(o, _)| it.stroke == *o) + || stroke.as_ref().is_some_and(|(o, _)| stroke_follows(it, o)) || corners.as_ref().is_some_and(|(o, _)| it.corners == o.named_to_path(&it.path)) || frame.as_ref().is_some_and(|(o, n)| it.text_frame().is_some_and(|t| t.options.clone().follow_general(o, n))) }; @@ -430,7 +436,7 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { it.fill = n.clone(); } if let Some((o, n)) = &stroke - && it.stroke == *o + && stroke_follows(it, o) { it.stroke = n.clone(); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 526f421a8..a871b70de 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -980,6 +980,28 @@ fn object_style_text_frame_general_options_leave_the_other_frame_settings() { assert!(s.execute("style.object.edit", &json!({"name": name, "textFrame": {"columns": 60}})).is_err()); } +/// A stroke added to a style that set none reaches a drawn shape still carrying its default 1 pt +/// stroke and a frame with none, and leaves a shape or text frame with its own stroke. +#[test] +fn a_stroke_added_to_an_object_style_reaches_default_strokes() { + use designcraft_doc::ItemId; + let mut s = session(); + s.execute("style.object.create", &json!({"name": "Boxed", "fromSelection": false})).unwrap(); + let frame = |s: &mut Session, x: f64, content: &str| { + s.execute("frame.create", &json!({"rect": [x, 36, x + 50.0, 86], "content": content, "caret": false})).unwrap()["id"].as_u64().unwrap() + }; + let (shape, text, own) = (frame(&mut s, 36.0, "unassigned"), frame(&mut s, 100.0, "text"), frame(&mut s, 200.0, "unassigned")); + let stroked_text = frame(&mut s, 300.0, "text"); + s.execute("object.stroke", &json!({"ids": [own], "weight": 9})).unwrap(); + s.execute("object.stroke", &json!({"ids": [stroked_text], "weight": 1})).unwrap(); + s.execute("style.object.apply", &json!({"name": "Boxed", "ids": [shape, text, own, stroked_text]})).unwrap(); + let r = s.execute("style.object.edit", &json!({"name": "Boxed", "stroke": {"weight": 4}})).unwrap(); + assert_eq!(r["updated"], 2, "{r}"); + let weight = |s: &Session, id: u64| s.doc().unwrap().doc.item(ItemId(id)).unwrap().stroke.weight; + assert_eq!((weight(&s, shape), weight(&s, text), weight(&s, own)), (4.0, 4.0, 9.0)); + assert_eq!(weight(&s, stroked_text), 1.0, "a text frame's own 1 pt stroke stays"); +} + #[test] fn object_style_effects_reach_grouped_and_anchored_items() { use designcraft_doc::ItemId; From b6d6d7e0911a92dd0a1779a7912ba2fababe8c40 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:26:11 -0800 Subject: [PATCH 0967/1349] Text wrap: relinked images and graphic wraps on anchored frames update the layout - The composition cache compares each Alpha Channel outline by a serial number, so a relink or link update lays the text out again around the new image. - A contour clipped by its frame blocks only the part of the outline the frame shows, even where the two share x positions in one line band. A fragmented frame, or shapes too detailed for a line's budget, keep the intersection of the two projections. - An anchored frame whose wrap is set only on its placed graphic wraps text. - The default alpha threshold is not saved. - docs/typography-parity.md describes the Alpha Channel contour. --- crates/compose/src/cache.rs | 10 +- crates/compose/src/lib.rs | 193 +++++++++++++++++++++++++--- crates/compose/src/tests.rs | 77 +++++++++++ crates/compose/src/wrap.rs | 5 +- crates/doc/src/item/text_frame.rs | 29 ++++- crates/doc/src/lib.rs | 10 ++ crates/engine/src/cmd/alpha_wrap.rs | 38 +++++- docs/typography-parity.md | 2 +- 8 files changed, 337 insertions(+), 27 deletions(-) diff --git a/crates/compose/src/cache.rs b/crates/compose/src/cache.rs index 5e4cb0911..72ef7fff4 100644 --- a/crates/compose/src/cache.rs +++ b/crates/compose/src/cache.rs @@ -5,7 +5,8 @@ //! wrapping item on the frames' spreads, and the same for every story whose anchored objects wrap //! its text ([`crate::wrap::neighbours`]). An anchored frame's entry also records where its host //! story's composition places it. Entries hold clones of those `Arc`s, so the pointers -//! can't be reused by other allocations while the entry lives. +//! can't be reused by other allocations while the entry lives. The document's Alpha Channel +//! outlines count by serial number, which no other outline shares. use std::collections::{HashMap, HashSet}; use std::sync::{Arc, Mutex, PoisonError}; @@ -85,6 +86,9 @@ fn doc_signature(doc: &Document) -> u64 { (Arc::as_ptr(&doc.styles) as usize).hash(&mut h); format!("{:?}", doc.text_variables).hash(&mut h); sections_hash(doc).hash(&mut h); + for o in &doc.alpha_outlines { + o.serial.hash(&mut h); + } h.finish() } @@ -407,6 +411,10 @@ fn signature(doc: &Document, story: &Arc) -> (Vec, Vec>) usize::from(g.relative_to == designcraft_doc::GridRelative::TopMargin), ]; sig.extend([g.start, g.increment].into_iter().flat_map(bits)); + // Alpha Channel outlines: a relink traces one again without changing the story or the items + // that wrap it. + sig.extend(doc.alpha_outlines.iter().flat_map(|o| [(o.serial & 0xffff_ffff) as usize, (o.serial >> 32) as usize])); + sig.push(usize::MAX); let mut keep = Vec::new(); let mut spreads = Vec::new(); for f in &story.frames { diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 62e319f36..ac563b616 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -388,6 +388,10 @@ pub struct Contour { /// Points a contour outline may have; a larger outline wraps around its bounding box. pub const MAX_CONTOUR_POINTS: usize = 8192; +/// Edge visits a clipped contour may take for one line band; past it, the line's spans come from +/// the two shapes' projections instead of their intersection. +const MAX_CLIPPED_WORK: usize = 1 << 20; + impl Contour { /// The outline of `path` (after `to_inner`), flattened; None if it is empty or too detailed. fn of(path: &designcraft_geom::BezPath, to_inner: designcraft_geom::Affine, offset: f64) -> Option { @@ -448,26 +452,164 @@ impl Contour { } if !self.clip.is_empty() { let clip = rings_band_spans(&self.clip, low, high); - let mut cut = Vec::new(); - let (mut i, mut j) = (0, 0); - while let (Some(&(a, b)), Some(&(c, d))) = (spans.get(i), clip.get(j)) { - let (lo, hi) = (a.max(c), b.min(d)); - // A zero-width span (a vertical open path) is kept where the clip covers it. - if lo < hi || (a == b && lo == hi) { - cut.push((lo, hi)); - } - if b < d { - i += 1; - } else { - j += 1; - } - } - spans = cut; + // A fragmented frame, or shapes too detailed to compare within each line's budget, + // take the common part of the two projections, which can block more than the frame + // shows. + let exact = if clip.len() > 128 { None } else { clipped_band_spans(&self.rings, &self.clip, low, high) }; + spans = exact.unwrap_or_else(|| intersect_spans(&spans, &clip)); } merge_spans(spans.into_iter().map(|(a, b)| (a - self.offset, b + self.offset)).collect()) } } +/// The sorted spans in both `a` and `b` (each sorted and merged). A zero-width span (a vertical +/// open path) is kept where the other covers it. +fn intersect_spans(a: &[(f64, f64)], b: &[(f64, f64)]) -> Vec<(f64, f64)> { + let mut out = Vec::new(); + let (mut i, mut j) = (0, 0); + while let (Some(&(p, q)), Some(&(r, s))) = (a.get(i), b.get(j)) { + let (lo, hi) = (p.max(r), q.min(s)); + if lo < hi || (lo == hi && (p == q || r == s)) { + out.push((lo, hi)); + } + if q < s { + i += 1; + } else { + j += 1; + } + } + out +} + +/// Occupied intervals across the band `y0..y1` of the part of `rings` inside `clip` (both filled +/// by the non-zero rule). A vertical line through a point of that part either crosses the middle +/// of the band inside both shapes, or stops inside the band on an edge of one shape that lies +/// inside the other. The spans are the middle slice of both shapes and the parts of each +/// shape's edges in the band that lie inside the other, so a part of the outline outside the +/// clip blocks nothing, even where it shares x positions with the clip in the same band. +/// None when that takes more than [`MAX_CLIPPED_WORK`] edge visits. +fn clipped_band_spans(rings: &[Vec], clip: &[Vec], y0: f64, y1: f64) -> Option> { + let middle = y0 * 0.5 + y1 * 0.5; + let mut spans = intersect_spans(&merge_spans(middle_spans(rings, middle)), &merge_spans(middle_spans(clip, middle))); + let mut budget = MAX_CLIPPED_WORK; + edges_inside(rings, clip, y0, y1, &mut budget, &mut spans)?; + edges_inside(clip, rings, y0, y1, &mut budget, &mut spans)?; + Some(merge_spans(spans)) +} + +/// Takes `n` edge visits from `budget`; None when it doesn't hold that many. +fn spend(budget: &mut usize, n: usize) -> Option<()> { + *budget = budget.checked_sub(n)?; + Some(()) +} + +/// Pushes to `out` the x-ranges of the parts of `rings`' edges within the band `y0..y1` that lie +/// inside `other` or on its boundary. None when `budget` runs out. +fn edges_inside(rings: &[Vec], other: &[Vec], y0: f64, y1: f64, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { + let n = other.iter().map(Vec::len).sum::().max(1); + for ring in rings { + let Some(&last) = ring.last() else { continue }; + let mut a = last; + for &b in ring { + let dy = b.y - a.y; + if a.y.max(b.y) >= y0 && a.y.min(b.y) <= y1 { + let (t0, t1) = if dy.abs() < 1e-12 { + (0.0, 1.0) + } else { + let (u, v) = ((y0 - a.y) / dy, (y1 - a.y) / dy); + (u.min(v).clamp(0.0, 1.0), u.max(v).clamp(0.0, 1.0)) + }; + let (p, q) = (a + (b - a) * t0, a + (b - a) * t1); + segment_inside(p, q, other, n, budget, out)?; + } + a = b; + } + } + Some(()) +} + +/// Pushes to `out` the x-ranges of the parts of segment `p`–`q` inside `rings` (`n` edges) or on +/// their boundary: the segment is split where it meets their edges, and each piece is tested at +/// its middle. Each pass over the edges takes `n` from `budget`; None when it runs out. +fn segment_inside(p: Point, q: Point, rings: &[Vec], n: usize, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { + let r = q - p; + let len2 = r.hypot2(); + if !len2.is_finite() { + return Some(()); + } + let at = |t: f64| p + r * t; + spend(budget, n)?; + if len2 < 1e-24 { + if inside_or_on(rings, p) { + out.push((p.x, p.x)); + } + return Some(()); + } + let (ylo, yhi) = (p.y.min(q.y), p.y.max(q.y)); + let mut ts = vec![0.0, 1.0]; + for ring in rings { + let Some(&last) = ring.last() else { continue }; + let mut c = last; + for &d in ring { + if c.y.max(d.y) >= ylo - 1e-9 && c.y.min(d.y) <= yhi + 1e-9 { + let e = d - c; + let denom = r.cross(e); + let w = c - p; + if denom.abs() > 1e-12 * (len2 * e.hypot2()).sqrt() { + let (t, u) = (w.cross(e) / denom, w.cross(r) / denom); + if (-1e-9..=1.0 + 1e-9).contains(&u) && (0.0..=1.0).contains(&t) { + ts.push(t); + } + } else if w.cross(r).abs() <= 1e-9 * len2.sqrt() { + // Collinear: the edge's ends split the segment. + for t in [w.dot(r) / len2, (d - p).dot(r) / len2] { + if (0.0..=1.0).contains(&t) { + ts.push(t); + } + } + } + } + c = d; + } + } + ts.sort_by(f64::total_cmp); + ts.dedup_by(|a, b| (*a - *b).abs() < 1e-12); + for w in ts.windows(2) { + let (u, v) = (w[0], w[1]); + spend(budget, n)?; + if inside_or_on(rings, at(u * 0.5 + v * 0.5)) { + let (x0, x1) = (at(u).x, at(v).x); + out.push((x0.min(x1), x0.max(x1))); + } + } + Some(()) +} + +/// Is `pt` inside `rings` (non-zero rule) or within a hair of one of their edges? +fn inside_or_on(rings: &[Vec], pt: Point) -> bool { + let mut winding = 0i32; + for ring in rings { + let Some(&last) = ring.last() else { continue }; + let mut a = last; + for &b in ring { + let e = b - a; + let len2 = e.hypot2(); + let t = if len2 > 0.0 { ((pt - a).dot(e) / len2).clamp(0.0, 1.0) } else { 0.0 }; + if (a + e * t - pt).hypot2() < 1e-18 { + return true; + } + if (a.y <= pt.y && pt.y < b.y) || (b.y <= pt.y && pt.y < a.y) { + let x = a.x + (pt.y - a.y) / e.y * e.x; + if x > pt.x { + winding += if e.y > 0.0 { 1 } else { -1 }; + } + } + a = b; + } + } + winding != 0 +} + /// Sorted, overlapping spans joined. Zero-width spans (a vertical edge of an open path) are kept: /// the wrap offset widens them, and without one they still split the line there. fn merge_spans(mut spans: Vec<(f64, f64)>) -> Vec<(f64, f64)> { @@ -485,9 +627,7 @@ fn merge_spans(mut spans: Vec<(f64, f64)>) -> Vec<(f64, f64)> { } fn rings_band_spans(rings: &[Vec], y0: f64, y1: f64) -> Vec<(f64, f64)> { - let mut spans = Vec::new(); - let mut crossings = Vec::new(); - let middle = y0 * 0.5 + y1 * 0.5; + let mut spans = middle_spans(rings, y0 * 0.5 + y1 * 0.5); for ring in rings { let Some(&last) = ring.last() else { continue }; let mut a = last; @@ -503,6 +643,21 @@ fn rings_band_spans(rings: &[Vec], y0: f64, y1: f64) -> Vec<(f64, f64)> { let (x0, x1) = (a.x + t0 * (b.x - a.x), a.x + t1 * (b.x - a.x)); spans.push((x0.min(x1), x0.max(x1))); } + a = b; + } + } + merge_spans(spans) +} + +/// The intervals of the line at height `middle` inside `rings` (non-zero rule), unsorted. +fn middle_spans(rings: &[Vec], middle: f64) -> Vec<(f64, f64)> { + let mut spans = Vec::new(); + let mut crossings = Vec::new(); + for ring in rings { + let Some(&last) = ring.last() else { continue }; + let mut a = last; + for &b in ring { + let dy = b.y - a.y; if (a.y <= middle && middle < b.y) || (b.y <= middle && middle < a.y) { let x = a.x + (middle - a.y) / dy * (b.x - a.x); if x.is_finite() { @@ -524,7 +679,7 @@ fn rings_band_spans(rings: &[Vec], y0: f64, y1: f64) -> Vec<(f64, f64)> { winding += delta; previous = Some(x); } - merge_spans(spans) + spans } /// The closed polylines of `path` (after `to_inner`), flattened; None if it is empty or too detailed. diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 3df861733..ab108b03b 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -7581,6 +7581,38 @@ fn anchored_object_wraps_another_storys_text() { assert!(lines_in_band(&moved, 200.0, 260.0).iter().all(|l| l.x0 >= left + 100.0 - 1e-6)); } +/// An anchored frame whose wrap is set only on its placed graphic (Direct Selection) wraps +/// another story's text as a wrap set on the frame does. +#[test] +fn anchored_graphic_wrap_wraps_another_storys_text() { + let long = [LOREM; 3].join(" "); + let (mut d, a, fa) = doc_with("Anchor here.", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + let lid = d.default_layer(); + let (_, b) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(320.0, 0.0, 620.0, 400.0), lid, &long, ParaFormat::default()).unwrap(); + let left = all_lines(&compose_story(&d, b, &ComposeOptions::default()))[0].x0; + let area = d.item(fa).unwrap().text_area(); + anchor_box(&mut d, a, 0, left - area.x0, 100.0 - area.y0, false, WrapMode::None); + let wrap = designcraft_doc::TextWrap { mode: WrapMode::BoundingBox, ..Default::default() }; + let obj = std::sync::Arc::make_mut(&mut d.story_mut(a).unwrap().objects[0]); + obj.item.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic { + layer_options: None, + asset: designcraft_doc::AssetId(1), + size: (100.0, 60.0), + xf: designcraft_geom::Affine::IDENTITY, + clip: None, + auto_fit: designcraft_doc::Fitting::None, + fit_align: 0, + crop: [0.0; 4], + wrap, + fill: Default::default(), + }); + let cs = compose_story(&d, b, &ComposeOptions::default()); + let band = lines_in_band(&cs, 100.0, 160.0); + assert!(!band.is_empty()); + assert!(band.iter().all(|l| l.x0 >= left + 100.0 - 1e-6), "{:?}", band.iter().map(|l| l.x0).collect::>()); + assert!(lines_in_band(&cs, 0.0, 80.0).iter().all(|l| (l.x0 - left).abs() < 1e-6)); +} + /// An anchored object's wrap is built as a page item's: a contour on both sides of an oval sets /// text left and right of it, closer in where the oval narrows. #[test] @@ -8479,6 +8511,51 @@ fn a_vertical_open_path_keeps_its_offset() { assert_eq!(c.band_spans(40.0, 50.0), vec![(10.0, 10.0)]); } +/// An outline counts only where its frame shows it: a part of it in a notch of the frame blocks +/// nothing, even where the frame covers the same x positions lower in the same line band. +#[test] +fn a_clipped_contour_blocks_only_what_its_frame_shows() { + let poly = |pts: &[(f64, f64)]| { + let mut p = designcraft_geom::BezPath::new(); + p.move_to(pts[0]); + for &q in &pts[1..] { + p.line_to(q); + } + p.close_path(); + p + }; + let id = designcraft_geom::Affine::IDENTITY; + // An L-shaped frame with a notch at x 10..40 above y = 6. + let frame = poly(&[(0.0, 0.0), (10.0, 0.0), (10.0, 6.0), (40.0, 6.0), (40.0, 10.0), (0.0, 10.0)]); + // An outline in the notch only. + let c = Contour::of(&poly(&[(20.0, 0.0), (40.0, 0.0), (40.0, 4.0), (20.0, 4.0)]), id, 0.0).unwrap(); + assert_eq!(c.band_spans(0.0, 10.0), vec![(20.0, 40.0)]); + assert_eq!(c.within(&frame, id).band_spans(0.0, 10.0), Vec::<(f64, f64)>::new(), "the frame shows none of it"); + // Reaching below the notch, where the frame shows it from y = 6 to 8. + let c = Contour::of(&poly(&[(20.0, 0.0), (40.0, 0.0), (40.0, 8.0), (20.0, 8.0)]), id, 0.0).unwrap(); + assert_eq!(c.within(&frame, id).band_spans(0.0, 10.0), vec![(20.0, 40.0)]); + // A band that crosses both shapes whole keeps their common part, widened by the offset. + let c = Contour::of(&poly(&[(5.0, -10.0), (30.0, -10.0), (30.0, 20.0), (5.0, 20.0)]), id, 2.0).unwrap(); + assert_eq!(c.within(&frame, id).band_spans(7.0, 9.0), vec![(3.0, 32.0)]); + // A frame in more than 128 pieces across the band takes the common part of the projections. + let mut fragmented = frame.clone(); + for i in 0..200 { + let x = 1000.0 + 2.0 * f64::from(i); + fragmented.extend(poly(&[(x, 0.0), (x + 1.0, 0.0), (x + 1.0, 10.0), (x, 10.0)]).elements().iter().copied()); + } + let c = Contour::of(&poly(&[(20.0, 0.0), (40.0, 0.0), (40.0, 4.0), (20.0, 4.0)]), id, 0.0).unwrap(); + assert_eq!(c.within(&fragmented, id).band_spans(0.0, 10.0), vec![(20.0, 40.0)]); + // So does a frame and an outline too detailed to compare within a line's budget: here 2,000 + // points on the frame's bottom edge and on the outline's top edge. + let mut detailed = vec![(0.0, 0.0), (10.0, 0.0), (10.0, 6.0), (40.0, 6.0), (40.0, 10.0)]; + detailed.extend((1..2000).map(|i| (40.0 - 0.02 * f64::from(i), 10.0))); + detailed.push((0.0, 10.0)); + let mut notch: Vec<(f64, f64)> = (0..2000).map(|i| (20.0 + 0.01 * f64::from(i), 0.0)).collect(); + notch.extend([(40.0, 0.0), (40.0, 4.0), (20.0, 4.0)]); + let c = Contour::of(&poly(¬ch), id, 0.0).unwrap(); + assert_eq!(c.within(&poly(&detailed), id).band_spans(0.0, 10.0), vec![(20.0, 40.0)]); +} + /// Rule Above's offset runs from the first line's baseline up to the rule's bottom edge, as in /// InDesign: a rule set clear of the cap height sits between the rows, not across the row above /// (an INDD project list whose rules crossed the previous paragraph's text). diff --git a/crates/compose/src/wrap.rs b/crates/compose/src/wrap.rs index 98219b066..6de1d3ace 100644 --- a/crates/compose/src/wrap.rs +++ b/crates/compose/src/wrap.rs @@ -18,7 +18,7 @@ //! is composed at most that many more times (at least [`MIN_PASSES`]), and never more than //! [`MAX_PASSES`]. -use designcraft_doc::{AnchorPosition, AnchoredObject, Document, Item, OBJECT_MARK, PageSide, SpreadRef, Story, StoryId, WrapMode}; +use designcraft_doc::{AnchorPosition, AnchoredObject, Document, Item, OBJECT_MARK, PageSide, SpreadRef, Story, StoryId}; use designcraft_geom::Affine; use crate::{ComposeOptions, ComposedStory, Exclusion, FrameSpec}; @@ -48,8 +48,9 @@ pub(crate) struct Obstacle<'a> { anchor: Option, } +/// The wrap may be set on the frame or on its placed graphic (Direct Selection). fn wraps(o: &AnchoredObject) -> bool { - o.item.wrap.mode != WrapMode::None && !o.item.hidden + o.item.has_wrap() && !o.item.hidden } /// Does `story` have an anchored object whose wrap can push text? diff --git a/crates/doc/src/item/text_frame.rs b/crates/doc/src/item/text_frame.rs index 62f12eb24..f31f14060 100644 --- a/crates/doc/src/item/text_frame.rs +++ b/crates/doc/src/item/text_frame.rs @@ -272,7 +272,7 @@ pub enum ContourType { BoundingBox, /// Edges detected in the image. Composition follows the frame path. DetectEdges, - /// The image's alpha channel. Composition follows the frame path. + /// The image's alpha channel. Composition follows the outline of the image's visible pixels. AlphaChannel, /// A path saved in the image. Composition follows the frame path. PhotoshopPath, @@ -302,10 +302,16 @@ pub struct TextWrap { /// transparent holes it encloses (off: holes are blocked with the shape around them). #[serde(skip_serializing_if = "std::ops::Not::not")] pub inside_edges: bool, - /// Alpha Channel contour: pixels more opaque than this (0..254) count as the image. + /// Alpha Channel contour: pixels more opaque than this (0..254) count as the image. Saved only + /// when it isn't the default. + #[serde(skip_serializing_if = "is_default_alpha_threshold")] pub alpha_threshold: u8, } +fn is_default_alpha_threshold(t: &u8) -> bool { + *t == DEFAULT_ALPHA_THRESHOLD +} + /// DesignCraft's default alpha threshold for Alpha Channel contour wraps. pub const DEFAULT_ALPHA_THRESHOLD: u8 = 25; @@ -343,3 +349,22 @@ pub struct TextFrame { #[serde(default)] pub options: TextFrameOptions, } + +#[cfg(test)] +mod tests { + use super::*; + + /// The alpha threshold is saved only when it isn't the default, so a wrap saved before it + /// existed is saved the same way, and reads back as the default. + #[test] + fn the_default_alpha_threshold_is_not_saved() { + let wrap = TextWrap { mode: WrapMode::Contour, ..Default::default() }; + let v = serde_json::to_value(&wrap).unwrap(); + assert!(v.get("alphaThreshold").is_none(), "{v}"); + assert_eq!(serde_json::from_value::(v).unwrap(), wrap); + let set = TextWrap { alpha_threshold: 200, ..wrap }; + let v = serde_json::to_value(&set).unwrap(); + assert_eq!(v["alphaThreshold"], 200); + assert_eq!(serde_json::from_value::(v).unwrap(), set); + } +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 8f105457c..f26ef10ad 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -674,9 +674,19 @@ pub struct AlphaOutline { /// under the same id, and the outline is traced again. (Weak, so it doesn't keep old image /// data alive, and its address can't be reused by new data while it's held.) pub source: std::sync::Weak>, + /// A number no other outline made in this process has ([`AlphaOutline::next_serial`]). + /// Composition caches compare it: an outline traced again after a relink has a new one, + /// while a dropped outline's address can be reused. + pub serial: u64, } impl AlphaOutline { + /// A serial number not given out before in this process. + pub fn next_serial() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + } + /// Traced from `data`, the asset's current image data. pub fn traced_from(&self, data: &Arc>) -> bool { std::ptr::eq(self.source.as_ptr(), Arc::as_ptr(data)) diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs index b4009de1d..1ee2919a1 100644 --- a/crates/engine/src/cmd/alpha_wrap.rs +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -62,7 +62,16 @@ pub(crate) fn sync(doc: &mut Document) { /// The empty outline standing for an image `trace` found none in: zero-size, which composition /// takes as no outline, and dropped like a traced one when the asset's data changes. fn no_outline(data: &Arc>, asset: AssetId, threshold: u8) -> AlphaOutline { - AlphaOutline { asset, threshold, width: 0, height: 0, outer: Default::default(), holes: Default::default(), source: Arc::downgrade(data) } + AlphaOutline { + asset, + threshold, + width: 0, + height: 0, + outer: Default::default(), + holes: Default::default(), + source: Arc::downgrade(data), + serial: AlphaOutline::next_serial(), + } } /// The outline of the pixels of `data` more opaque than `threshold`. None for an image that @@ -112,7 +121,8 @@ pub(crate) fn trace(data: &Arc>, asset: AssetId, threshold: u8) -> Optio PathData::from_bezpath(&p) }; let source = Arc::downgrade(data); - return Some(AlphaOutline { asset, threshold, width: w, height: h, outer: path(&outer), holes: path(&holes), source }); + let serial = AlphaOutline::next_serial(); + return Some(AlphaOutline { asset, threshold, width: w, height: h, outer: path(&outer), holes: path(&holes), source, serial }); } finer = Some((mask, cols, rows)); grid /= 2; @@ -502,4 +512,28 @@ mod tests { assert!(s.execute("object.textWrap", &bad).is_err()); } } + + /// Replacing the image data under the same asset, as a relink or link update does, lays the + /// text out again around the new outline: neither the story nor the frames change. + #[test] + fn a_relinked_image_lays_the_text_out_again() { + let (mut s, image, story) = page(&png(|x, _| (8..20).contains(&x) || (44..56).contains(&x)), [150.0, 120.0, 178.0, 170.0]); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(!overset(&s, story), "the gap between the legs stays open"); + let Some(designcraft_doc::Content::Graphic(g)) = + s.doc().unwrap().doc.item(designcraft_doc::ItemId(image.as_u64().unwrap())).map(|it| it.content.clone()) + else { + panic!("a graphic") + }; + // The new image has no gap: one band across both legs. + let solid = Arc::new(png(|x, _| (8..56).contains(&x))); + s.edit(|d, _| { + let mut a = (**d.assets.get(&g.asset).unwrap()).clone(); + a.data = solid.clone(); + d.assets.insert(g.asset, Arc::new(a)); + Ok(()) + }) + .unwrap(); + assert!(overset(&s, story), "the new image covers the caption"); + } } diff --git a/docs/typography-parity.md b/docs/typography-parity.md index 8e17cd2a9..599c20b39 100644 --- a/docs/typography-parity.md +++ b/docs/typography-parity.md @@ -59,7 +59,7 @@ Fidelity: **unmeasured** unless stated. | Paragraph rules, borders, shading | ✓ | ✓ | ✓ | | | Balance ragged lines | ✓ | ✓ | ✓ | | | Optical margin alignment | per story with a size, Ignore Optical Margin per paragraph and style | ✓ (hang table of our own, scaled by the story's size; Story panel; IDML `StoryPreference`, `IgnoreEdgeAlignment`) | ~ | hang amounts are ours, InDesign's unknown (#947) | -| Text wrap | bounding box, shape, jump object/column, wrap sides (text on both sides of an object), contour options, on page items and anchored objects | ✓ | ~ | Detect Edges, Alpha Channel and Photoshop Path contours follow the frame's path (composition doesn't read the image) | +| Text wrap | bounding box, shape, jump object/column, wrap sides (text on both sides of an object), contour options, on page items and anchored objects | ✓ | ~ | Alpha Channel contours follow the image's visible pixels within the frame (threshold, Include Inside Edges); Detect Edges and Photoshop Path contours follow the frame's path (composition doesn't read the image) | | Anchored objects | inline, above line, custom | ✓ | ~ | anchored objects in table cells not drawn (#163) | | Footnotes, endnotes | ✓ | ✓ | ~ | footnotes don't split across columns yet | | Type on a path | ✓ | ✓ | ✓ | | From 2e1d17e1fa2dcdab33043ebe204713f3f3304375 Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 05:32:14 +0000 Subject: [PATCH 0968/1349] Apply review fixes - crates/ui-egui/src/preflight_worker.rs --- crates/ui-egui/src/preflight_worker.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/preflight_worker.rs b/crates/ui-egui/src/preflight_worker.rs index ddcdffe68..4da6224e5 100644 --- a/crates/ui-egui/src/preflight_worker.rs +++ b/crates/ui-egui/src/preflight_worker.rs @@ -151,7 +151,10 @@ fn issues_at(app: &mut DesignApp, ctx: &egui::Context, now: f64) -> Option Date: Wed, 11 Nov 2026 21:33:24 -0800 Subject: [PATCH 0969/1349] Object styles: edits reach text frames anchored in stories, cells and notes style.object.edit updates the attributes and paragraph styles of text frames anchored in stories, table cells and notes, as IDML import places them, as it does for frames on spreads. --- crates/engine/src/cmd/style/object.rs | 18 +++++------------- crates/engine/src/tests.rs | 25 +++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/style/object.rs b/crates/engine/src/cmd/style/object.rs index dc5f81643..8a156d654 100644 --- a/crates/engine/src/cmd/style/object.rs +++ b/crates/engine/src/cmd/style/object.rs @@ -422,7 +422,7 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { || corners.as_ref().is_some_and(|(o, _)| it.corners == o.named_to_path(&it.path)) || frame.as_ref().is_some_and(|(o, n)| it.text_frame().is_some_and(|t| t.options.clone().follow_general(o, n))) }; - let updated = d.update_items( + let updated = d.update_placed_items( |it| it.object_style == new.name && follows(it), |it| { if let Some((o, n)) = &effects @@ -458,18 +458,10 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { // is in the old one's; when the style set none before, all of it does. let mut restyled = 0; if new.paragraph_style.is_some() && (new.paragraph_style != old.paragraph_style || new.apply_next_style != old.apply_next_style) { - let mut stories = Vec::new(); - for sp in d.spreads.iter().chain(d.parents.iter()) { - for it in &sp.items { - it.walk(&mut |i| { - if i.object_style == new.name - && let Some(tf) = i.text_frame() - { - stories.push(tf.story); - } - }); - } - } + // Frames on spreads and parents, in groups, and anchored in stories, table cells and + // notes (as IDML import places them). + let mut stories: Vec<_> = + d.placed_items().into_iter().filter(|i| i.object_style == new.name).filter_map(|i| i.text_frame().map(|tf| tf.story)).collect(); stories.sort_unstable(); stories.dedup(); let styles = d.styles.clone(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a871b70de..5824be21c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1002,6 +1002,31 @@ fn a_stroke_added_to_an_object_style_reaches_default_strokes() { assert_eq!(weight(&s, stroked_text), 1.0, "a text frame's own 1 pt stroke stays"); } +/// A text frame anchored in a story (as IDML import places one) takes a new paragraph style of +/// its object style like a frame on the page. +#[test] +fn an_object_style_edit_restyles_an_anchored_text_frame() { + use designcraft_doc::ItemId; + let mut s = session(); + s.execute("style.paragraph.create", &json!({"name": "Body"})).unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Lead"})).unwrap(); + s.execute("style.object.create", &json!({"name": "Sidebar", "fromSelection": false, "paragraphStyle": "Body"})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 36, 136, 86], "content": "text", "text": "Inner", "caret": false})).unwrap(); + let (inner, inner_story) = (ItemId(r["id"].as_u64().unwrap()), designcraft_doc::StoryId(r["story"].as_u64().unwrap())); + s.execute("style.object.apply", &json!({"name": "Sidebar", "ids": [inner.0]})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 200, 400, 400], "content": "text", "text": "Before after.", "caret": false})).unwrap(); + let host = designcraft_doc::StoryId(r["story"].as_u64().unwrap()); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let it = d.item(inner).unwrap().clone(); + std::sync::Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id != inner); + d.story_mut(host).unwrap().insert_object(7, designcraft_doc::AnchoredObject::new(it, Default::default())); + } + let r = s.execute("style.object.edit", &json!({"name": "Sidebar", "paragraphStyle": "Lead"})).unwrap(); + assert_eq!(r["restyled"], 1, "{r}"); + assert_eq!(s.doc().unwrap().doc.story(inner_story).unwrap().paras[0].style, "Lead"); +} + #[test] fn object_style_effects_reach_grouped_and_anchored_items() { use designcraft_doc::ItemId; From 544ebaf571db68f904a10b896f41e063bba94b96 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:33:53 -0800 Subject: [PATCH 0970/1349] Text wrap: a relinked image's new outline recomposes the text around it - each traced Alpha Channel outline has a serial number, and the composition signatures include the outlines in use, so a relink or link update that changes only the image data no longer leaves text laid out around the old image - a wrap with the default alpha threshold is saved without it, as before thresholds were stored - docs/typography-parity.md says Alpha Channel contours follow the image's visible pixels --- crates/compose/src/cache.rs | 13 ++++++++ crates/doc/src/item/text_frame.rs | 5 +++ crates/doc/src/lib.rs | 9 ++++++ crates/engine/src/cmd/alpha_wrap.rs | 48 +++++++++++++++++++++++++++-- docs/typography-parity.md | 2 +- 5 files changed, 74 insertions(+), 3 deletions(-) diff --git a/crates/compose/src/cache.rs b/crates/compose/src/cache.rs index 5e4cb0911..c1f52d162 100644 --- a/crates/compose/src/cache.rs +++ b/crates/compose/src/cache.rs @@ -85,6 +85,18 @@ fn doc_signature(doc: &Document) -> u64 { (Arc::as_ptr(&doc.styles) as usize).hash(&mut h); format!("{:?}", doc.text_variables).hash(&mut h); sections_hash(doc).hash(&mut h); + outlines_hash(doc).hash(&mut h); + h.finish() +} + +/// The Alpha Channel outlines text wraps around: a relink traces a new one while the items and +/// stories stay the same. +fn outlines_hash(doc: &Document) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + for o in &doc.alpha_outlines { + o.serial.hash(&mut h); + } h.finish() } @@ -405,6 +417,7 @@ fn signature(doc: &Document, story: &Arc) -> (Vec, Vec>) sections_hash(doc) as usize, doc.font_scope as usize, usize::from(g.relative_to == designcraft_doc::GridRelative::TopMargin), + outlines_hash(doc) as usize, ]; sig.extend([g.start, g.increment].into_iter().flat_map(bits)); let mut keep = Vec::new(); diff --git a/crates/doc/src/item/text_frame.rs b/crates/doc/src/item/text_frame.rs index 62f12eb24..2e7506f26 100644 --- a/crates/doc/src/item/text_frame.rs +++ b/crates/doc/src/item/text_frame.rs @@ -303,12 +303,17 @@ pub struct TextWrap { #[serde(skip_serializing_if = "std::ops::Not::not")] pub inside_edges: bool, /// Alpha Channel contour: pixels more opaque than this (0..254) count as the image. + #[serde(skip_serializing_if = "is_default_alpha_threshold")] pub alpha_threshold: u8, } /// DesignCraft's default alpha threshold for Alpha Channel contour wraps. pub const DEFAULT_ALPHA_THRESHOLD: u8 = 25; +fn is_default_alpha_threshold(t: &u8) -> bool { + *t == DEFAULT_ALPHA_THRESHOLD +} + impl Default for TextWrap { fn default() -> Self { TextWrap { diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 8f105457c..2b18c8f47 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -674,9 +674,18 @@ pub struct AlphaOutline { /// under the same id, and the outline is traced again. (Weak, so it doesn't keep old image /// data alive, and its address can't be reused by new data while it's held.) pub source: std::sync::Weak>, + /// A number no other outline traced in this process has ([`AlphaOutline::next_serial`]): + /// composition caches compare it to tell a new outline from the one they used. + pub serial: u64, } impl AlphaOutline { + /// A serial number for a new outline, unique within the process. + pub fn next_serial() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + } + /// Traced from `data`, the asset's current image data. pub fn traced_from(&self, data: &Arc>) -> bool { std::ptr::eq(self.source.as_ptr(), Arc::as_ptr(data)) diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs index b4009de1d..585f29350 100644 --- a/crates/engine/src/cmd/alpha_wrap.rs +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -62,7 +62,16 @@ pub(crate) fn sync(doc: &mut Document) { /// The empty outline standing for an image `trace` found none in: zero-size, which composition /// takes as no outline, and dropped like a traced one when the asset's data changes. fn no_outline(data: &Arc>, asset: AssetId, threshold: u8) -> AlphaOutline { - AlphaOutline { asset, threshold, width: 0, height: 0, outer: Default::default(), holes: Default::default(), source: Arc::downgrade(data) } + AlphaOutline { + asset, + threshold, + width: 0, + height: 0, + outer: Default::default(), + holes: Default::default(), + source: Arc::downgrade(data), + serial: AlphaOutline::next_serial(), + } } /// The outline of the pixels of `data` more opaque than `threshold`. None for an image that @@ -112,7 +121,8 @@ pub(crate) fn trace(data: &Arc>, asset: AssetId, threshold: u8) -> Optio PathData::from_bezpath(&p) }; let source = Arc::downgrade(data); - return Some(AlphaOutline { asset, threshold, width: w, height: h, outer: path(&outer), holes: path(&holes), source }); + let serial = AlphaOutline::next_serial(); + return Some(AlphaOutline { asset, threshold, width: w, height: h, outer: path(&outer), holes: path(&holes), source, serial }); } finer = Some((mask, cols, rows)); grid /= 2; @@ -428,6 +438,40 @@ mod tests { assert_eq!((b.x0, b.x1), (24.0, 40.0), "the new image's outline"); } + /// A wrap with the default threshold saves as it did before thresholds were stored; another + /// threshold is saved. + #[test] + fn the_default_threshold_is_left_out_of_a_saved_wrap() { + let v = serde_json::to_value(designcraft_doc::TextWrap::default()).unwrap(); + assert!(v.get("alphaThreshold").is_none(), "{v}"); + let back: designcraft_doc::TextWrap = serde_json::from_value(v).unwrap(); + assert_eq!(back.alpha_threshold, designcraft_doc::DEFAULT_ALPHA_THRESHOLD); + let w = designcraft_doc::TextWrap { alpha_threshold: 200, ..Default::default() }; + assert_eq!(serde_json::to_value(w).unwrap()["alphaThreshold"], 200); + } + + /// A relink that changes only the image data recomposes the text around the new outline. + #[test] + fn text_is_composed_again_around_a_relinked_images_outline() { + let (mut s, image, story) = page(&png(|x, _| x < 32), [180.0, 150.0, 220.0, 178.0]); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(!overset(&s, story), "the left half is visible: the caption on the right is set"); + let Some(designcraft_doc::Content::Graphic(g)) = + s.doc().unwrap().doc.item(designcraft_doc::ItemId(image.as_u64().unwrap())).map(|it| it.content.clone()) + else { + panic!("a graphic") + }; + let right = Arc::new(png(|x, _| x >= 32)); + s.edit(|d, _| { + let mut a = (**d.assets.get(&g.asset).unwrap()).clone(); + a.data = right.clone(); + d.assets.insert(g.asset, Arc::new(a)); + Ok(()) + }) + .unwrap(); + assert!(overset(&s, story), "the right half is visible now: it covers the caption"); + } + /// An image anchored in text keeps its outline: anchored objects wrap the lines after their /// anchor, and they are kept in the story, not on the spread. #[test] diff --git a/docs/typography-parity.md b/docs/typography-parity.md index 8e17cd2a9..0b3c030cf 100644 --- a/docs/typography-parity.md +++ b/docs/typography-parity.md @@ -59,7 +59,7 @@ Fidelity: **unmeasured** unless stated. | Paragraph rules, borders, shading | ✓ | ✓ | ✓ | | | Balance ragged lines | ✓ | ✓ | ✓ | | | Optical margin alignment | per story with a size, Ignore Optical Margin per paragraph and style | ✓ (hang table of our own, scaled by the story's size; Story panel; IDML `StoryPreference`, `IgnoreEdgeAlignment`) | ~ | hang amounts are ours, InDesign's unknown (#947) | -| Text wrap | bounding box, shape, jump object/column, wrap sides (text on both sides of an object), contour options, on page items and anchored objects | ✓ | ~ | Detect Edges, Alpha Channel and Photoshop Path contours follow the frame's path (composition doesn't read the image) | +| Text wrap | bounding box, shape, jump object/column, wrap sides (text on both sides of an object), contour options, on page items and anchored objects | ✓ | ~ | Alpha Channel contours follow the outline of the image's visible pixels; Detect Edges and Photoshop Path contours follow the frame's path | | Anchored objects | inline, above line, custom | ✓ | ~ | anchored objects in table cells not drawn (#163) | | Footnotes, endnotes | ✓ | ✓ | ~ | footnotes don't split across columns yet | | Type on a path | ✓ | ✓ | ✓ | | From 6b9c47fdb2a514a1a00829e17f24e8699cf7d6ae Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 05:37:36 +0000 Subject: [PATCH 0971/1349] Apply review fixes - crates/ui-egui/src/app/clipboard.rs - docs/egui-037-migration-plan.md --- crates/ui-egui/src/app/clipboard.rs | 2 +- docs/egui-037-migration-plan.md | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/app/clipboard.rs b/crates/ui-egui/src/app/clipboard.rs index bff5156f7..a50aff456 100644 --- a/crates/ui-egui/src/app/clipboard.rs +++ b/crates/ui-egui/src/app/clipboard.rs @@ -59,7 +59,7 @@ impl DesignApp { if !typing && !ours && !copied_here - && text.is_none_or(is_bare_address) + && text.is_none_or(|t| t.trim().is_empty() || is_bare_address(t)) && let Some(image) = self.services.clipboard_image.as_mut().and_then(|f| f()) { return Pasted::Image(image); diff --git a/docs/egui-037-migration-plan.md b/docs/egui-037-migration-plan.md index 165db7892..dc77c55e7 100644 --- a/docs/egui-037-migration-plan.md +++ b/docs/egui-037-migration-plan.md @@ -494,9 +494,8 @@ Clipboard: freshness, owner/seat changes, empty/absent offers, self-paste, canceled/slow transfers, password exclusion and no unchanged-selection reclaim on wlroots/KWin/Mutter. Native capability evidence is still required; compile-only is not acceptance. -- `Event::PasteImage` is new but DesignCraft has no image-paste contract. Leave it - unhandled rather than inventing a placement path. Add a test that it does not panic and - does not leak into text paste. +- `Event::PasteImage` (an image on the clipboard with no text) pastes through `edit.pasteImage`: in the + selected empty frame, else centered in the view, and never into text being edited. Keyboard layouts: after the fork pin, `RawInput::keyboard_layout_is_latin` and `RawInput::latin_layout_chars` (E19) must preserve tool and command shortcuts on Russian, From 2852a80c3e42f994b74bfe28db3a20644f9a148d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:42:18 -0800 Subject: [PATCH 0972/1349] Object styles: paragraph styles follow paragraph by paragraph; rename reaches every placement - Editing a style's paragraph style restyles each paragraph still in the old style; a paragraph given another style keeps it. - Renaming a style updates objects anchored in table cells and notes. - corners refuses keys other than shape, size and corners. --- crates/doc/src/styles.rs | 16 ++++++++++++++++ crates/engine/src/cmd/style/object.rs | 19 ++++++++++++++----- crates/engine/src/tests.rs | 22 ++++++++++++++++++++++ 3 files changed, 52 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/styles.rs b/crates/doc/src/styles.rs index 98923762c..3a5ea58c3 100644 --- a/crates/doc/src/styles.rs +++ b/crates/doc/src/styles.rs @@ -115,6 +115,22 @@ impl ObjectStyle { self.paragraph_styles(styles, st.paras.len()).is_none_or(|want| st.paras.iter().zip(&want).all(|(f, w)| f.style == *w)) } + /// After an edit from `old`: the paragraphs of `st` still in the paragraph style `old` gives + /// them (every paragraph, when `old` set none) with the one this style gives each, where that + /// differs. A paragraph in another style is left out. + pub fn restyle_from(&self, old: &ObjectStyle, styles: &Styles, st: &Story) -> Vec<(usize, String)> { + let n = st.paras.len(); + let Some(want) = self.paragraph_styles(styles, n) else { return Vec::new() }; + let was = old.paragraph_styles(styles, n); + st.paras + .iter() + .zip(want) + .enumerate() + .filter(|(i, (f, w))| was.as_ref().is_none_or(|was| f.style == was[*i]) && f.style != *w) + .map(|(i, (_, w))| (i, w)) + .collect() + } + /// Put a story's paragraphs in the paragraph styles this style gives them; `false` when it /// sets none or they already are. pub fn restyle(&self, styles: &Styles, st: &mut Story) -> bool { diff --git a/crates/engine/src/cmd/style/object.rs b/crates/engine/src/cmd/style/object.rs index 8a156d654..69368f82c 100644 --- a/crates/engine/src/cmd/style/object.rs +++ b/crates/engine/src/cmd/style/object.rs @@ -309,6 +309,9 @@ fn corners_param( return Ok(Some(None)); } let o = v.as_object().ok_or_else(|| bad(cmd, "`corners` must be an object or null"))?; + if let Some(k) = o.keys().find(|k| !["shape", "size", "corners"].contains(&k.as_str())) { + return Err(bad(cmd, format!("corners.{k} is not a corner setting (shape, size, corners)"))); + } let mut c = if o.contains_key("corners") { serde_json::from_value::(v.clone()).map_err(|e| bad(cmd, format!("corners: {e}")))? } else { @@ -395,7 +398,7 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { *n = r.clone(); } } - d.update_items(|it| it.object_style == name, |it| it.object_style = r.clone()); + d.update_placed_items(|it| it.object_style == name, |it| it.object_style = r.clone()); } // An item follows each attribute the style sets while it has the style's value. When the // style didn't set it before, items with the default follow (the default styles are on @@ -454,8 +457,8 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { } }, ); - // The text of the frames using the style takes a new paragraph style (or chain) while it - // is in the old one's; when the style set none before, all of it does. + // Each paragraph of the frames using the style takes the new paragraph style (or chain) + // while it is in the old one's; when the style set none before, every paragraph does. let mut restyled = 0; if new.paragraph_style.is_some() && (new.paragraph_style != old.paragraph_style || new.apply_next_style != old.apply_next_style) { // Frames on spreads and parents, in groups, and anchored in stories, table cells and @@ -466,10 +469,16 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { stories.dedup(); let styles = d.styles.clone(); for sid in stories { - if d.story(sid).is_some_and(|st| old.story_follows(&styles, st)) + let changes = d.story(sid).map(|st| new.restyle_from(&old, &styles, st)).unwrap_or_default(); + if !changes.is_empty() && let Some(st) = d.story_mut(sid) - && new.restyle(&styles, st) { + for (i, w) in changes { + if let Some(f) = st.paras.get_mut(i) { + f.style = w; + } + } + st.rev = st.rev.wrapping_add(1); restyled += 1; } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 5824be21c..37e8939ae 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -799,6 +799,7 @@ fn object_styles_carry_corners_and_their_stroke_and_corners_can_be_edited() { json!({"stroke": {"swatch": "Nope"}}), json!({"stroke": {"wieght": 5}}), json!({"fill": {"tnt": 0.5}}), + json!({"corners": {"shpae": "rounded"}}), ] { let mut p = bad.clone(); p["name"] = json!("Framed"); @@ -1002,6 +1003,27 @@ fn a_stroke_added_to_an_object_style_reaches_default_strokes() { assert_eq!(weight(&s, stroked_text), 1.0, "a text frame's own 1 pt stroke stays"); } +/// A paragraph-style edit of an object style reaches each paragraph still in the old style, and a +/// paragraph given another style keeps it. +#[test] +fn an_object_style_edit_restyles_paragraph_by_paragraph() { + use designcraft_doc::ItemId; + let mut s = session(); + for n in ["Body", "Lead", "Own"] { + s.execute("style.paragraph.create", &json!({"name": n})).unwrap(); + } + s.execute("style.object.create", &json!({"name": "Boxed", "fromSelection": false, "paragraphStyle": "Body"})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 36, 336, 336], "content": "text", "text": "One\nTwo\nThree", "caret": false})).unwrap(); + let (id, story) = (r["id"].as_u64().unwrap(), r["story"].clone()); + s.execute("style.object.apply", &json!({"name": "Boxed", "ids": [id]})).unwrap(); + s.execute("text.select", &json!({"story": story, "anchor": 4, "focus": 7})).unwrap(); + s.execute("style.paragraph.apply", &json!({"name": "Own"})).unwrap(); + s.execute("style.object.edit", &json!({"name": "Boxed", "paragraphStyle": "Lead"})).unwrap(); + let d = &s.doc().unwrap().doc; + let sid = d.item(ItemId(id)).unwrap().text_frame().unwrap().story; + assert_eq!(d.story(sid).unwrap().paras.iter().map(|p| p.style.as_str()).collect::>(), ["Lead", "Own", "Lead"]); +} + /// A text frame anchored in a story (as IDML import places one) takes a new paragraph style of /// its object style like a frame on the page. #[test] From 113d2e960d04472e068cb16eb0fb12d843346ea9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:44:13 -0800 Subject: [PATCH 0973/1349] Type: Em Space and En Space go in at an insertion point only With text selected, Type > Insert White Space > Em Space and En Space are disabled, and their shortcuts leave the selection as it is instead of replacing it with the space. --- crates/ui-egui/src/menus/run.rs | 9 +++++++-- crates/ui-egui/src/menus/state.rs | 4 +++- crates/ui-egui/src/menus/tests.rs | 6 ++++++ 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index e661b2e11..b6310b88e 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -844,8 +844,13 @@ fn run_ui_part4(app: &mut DesignApp, id: &str, p: &Value) -> Option app.run("text.insert", json!({"text": "\u{e000}", "raw": true})), - "app.insertEmSpace" => app.run("text.insert", json!({"text": "\u{2003}", "raw": true})), - "app.insertEnSpace" => app.run("text.insert", json!({"text": "\u{2002}", "raw": true})), + "app.insertEmSpace" | "app.insertEnSpace" => { + if !menu_enabled(app, id) { + return Some(Err("place the insertion point in text to insert a space".into())); + } + let space = if id == "app.insertEmSpace" { "\u{2003}" } else { "\u{2002}" }; + app.run("text.insert", json!({"text": space, "raw": true})) + } // `panel_docking::command` takes the dock panels (and the Window › Styles group) first. "window.panel" => { let panel = p.get("panel").and_then(Value::as_str).unwrap_or("properties"); diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 3cbec35b8..8d41a4a43 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -175,8 +175,10 @@ pub fn menu_enabled(app: &DesignApp, id: &str) -> bool { if id.starts_with("fit.") { return enabled(app, "object.fit"); } + // Em Space and En Space go in at an insertion point only; they do not replace selected text. if matches!(id, "app.insertEmSpace" | "app.insertEnSpace") { - return enabled(app, "text.insert"); + let caret = app.session.active().and_then(|d| d.selection.text).is_some_and(|t| t.is_caret()); + return caret && enabled(app, "text.insert"); } if id == "guide.selectAll" && (!app.ui.guides || app.ui.guides_locked) { return false; diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 24ccb02a0..876b5e74d 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -2512,6 +2512,12 @@ fn type_shortcuts_insert_spaces_justify_all_lines_and_open_paragraph_rules() { assert!(!menu_enabled(&app, "app.insertEmSpace") && !menu_enabled(&app, "app.insertEnSpace")); press(&mut app, &ctx, Key::M, Modifiers::COMMAND | Modifiers::SHIFT); assert_eq!(story_text(&app, &story), "ab"); + // Selected text: the spaces go in at an insertion point only, so the selection stays. + app.run("text.select", json!({"story": story, "anchor": 0, "focus": 2})).unwrap(); + assert!(!menu_enabled(&app, "app.insertEmSpace") && !menu_enabled(&app, "app.insertEnSpace")); + press(&mut app, &ctx, Key::M, Modifiers::COMMAND | Modifiers::SHIFT); + press(&mut app, &ctx, Key::N, Modifiers::COMMAND | Modifiers::SHIFT); + assert_eq!(story_text(&app, &story), "ab", "a selection is not replaced by a space"); app.run("text.select", json!({"story": story, "anchor": 1, "focus": 1})).unwrap(); assert!(menu_enabled(&app, "app.insertEmSpace") && menu_enabled(&app, "app.insertEnSpace")); press(&mut app, &ctx, Key::M, Modifiers::COMMAND | Modifiers::SHIFT); From 30c72a032eb78658c6db7582047ec883e35d0186 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:44:46 -0800 Subject: [PATCH 0974/1349] Compose: vertical justification keeps text out of a wrap under it Center, Bottom and Justify moved the lines down without looking at text wraps, so a number aligned to the bottom of its frame was drawn over a bar whose wrap should have kept it above the bar. The lines now move down only as far as the wraps under them allow. A baseline comes down to the top of a wrap under its slot, and a table fragment stops with its bottom there. Contour wraps are checked along the band each line sweeps through, beside the line as well as under it. Only wraps that reach into a line's column count, as when the lines are set. Center and Bottom move the lines together by the least room; Justify keeps the first row in place and limits each later row by the wrap under it. An anchored object that moves with its line is skipped under Center and Bottom. --- crates/compose/src/lib.rs | 192 ++++++++++++++++++++++- crates/compose/src/tests.rs | 297 +++++++++++++++++++++++++++++++++++- 2 files changed, 480 insertions(+), 9 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index abac72985..9eaafdc5d 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -3159,7 +3159,9 @@ fn finish_composition(input: FinishInput<'_>) -> ComposedStory { let before: Vec = ft.tables.iter().map(|t| ft.lines.get(t.line).map_or(0.0, |l| l.baseline)).collect(); let spanned = ft.columns.len() > 1 && ft.lines.iter().any(|l| span_paras.get(l.para) == Some(&true)) || ft.lines.iter().any(|l| split_paras.get(l.para) == Some(&true)); - vertical_justify(ft, f, spanned, &doc.footnote_options); + let anchors: Vec = + if ft.objects.is_empty() { Vec::new() } else { story.text.match_indices(designcraft_doc::OBJECT_MARK).map(|(i, _)| i).collect() }; + vertical_justify(ft, f, spanned, &doc.footnote_options, &anchors); for (t, b) in ft.tables.iter_mut().zip(before) { let now = ft.lines.get(t.line).map_or(b, |l| l.baseline); t.shift(now - b); @@ -5483,8 +5485,9 @@ fn rule_decos(doc: &Document, r: &designcraft_doc::Rule, rect: Rect, (color, tin out } -/// `spanned`: a paragraph spans the frame's columns, so the lines move together. -fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &designcraft_doc::FootnoteOptions) { +/// `spanned`: a paragraph spans the frame's columns, so the lines move together. `anchors`: the +/// story byte of each anchored object's mark, by object index. +fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &designcraft_doc::FootnoteOptions, anchors: &[usize]) { if ft.lines.is_empty() || f.opts.vertical_justification == VerticalJustification::Top { return; } @@ -5494,6 +5497,18 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de // Per column (or all lines together). let ncols = if spanned { 1 } else { ft.columns.len().max(1) as u32 }; for c in 0..ncols { + let rooms = wrap_rooms(ft, f, c, spanned, anchors); + // Center and Bottom move the lines together: the nearest text wrap under them is the + // bottom of the room they move down into. Justify checks each row's room below. + let raised; + let together = f.opts.vertical_justification != VerticalJustification::Justify; + let f = match together.then(|| wrap_bottom(ft, f, c, spanned, &rooms)).flatten() { + Some(y1) => { + raised = FrameSpec { area: Rect { y1, ..f.area }, ..f.clone() }; + &raised + } + None => f, + }; let idx: Vec = ft.lines.iter().enumerate().filter(|(_, l)| spanned || l.column == c).map(|(i, _)| i).collect(); let (Some(&a), Some(_)) = (idx.first(), idx.last()) else { continue }; let bottom = idx.iter().map(|&i| ft.lines[i].baseline + ft.lines[i].descent).fold(f64::NEG_INFINITY, f64::max); @@ -5538,11 +5553,31 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de } let gaps = starts.iter().filter(|s| **s).count(); let limit = f.opts.vj_paragraph_spacing_limit.max(0.0); - let para = if gaps > 0 && limit > 0.0 { (space / gaps as f64).min(limit) } else { 0.0 }; - let per = (space - para * gaps as f64) / n as f64; - let mut shift = vec![0.0; n + 1]; - for k in 1..=n { - shift[k] = shift[k - 1] + per + if starts[k] { para } else { 0.0 }; + let shifts = |space: f64| { + let para = if gaps > 0 && limit > 0.0 { (space / gaps as f64).min(limit) } else { 0.0 }; + let per = (space - para * gaps as f64) / n as f64; + let mut shift = vec![0.0; n + 1]; + for k in 1..=n { + shift[k] = shift[k - 1] + per + if starts[k] { para } else { 0.0 }; + } + shift + }; + // Each row moves no further than a text wrap under it allows; every row's + // shift grows with the space, so the most space that keeps them all clear is + // found by bisection. + let clear = |shift: &[f64]| idx.iter().zip(&rows).all(|(&i, &k)| shift[k] <= rooms[i].max(0.0) + 1e-9); + let mut shift = shifts(space); + if !clear(&shift) { + let (mut lo, mut hi) = (0.0, space); + for _ in 0..64 { + let mid = (lo + hi) / 2.0; + if clear(&shifts(mid)) { + lo = mid; + } else { + hi = mid; + } + } + shift = shifts(lo); } for (&i, &k) in idx.iter().zip(&rows) { ft.lines[i].baseline += shift[k]; @@ -5564,6 +5599,147 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de } } +/// The bottom of the room Center and Bottom move the lines of column `c` (every column when +/// `spanned`) down into, when a text wrap under them sits above the text area's bottom (None +/// otherwise): the bottom the lines are aligned by (the lowest descent or table bottom) plus the +/// least of `rooms` (from [`wrap_rooms`]), so the text moves down by that room and no further. +fn wrap_bottom(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, rooms: &[f64]) -> Option { + let in_col = |k: u32| spanned || k == c; + let lines = ft.lines.iter().zip(rooms).filter(|(l, _)| in_col(l.column)); + let room = lines.clone().map(|(_, r)| *r).fold(f64::INFINITY, f64::min); + let bottom = lines + .map(|(l, _)| l.baseline + l.descent) + .chain(ft.tables.iter().filter(|t| in_col(t.column)).map(|t| t.rect.y1)) + .fold(f64::NEG_INFINITY, f64::max); + if !room.is_finite() || !bottom.is_finite() { + return None; + } + let y1 = bottom + room.max(0.0); + (y1 < f.area.y1).then_some(y1) +} + +/// How far each line of column `c` (every column when `spanned`) may move down before a text +/// wrap stops it, by index in `ft.lines` (infinite without one); a table fragment's room counts +/// for its line. No line moves into a wrap under its slot. As when lines are set around a wrap, a +/// line's band runs from its top to its baseline, so a baseline may come down to a wrap's top; a +/// table fragment stops with its bottom there. A wrap without a contour counts by its bounding +/// box. Beside or under a contour, the line moves down only as far as its band stays clear of the +/// contour on its way down (to 0.01 pt). Only wraps that reach into a line's column (or the +/// columns it spans) count, as when the lines are set. An anchored object that moves with the +/// lines being justified (inline, above the line, or positioned from its anchor and not kept +/// within its column) is skipped, except under Justify. Justify keeps the first row in place, so +/// its room stays infinite. `anchors` holds the story byte of each anchored object's mark, by +/// object index. +fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[usize]) -> Vec { + const EPS: f64 = 1e-6; + // One-sided wraps also block the column on the other side of the object: the x-range wrap + // `e` keeps text out of in column `col`, from the object's x-range `a..b` there (None when that + // range misses the column). + let sided = |e: &Exclusion, col: Rect, (a, b): (f64, f64)| -> Option<(f64, f64)> { + let r = e.rect; + (a < col.x1 && b > col.x0).then_some(match e.side { + WrapSide::LeftSide => (a, f64::INFINITY), + WrapSide::RightSide => (f64::NEG_INFINITY, b), + WrapSide::LargestArea if r.x0 - col.x0 >= col.x1 - r.x1 => (a, f64::INFINITY), + WrapSide::LargestArea => (f64::NEG_INFINITY, b), + WrapSide::BothSides | WrapSide::TowardsSpine | WrapSide::AwayFromSpine => (a, b), + }) + }; + // The x-range a wrap under the text keeps it out of in column `col`; None when text may stay beside it. + let blocked = |e: &Exclusion, col: Rect| -> Option<(f64, f64)> { + let r = e.rect; + match e.mode { + WrapMode::None => None, + WrapMode::JumpObject | WrapMode::JumpToNextColumn => (r.x0 < col.x1 && r.x1 > col.x0).then_some((f64::NEG_INFINITY, f64::INFINITY)), + WrapMode::BoundingBox | WrapMode::Contour => sided(e, col, (r.x0, r.x1)), + } + }; + let in_col = |k: u32| spanned || k == c; + // An own-story anchored object whose anchor is on one of these lines and whose position + // follows its line moves with the text. Justify moves later lines further than earlier ones, + // so there the object's current top still limits the lines after its anchor. + let moves_with_text = |e: &Exclusion| { + let Some(a) = e.after.filter(|_| f.opts.vertical_justification != VerticalJustification::Justify) else { return false }; + // The object whose mark is the anchor, placed on one of these lines. + let Some(o) = ft.objects.iter().find(|o| anchors.get(o.index) == Some(&a) && ft.lines.get(o.line).is_some_and(|l| in_col(l.column))) else { + return false; + }; + match &o.object.position { + designcraft_doc::AnchorPosition::Inline { .. } | designcraft_doc::AnchorPosition::AboveLine { .. } => true, + // Kept within the column, it can stop at the column's edge instead of following. + designcraft_doc::AnchorPosition::Custom { y_relative, keep_within_column, .. } => { + *y_relative == designcraft_doc::anchored::AnchorRelative::Anchor && !keep_within_column + } + } + }; + // Justify keeps the first row (its segments and a table on them) in place, so wraps under it + // set no limit. + let first = ft.lines.iter().find(|l| in_col(l.column)).map(|l| l.baseline); + let fixed = |line: usize| { + f.opts.vertical_justification == VerticalJustification::Justify + && ft.lines.get(line).zip(first).is_some_and(|(l, b)| (l.baseline - b).abs() <= 1e-9) + }; + // (line, story byte, column, slot x-range, top, bottom) of each line (its band runs from its + // top to its baseline) and table fragment. + let lines = ft + .lines + .iter() + .enumerate() + .filter(|(_, l)| in_col(l.column)) + .map(|(i, l)| (i, l.range.start, l.column, l.x0, l.x1, l.baseline - l.ascent, l.baseline)); + let tables = ft.tables.iter().filter(|t| in_col(t.column)).map(|t| (t.line, t.anchor, t.column, t.rect.x0, t.rect.x1, t.rect.y0, t.rect.y1)); + let mut rooms = vec![f64::INFINITY; ft.lines.len()]; + for (line, start, k, x0, x1, top, bottom) in lines.chain(tables) { + let Some(&before) = rooms.get(line) else { continue }; + if fixed(line) { + continue; + } + let mut room = before; + // A line that spans columns reaches past its own column. + let col = ft.columns.get(k as usize).copied().unwrap_or(f.area); + let col = Rect { x0: col.x0.min(x0), x1: col.x1.max(x1), ..col }; + let meets = |(a, b): (f64, f64)| a < x1 - EPS && b > x0 + EPS; + for e in f.exclusions.iter().filter(|e| e.wraps_line(start) && !moves_with_text(e)) { + let r = e.rect; + if let (WrapMode::BoundingBox | WrapMode::Contour, Some(contour)) = (e.mode, &e.contour) + && r.y1 > top + && sided(e, col, (r.x0, r.x1)).is_some_and(meets) + { + // A contour beside or under this line whose box reaches the line's slot (the + // contour stays inside its box). Moved down by `d`, the line's band sweeps from its + // top to its baseline plus `d`; the contour's extent there only grows with `d`, so + // the furthest clear move is found by bisection to 0.01 pt. + let hits = |d: f64| contour.band_extent(top, bottom + d).and_then(|x| sided(e, col, x)).is_some_and(meets); + let (mut lo, mut hi) = ((r.y0 - bottom).max(0.0), (r.y1 - top).min(f.area.y1 - bottom).min(room)); + if lo < hi && hits(hi) { + if hits(lo) { + hi = lo; + } + for _ in 0..64 { + if hi - lo <= 0.01 { + break; + } + let mid = (lo + hi) / 2.0; + if hits(mid) { + hi = mid; + } else { + lo = mid; + } + } + room = room.min(lo); + } + } else if r.y0 >= bottom - EPS { + // A wrap at or under this line. + if blocked(e, col).is_some_and(meets) { + room = room.min(r.y0 - bottom); + } + } + } + rooms[line] = room; + } + rooms +} + // ---------- caret and hit testing (Type tool) ---------- /// Two stacked glyphs this far apart in `y` sit on different rows (warichu). diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index f15f1e33d..4354aeb47 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -573,6 +573,301 @@ fn wrap_on_both_sides_sets_text_left_then_right_of_the_object() { assert!(!cs.is_overset()); } +/// A 60 × 200 pt frame at the origin holding `text` with vertical justification `vj`, and a bar +/// at `bar` whose text wrap `wrap` keeps 1 mm above it: (baseline, descent) of each line, the +/// text area and the wrap's top (None when the bar doesn't wrap the frame). +fn bar_chart_lines( + text: &str, + vj: designcraft_doc::VerticalJustification, + wrap: WrapMode, + side: WrapSide, + bar: Rect, +) -> (Vec<(f64, f64)>, Rect, Option) { + let (mut d, sid, fid) = doc_with(text, Rect::new(0.0, 0.0, 60.0, 200.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = vj; + let lid = d.default_layer(); + let id = ItemId(d.alloc()); + let mut it = designcraft_doc::Item::new(id, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(bar)); + it.wrap.mode = wrap; + it.wrap.side = side; + it.wrap.offsets = [72.0 / 25.4, 0.0, 0.0, 0.0]; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let spec = frame_specs(&d, sid).remove(0); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + let lines = all_lines(&cs).iter().map(|l| (l.baseline, l.descent)).collect(); + (lines, spec.area, spec.exclusions.first().map(|e| e.rect.y0)) +} + +/// Bottom, Center and Justify keep the lines out of a text wrap under them: a number aligned to +/// the bottom of its frame sits on the wrap's top offset over a bar instead of on the bar (#1831), +/// with every wrap mode that stops text there. +#[test] +fn vertical_justification_stops_at_a_wrap_under_the_text() { + use designcraft_doc::VerticalJustification::{Bottom, Center, Justify, Top}; + let bar = Rect::new(0.0, 150.0, 60.0, 300.0); + for wrap in [WrapMode::BoundingBox, WrapMode::Contour, WrapMode::JumpObject, WrapMode::JumpToNextColumn] { + let run = |vj, text| bar_chart_lines(text, vj, wrap, WrapSide::BothSides, bar); + let (top, _, wrap_top) = run(Top, "42"); + let wrap_top = wrap_top.unwrap(); + assert!((wrap_top - (150.0 - 72.0 / 25.4)).abs() < 1e-6, "{wrap:?}: the wrap's top is 1 mm above the bar: {wrap_top}"); + + let (bottom, _, _) = run(Bottom, "42"); + let b = bottom[0].0; + assert!((b - wrap_top).abs() < 1e-6, "{wrap:?}: Bottom put the baseline at {b}, not on the wrap's top at {wrap_top}"); + assert!(b > top[0].0 + 50.0, "{wrap:?}: Bottom moved the line down: {b}, {}", top[0].0); + + // Center takes half the room Bottom takes. + let (center, _, _) = run(Center, "42"); + assert!((center[0].0 - top[0].0 - (b - top[0].0) / 2.0).abs() < 1e-6, "{wrap:?}: Center at {}, Bottom at {b}", center[0].0); + + // Justify keeps the first baseline and puts the last where Bottom puts it. + let (top2, _, _) = run(Top, "12\n34"); + let (bottom2, _, _) = run(Bottom, "12\n34"); + let (justify, _, _) = run(Justify, "12\n34"); + assert_eq!(justify.len(), 2); + assert!((justify[0].0 - top2[0].0).abs() < 1e-6, "{wrap:?}: Justify moved the first line: {justify:?}"); + assert!((justify[1].0 - bottom2[1].0).abs() < 1e-6, "{wrap:?}: Justify {justify:?}, Bottom {bottom2:?}"); + assert!(justify[1].0 <= wrap_top + 1e-6); + } +} + +/// Without a wrap, or beside one, Bottom still moves the text down to the text area's bottom. +#[test] +fn vertical_justification_passes_wraps_that_do_not_stop_the_text() { + use designcraft_doc::VerticalJustification::Bottom; + // Wrap off: the number goes down over the bar. + let (lines, area, wrap_top) = bar_chart_lines("42", Bottom, WrapMode::None, WrapSide::BothSides, Rect::new(0.0, 150.0, 60.0, 300.0)); + assert!(wrap_top.is_none()); + assert!(lines[0].0 > 150.0 && lines[0].0 <= area.y1 + 1e-6, "{lines:?}"); + // A bar on the right half from the frame's top: the number is set beside it and goes down + // beside it. + let (lines, area, wrap_top) = bar_chart_lines("42", Bottom, WrapMode::BoundingBox, WrapSide::BothSides, Rect::new(30.0, 0.0, 60.0, 300.0)); + assert!(wrap_top.is_some()); + assert!(lines[0].0 > 150.0 && lines[0].0 <= area.y1 + 1e-6, "{lines:?}"); +} + +/// A one-sided wrap in the second column leaves the first column's lines free to go down, as it +/// leaves them when they are set. +#[test] +fn vertical_justification_passes_a_one_sided_wrap_in_another_column() { + let (mut d, sid, fid) = doc_with("One", Rect::new(0.0, 0.0, 400.0, 200.0), ParaAttrs::default()); + let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options; + o.columns = 2; + o.vertical_justification = designcraft_doc::VerticalJustification::Bottom; + let lid = d.default_layer(); + let mut it = designcraft_doc::Item::new( + ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(250.0, 100.0, 350.0, 300.0)), + ); + it.wrap.mode = WrapMode::BoundingBox; + it.wrap.side = WrapSide::RightSide; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let l = all_lines(&cs)[0]; + assert_eq!(l.column, 0); + assert!((l.baseline + l.descent - 200.0).abs() < 1e-6, "baseline {}, descent {}", l.baseline, l.descent); +} + +/// Beside a contour that widens further down, Bottom moves a line only as far as its band stays +/// clear of the contour. +#[test] +fn vertical_justification_stops_where_a_contour_beside_the_text_widens() { + use designcraft_doc::VerticalJustification::{Bottom, Top}; + // Right edge fixed at 60, left edge x = 55 − 50y/190 from y = 0 down to y = 190. + let edge = |y: f64| 55.0 - 50.0 * y / 190.0; + let pts = [Point::new(55.0, 0.0), Point::new(60.0, 0.0), Point::new(60.0, 190.0), Point::new(5.0, 190.0)]; + let run = |vj| { + let (mut d, sid, fid) = doc_with("42", Rect::new(0.0, 0.0, 60.0, 200.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = vj; + let lid = d.default_layer(); + let path = designcraft_geom::path::PathData::single(designcraft_geom::path::SubPath::polyline(&pts, true)); + let mut it = designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Polygon, path); + it.wrap.mode = WrapMode::Contour; + it.wrap.side = WrapSide::BothSides; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + let l = all_lines(&cs)[0]; + (l.baseline, l.x1) + }; + let (top, x1) = run(Top); + assert!(x1 <= edge(top) + 1e-6, "Top sets the line clear of the contour: x1 {x1}, edge {}", edge(top)); + let (bottom, x1) = run(Bottom); + assert!(bottom >= top - 1e-6 && bottom < 190.0, "Bottom at {bottom}, Top at {top}"); + assert!(x1 <= edge(bottom) + 1e-6, "Bottom moved the line into the contour: baseline {bottom}, x1 {x1}, edge {}", edge(bottom)); +} + +/// Under a contour whose box starts beside the column and which widens into it further down, +/// Bottom moves a line down to where the contour meets its slot, not to the top of the box. +#[test] +fn vertical_justification_stops_where_a_contour_under_the_text_meets_it() { + // Left edge x = 70 − 40(y − 100)/90 from y = 100 down to y = 190: it crosses the column's + // right edge (60) at y = 122.5. + let pts = [Point::new(70.0, 100.0), Point::new(80.0, 100.0), Point::new(80.0, 190.0), Point::new(30.0, 190.0)]; + let (mut d, sid, fid) = doc_with("42", Rect::new(0.0, 0.0, 60.0, 200.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Bottom; + let lid = d.default_layer(); + let path = designcraft_geom::path::PathData::single(designcraft_geom::path::SubPath::polyline(&pts, true)); + let mut it = designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Polygon, path); + it.wrap.mode = WrapMode::Contour; + it.wrap.side = WrapSide::BothSides; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + let b = all_lines(&cs)[0].baseline; + assert!(b <= 122.5 + 1e-6, "Bottom moved the baseline to {b}, past where the contour meets the column at 122.5"); + assert!(b > 122.0, "Bottom stopped the line at {b}, short of where the contour meets the column at 122.5"); +} + +/// An object anchored in the text and positioned from its anchor moves down with the lines, so +/// Center places lines above it as it places them without its wrap. +#[test] +fn vertical_justification_passes_an_anchored_object_that_moves_with_the_text() { + let baselines = |wrap| { + let (mut d, sid, fid) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Center; + // Hung 40 pt under the first line's baseline, under the second line. + anchor_box(&mut d, sid, 1, 0.0, 40.0, true, wrap); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + all_lines(&cs).iter().map(|l| l.baseline).collect::>() + }; + let plain = baselines(WrapMode::None); + let wrapped = baselines(WrapMode::BoundingBox); + assert_eq!(plain.len(), 2); + assert!(plain[0] > 150.0, "Center moved the lines down: {plain:?}"); + assert_eq!(plain.len(), wrapped.len()); + assert!(plain.iter().zip(&wrapped).all(|(a, b)| (a - b).abs() < 1e-6), "without the wrap {plain:?}, with it {wrapped:?}"); +} + +/// Justify keeps the first line in place, so a wrap between it and the next line does not stop +/// the later lines from spreading down to the text area's bottom. +#[test] +fn vertical_justify_passes_a_wrap_under_the_first_line() { + let (mut d, sid, fid) = doc_with("One\nTwo\nSix", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Justify; + let lid = d.default_layer(); + let mut it = designcraft_doc::Item::new( + ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(0.0, 20.0, 300.0, 40.0)), + ); + it.wrap.mode = WrapMode::JumpObject; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + assert_eq!(lines.len(), 3); + assert!( + lines[0].baseline < 20.0 && lines[1].baseline - lines[1].ascent >= 40.0 - 1e-6, + "{:?}", + lines.iter().map(|l| l.baseline).collect::>() + ); + let last = lines[2]; + assert!((last.baseline + last.descent - 400.0).abs() < 1e-6, "{:?}", lines.iter().map(|l| l.baseline).collect::>()); +} + +/// Justify moves each row by its own share of the space, so a wrap between the second and third +/// rows limits the second row's move, not the third's. +#[test] +fn vertical_justify_limits_each_row_by_the_wrap_under_it() { + use designcraft_doc::VerticalJustification::{Justify, Top}; + let para = ParaAttrs { space_before: Some(40.0), ..Default::default() }; + let run = |vj, bar: Option| { + let (mut d, sid, fid) = doc_with("One\nTwo\nSix", Rect::new(0.0, 0.0, 300.0, 400.0), para.clone()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = vj; + if let Some(bar) = bar { + let lid = d.default_layer(); + let mut it = + designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(bar)); + it.wrap.mode = WrapMode::JumpObject; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + } + let cs = compose_story(&d, sid, &ComposeOptions::default()); + all_lines(&cs).iter().map(|l| (l.baseline, l.ascent, l.descent)).collect::>() + }; + let top = run(Top, None); + assert_eq!(top.len(), 3); + let b2 = top[1].0; + let (b3, a3, _) = top[2]; + // A bar 20 pt under the second baseline, clear of the third line. + let bar = Rect::new(0.0, b2 + 20.0, 300.0, b2 + 30.0); + assert!(b3 - a3 > bar.y1, "the third line starts under the bar: {top:?}"); + let set = run(Top, Some(bar)); + assert!(set.iter().zip(&top).all(|(a, b)| (a.0 - b.0).abs() < 1e-6), "the bar moves no line: {set:?}"); + let justify = run(Justify, Some(bar)); + assert!((justify[0].0 - top[0].0).abs() < 1e-6, "{justify:?}"); + // The second row's baseline comes down to the bar; the third row moves twice as far. + let moved = justify[1].0 - b2; + assert!((moved - 20.0).abs() < 1e-6, "the second row moved {moved}: {justify:?}"); + assert!((justify[2].0 - b3 - 2.0 * moved).abs() < 1e-6, "{justify:?}"); +} + +/// Each anchored object's own position decides whether its wrap moves with the text: a fixed +/// object without a wrap on the same line leaves the moving one skipped. +#[test] +fn vertical_justification_matches_each_wrap_to_its_anchored_object() { + let baselines = |wrap| { + let (mut d, sid, fid) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Center; + // A fixed object from the frame's top, then one hung 40 pt under the first line. + anchor_box(&mut d, sid, 1, 150.0, 0.0, false, WrapMode::None); + anchor_box(&mut d, sid, 1 + OBJECT_LEN, 0.0, 40.0, true, wrap); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert_eq!(cs.frames[0].objects.len(), 2); + all_lines(&cs).iter().map(|l| l.baseline).collect::>() + }; + let plain = baselines(WrapMode::None); + let wrapped = baselines(WrapMode::BoundingBox); + assert!(plain[0] > 150.0, "Center moved the lines down: {plain:?}"); + assert_eq!(plain.len(), wrapped.len()); + assert!(plain.iter().zip(&wrapped).all(|(a, b)| (a - b).abs() < 1e-6), "without the wrap {plain:?}, with it {wrapped:?}"); +} + +/// An object positioned from its anchor but kept within its column can stop at the column's +/// bottom, so Bottom does not move the lines after its anchor into it. +#[test] +fn vertical_justification_stops_at_an_anchored_object_kept_within_its_column() { + let (mut d, sid, fid) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Bottom; + anchor_box(&mut d, sid, 1, 0.0, 40.0, true, WrapMode::BoundingBox); + if let designcraft_doc::AnchorPosition::Custom { keep_within_column, .. } = + &mut std::sync::Arc::make_mut(&mut d.story_mut(sid).unwrap().objects[0]).position + { + *keep_within_column = true; + } + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + let o = &cs.frames[0].objects[0]; + let (top, bottom) = (o.origin.y, o.origin.y + 60.0); + assert!(bottom <= 400.0 + 1e-6, "the object stays in the column: {top}..{bottom}"); + let l = lines[1]; + assert!( + l.baseline <= top + 1e-6 || l.baseline - l.ascent >= bottom - 1e-6, + "the second line at {} meets the object at {top}..{bottom}", + l.baseline + ); +} + +/// Justify keeps the first line in place and moves later lines further, so an object anchored in +/// the first line and hung under the last one still stops the lines after its anchor. +#[test] +fn vertical_justify_stops_at_an_object_anchored_above_the_lines_it_wraps() { + let (mut d, sid, fid) = doc_with("One\nTwo\nSix", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Justify; + anchor_box(&mut d, sid, 1, 0.0, 50.0, true, WrapMode::BoundingBox); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + assert_eq!(lines.len(), 3); + let top = cs.frames[0].objects[0].origin.y; + assert!((top - lines[0].baseline - 50.0).abs() < 1e-6, "the object hangs 50 pt under the first line: {top}, {}", lines[0].baseline); + let last = lines[2].baseline; + assert!(last <= top + 1e-6, "Justify moved the last line to {last}, into the object at {top}"); + assert!(last > lines[0].baseline + 40.0, "Justify spread the lines: {:?}", lines.iter().map(|l| l.baseline).collect::>()); +} + /// Same As Clipping follows a placed graphic's clipping path: beside a triangle that widens /// downwards, text reaches further in at the narrow top than at the wide bottom. #[test] @@ -2291,7 +2586,7 @@ fn vertical_justification_counts_table_fragment_bottoms() { let mut spec = frame_specs(&d, sid).remove(0); spec.opts.vertical_justification = mode; - vertical_justify(&mut ft, &spec, false, &d.footnote_options); + vertical_justify(&mut ft, &spec, false, &d.footnote_options, &[]); let moved = ft.lines[anchor].baseline - baseline; let limit = ft.notes[0].rect.y0 - d.footnote_options.space_before; From ae1de74270e747cddeb60c112487edf3a6c72265 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:45:24 -0800 Subject: [PATCH 0975/1349] Text wrap: an Alpha Channel contour counts only inside the graphic's clipping path Opaque pixels outside the placed graphic's clipping path (inverted or not) are not drawn, and they no longer push text aside. An outline that only touches a clip's edge blocks nothing. --- crates/compose/src/lib.rs | 237 +++++++++++++++++++++++++----------- crates/compose/src/tests.rs | 56 +++++++++ 2 files changed, 223 insertions(+), 70 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index ac563b616..76df87568 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -382,9 +382,36 @@ pub struct Contour { /// The frame path of an outline taken from a placed graphic: the frame clips the graphic, so /// the outline counts only within it (empty: no clip). pub clip: Vec>, + /// The placed graphic's clipping path, for an outline traced from the graphic's pixels: the + /// outline counts only inside it too (empty: none). An inverted clipping path is filled + /// even-odd ([`designcraft_doc::Graphic::clip_region`]). + pub graphic_clip: Vec>, + pub graphic_clip_even_odd: bool, pub offset: f64, } +/// A filled shape: closed polylines and their fill rule (non-zero, or even-odd). +#[derive(Clone, Copy)] +struct Region<'a> { + rings: &'a [Vec], + even_odd: bool, +} + +impl Region<'_> { + fn nonzero(rings: &[Vec]) -> Region<'_> { + Region { rings, even_odd: false } + } + + /// Is a point with this winding number filled? + fn fills(self, winding: i32) -> bool { + if self.even_odd { winding % 2 != 0 } else { winding != 0 } + } + + fn edges(self) -> usize { + self.rings.iter().map(Vec::len).sum() + } +} + /// Points a contour outline may have; a larger outline wraps around its bounding box. pub const MAX_CONTOUR_POINTS: usize = 8192; @@ -396,7 +423,13 @@ impl Contour { /// The outline of `path` (after `to_inner`), flattened; None if it is empty or too detailed. fn of(path: &designcraft_geom::BezPath, to_inner: designcraft_geom::Affine, offset: f64) -> Option { let rings = flatten_rings(path, to_inner)?; - offset.is_finite().then_some(Contour { rings, clip: Vec::new(), offset: offset.max(0.0) }) + offset.is_finite().then_some(Contour { + rings, + clip: Vec::new(), + graphic_clip: Vec::new(), + graphic_clip_even_odd: false, + offset: offset.max(0.0), + }) } /// This outline counted only within `frame` (after `to_inner`); unclipped if the frame is @@ -408,18 +441,41 @@ impl Contour { } } + /// This outline counted only inside the graphic's clipping region `clip` (after `to_inner`), + /// filled even-odd when `even_odd` is set; unchanged if the region is empty or too detailed. + fn within_graphic_clip(self, clip: &designcraft_geom::BezPath, even_odd: bool, to_inner: designcraft_geom::Affine) -> Contour { + match flatten_rings(clip, to_inner) { + Some(graphic_clip) => Contour { graphic_clip, graphic_clip_even_odd: even_odd, ..self }, + None => self, + } + } + /// The outline mapped by `a`. fn transformed(self, a: designcraft_geom::Affine) -> Contour { let map = |rings: Vec>| rings.into_iter().map(|r| r.into_iter().map(|p| a * p).collect()).collect(); - Contour { rings: map(self.rings), clip: map(self.clip), offset: self.offset } + Contour { + rings: map(self.rings), + clip: map(self.clip), + graphic_clip: map(self.graphic_clip), + graphic_clip_even_odd: self.graphic_clip_even_odd, + offset: self.offset, + } + } + + /// The clips the outline counts within. + fn clips(&self) -> impl Iterator> { + let frame = (!self.clip.is_empty()).then(|| Region::nonzero(&self.clip)); + let graphic = (!self.graphic_clip.is_empty()).then_some(Region { rings: &self.graphic_clip, even_odd: self.graphic_clip_even_odd }); + frame.into_iter().chain(graphic) } fn bounds(&self) -> Rect { - let Some(r) = rings_bounds(&self.rings) else { return Rect::ZERO }; - let r = match rings_bounds(&self.clip) { - Some(c) => r.intersect(c), - None => r, - }; + let Some(mut r) = rings_bounds(&self.rings) else { return Rect::ZERO }; + for c in self.clips() { + if let Some(b) = rings_bounds(c.rings) { + r = r.intersect(b); + } + } r.inflate(self.offset, self.offset) } @@ -429,8 +485,8 @@ impl Contour { fn band_extent(&self, y0: f64, y1: f64) -> Option<(f64, f64)> { let (y0, y1) = (y0 - self.offset, y1 + self.offset); let (mut lo, mut hi) = rings_band_extent(&self.rings, y0, y1)?; - if !self.clip.is_empty() { - let (a, b) = rings_band_extent(&self.clip, y0, y1)?; + for c in self.clips() { + let (a, b) = rings_band_extent(c.rings, y0, y1)?; (lo, hi) = (lo.max(a), hi.min(b)); } (lo <= hi).then_some((lo - self.offset, hi + self.offset)) @@ -444,19 +500,21 @@ impl Contour { if !low.is_finite() || !high.is_finite() || high < low { return self.band_extent(y0, y1).into_iter().collect(); } - let mut spans = rings_band_spans(&self.rings, low, high); + let mut spans = rings_band_spans(Region::nonzero(&self.rings), low, high); // Extremely fragmented imported paths use the conservative outer extent, bounding the // work of subtracting intervals from every line. A traced 128-column mask stays below it. if spans.len() > 128 { return self.band_extent(y0, y1).into_iter().collect(); } - if !self.clip.is_empty() { - let clip = rings_band_spans(&self.clip, low, high); - // A fragmented frame, or shapes too detailed to compare within each line's budget, - // take the common part of the two projections, which can block more than the frame - // shows. - let exact = if clip.len() > 128 { None } else { clipped_band_spans(&self.rings, &self.clip, low, high) }; - spans = exact.unwrap_or_else(|| intersect_spans(&spans, &clip)); + let clips: Vec = self.clips().collect(); + if !clips.is_empty() { + let projected: Vec> = clips.iter().map(|c| rings_band_spans(*c, low, high)).collect(); + // A fragmented clip, or shapes too detailed to compare within each line's budget, + // take the common part of the projections, which can block more than the clips show. + let mut shapes = vec![Region::nonzero(&self.rings)]; + shapes.extend(&clips); + let exact = if projected.iter().any(|p| p.len() > 128) { None } else { clipped_band_spans(&shapes, low, high) }; + spans = exact.unwrap_or_else(|| projected.iter().fold(spans, |s, p| intersect_spans(&s, p))); } merge_spans(spans.into_iter().map(|(a, b)| (a - self.offset, b + self.offset)).collect()) } @@ -481,19 +539,22 @@ fn intersect_spans(a: &[(f64, f64)], b: &[(f64, f64)]) -> Vec<(f64, f64)> { out } -/// Occupied intervals across the band `y0..y1` of the part of `rings` inside `clip` (both filled -/// by the non-zero rule). A vertical line through a point of that part either crosses the middle -/// of the band inside both shapes, or stops inside the band on an edge of one shape that lies -/// inside the other. The spans are the middle slice of both shapes and the parts of each -/// shape's edges in the band that lie inside the other, so a part of the outline outside the -/// clip blocks nothing, even where it shares x positions with the clip in the same band. -/// None when that takes more than [`MAX_CLIPPED_WORK`] edge visits. -fn clipped_band_spans(rings: &[Vec], clip: &[Vec], y0: f64, y1: f64) -> Option> { +/// Occupied intervals across the band `y0..y1` of the part of the plane inside every one of +/// `shapes` (an outline and its clips). A vertical line through a point of that part either +/// crosses the middle of the band inside all the shapes, or stops inside the band on an edge of +/// one shape that lies inside the others. The spans are the middle slice of all the shapes and +/// the parts of each shape's edges in the band that lie inside the others, so a part of the +/// outline outside a clip blocks nothing, even where it shares x positions with the clip in the +/// same band. None when that takes more than [`MAX_CLIPPED_WORK`] edge visits. +fn clipped_band_spans(shapes: &[Region], y0: f64, y1: f64) -> Option> { let middle = y0 * 0.5 + y1 * 0.5; - let mut spans = intersect_spans(&merge_spans(middle_spans(rings, middle)), &merge_spans(middle_spans(clip, middle))); + let mut slices = shapes.iter().map(|s| merge_spans(middle_spans(*s, middle))); + let first = slices.next()?; + let mut spans = slices.fold(first, |a, b| intersect_spans(&a, &b)); let mut budget = MAX_CLIPPED_WORK; - edges_inside(rings, clip, y0, y1, &mut budget, &mut spans)?; - edges_inside(clip, rings, y0, y1, &mut budget, &mut spans)?; + for k in 0..shapes.len() { + edges_inside(shapes, k, y0, y1, &mut budget, &mut spans)?; + } Some(merge_spans(spans)) } @@ -503,10 +564,12 @@ fn spend(budget: &mut usize, n: usize) -> Option<()> { Some(()) } -/// Pushes to `out` the x-ranges of the parts of `rings`' edges within the band `y0..y1` that lie -/// inside `other` or on its boundary. None when `budget` runs out. -fn edges_inside(rings: &[Vec], other: &[Vec], y0: f64, y1: f64, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { - let n = other.iter().map(Vec::len).sum::().max(1); +/// Pushes to `out` the x-ranges of the parts of the edges of `shapes[k]` within the band `y0..y1` +/// that bound the part of the plane inside all of `shapes` ([`segment_inside`]). None when +/// `budget` runs out. +fn edges_inside(shapes: &[Region], k: usize, y0: f64, y1: f64, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { + let n = shapes.iter().map(|o| o.edges()).sum::().max(1); + let rings = shapes.get(k)?.rings; for ring in rings { let Some(&last) = ring.last() else { continue }; let mut a = last; @@ -520,7 +583,7 @@ fn edges_inside(rings: &[Vec], other: &[Vec], y0: f64, y1: f64, bu (u.min(v).clamp(0.0, 1.0), u.max(v).clamp(0.0, 1.0)) }; let (p, q) = (a + (b - a) * t0, a + (b - a) * t1); - segment_inside(p, q, other, n, budget, out)?; + segment_inside(p, q, shapes, k, n, budget, out)?; } a = b; } @@ -528,26 +591,41 @@ fn edges_inside(rings: &[Vec], other: &[Vec], y0: f64, y1: f64, bu Some(()) } -/// Pushes to `out` the x-ranges of the parts of segment `p`–`q` inside `rings` (`n` edges) or on -/// their boundary: the segment is split where it meets their edges, and each piece is tested at -/// its middle. Each pass over the edges takes `n` from `budget`; None when it runs out. -fn segment_inside(p: Point, q: Point, rings: &[Vec], n: usize, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { +/// Pushes to `out` the x-ranges of the parts of segment `p`–`q`, an edge of `shapes[k]`, that +/// bound the part of the plane inside all of `shapes` (`n` edges in all). The segment is split +/// where it meets the other shapes' edges, and each piece is tested at its middle: it counts when +/// the points just beside it on one side are inside all the shapes. Where `shapes[k]` has no area +/// on either side (an open path), it counts when it is inside the other shapes or on their +/// boundary. Each pass over the edges takes `n` from `budget`; None when it runs out. +fn segment_inside(p: Point, q: Point, shapes: &[Region], k: usize, n: usize, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { let r = q - p; let len2 = r.hypot2(); if !len2.is_finite() { return Some(()); } let at = |t: f64| p + r * t; + let in_others = |pt: Point| shapes.iter().enumerate().all(|(i, s)| i == k || inside_or_on(*s, pt)); spend(budget, n)?; if len2 < 1e-24 { - if inside_or_on(rings, p) { + if in_others(p) { out.push((p.x, p.x)); } return Some(()); } + // A step to either side of the segment, well above rounding at page coordinates. + let side = r.turn_90() * (1e-6 / len2.sqrt()); + let bounds_the_part = |m: Point| { + let own = shapes.get(k).copied(); + let in_own = |pt: Point| own.is_some_and(|s| inside_or_on(s, pt)); + let (a, b) = (m + side, m - side); + match (in_own(a), in_own(b)) { + (false, false) => in_others(m), + (ia, ib) => (ia && in_others(a)) || (ib && in_others(b)), + } + }; let (ylo, yhi) = (p.y.min(q.y), p.y.max(q.y)); let mut ts = vec![0.0, 1.0]; - for ring in rings { + for ring in shapes.iter().enumerate().filter(|(i, _)| *i != k).flat_map(|(_, s)| s.rings) { let Some(&last) = ring.last() else { continue }; let mut c = last; for &d in ring { @@ -576,8 +654,8 @@ fn segment_inside(p: Point, q: Point, rings: &[Vec], n: usize, budget: &m ts.dedup_by(|a, b| (*a - *b).abs() < 1e-12); for w in ts.windows(2) { let (u, v) = (w[0], w[1]); - spend(budget, n)?; - if inside_or_on(rings, at(u * 0.5 + v * 0.5)) { + spend(budget, 3 * n)?; + if bounds_the_part(at(u * 0.5 + v * 0.5)) { let (x0, x1) = (at(u).x, at(v).x); out.push((x0.min(x1), x0.max(x1))); } @@ -585,10 +663,10 @@ fn segment_inside(p: Point, q: Point, rings: &[Vec], n: usize, budget: &m Some(()) } -/// Is `pt` inside `rings` (non-zero rule) or within a hair of one of their edges? -fn inside_or_on(rings: &[Vec], pt: Point) -> bool { +/// Is `pt` inside `shape` or within a hair of one of its edges? +fn inside_or_on(shape: Region, pt: Point) -> bool { let mut winding = 0i32; - for ring in rings { + for ring in shape.rings { let Some(&last) = ring.last() else { continue }; let mut a = last; for &b in ring { @@ -607,7 +685,7 @@ fn inside_or_on(rings: &[Vec], pt: Point) -> bool { a = b; } } - winding != 0 + shape.fills(winding) } /// Sorted, overlapping spans joined. Zero-width spans (a vertical edge of an open path) are kept: @@ -626,9 +704,9 @@ fn merge_spans(mut spans: Vec<(f64, f64)>) -> Vec<(f64, f64)> { out } -fn rings_band_spans(rings: &[Vec], y0: f64, y1: f64) -> Vec<(f64, f64)> { - let mut spans = middle_spans(rings, y0 * 0.5 + y1 * 0.5); - for ring in rings { +fn rings_band_spans(shape: Region, y0: f64, y1: f64) -> Vec<(f64, f64)> { + let mut spans = middle_spans(shape, y0 * 0.5 + y1 * 0.5); + for ring in shape.rings { let Some(&last) = ring.last() else { continue }; let mut a = last; for &b in ring { @@ -649,11 +727,11 @@ fn rings_band_spans(rings: &[Vec], y0: f64, y1: f64) -> Vec<(f64, f64)> { merge_spans(spans) } -/// The intervals of the line at height `middle` inside `rings` (non-zero rule), unsorted. -fn middle_spans(rings: &[Vec], middle: f64) -> Vec<(f64, f64)> { +/// The intervals of the line at height `middle` inside `shape`, unsorted. +fn middle_spans(shape: Region, middle: f64) -> Vec<(f64, f64)> { let mut spans = Vec::new(); let mut crossings = Vec::new(); - for ring in rings { + for ring in shape.rings { let Some(&last) = ring.last() else { continue }; let mut a = last; for &b in ring { @@ -671,7 +749,7 @@ fn middle_spans(rings: &[Vec], middle: f64) -> Vec<(f64, f64)> { let mut winding = 0i32; let mut previous = None; for (x, delta) in crossings { - if winding != 0 + if shape.fills(winding) && let Some(start) = previous { spans.push((start, x)); @@ -782,7 +860,7 @@ fn nothing_visible_wraps_nothing(doc: &Document, it: &Item, wrap: &designcraft_d fn wrap_exclusion( wrap: &designcraft_doc::TextWrap, b: Rect, - outline: impl FnOnce() -> Option<(designcraft_geom::BezPath, Option)>, + outline: impl FnOnce() -> Option, xf: Affine, inv: Affine, left_page: bool, @@ -802,24 +880,42 @@ fn wrap_exclusion( let contour = matches!(wrap.mode, WrapMode::BoundingBox | WrapMode::Contour).then_some(custom); return Exclusion { rect, mode: wrap.mode, side, contour, after: None }; } - let contour = if wrap.mode == WrapMode::Contour { outline() } else { None }.and_then(|(path, frame)| { - let c = Contour::of(&path, inv * xf, o[0])?; - Some(match frame { - Some(frame) => c.within(&frame, inv * xf), - None => c, - }) + let contour = if wrap.mode == WrapMode::Contour { outline() } else { None }.and_then(|src| { + let mut c = Contour::of(&src.path, inv * xf, o[0])?; + if let Some(frame) = &src.frame { + c = c.within(frame, inv * xf); + } + if let Some((clip, even_odd)) = &src.graphic_clip { + c = c.within_graphic_clip(clip, *even_odd, inv * xf); + } + Some(c) }); let rect = contour.as_ref().map_or_else(|| inv.transform_rect_bbox(r), Contour::bounds); Exclusion { rect, mode: wrap.mode, side, contour, after: None } } -/// The outline a contour wrap of `kind` around frame `it` follows, in the frame's inner space, and -/// for an outline taken from the placed graphic, the frame path that clips it. Bounding Box -/// follows the part of the placed graphic the frame shows; Same As Clipping follows the graphic's -/// clipping path when it has one; Alpha Channel follows the image's traced outline when the -/// engine has traced one; detected edges and image paths follow the frame's path (as other -/// frames do). -fn contour_path(doc: &Document, it: &Item, wrap: &designcraft_doc::TextWrap) -> (designcraft_geom::BezPath, Option) { +/// The outline a contour wrap follows, in the frame's inner space, with what clips it. +struct Outline { + path: designcraft_geom::BezPath, + /// For an outline taken from the placed graphic: the frame path that clips it. + frame: Option, + /// For an outline traced from the graphic's pixels: the graphic's clipping region, and + /// whether it is filled even-odd. + graphic_clip: Option<(designcraft_geom::BezPath, bool)>, +} + +impl Outline { + fn clipped_by(path: designcraft_geom::BezPath, frame: designcraft_geom::BezPath) -> Outline { + Outline { path, frame: Some(frame), graphic_clip: None } + } +} + +/// The outline a contour wrap of `kind` around frame `it` follows. Bounding Box follows the part +/// of the placed graphic the frame shows; Same As Clipping follows the graphic's clipping path +/// when it has one; Alpha Channel follows the image's traced outline when the engine has traced +/// one, within the graphic's clipping path too; detected edges and image paths follow the frame's +/// path (as other frames do). +fn contour_path(doc: &Document, it: &Item, wrap: &designcraft_doc::TextWrap) -> Outline { let frame = designcraft_geom::corners::apply(&it.path, &it.corners); let kind = wrap.contour; if kind == designcraft_doc::ContourType::AlphaChannel @@ -833,19 +929,20 @@ fn contour_path(doc: &Document, it: &Item, wrap: &designcraft_doc::TextWrap) -> if wrap.inside_edges { path.extend(o.holes.to_bezpath().iter()); } - return (g.xf * to_graphic * path, Some(frame)); + // The clipping path hides the pixels outside it. + return Outline { graphic_clip: g.clip_region(), ..Outline::clipped_by(g.xf * to_graphic * path, frame) }; } if kind == designcraft_doc::ContourType::SameAsClipping && let Some((path, _)) = it.graphic().and_then(|g| g.clip_region()) { - return (path, Some(frame)); + return Outline::clipped_by(path, frame); } if kind == designcraft_doc::ContourType::BoundingBox && let Some(r) = it.graphic().and_then(|g| g.shown_bounds(it.inner_bounds())) { - return (designcraft_geom::kurbo::Shape::to_path(&r, 0.1), Some(frame)); + return Outline::clipped_by(designcraft_geom::kurbo::Shape::to_path(&r, 0.1), frame); } - (frame, None) + Outline { path: frame, frame: None, graphic_clip: None } } /// One frame of the thread, ready for composition. diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index ab108b03b..e8fb2aac8 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -573,6 +573,62 @@ fn wrap_on_both_sides_sets_text_left_then_right_of_the_object() { assert!(!cs.is_overset()); } +/// An Alpha Channel contour counts only where the graphic's clipping path shows the image: here +/// the visible pixels are in the right half and the clipping path shows the left half, so the +/// image wraps nothing; inverted, the clipping path shows the right half and the image wraps. +#[test] +fn an_alpha_channel_contour_stops_at_the_clipping_path() { + use designcraft_geom::{PathData, Point, SubPath}; + let rect = |x0: f64, x1: f64| { + PathData::single(SubPath::polyline(&[Point::new(x0, 0.0), Point::new(x1, 0.0), Point::new(x1, 200.0), Point::new(x0, 200.0)], true)) + }; + let lines_beside = |invert: bool| { + let (mut d, sid, _) = doc_with(&[LOREM; 4].join(" "), Rect::new(0.0, 0.0, 300.0, 800.0), ParaAttrs::default()); + let lid = d.default_layer(); + let asset = designcraft_doc::AssetId(d.alloc()); + let mut it = designcraft_doc::Item::new( + ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(150.0, 100.0, 300.0, 300.0)), + ); + let mut clip = designcraft_doc::ClippingPath::new(designcraft_doc::ClippingKind::DetectEdges, rect(0.0, 75.0)); + clip.invert = invert; + it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic { + layer_options: None, + asset, + size: (150.0, 200.0), + xf: designcraft_geom::Affine::translate((150.0, 100.0)), + clip: Some(std::sync::Arc::new(clip)), + auto_fit: Default::default(), + fit_align: 0, + crop: [0.0; 4], + wrap: Default::default(), + fill: Default::default(), + }); + it.wrap.mode = WrapMode::Contour; + it.wrap.side = WrapSide::LeftSide; + it.wrap.contour = designcraft_doc::ContourType::AlphaChannel; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + d.alpha_outlines.push(std::sync::Arc::new(designcraft_doc::AlphaOutline { + asset, + threshold: designcraft_doc::DEFAULT_ALPHA_THRESHOLD, + width: 150, + height: 200, + outer: rect(75.0, 150.0), + holes: PathData::default(), + source: std::sync::Weak::new(), + serial: designcraft_doc::AlphaOutline::next_serial(), + })); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + cs.frames[0].lines.iter().filter(|l| l.baseline - l.ascent > 100.0 && l.baseline + l.descent < 300.0).map(|l| l.x1).collect::>() + }; + let shown_left = lines_beside(false); + assert!(!shown_left.is_empty() && shown_left.iter().all(|x| *x > 260.0), "nothing visible wraps nothing: {shown_left:?}"); + let shown_right = lines_beside(true); + assert!(!shown_right.is_empty() && shown_right.iter().all(|x| *x <= 225.0 + 1e-6), "the right half wraps: {shown_right:?}"); +} + /// Same As Clipping follows a placed graphic's clipping path: beside a triangle that widens /// downwards, text reaches further in at the narrow top than at the wide bottom. #[test] From e2c6d7b36c55ce42a40533633f02fd9e3726d239 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:47:33 -0800 Subject: [PATCH 0976/1349] Object styles: a null fromSelection or applyNextStyle is refused --- crates/engine/src/cmd/style/object.rs | 2 +- crates/engine/src/tests.rs | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/style/object.rs b/crates/engine/src/cmd/style/object.rs index 69368f82c..b22388372 100644 --- a/crates/engine/src/cmd/style/object.rs +++ b/crates/engine/src/cmd/style/object.rs @@ -237,7 +237,7 @@ fn text_frame_param( /// A true/false parameter, when given. fn bool_param(cmd: &str, p: &Value, key: &str) -> Result> { match p.get(key) { - None | Some(Value::Null) => Ok(None), + None => Ok(None), Some(Value::Bool(b)) => Ok(Some(*b)), Some(_) => Err(bad(cmd, format!("`{key}` must be true or false"))), } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 37e8939ae..5a8fc30e6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -808,6 +808,8 @@ fn object_styles_carry_corners_and_their_stroke_and_corners_can_be_edited() { assert!(s.execute("style.object.create", &p).is_err(), "{bad}"); } assert!(s.execute("style.object.create", &json!({"name": "Other", "fromSelection": "yes"})).is_err()); + assert!(s.execute("style.object.create", &json!({"name": "Other", "fromSelection": null})).is_err()); + assert!(s.execute("style.object.edit", &json!({"name": "Framed", "applyNextStyle": null})).is_err()); // A size outside 0–10000 pt is refused, not changed. for size in [-1.0, 10_001.0] { assert!(s.execute("style.object.edit", &json!({"name": "Framed", "corners": {"size": size}})).is_err(), "{size}"); From bdabdc8155cfc69fe793240cfa83e2d418c70e53 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:51:37 -0800 Subject: [PATCH 0977/1349] Preflight: show a pending first check as checking, and rebuild document indexes on grid changes - The status bar and the Preflight panel show a gray light and "Checking" until the active document's first check ends, instead of a green "No errors". - The cross-reference and running-header indexes are keyed on the baseline grid and the font scope as well, so a change to either builds them again, in a cache and in a cache over it. - The test helper that waits for the preflight worker fails when the worker ends without a result. --- crates/compose/src/cache.rs | 3 ++ crates/compose/src/tests.rs | 26 ++++++++++++ crates/ui-egui/src/chrome/status_bar.rs | 17 +++++--- crates/ui-egui/src/panels.rs | 10 +++-- crates/ui-egui/src/panels/properties/links.rs | 17 ++++++-- crates/ui-egui/src/preflight_worker.rs | 8 ---- crates/ui-egui/src/preflight_worker/tests.rs | 41 ++++++++++++++++++- 7 files changed, 101 insertions(+), 21 deletions(-) diff --git a/crates/compose/src/cache.rs b/crates/compose/src/cache.rs index 9cf96e497..dd7180915 100644 --- a/crates/compose/src/cache.rs +++ b/crates/compose/src/cache.rs @@ -88,6 +88,9 @@ fn doc_signature(doc: &Document) -> u64 { (Arc::as_ptr(&doc.styles) as usize).hash(&mut h); format!("{:?}", doc.text_variables).hash(&mut h); sections_hash(doc).hash(&mut h); + // The compositions the indexes are built from also depend on these (see `signature`). + let g = &doc.settings.baseline_grid; + (doc.font_scope, g.relative_to == designcraft_doc::GridRelative::TopMargin, g.start.to_bits(), g.increment.to_bits()).hash(&mut h); h.finish() } diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 900bced97..7f900dd5b 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -8175,6 +8175,32 @@ fn a_cache_over_another_reads_it_without_writing_to_it() { assert!(base.composed_for(&old, sid).is_none(), "the base holds nothing of the older state"); } +/// The cross-reference and running-header indexes are built from compositions that depend on the +/// baseline grid and the font scope, so a change to either builds them again, in a cache and in a +/// cache over it. +#[test] +fn the_document_indexes_are_rebuilt_when_the_grid_or_font_scope_changes() { + let para = ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }; + let (d, _, _) = doc_with(LOREM, Rect::new(0.0, 0.0, 200.0, 600.0), para); + let base = Arc::new(Cache::new()); + let (xrefs, running) = (base.xref_index(&d), base.running_index(&d)); + let mut grid = d.clone(); + grid.settings.baseline_grid.increment = 30.0; + let mut scope = d.clone(); + scope.font_scope += 1; + for (changed, what) in [(&grid, "grid"), (&scope, "font scope")] { + let reader = Cache::over(Arc::clone(&base)); + assert!(!Arc::ptr_eq(&reader.xref_index(changed), &xrefs), "{what}: the base's cross-reference index is not used"); + assert!(!Arc::ptr_eq(&reader.running_index(changed), &running), "{what}: the base's running-header index is not used"); + let own = Cache::new(); + let (x, r) = (own.xref_index(&d), own.running_index(&d)); + assert!(!Arc::ptr_eq(&own.xref_index(changed), &x), "{what}: cross-reference index rebuilt"); + assert!(!Arc::ptr_eq(&own.running_index(changed), &r), "{what}: running-header index rebuilt"); + } + let reader = Cache::over(Arc::clone(&base)); + assert!(Arc::ptr_eq(&reader.xref_index(&d), &xrefs), "the same state uses the base's index"); +} + /// Two single pages 618 pt tall, top margins 36 and 48, each with an overset 11/13 story aligned /// to a baseline grid (start 0, increment 13) and a frame filling its margin box (bottom 582). fn grid_margin_doc(relative_to: designcraft_doc::GridRelative) -> (Document, [StoryId; 2]) { diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index c602b1721..765ec66fc 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -169,19 +169,24 @@ pub fn status_bar(app: &mut DesignApp, ui: &mut egui::Ui) { ui.painter().circle_filled( r.center(), 4.0, - if errors == 0 { Color32::from_rgb(60, 200, 90) } else { Color32::from_rgb(235, 50, 50) }, + match errors { + None => t.text_dim, + Some(0) => Color32::from_rgb(60, 200, 90), + Some(_) => Color32::from_rgb(235, 50, 50), + }, ); - let count = if errors == 0 { - format!("{} ▾", crate::i18n::tr(&app.ui.language, "No errors")) - } else { - format!( + let count = match errors { + // The active document's first check hasn't ended. + None => format!("{} ▾", crate::i18n::tr(&app.ui.language, "Checking")), + Some(0) => format!("{} ▾", crate::i18n::tr(&app.ui.language, "No errors")), + Some(errors) => format!( "{} ▾", crate::i18n::count_label( &app.ui.language, if errors == 1 && !crate::i18n::category_first(&app.ui.language) { "error" } else { "errors" }, errors ) - ) + ), }; // As in InDesign, the count opens a menu that leads to the Preflight panel. let menu = crate::menus::menu_button(ui, egui::RichText::new(count).font(small.clone()), |ui| { diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 45606f4cd..33d9bd3c4 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -299,9 +299,13 @@ pub fn text_attrs(app: &mut DesignApp) -> Option { if v.is_null() { None } else { Some(serde_json::to_value(v).ok()?) } } -/// Count the preflight errors last found for the active document (0 until its first check ends). -pub fn preflight_errors(app: &mut DesignApp, ctx: &egui::Context) -> usize { - crate::preflight_worker::issues(app, ctx).map_or(0, |issues| issues.iter().filter(|i| i.severity == "error").count()) +/// Count the preflight errors last found for the active document: `None` until its first check +/// ends, and 0 with no document open. +pub fn preflight_errors(app: &mut DesignApp, ctx: &egui::Context) -> Option { + match crate::preflight_worker::issues(app, ctx) { + Some(issues) => Some(issues.iter().filter(|i| i.severity == "error").count()), + None => app.session.active().is_none().then_some(0), + } } /// Height of one swatch-menu row. diff --git a/crates/ui-egui/src/panels/properties/links.rs b/crates/ui-egui/src/panels/properties/links.rs index 7a1a6f0d0..f161f35f4 100644 --- a/crates/ui-egui/src/panels/properties/links.rs +++ b/crates/ui-egui/src/panels/properties/links.rs @@ -300,18 +300,29 @@ pub fn info_panel(app: &mut DesignApp, ui: &mut egui::Ui) { pub fn preflight_panel(app: &mut DesignApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); - let issues = crate::preflight_worker::issues(app, ui.ctx()).unwrap_or_default(); + let found = crate::preflight_worker::issues(app, ui.ctx()); + // The active document's first check hasn't ended. + let checking = found.is_none() && app.session.active().is_some(); + let issues = found.unwrap_or_default(); let errors = issues.iter().filter(|i| i.severity == "error").count(); ui.horizontal(|ui| { let (r, _) = ui.allocate_exact_size(vec2(10.0, 10.0), egui::Sense::hover()); ui.painter().circle_filled( r.center(), 4.5, - if errors == 0 { egui::Color32::from_rgb(60, 200, 90) } else { egui::Color32::from_rgb(235, 50, 50) }, + if checking { + t.text_dim + } else if errors == 0 { + egui::Color32::from_rgb(60, 200, 90) + } else { + egui::Color32::from_rgb(235, 50, 50) + }, ); crate::rtl::label( ui, - if issues.is_empty() { + if checking { + crate::i18n::tr(&app.ui.language, "Checking").to_string() + } else if issues.is_empty() { crate::i18n::tr(&app.ui.language, "No errors").to_string() } else { format!( diff --git a/crates/ui-egui/src/preflight_worker.rs b/crates/ui-egui/src/preflight_worker.rs index 4da6224e5..02b27832e 100644 --- a/crates/ui-egui/src/preflight_worker.rs +++ b/crates/ui-egui/src/preflight_worker.rs @@ -420,13 +420,5 @@ pub(crate) fn start_worker(app: &mut DesignApp, ctx: &egui::Context) { app.preflight.worker.channels = spawn(ctx.clone(), &app.preflight.worker.live); } -/// Waits in a test for the worker's next result and keeps it, as a frame that polls would. -#[cfg(all(test, not(target_arch = "wasm32")))] -pub(crate) fn wait_for_worker(app: &mut DesignApp) { - if let Some(found) = app.preflight.worker.wait() { - app.preflight.keep(found); - } -} - #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/preflight_worker/tests.rs b/crates/ui-egui/src/preflight_worker/tests.rs index 9cc9a394b..ba0bfad67 100644 --- a/crates/ui-egui/src/preflight_worker/tests.rs +++ b/crates/ui-egui/src/preflight_worker/tests.rs @@ -1,6 +1,7 @@ use std::sync::Arc; use egui::vec2; +use egui_kittest::kittest::Queryable; use serde_json::json; use super::Checked; @@ -30,6 +31,14 @@ fn found(app: &crate::DesignApp) -> Option<(usize, bool)> { Some((f.issues.iter().filter(|i| i.severity == "error").count(), f.of.same(&now))) } +/// Waits for the worker's next result and keeps it, as a frame that polls would. Panics when the +/// worker has ended without one. +#[cfg(not(target_arch = "wasm32"))] +fn wait_for_worker(app: &mut crate::DesignApp) { + let Some(found) = app.preflight.worker.wait() else { panic!("the preflight worker ended before it sent a result") }; + app.preflight.keep(found); +} + /// A worker whose thread never takes a job: the test reads the queue. fn stalled_worker(app: &mut crate::DesignApp) -> (std::sync::mpsc::Receiver, std::sync::mpsc::Sender) { let (tx, jobs) = std::sync::mpsc::sync_channel(1); @@ -298,9 +307,39 @@ fn the_worker_checks_and_the_interface_thread_does_not() { assert_eq!(h.state().app.preflight.inline_checks, 0, "no check ran on the interface thread"); // The last frame handed the current state to the worker, whose last answer is for it. while found(&h.state().app) != Some((1, true)) { - super::wait_for_worker(&mut h.state_mut().app); + wait_for_worker(&mut h.state_mut().app); } let issues = super::issues(&mut h.state_mut().app, &ctx).unwrap(); assert_eq!(issues.iter().filter(|i| i.severity == "error").count(), 1); assert_eq!(h.state().app.preflight.inline_checks, 0, "the worker's answer is kept, not checked again"); } + +/// Until the active document's first check ends, the status bar and the Preflight panel show that +/// it is being checked, not a clean result. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn the_first_check_shows_as_checking() { + let (mut app, _) = overset_app(); + app.ui.dock_tab = "properties".into(); + let (_jobs, _done) = stalled_worker(&mut app); + let mut h = test_window::open(app, vec2(1200.0, 700.0)); + h.state_mut().app.run("window.panel", json!({"panel": "preflight"})).unwrap(); + h.run_steps(5); + assert!(h.state().app.preflight.found.is_empty(), "nothing found yet"); + assert_eq!(h.state().app.preflight.inline_checks, 0); + assert!(h.query_by_label("Checking ▾").is_some(), "the status bar shows the check"); + assert!(h.query_by_label("No errors ▾").is_none()); + assert!(h.query_by_label("Checking").is_some(), "the Preflight panel shows the check"); + assert!(h.query_by_label("No errors").is_none()); +} + +/// Waiting for a worker that ended before it answered fails the test instead of leaving it +/// waiting. +#[cfg(not(target_arch = "wasm32"))] +#[test] +#[should_panic(expected = "the preflight worker ended before it sent a result")] +fn waiting_for_a_worker_that_ended_fails() { + let (mut app, _) = overset_app(); + drop(stalled_worker(&mut app)); + wait_for_worker(&mut app); +} From 68549972945974011ace631f428ea283a1f2f72e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:53:45 -0800 Subject: [PATCH 0978/1349] Render: a feathered object's bevel and inner effects fade with it A basic, directional or gradient feather faded only the object's body. Its bevel, inner glow, inner shadow and satin were drawn afterwards over the whole shape, so where the feather let the page show through, the bevel's highlight and the inner glow screened whatever lay behind the object. Text under the feathered edge of a beveled frame turned lighter until the frame was moved off it. Each inner effect is now faded by the same feathers before it blends with what is behind the object, so a feathered object fades to transparent at its edge with its effects. --- crates/render/src/fx.rs | 565 +++++++++++++++++++++++++--------------- 1 file changed, 349 insertions(+), 216 deletions(-) diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index 7c7c91fe1..f9b40ba9b 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -15,7 +15,8 @@ //! - Inner glow, bevel and emboss, satin: built like the inner shadow (an offset inverse of the //! shape, blurred and clipped) with screen / multiply blending; satin XORs two offset copies. //! - Feather: the object is masked by its shape inset by half the width and blurred, so the -//! edge fades from ~0 at the path to full strength `width` inside. +//! edge fades from ~0 at the path to full strength `width` inside. The basic, directional and +//! gradient feathers fade the inner effects with the object. use designcraft_doc::Item; use designcraft_geom::{Affine, BezPath, Rect, Shape, Vec2}; @@ -46,6 +47,17 @@ pub(crate) fn outset(it: &Item) -> f64 { o } +/// Whether `it` has a basic feather: a width on a closed shape. +fn basic_feather(it: &Item) -> bool { + it.effects.feather > 0.0 && it.path.is_closed() +} + +/// Whether any of `it`'s feathers (basic, directional, gradient) fades it. +fn fades(it: &Item) -> bool { + let e = &it.effects; + basic_feather(it) || e.directional_feather.on && e.directional_feather.widths.iter().any(|w| *w > 0.0) || e.gradient_feather.on +} + /// (blur σ, growth) in points for an effect `size` with `pct` percent hardened. fn split(size: f64, pct: f64) -> (f64, f64) { let size = bound(size).max(0.0); @@ -149,17 +161,245 @@ impl Renderer { ctx.pop_layer(); } } - // Gradient feather: the object (feathered or not) drawn in its own layer, then kept as - // much as the opacity gradient says. - let gf = &e.gradient_feather; - let directional = e.directional_feather.on && e.directional_feather.widths.iter().any(|w| *w > 0.0); - if gf.on || directional { + // The object, feathered or not, drawn in its own layer and faded there. A basic feather + // clips the body to the shape at device resolution; only its blurred mask may be drawn + // offscreen at a lower one. + let fading = fades(it); + let basic = basic_feather(it); + if fading { ctx.set_transform(Affine::IDENTITY); ctx.push_layer(None, None, None, None, None); } - // The object, feathered or not. Choke keeps that much of the width opaque (a shorter - // fade); Sharp and Rounded corners follow the inset shape more tightly than Diffused. - if e.feather > 0.0 && it.path.is_closed() { + if basic { + ctx.set_transform(f.view * xf); + ctx.push_clip_layer(bp); + } + self.draw_body(ctx, f, it, bp, xf, page); + if basic { + ctx.pop_layer(); + } + if fading { + self.fade(ctx, f, it, bp, xf, reach); + ctx.pop_layer(); + } + if !it.path.is_closed() { + return; + } + // The feathers fade the inner effects with the object: each one is faded in its own + // layer before it blends with what is behind. + let fade = fading.then_some(it); + // An image's edge is where it is opaque, not the frame: inner shadows, glows and bevels + // follow what is painted when the frame holds a graphic. + let painted = matches!(it.content, designcraft_doc::Content::Graphic(_)).then_some((it, page)); + // Inner shadow, clipped to the shape. + if e.inner_shadow.on + && let Some(c) = doc.resolve_color(&e.inner_shadow.color, 1.0) + { + let s = &e.inner_shadow; + let (sigma, choke) = split(s.size, s.choke); + let off = offset(doc.light_angle(s.angle, s.global_light), s.distance); + self.inner_edge( + ctx, + f, + reach, + bp, + xf, + off, + sigma, + choke, + color_of(&c, s.opacity.clamp(0.0, 1.0)), + crate::blend_mode(s.mode).mix, + painted, + fade, + ); + } + // Inner glow: from the edges inwards (or out from the centre), screened over the object. + if e.inner_glow.on + && let Some(c) = doc.resolve_color(&e.inner_glow.color, 1.0) + { + let g = &e.inner_glow; + let (sigma, choke) = split(g.size, g.choke); + // Precise keeps the glow close to the edge: a tighter blur. + let sigma = if g.technique == designcraft_doc::GlowTechnique::Precise { sigma * 0.4 } else { sigma }; + let mix = crate::blend_mode(g.mode).mix; + let paint = color_of(&c, g.opacity.clamp(0.0, 1.0)); + if g.center { + self.with_blended_filters(ctx, f, reach, sigma, mix, (bp, xf), fade, |_, c, fr| { + c.set_transform(fr.view); + c.push_layer(None, None, None, None, Some(blur(sigma))); + c.set_transform(fr.view * xf); + c.set_paint(paint); + c.fill_path(bp); + // Fade towards the edge: cut a band of the glow's size away. + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestOut)), None, None, None); + c.set_transform(fr.view * xf); + c.set_paint(peniko::Color::BLACK); + c.set_stroke(kurbo::Stroke::new((bound(g.size) - choke).max(0.5) * 2.0).with_join(kurbo::Join::Round)); + c.stroke_path(bp); + c.pop_layer(); + c.pop_layer(); + }); + } else { + self.inner_edge(ctx, f, reach, bp, xf, Vec2::ZERO, sigma, choke, paint, mix, painted, fade); + } + } + // Satin: the shape shifted both ways along the angle, blurred, where exactly one covers. + if e.satin.on + && let Some(c) = doc.resolve_color(&e.satin.color, 1.0) + { + let st = &e.satin; + let off = offset(st.angle, st.distance / 2.0); + let sigma = bound(st.size).max(0.0) / 2.0; + let paint = color_of(&c, st.opacity.clamp(0.0, 1.0)); + let invert = st.invert; + self.with_blended_filters(ctx, f, reach, sigma, Mix::Multiply, (bp, xf), fade, |_, c, fr| { + c.set_transform(fr.view); + c.push_layer(None, None, None, None, Some(blur(sigma))); + if invert { + c.set_transform(fr.view * xf); + c.set_paint(paint); + c.fill_path(bp); + } + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, if invert { Compose::DestOut } else { Compose::SrcOver })), None, None, None); + c.set_transform(fr.view * Affine::translate(off) * xf); + c.set_paint(paint); + c.fill_path(bp); + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::Xor)), None, None, None); + c.set_transform(fr.view * Affine::translate(-off) * xf); + c.fill_path(bp); + c.pop_layer(); + c.pop_layer(); + c.pop_layer(); + }); + } + // Bevel and Emboss (inner bevel): highlight from the lit side, shadow from the other. + if e.bevel.on { + let b = &e.bevel; + let off = offset(doc.light_angle(b.angle, b.global_light), bound(b.size) * (b.depth / 100.0).clamp(0.01, 10.0) * 0.5); + let sigma = bound(b.size).max(0.0) / 2.0; + if let Some(c) = doc.resolve_color(&b.highlight, 1.0) { + // The inverse shape moved away from the light lights the edges facing it. + let paint = color_of(&c, b.highlight_opacity.clamp(0.0, 1.0)); + self.inner_edge(ctx, f, reach, bp, xf, off, sigma, 0.0, paint, Mix::Screen, painted, fade); + } + if let Some(c) = doc.resolve_color(&b.shadow, 1.0) { + let paint = color_of(&c, b.shadow_opacity.clamp(0.0, 1.0)); + self.inner_edge(ctx, f, reach, bp, xf, -off, sigma, 0.0, paint, Mix::Multiply, painted, fade); + } + } + } + + /// An inner shadow-like edge: everything outside the shape moved by `off`, blurred by + /// `sigma`, clipped to the shape and blended with `mix`. With `painted` (an object and the + /// page it shows on), the shape is what the object paints, so a transparent part of an image + /// is outside it: the edge runs along the image's opaque pixels, not the frame. With `fade`, + /// the edge fades with that object's feathers. + #[allow(clippy::too_many_arguments)] + fn inner_edge( + &mut self, + ctx: &mut RenderContext, + f: &Frame, + reach: Rect, + bp: &BezPath, + xf: Affine, + off: Vec2, + sigma: f64, + choke: f64, + paint: peniko::Color, + mix: Mix, + painted: Option<(&Item, ShownOn)>, + fade: Option<&Item>, + ) { + let sigma = bound(sigma).max(0.0); + let choke = bound(choke); + if let Some((it, page)) = painted { + self.with_blended_filters(ctx, f, reach, sigma, mix, (bp, xf), fade, |me, c, fr| { + let pad = sigma * 4.0 + choke + off.hypot() + 4.0 * fr.px; + let area = reach.inflate(pad, pad); + // The colour everywhere but under the painted pixels moved by `off`, blurred, ... + c.set_transform(fr.view); + c.push_layer(None, None, None, None, None); + c.push_layer(None, None, None, None, Some(blur(sigma))); + c.set_paint(paint); + c.fill_rect(&area); + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestOut)), None, None, None); + let moved = Frame { view: fr.view * Affine::translate(off), ..*fr }; + me.draw_body(c, &moved, it, bp, xf, page); + c.pop_layer(); + c.pop_layer(); + // ... kept only where the object paints. + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestIn)), None, None, None); + me.draw_body(c, fr, it, bp, xf, page); + c.pop_layer(); + c.pop_layer(); + }); + return; + } + self.with_blended_filters(ctx, f, reach, sigma, mix, (bp, xf), fade, |_, c, fr| { + c.set_transform(fr.view); + c.push_layer(None, None, None, None, Some(blur(sigma))); + // Everything outside the offset shape, so the colour bleeds in from the edges. + let m = Affine::translate(off) * xf; + let pad = sigma * 4.0 + choke + off.hypot() + 4.0 * fr.px; + let mut inv = m.transform_rect_bbox(bp.bounding_box()).inflate(pad, pad).to_path(0.1); + let mut shape = bp.clone(); + shape.apply_affine(m); + inv.extend(shape.iter()); + c.set_paint(paint); + c.set_fill_rule(peniko::Fill::EvenOdd); + c.fill_path(&inv); + c.set_fill_rule(peniko::Fill::NonZero); + if choke > 0.0 { + c.set_stroke(kurbo::Stroke::new(choke * 2.0).with_join(kurbo::Join::Round)); + c.stroke_path(&shape); + } + c.pop_layer(); + }); + } + + /// [`Renderer::with_filters`] clipped to `clip` (a path and its spread transform), blended with + /// `mix`. The effect's blend must see the object's backdrop, outside its clipping and offscreen + /// filter layers. Putting it inside the clip blends with transparent pixels instead. With + /// `fade`, what `draw` paints is faded by that object's feathers before it blends. + #[allow(clippy::too_many_arguments)] + fn with_blended_filters( + &mut self, + ctx: &mut RenderContext, + f: &Frame, + reach: Rect, + sigma: f64, + mix: Mix, + clip: (&BezPath, Affine), + fade: Option<&Item>, + draw: impl FnOnce(&mut Self, &mut RenderContext, &Frame), + ) { + let layered = mix != Mix::Normal || fade.is_some(); + if layered { + ctx.set_transform(Affine::IDENTITY); + ctx.push_layer(None, Some(BlendMode::new(mix, Compose::SrcOver)), None, None, None); + } + self.with_filters(ctx, f, reach, sigma, Some(clip), draw); + if let Some(it) = fade { + self.fade(ctx, f, it, clip.0, clip.1, reach); + } + if layered { + ctx.pop_layer(); + } + } + + /// Fade what was drawn in the current layer by `it`'s feathers: the basic feather's blurred + /// inset shape, a ramp for each directional feather side and the gradient feather. `bp` and + /// `xf` are the object's shape and spread transform, `reach` (spread space) what it paints. + fn fade(&mut self, ctx: &mut RenderContext, f: &Frame, it: &Item, bp: &BezPath, xf: Affine, reach: Rect) { + let e = &it.effects; + // Choke keeps that much of the width opaque (a shorter fade); Sharp and Rounded corners + // follow the inset shape more tightly than Diffused. + if basic_feather(it) { let fo = &e.feather_options; let w = bound(e.feather) * (1.0 - fo.choke.clamp(0.0, 100.0) / 100.0).max(0.01); let (sigma, join) = match fo.corners { @@ -167,12 +407,7 @@ impl Renderer { designcraft_doc::FeatherCorners::Rounded => (w / 3.0, kurbo::Join::Round), designcraft_doc::FeatherCorners::Sharp => (w / 6.0, kurbo::Join::Miter), }; - // The body and its clip stay at device resolution; only the blurred mask may be drawn - // offscreen at a lower one. - ctx.set_transform(f.view * xf); - ctx.push_clip_layer(bp); - self.draw_body(ctx, f, it, bp, xf, page); - // Keep the body where the blurred inset silhouette is. + // Keep what was drawn where the blurred inset silhouette is. ctx.set_transform(Affine::IDENTITY); ctx.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestIn)), None, None, None); self.with_filters(ctx, f, reach, sigma, None, |_, c, fr| { @@ -190,9 +425,6 @@ impl Renderer { c.pop_layer(); }); ctx.pop_layer(); - ctx.pop_layer(); - } else { - self.draw_body(ctx, f, it, bp, xf, page); } // Directional feather: one fading ramp per side, multiplied in. let df = &e.directional_feather; @@ -222,206 +454,9 @@ impl Renderer { ctx.pop_layer(); } } - if gf.on { + if e.gradient_feather.on { gradient_feather_mask(ctx, f, it, xf); } - if gf.on || directional { - ctx.pop_layer(); - } - if !it.path.is_closed() { - return; - } - // An image's edge is where it is opaque, not the frame: inner shadows, glows and bevels - // follow what is painted when the frame holds a graphic. - let painted = matches!(it.content, designcraft_doc::Content::Graphic(_)).then_some((it, page)); - // Inner shadow, clipped to the shape. - if e.inner_shadow.on - && let Some(c) = doc.resolve_color(&e.inner_shadow.color, 1.0) - { - let s = &e.inner_shadow; - let (sigma, choke) = split(s.size, s.choke); - let off = offset(doc.light_angle(s.angle, s.global_light), s.distance); - self.inner_edge( - ctx, - f, - reach, - bp, - xf, - off, - sigma, - choke, - color_of(&c, s.opacity.clamp(0.0, 1.0)), - crate::blend_mode(s.mode).mix, - painted, - ); - } - // Inner glow: from the edges inwards (or out from the centre), screened over the object. - if e.inner_glow.on - && let Some(c) = doc.resolve_color(&e.inner_glow.color, 1.0) - { - let g = &e.inner_glow; - let (sigma, choke) = split(g.size, g.choke); - // Precise keeps the glow close to the edge: a tighter blur. - let sigma = if g.technique == designcraft_doc::GlowTechnique::Precise { sigma * 0.4 } else { sigma }; - let mix = crate::blend_mode(g.mode).mix; - let paint = color_of(&c, g.opacity.clamp(0.0, 1.0)); - if g.center { - self.with_blended_filters(ctx, f, reach, sigma, mix, (bp, xf), |_, c, fr| { - c.set_transform(fr.view); - c.push_layer(None, None, None, None, Some(blur(sigma))); - c.set_transform(fr.view * xf); - c.set_paint(paint); - c.fill_path(bp); - // Fade towards the edge: cut a band of the glow's size away. - c.set_transform(Affine::IDENTITY); - c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestOut)), None, None, None); - c.set_transform(fr.view * xf); - c.set_paint(peniko::Color::BLACK); - c.set_stroke(kurbo::Stroke::new((bound(g.size) - choke).max(0.5) * 2.0).with_join(kurbo::Join::Round)); - c.stroke_path(bp); - c.pop_layer(); - c.pop_layer(); - }); - } else { - self.inner_edge(ctx, f, reach, bp, xf, Vec2::ZERO, sigma, choke, paint, mix, painted); - } - } - // Satin: the shape shifted both ways along the angle, blurred, where exactly one covers. - if e.satin.on - && let Some(c) = doc.resolve_color(&e.satin.color, 1.0) - { - let st = &e.satin; - let off = offset(st.angle, st.distance / 2.0); - let sigma = bound(st.size).max(0.0) / 2.0; - let paint = color_of(&c, st.opacity.clamp(0.0, 1.0)); - let invert = st.invert; - self.with_blended_filters(ctx, f, reach, sigma, Mix::Multiply, (bp, xf), |_, c, fr| { - c.set_transform(fr.view); - c.push_layer(None, None, None, None, Some(blur(sigma))); - if invert { - c.set_transform(fr.view * xf); - c.set_paint(paint); - c.fill_path(bp); - } - c.set_transform(Affine::IDENTITY); - c.push_layer(None, Some(BlendMode::new(Mix::Normal, if invert { Compose::DestOut } else { Compose::SrcOver })), None, None, None); - c.set_transform(fr.view * Affine::translate(off) * xf); - c.set_paint(paint); - c.fill_path(bp); - c.set_transform(Affine::IDENTITY); - c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::Xor)), None, None, None); - c.set_transform(fr.view * Affine::translate(-off) * xf); - c.fill_path(bp); - c.pop_layer(); - c.pop_layer(); - c.pop_layer(); - }); - } - // Bevel and Emboss (inner bevel): highlight from the lit side, shadow from the other. - if e.bevel.on { - let b = &e.bevel; - let off = offset(doc.light_angle(b.angle, b.global_light), bound(b.size) * (b.depth / 100.0).clamp(0.01, 10.0) * 0.5); - let sigma = bound(b.size).max(0.0) / 2.0; - if let Some(c) = doc.resolve_color(&b.highlight, 1.0) { - // The inverse shape moved away from the light lights the edges facing it. - self.inner_edge(ctx, f, reach, bp, xf, off, sigma, 0.0, color_of(&c, b.highlight_opacity.clamp(0.0, 1.0)), Mix::Screen, painted); - } - if let Some(c) = doc.resolve_color(&b.shadow, 1.0) { - self.inner_edge(ctx, f, reach, bp, xf, -off, sigma, 0.0, color_of(&c, b.shadow_opacity.clamp(0.0, 1.0)), Mix::Multiply, painted); - } - } - } - - /// An inner shadow-like edge: everything outside the shape moved by `off`, blurred by - /// `sigma`, clipped to the shape and blended with `mix`. With `painted` (an object and the - /// page it shows on), the shape is what the object paints, so a transparent part of an image - /// is outside it: the edge runs along the image's opaque pixels, not the frame. - #[allow(clippy::too_many_arguments)] - fn inner_edge( - &mut self, - ctx: &mut RenderContext, - f: &Frame, - reach: Rect, - bp: &BezPath, - xf: Affine, - off: Vec2, - sigma: f64, - choke: f64, - paint: peniko::Color, - mix: Mix, - painted: Option<(&Item, ShownOn)>, - ) { - let sigma = bound(sigma).max(0.0); - let choke = bound(choke); - if let Some((it, page)) = painted { - self.with_blended_filters(ctx, f, reach, sigma, mix, (bp, xf), |me, c, fr| { - let pad = sigma * 4.0 + choke + off.hypot() + 4.0 * fr.px; - let area = reach.inflate(pad, pad); - // The colour everywhere but under the painted pixels moved by `off`, blurred, ... - c.set_transform(fr.view); - c.push_layer(None, None, None, None, None); - c.push_layer(None, None, None, None, Some(blur(sigma))); - c.set_paint(paint); - c.fill_rect(&area); - c.set_transform(Affine::IDENTITY); - c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestOut)), None, None, None); - let moved = Frame { view: fr.view * Affine::translate(off), ..*fr }; - me.draw_body(c, &moved, it, bp, xf, page); - c.pop_layer(); - c.pop_layer(); - // ... kept only where the object paints. - c.set_transform(Affine::IDENTITY); - c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestIn)), None, None, None); - me.draw_body(c, fr, it, bp, xf, page); - c.pop_layer(); - c.pop_layer(); - }); - return; - } - self.with_blended_filters(ctx, f, reach, sigma, mix, (bp, xf), |_, c, fr| { - c.set_transform(fr.view); - c.push_layer(None, None, None, None, Some(blur(sigma))); - // Everything outside the offset shape, so the colour bleeds in from the edges. - let m = Affine::translate(off) * xf; - let pad = sigma * 4.0 + choke + off.hypot() + 4.0 * fr.px; - let mut inv = m.transform_rect_bbox(bp.bounding_box()).inflate(pad, pad).to_path(0.1); - let mut shape = bp.clone(); - shape.apply_affine(m); - inv.extend(shape.iter()); - c.set_paint(paint); - c.set_fill_rule(peniko::Fill::EvenOdd); - c.fill_path(&inv); - c.set_fill_rule(peniko::Fill::NonZero); - if choke > 0.0 { - c.set_stroke(kurbo::Stroke::new(choke * 2.0).with_join(kurbo::Join::Round)); - c.stroke_path(&shape); - } - c.pop_layer(); - }); - } - - /// [`Renderer::with_filters`] clipped to `clip` (a path and its spread transform), blended with - /// `mix`. The effect's blend must see the object's backdrop, outside its clipping and offscreen - /// filter layers. Putting it inside the clip blends with transparent pixels instead. - #[allow(clippy::too_many_arguments)] - fn with_blended_filters( - &mut self, - ctx: &mut RenderContext, - f: &Frame, - reach: Rect, - sigma: f64, - mix: Mix, - clip: (&BezPath, Affine), - draw: impl FnOnce(&mut Self, &mut RenderContext, &Frame), - ) { - if mix != Mix::Normal { - ctx.set_transform(Affine::IDENTITY); - ctx.push_layer(None, Some(BlendMode::new(mix, Compose::SrcOver)), None, None, None); - } - self.with_filters(ctx, f, reach, sigma, Some(clip), draw); - if mix != Mix::Normal { - ctx.pop_layer(); - } } /// Run `draw`, which pushes filter layers. Single-threaded contexts draw directly. On a @@ -607,4 +642,102 @@ mod tests { // The transparent half shows the page: no shadow painted there. assert!(lum(150) > 700, "nothing over the transparent part: {}", lum(150)); } + + /// A feathered object fades to transparent at its edge, its bevel and inner glow included: where + /// the feather shows what is behind the object, the highlight and shadow leave it as it is. + #[test] + fn feathers_fade_the_inner_effects_with_the_object() { + use designcraft_doc::build::NewDocument; + use designcraft_doc::{Document, Fill, SpreadRef}; + let doc = |image: bool, feather: u8, inner: u8| { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let mut back = Item::new( + designcraft_doc::ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(50.0, 50.0, 350.0, 350.0)), + ); + back.fill = Fill::swatch("C=0 M=100 Y=0 K=0"); + d.insert_item(SpreadRef::Doc(0), back, None).unwrap(); + let mut it = Item::new( + designcraft_doc::ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 300.0, 300.0)), + ); + if image { + let img = image::RgbaImage::from_pixel(20, 20, image::Rgba([40, 160, 90, 255])); + let mut png = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let aid = designcraft_doc::AssetId(d.alloc()); + d.assets.insert( + aid, + std::sync::Arc::new(designcraft_doc::Asset { + id: aid, + name: "green.png".into(), + mime: "image/png".into(), + data: std::sync::Arc::new(png), + pixels: Some((20, 20)), + ..Default::default() + }), + ); + it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic { + layer_options: None, + asset: aid, + size: (200.0, 200.0), + xf: Affine::translate((100.0, 100.0)), + clip: None, + auto_fit: Default::default(), + fit_align: 4, + crop: [0.0; 4], + wrap: Default::default(), + fill: Default::default(), + }); + } else { + it.fill = Fill::swatch("C=100 M=0 Y=0 K=0"); + } + let e = &mut it.effects; + match feather { + 0 => e.feather = 30.0, + 1 => (e.directional_feather.on, e.directional_feather.widths) = (true, [30.0; 4]), + _ => e.gradient_feather.on = true, + } + match inner { + 0 => {} + 1 => (e.bevel.on, e.bevel.size) = (true, 12.0), + _ => (e.inner_glow.on, e.inner_glow.color, e.inner_glow.opacity, e.inner_glow.size) = (true, "[Paper]".into(), 1.0, 20.0), + } + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + d + }; + let px = |d: &Document, threads: u16, x: u32| { + let mut r = Renderer::new(); + r.threads = threads; + r.render_page(d, &crate::Cache::new(), 0, 1.0, false, &crate::RenderOptions::default()).unwrap().pixel(x, 200) + }; + let diff = |a: [u8; 4], b: [u8; 4]| a.iter().zip(b).map(|(p, q)| u32::from(p.abs_diff(q))).sum::(); + for image in [false, true] { + for feather in 0..3 { + for threads in [0, 4] { + let plain = doc(image, feather, 0); + // The object's faded edges: the left and right ones for the basic and directional + // feathers, the right one for the gradient feather (opaque on the left). + let edges: &[u32] = if feather == 2 { &[299] } else { &[100, 299] }; + for &x in edges { + let behind = px(&plain, threads, 70); + let faded = px(&plain, threads, x); + assert!(diff(faded, behind) < 40, "image {image} feather {feather}: the edge at {x} shows what is behind"); + for inner in [1, 2] { + let with = px(&doc(image, feather, inner), threads, x); + assert!( + diff(with, faded) < 30, + "image {image} feather {feather} inner {inner} threads {threads}: {with:?} over the faded edge at {x}, {faded:?} without" + ); + } + } + } + } + } + } } From eda934fff0e4c0df47bd18e92499cc4dfdecbbe0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:54:27 -0800 Subject: [PATCH 0979/1349] Compose: vertical justification keeps moved lines inside a shaped frame Center, Bottom and Justify moved the lines of a shaped frame without testing them against the outline, so in a frame that narrows towards the bottom a line set in a wide band ended up crossing the outline. Each moved line's slot is now tested against the outline over its new band, as when the line was fitted, and the text goes only as far down as every slot fits. In a frame that narrows and widens again, the search scans the rooms from the most down (every point, at most 512 steps) before halving, so the text can still reach a lower part past a narrow waist. --- crates/compose/src/lib.rs | 39 +++++++++++++++++++--- crates/compose/src/tests.rs | 65 +++++++++++++++++++++++++++++++++++-- 2 files changed, 96 insertions(+), 8 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 72c0f69cb..0188ee1cf 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -5514,7 +5514,8 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de // frames as in rectangular ones. Above footnotes, and in vertical frames, the descenders // stay inside the text area, as when the lines are fitted. // `space`: the room under the bottom of the text. - let space = if f.vertical || note_top <= f.area.y1 { limit - ink_bottom } else { limit - last_baseline }; + let inside = f.vertical || note_top <= f.area.y1; + let space = if inside { limit - ink_bottom } else { limit - last_baseline }; if space <= 0.0 { continue; } @@ -5560,14 +5561,42 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de }; // Only the last row's descenders hang below the bottom of the text: an earlier line whose // ink reaches below the last baseline (tight leading) isn't moved past the text area. - let fits = |shift: &[f64]| { - idx.iter().zip(&rows).all(|(&i, &k)| k == n || shift[k] <= 0.0 || ft.lines[i].baseline + ft.lines[i].descent + shift[k] <= limit + 1e-9) + // In a shaped frame each moved line's slot stays inside the outline over its new band, as + // when the line was fitted: a frame that narrows towards the bottom holds the text higher. + let in_outline = |l: &Line, last: bool, dy: f64| match &f.outline { + Some(o) => { + let b = l.baseline + dy; + let desc = if last && !inside { 0.0 } else { l.descent.max(0.0) }; + let tol = 1e-6; + o.intervals(l.x0, l.x1, (b - l.ascent).max(f.area.y0).min(b), b + desc).iter().any(|&(a, z)| a <= l.x0 + tol && z >= l.x1 - tol) + } + None => true, }; - // Every row moves no less as `space` grows, so the most room that fits is found by halving. + // The lowest lines are tested first: they are the ones a narrowing outline stops. + let fits = |shift: &[f64]| { + idx.iter().zip(&rows).rev().all(|(&i, &k)| { + let l = &ft.lines[i]; + shift[k] <= 0.0 || ((k == n || l.baseline + l.descent + shift[k] <= limit + 1e-9) && in_outline(l, k == n, shift[k])) + }) + }; + // Every row moves no less as `space` grows, so in a rectangular frame the most room that + // fits is found by halving. A shaped frame can narrow and widen again further down: there + // the rooms are scanned from the most down to none, every point (at most 512 steps, each + // usually stopped by the lowest line), and the step between the first that fits and the + // one above it is then halved. let mut shift = shifts(space); if !fits(&shift) { + let steps = if f.outline.is_some() { space.ceil().clamp(64.0, 512.0) as usize } else { 1 }; let (mut lo, mut hi) = (0.0, space); - for _ in 0..60 { + for j in 1..steps { + let s = space * (steps - j) as f64 / steps as f64; + if fits(&shifts(s)) { + lo = s; + break; + } + hi = s; + } + for _ in 0..50 { let mid = (lo + hi) / 2.0; if fits(&shifts(mid)) { lo = mid; diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index b94d94000..77eb0a076 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -2429,8 +2429,9 @@ fn a_corner_radius_keeps_a_cap_height_line_in_place() { } // A corner radius doesn't change where Bottom and Justify put the last baseline: on the - // bottom inset, as in a rectangular frame, with the descenders in the inset. - for insets in [[6.0; 4], [0.0, 0.0, 12.0, 0.0]] { + // bottom inset, as in a rectangular frame, with the descenders in the inset. Each radius is + // smaller than the inset, so the rounded corner stays clear of the text area. + for (insets, big) in [([6.0; 4], 4.0), ([0.0, 0.0, 12.0, 0.0], 6.0)] { for mode in [Bottom, Justify] { let compose_frame = |radius: f64| { let (mut d, sid, fid) = doc_with("Typography\ngypsy", Rect::new(0.0, 0.0, 200.0, 100.0), ParaAttrs::default()); @@ -2444,7 +2445,7 @@ fn a_corner_radius_keeps_a_cap_height_line_in_place() { (area, all_lines(&cs).iter().map(|l| l.baseline).collect::>()) }; let (area, square) = compose_frame(0.0); - for radius in [0.1 * mm, 6.0] { + for radius in [0.1 * mm, big] { let (_, rounded) = compose_frame(radius); assert_eq!(rounded.len(), square.len()); for (r, s) in rounded.iter().zip(&square) { @@ -2457,6 +2458,64 @@ fn a_corner_radius_keeps_a_cap_height_line_in_place() { } } +/// In a shaped frame, Center, Bottom and Justify keep each moved line's slot inside the outline: +/// a triangle that narrows downward holds the lines where their slots still fit, and one that +/// widens downward lets Bottom put the last baseline on the frame's bottom. +#[test] +fn vertical_justification_keeps_lines_inside_a_shaped_frame() { + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify}; + use designcraft_geom::{Anchor, PathData, Point, SubPath}; + let r = Rect::new(0.0, 0.0, 300.0, 300.0); + let compose_with = |tri: [Point; 3], mode: VerticalJustification| { + let (mut d, sid, fid) = doc_with("Typography\ngypsy", r, ParaAttrs::default()); + let it = d.item_mut(fid).unwrap(); + it.path = PathData::single(SubPath { anchors: tri.iter().map(|&p| Anchor::corner(p)).collect(), closed: true }); + let o = &mut it.text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.inset = [0.0; 4]; + let spec = frame_specs(&d, sid).remove(0); + assert!(spec.outline.is_some()); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines: Vec = all_lines(&cs).into_iter().cloned().collect(); + assert!(lines.len() >= 2, "{mode:?}: {lines:?}"); + (spec.area, lines) + }; + // Narrowing downward: |x - 150| <= (300 - y) / 2 over each slot's band, the last line's + // descenders left out. + let down = [Point::new(0.0, 0.0), Point::new(300.0, 0.0), Point::new(150.0, 300.0)]; + for mode in [Center, Bottom, Justify] { + let (area, lines) = compose_with(down, mode); + for (k, l) in lines.iter().enumerate() { + let bottom = if k + 1 == lines.len() { l.baseline } else { l.baseline + l.descent }; + let top = (l.baseline - l.ascent).max(area.y0); + for (x, y) in [(l.x0, top), (l.x1, top), (l.x0, bottom), (l.x1, bottom)] { + assert!((x - 150.0).abs() <= (300.0 - y) / 2.0 + 1e-3, "{mode:?}: line {k} corner ({x}, {y}) outside the triangle: {lines:?}"); + } + } + } + // Widening downward: moving down keeps every slot inside, so Bottom goes all the way. + let up = [Point::new(150.0, 0.0), Point::new(300.0, 300.0), Point::new(0.0, 300.0)]; + let (area, lines) = compose_with(up, Bottom); + let last = lines[lines.len() - 1].baseline; + assert!((last - area.y1).abs() < 1e-6, "Bottom: last baseline at {last}, frame bottom at {}: {lines:?}", area.y1); + + // Narrowing at a waist, full width again from 200 to 260 pt, then a point: Bottom sets the + // lines in the lower full-width part, past the waist. + let pts = [(0.0, 0.0), (300.0, 0.0), (300.0, 100.0), (200.0, 150.0), (300.0, 200.0), (300.0, 260.0), (150.0, 300.0)]; + let pts: Vec<(f64, f64)> = pts.iter().copied().chain([(0.0, 260.0), (0.0, 200.0), (100.0, 150.0), (0.0, 100.0)]).collect(); + let (mut d, sid, fid) = doc_with("Typography\ngypsy", r, ParaAttrs::default()); + let it = d.item_mut(fid).unwrap(); + it.path = PathData::single(SubPath { anchors: pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), closed: true }); + let o = &mut it.text_frame_mut().unwrap().options; + o.vertical_justification = Bottom; + o.inset = [0.0; 4]; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + let (first, last) = (lines[0], lines[lines.len() - 1]); + assert!(first.baseline - first.ascent >= 200.0 - 1e-6, "Bottom: first line top at {}", first.baseline - first.ascent); + assert!((last.baseline - 260.0).abs() < 1e-3, "Bottom: last baseline at {}", last.baseline); +} + #[test] fn table_rows_clear_footnotes_and_continue_in_the_next_column() { for span in [false, true] { From ffcd4e215fcc5c26485c536b33ded3539ab171b6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:55:29 -0800 Subject: [PATCH 0980/1349] Object styles: a rename that is not a name is refused --- crates/engine/src/cmd/style/object.rs | 3 ++ crates/engine/src/tests.rs | 59 ++++++++++++++++----------- 2 files changed, 38 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/style/object.rs b/crates/engine/src/cmd/style/object.rs index b22388372..a8572a3fa 100644 --- a/crates/engine/src/cmd/style/object.rs +++ b/crates/engine/src/cmd/style/object.rs @@ -367,6 +367,9 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { if let Some(tf) = text_frame_param(CMD, p, old.text_frame.as_ref())? { new.text_frame = tf; } + if p.get("rename").is_some_and(|r| !r.is_string()) { + return Err(bad(CMD, "`rename` must be a style name")); + } let rename = str_param(p, "rename").map(str::trim).filter(|r| *r != name).map(str::to_string); if let Some(r) = &rename { let builtin = name.starts_with('[') && name.ends_with(']'); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 5a8fc30e6..8ffd9fc1e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -752,6 +752,41 @@ fn object_style_effects_follow_the_style_until_overridden() { assert_eq!(s.doc().unwrap().revision, rev); } +/// `style.object.create` and `edit` refuse an unknown swatch, a misspelled setting, a word or null +/// for a switch, a rename that isn't a name and a corner size outside 0–10000 pt. +#[test] +fn object_style_parameters_are_checked() { + let mut s = session(); + s.execute("style.object.create", &json!({"name": "Framed", "fromSelection": false})).unwrap(); + for bad in [ + json!({"fill": "Nope"}), + json!({"fill": {"swatch": "Nope"}}), + json!({"stroke": {"swatch": "Nope"}}), + json!({"stroke": {"wieght": 5}}), + json!({"fill": {"tnt": 0.5}}), + json!({"corners": {"shpae": "rounded"}}), + json!({"corners": {"size": -1}}), + json!({"corners": {"size": 10_001}}), + json!({"applyNextStyle": null}), + ] { + let mut p = bad.clone(); + p["name"] = json!("Framed"); + assert!(s.execute("style.object.edit", &p).is_err(), "{bad}"); + p["name"] = json!("Other"); + assert!(s.execute("style.object.create", &p).is_err(), "{bad}"); + } + let c = json!({"shape": "rounded", "size": -1}); + assert!(s.execute("style.object.create", &json!({"name": "Odd", "corners": {"corners": [c, c, c, c]}})).is_err()); + for from in [json!("yes"), json!(null)] { + assert!(s.execute("style.object.create", &json!({"name": "Other", "fromSelection": from})).is_err(), "{from}"); + } + for rename in [json!(3), json!(null), json!(true)] { + assert!(s.execute("style.object.edit", &json!({"name": "Framed", "rename": rename})).is_err(), "{rename}"); + } + let names: Vec<_> = s.doc().unwrap().doc.styles.object.iter().map(|o| o.name.clone()).collect(); + assert!(!names.iter().any(|n| n == "Other" || n == "Odd"), "{names:?}"); +} + /// The course's "Rounded Corner Image, White Stroke" style: made from a frame with rounded corners /// and a paper stroke, applied to another frame, then edited (a thicker stroke, bigger corners): /// the frames that follow the style change, one with its own stroke keeps it; a rename follows. @@ -792,30 +827,6 @@ fn object_styles_carry_corners_and_their_stroke_and_corners_can_be_edited() { assert!(s.execute("style.object.edit", &json!({"name": "Framed", "rename": "[Basic Text Frame]"})).is_err()); assert!(s.execute("style.object.edit", &json!({"name": "[Basic Graphics Frame]", "rename": "Mine"})).is_err()); assert!(s.execute("style.object.edit", &json!({"name": "Framed", "corners": {"size": "big"}})).is_err()); - // An unknown swatch, a misspelled setting and a word for a switch are refused. - for bad in [ - json!({"fill": "Nope"}), - json!({"fill": {"swatch": "Nope"}}), - json!({"stroke": {"swatch": "Nope"}}), - json!({"stroke": {"wieght": 5}}), - json!({"fill": {"tnt": 0.5}}), - json!({"corners": {"shpae": "rounded"}}), - ] { - let mut p = bad.clone(); - p["name"] = json!("Framed"); - assert!(s.execute("style.object.edit", &p).is_err(), "{bad}"); - p["name"] = json!("Other"); - assert!(s.execute("style.object.create", &p).is_err(), "{bad}"); - } - assert!(s.execute("style.object.create", &json!({"name": "Other", "fromSelection": "yes"})).is_err()); - assert!(s.execute("style.object.create", &json!({"name": "Other", "fromSelection": null})).is_err()); - assert!(s.execute("style.object.edit", &json!({"name": "Framed", "applyNextStyle": null})).is_err()); - // A size outside 0–10000 pt is refused, not changed. - for size in [-1.0, 10_001.0] { - assert!(s.execute("style.object.edit", &json!({"name": "Framed", "corners": {"size": size}})).is_err(), "{size}"); - let c = json!({"shape": "rounded", "size": size}); - assert!(s.execute("style.object.create", &json!({"name": "Odd", "corners": {"corners": [c, c, c, c]}})).is_err(), "{size}"); - } // A negative stroke weight is refused when creating a style as when editing one. let styles = s.doc().unwrap().doc.styles.object.len(); for cmd in ["style.object.create", "style.object.edit"] { From 8463cef4a9c5837dd07fe1073941112cac6434f8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:59:10 -0800 Subject: [PATCH 0981/1349] Paste: refuse damaged clipboard images and journal one entry per paste - edit.pasteImage decodes the whole raster before it stores the image, so a file whose pixels are cut off after a whole header is refused. - edit.pasteImage is the only journal entry for a paste; the file.place it runs no longer adds a second one, so a replay places the image once. - Empty clipboard text beside an image counts as no text, so Edit > Paste pastes the image. - With a native menu, a pasted image event is ignored while the clipboard still holds what it held when objects were copied here. --- crates/engine/src/cmd/paste_image.rs | 52 ++++++++++++++++++++++++++-- crates/ui-egui/src/app/clipboard.rs | 27 ++++++++++----- crates/ui-egui/src/canvas/tests.rs | 28 +++++++++++++++ 3 files changed, 97 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/paste_image.rs b/crates/engine/src/cmd/paste_image.rs index d5197a90c..b5e1003ac 100644 --- a/crates/engine/src/cmd/paste_image.rs +++ b/crates/engine/src/cmd/paste_image.rs @@ -96,6 +96,11 @@ fn paste_image(s: &mut Session, p: &Value) -> Result { let bytes = super::base64_decode(b64); let (pw, ph) = raster_size(&bytes).ok_or_else(|| bad(ID, "the clipboard doesn't hold an image DesignCraft can read"))?; check_pasted_size(pw, ph).map_err(|e| bad(ID, e))?; + // The header can be whole while the pixels after it are cut off: decode the whole raster so + // a damaged image is refused instead of stored. + if designcraft_images::decode_rgba(&bytes).is_none() { + return Err(bad(ID, "the image on the clipboard is damaged and can't be read")); + } let sr = spread_param(p, ID)?; let at = match p.get("at") { None | Some(Value::Null) => None, @@ -116,7 +121,7 @@ fn paste_image(s: &mut Session, p: &Value) -> Result { _ => None, }; if let Some(frame) = empty_frame { - return s.execute("file.place", &json!({"base64": b64, "name": name, "frame": frame})); + return place(s, &json!({"base64": b64, "name": name, "frame": frame})); } let d = &s.doc()?.doc; let sp = d.spread(sr).ok_or_else(|| bad(ID, "no such spread"))?; @@ -130,7 +135,16 @@ fn paste_image(s: &mut Session, p: &Value) -> Result { let w = nw.min(d.settings.page_width * 0.6); let h = nh * w / nw; let spread = p.get("spread").cloned().unwrap_or(Value::Null); - s.execute("file.place", &json!({"base64": b64, "name": name, "spread": spread, "x": center.x - w / 2.0, "y": center.y - h / 2.0})) + place(s, &json!({"base64": b64, "name": name, "spread": spread, "x": center.x - w / 2.0, "y": center.y - h / 2.0})) +} + +/// Runs `file.place` inside this command. Only `edit.pasteImage` stays in the journal, so a +/// replay of the journal places the image once. +fn place(s: &mut Session, params: &Value) -> Result { + let journal = s.journal.len(); + let r = s.execute("file.place", params); + s.journal.truncate(journal); + r } #[cfg(test)] @@ -239,6 +253,40 @@ mod tests { assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed"); } + #[test] + fn a_damaged_image_with_a_whole_header_is_refused() { + let mut s = doc(); + let whole = png(40, 30); + let cut = &whole[..whole.len() / 2]; + assert_eq!(raster_size(cut), Some((40, 30)), "the header still reads"); + let (undo, assets) = (s.doc().unwrap().history.undo.len(), s.doc().unwrap().doc.assets.len()); + let e = s.execute(ID, &json!({"base64": base64_encode(cut)})).unwrap_err().to_string(); + assert!(e.contains("damaged"), "{e}"); + let st = s.doc().unwrap(); + assert_eq!((st.history.undo.len(), st.doc.assets.len()), (undo, assets), "nothing stored"); + } + + #[test] + fn each_paste_is_one_journal_entry_and_replays_once() { + let mut s = doc(); + let frame = s.execute("frame.create", &json!({"rect": [100, 100, 200, 300]})).unwrap()["id"].as_u64().unwrap(); + s.execute("selection.set", &json!({"ids": [frame]})).unwrap(); + let start = s.journal.len(); + let b64 = base64_encode(&png(10, 10)); + s.execute(ID, &json!({"base64": b64, "at": [500, 500]})).unwrap(); + s.execute(ID, &json!({"base64": b64, "at": [500, 500]})).unwrap(); + let entries = s.journal[start..].to_vec(); + assert_eq!(entries.iter().map(|(id, _)| id.as_str()).collect::>(), [ID, ID], "the frame and the new-frame paths"); + let items = |s: &Session| s.doc().unwrap().doc.spreads[0].items.len(); + let mut t = doc(); + t.execute("frame.create", &json!({"rect": [100, 100, 200, 300]})).unwrap(); + t.execute("selection.set", &json!({"ids": [frame]})).unwrap(); + for (id, p) in &entries { + t.execute(id, p).unwrap(); + } + assert_eq!(items(&t), items(&s), "the replay places each image once"); + } + #[test] fn images_beyond_the_pixel_limit_are_refused_before_they_are_encoded() { let e = pasted_png(9000, 8000, Vec::new()).unwrap_err(); diff --git a/crates/ui-egui/src/app/clipboard.rs b/crates/ui-egui/src/app/clipboard.rs index bff5156f7..faddd6f5b 100644 --- a/crates/ui-egui/src/app/clipboard.rs +++ b/crates/ui-egui/src/app/clipboard.rs @@ -31,18 +31,14 @@ impl DesignApp { if !matches!(id, "edit.paste" | "edit.pasteWithoutFormatting") || !(typing || id == "edit.paste") { return Pasted::Params(params); } + // Empty text counts as no text, so an image beside it still pastes. if params.get("text").is_none() - && let Some(text) = self.services.clipboard_text.as_mut().and_then(|f| f()) + && let Some(text) = self.services.clipboard_text.as_mut().and_then(|f| f()).filter(|t| !t.is_empty()) && let Some(o) = params.as_object_mut() { o.insert("text".into(), Value::String(text)); } - // Nothing was copied to the clipboard since objects were copied here (native menu, where - // the system raises a change count with every copy). - let unchanged = match self.object_clip_change { - Some(at_copy) => self.services.clipboard_change.as_mut().and_then(|f| f()) == Some(at_copy), - None => true, - }; + let unchanged = self.clipboard_unchanged_since_object_copy(); // Still what an object copy put there: paste those objects, not the placeholder text. let norm = |t: &str| t.replace("\r\n", "\n"); let ours = unchanged @@ -76,9 +72,24 @@ impl DesignApp { Pasted::Params(params) } + /// Nothing was copied to the clipboard since objects were copied here (native menu, where + /// the system raises a change count with every copy). + fn clipboard_unchanged_since_object_copy(&mut self) -> bool { + match self.object_clip_change { + Some(at_copy) => self.services.clipboard_change.as_mut().and_then(|f| f()) == Some(at_copy), + None => true, + } + } + /// Paste an image from the system clipboard as a placed image (`edit.pasteImage`), centered - /// in the view or in the selected empty frame. Text being edited takes no image. + /// in the view or in the selected empty frame. Text being edited takes no image. An image the + /// clipboard held before objects were copied here (native menu) is not pasted: the menu's + /// Paste pastes those objects. pub(crate) fn paste_clipboard_image(&mut self, image: ClipboardImage) -> Result { + let user = !self.in_control && !self.control_input_frame.load(std::sync::atomic::Ordering::Relaxed); + if user && self.session.clipboard.is_some() && self.object_clip_change.is_some() && self.clipboard_unchanged_since_object_copy() { + return Ok(Value::Null); + } let typing = self.session.active().is_some_and(|d| d.selection.text.is_some()); let file = if typing { Err("To paste the image, stop editing the text first (Esc).".to_string()) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 0937904d9..5b3f796dc 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1108,6 +1108,10 @@ fn edit_paste_from_the_menu_places_the_clipboard_image() { copy_elsewhere(&clip, Some("https://example.com/cat.png"), Some((8, 6))); crate::menus::activate(&mut app, "edit.paste", &Value::Null); assert_eq!(pasted_image(&app).map(|(px, _)| px), Some((8, 6))); + // Empty text beside the image counts as no text. + copy_elsewhere(&clip, Some(""), Some((12, 9))); + crate::menus::activate(&mut app, "edit.paste", &Value::Null); + assert_eq!(pasted_image(&app).map(|(px, _)| px), Some((12, 9))); // Other text wins over a picture of it. copy_elsewhere(&clip, Some("Some words"), Some((8, 6))); crate::menus::activate(&mut app, "edit.paste", &Value::Null); @@ -1150,6 +1154,30 @@ fn objects_copied_here_still_paste_as_objects_until_another_image_is_copied() { assert_eq!(pasted_image(&app).map(|(px, _)| px), Some((5, 5)), "the image copied again with the same address"); } +#[test] +fn a_paste_image_event_after_an_object_copy_does_not_paste_the_older_image() { + // A native menu: Copy leaves the older image on the system clipboard. + let (clip, services) = fake_clipboard(None, Some((40, 30))); + let mut app = DesignApp::new(designcraft_engine::Session::new(), services); + app.native_menu = true; + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [100, 100, 200, 200], "content": "text"})).unwrap()["id"].clone(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + crate::menus::activate(&mut app, "edit.copy", &Value::Null); + app.run("selection.set", json!({"ids": []})).unwrap(); + let mut h = harness(app); + let image = |w, h| egui::Event::PasteImage(std::sync::Arc::new(egui::ColorImage::filled([w, h], egui::Color32::RED))); + let items = h.state().session.doc().unwrap().doc.spreads[0].items.len(); + h.input_mut().events.push(image(40, 30)); + h.run_steps(2); + assert_eq!(h.state().session.doc().unwrap().doc.spreads[0].items.len(), items, "the older image is not pasted"); + // An image copied since then pastes. + copy_elsewhere(&clip, None, Some((20, 10))); + h.input_mut().events.push(image(20, 10)); + h.run_steps(2); + assert_eq!(pasted_image(h.state()).map(|(px, _)| px), Some((20, 10))); +} + #[test] fn the_paste_keys_place_an_image_in_the_selected_empty_frame_but_not_in_text() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); From ad828bd6503f92992f4751b50e2960153bc191b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 22:00:14 -0800 Subject: [PATCH 0982/1349] Text wrap: an opaque image's Alpha Channel contour is its rectangle Before, an image with no transparency wrapped like its frame, so a smaller image or one moved within its frame kept text out of the frame's empty part. --- crates/engine/src/cmd/alpha_wrap.rs | 61 +++++++++++++++-------------- 1 file changed, 32 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs index 585f29350..6ca0e78f9 100644 --- a/crates/engine/src/cmd/alpha_wrap.rs +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -52,7 +52,7 @@ pub(crate) fn sync(doc: &mut Document) { continue; } let Some(a) = doc.assets.get(&asset).filter(|a| a.is_raster()) else { continue }; - // An image with no outline (opaque, unreadable, too large) is remembered as an empty + // An image with no outline (unreadable, too large) is remembered as an empty // one, so later edits don't decode it again; the contour is then the frame's. let o = trace(&a.data, asset, threshold).unwrap_or_else(|| no_outline(&a.data, asset, threshold)); doc.alpha_outlines.push(Arc::new(o)); @@ -74,8 +74,8 @@ fn no_outline(data: &Arc>, asset: AssetId, threshold: u8) -> AlphaOutlin } } -/// The outline of the pixels of `data` more opaque than `threshold`. None for an image that -/// can't be read, is too large, or has no transparency (its contour is its rectangle). +/// The outline of the pixels of `data` more opaque than `threshold`: an image with no +/// transparency gives its rectangle. None for an image that can't be read or is too large. pub(crate) fn trace(data: &Arc>, asset: AssetId, threshold: u8) -> Option { let (w, h) = designcraft_images::pixel_size(data)?; if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PIXELS { @@ -92,13 +92,7 @@ pub(crate) fn trace(data: &Arc>, asset: AssetId, threshold: u8) -> Optio let (cols, rows) = (w.min(grid), h.min(grid)); let mask = match finer.as_ref().and_then(|(m, fc, fr)| coarsen(m, *fc, *fr, cols, rows)) { Some(m) => m, - None => { - let (mask, transparent) = occupancy(img.as_raw(), w, h, cols, rows, threshold); - if !transparent { - return None; - } - mask - } + None => occupancy(img.as_raw(), w, h, cols, rows, threshold), }; // Composition follows an outline of at most MAX_CONTOUR_POINTS path elements (holes // included, for Include Inside Edges): a ring of k points is k + 1 elements with its close. @@ -152,11 +146,9 @@ fn coarsen(mask: &[bool], fc: u32, fr: u32, cols: u32, rows: u32) -> Option (Vec, bool) { +/// opaque than `threshold` (a cell is visible when any of its pixels is). +fn occupancy(rgba: &[u8], w: u32, h: u32, cols: u32, rows: u32, threshold: u8) -> Vec { let mut mask = vec![false; (cols as usize) * (rows as usize)]; - let mut transparent = false; // A pixel's cell is (x * cols / w, y * rows / h). Along a row the column is counted up as x // passes each cell's edge (cols <= w, so at most one edge per pixel) instead of divided out. for (y, row) in rgba.chunks_exact(w as usize * 4).take(h as usize).enumerate() { @@ -168,16 +160,14 @@ fn occupancy(rgba: &[u8], w: u32, h: u32, cols: u32, rows: u32, threshold: u8) - edge += u64::from(w); } acc += u64::from(cols); - let alpha = px[3]; - transparent |= alpha < 255; - if alpha > threshold + if px[3] > threshold && let Some(c) = mask.get_mut(base + gx) { *c = true; } } } - (mask, transparent) + mask } /// The closed boundaries of the visible cells, split into outer boundaries and the boundaries of @@ -305,8 +295,10 @@ mod tests { let (a, b) = (o.outer.bounds().unwrap(), o.holes.bounds().unwrap()); assert_eq!((a.x0, a.y0, a.x1, a.y1), (8.0, 8.0, 56.0, 56.0)); assert_eq!((b.x0, b.y0, b.x1, b.y1), (24.0, 24.0, 40.0, 40.0)); - // An opaque image has no alpha outline. - assert!(trace(&Arc::new(png(|_, _| true)), AssetId(1), 25).is_none()); + // An opaque image's outline is its rectangle. + let o = trace(&Arc::new(png(|_, _| true)), AssetId(1), 25).unwrap(); + let a = o.outer.bounds().unwrap(); + assert_eq!((a.x0, a.y0, a.x1, a.y1, o.holes.subpaths.len()), (0.0, 0.0, 64.0, 64.0, 0)); } /// The cell masks match a pixel-by-pixel count (cell = x * cols / w, y * rows / h), and a @@ -331,13 +323,13 @@ mod tests { } } } - assert_eq!(occupancy(&rgba, w, h, cols, rows, 25), (expect, true), "{cols} x {rows}"); + assert_eq!(occupancy(&rgba, w, h, cols, rows, 25), expect, "{cols} x {rows}"); } - let (fine, _) = occupancy(&rgba, w, h, 256, 256, 25); - assert_eq!(coarsen(&fine, 256, 256, 128, 128), Some(occupancy(&rgba, w, h, 128, 128, 25).0)); + let fine = occupancy(&rgba, w, h, 256, 256, 25); + assert_eq!(coarsen(&fine, 256, 256, 128, 128), Some(occupancy(&rgba, w, h, 128, 128, 25))); // Same count on one side, twice on the other. - let (fine, _) = occupancy(&rgba, w, h, 128, 256, 25); - assert_eq!(coarsen(&fine, 128, 256, 128, 128), Some(occupancy(&rgba, w, h, 128, 128, 25).0)); + let fine = occupancy(&rgba, w, h, 128, 256, 25); + assert_eq!(coarsen(&fine, 128, 256, 128, 128), Some(occupancy(&rgba, w, h, 128, 128, 25))); // Any other ratio is read from the pixels. assert_eq!(coarsen(&fine, 128, 256, 100, 128), None); } @@ -366,10 +358,9 @@ mod tests { assert!(s.doc().unwrap().doc.alpha_outlines.is_empty()); } - /// An image with no outline (here opaque) is remembered as an empty one: later edits don't - /// trace it again, and the contour is the frame's. + /// An outline is traced once: later edits keep it. #[test] - fn an_image_with_no_outline_is_not_traced_on_every_edit() { + fn an_outline_is_not_traced_on_every_edit() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); let data = png(|_, _| true); @@ -380,12 +371,24 @@ mod tests { s.execute("object.textWrap", &json!({"ids": [id], "mode": "contour", "contour": "alphaChannel"})).unwrap(); let first = s.doc().unwrap().doc.alpha_outlines.clone(); assert_eq!(first.len(), 1, "remembered"); - assert_eq!((first[0].width, first[0].height), (0, 0), "as no outline"); s.execute("frame.create", &json!({"rect": [300, 300, 350, 350]})).unwrap(); let after = &s.doc().unwrap().doc.alpha_outlines; assert!(Arc::ptr_eq(&first[0], &after[0]), "kept, not traced again"); } + /// An opaque image's Alpha Channel contour is its rectangle, not the frame: moved within its + /// frame, it leaves the empty part of the frame to the text. + #[test] + fn an_opaque_image_wraps_its_rectangle() { + let (mut s, image, story) = page(&png(|_, _| true), [105.0, 150.0, 125.0, 178.0]); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(overset(&s, story), "the image covers the caption"); + // The graphic moved 30 pt right within its frame: the frame's left 30 pt are empty. + s.execute("selection.set", &json!({"ids": [image], "content": true})).unwrap(); + s.execute("transform.move", &json!({"dx": 30, "dy": 0})).unwrap(); + assert!(!overset(&s, story), "the empty part of the frame takes the caption"); + } + /// Outlines are traced for a wrap set on the placed graphic and for frames inside groups, and /// traced again when the image's data changes under the same asset (relink, link update). #[test] From 4122adc65f60eb79402e3a73e9ed07aeb65e9a87 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 22:04:10 -0800 Subject: [PATCH 0983/1349] Text wrap: Alpha Channel outlines in use are looked up in sets --- crates/engine/src/cmd/alpha_wrap.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs index 6ca0e78f9..86b864a61 100644 --- a/crates/engine/src/cmd/alpha_wrap.rs +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -3,6 +3,7 @@ //! The outline is traced once per image and threshold, in the image's pixel space, and kept on //! the document ([`designcraft_doc::AlphaOutline`]). Composition maps it through the graphic's //! current transform, so it follows the image when it is moved, scaled or refitted. +use std::collections::BTreeSet; use std::sync::Arc; use designcraft_doc::{AlphaOutline, AssetId, ContourType, Document, Item, WrapMode}; @@ -18,14 +19,14 @@ const MAX_EDGES: usize = 1 << 16; /// Trace the outlines new Alpha Channel contours need and drop the ones nothing uses. Cheap when /// nothing changed: tracing happens only for an image and threshold not seen before. pub(crate) fn sync(doc: &mut Document) { - let mut wanted: Vec<(AssetId, u8)> = Vec::new(); + let mut wanted: BTreeSet<(AssetId, u8)> = BTreeSet::new(); // Every frame, in groups and Paste Into containers too, with the wrap set on the frame or on // its placed graphic (Direct Selection sets the graphic's). let mut want = |it: &Item| { let Some(g) = it.graphic() else { return }; for w in [&it.wrap, &g.wrap] { - if w.mode == WrapMode::Contour && w.contour == ContourType::AlphaChannel && !wanted.contains(&(g.asset, w.alpha_threshold)) { - wanted.push((g.asset, w.alpha_threshold)); + if w.mode == WrapMode::Contour && w.contour == ContourType::AlphaChannel { + wanted.insert((g.asset, w.alpha_threshold)); } } }; @@ -47,8 +48,9 @@ pub(crate) fn sync(doc: &mut Document) { // An outline traced from data the asset no longer has (relinked or updated) is traced again. let assets = &doc.assets; doc.alpha_outlines.retain(|o| wanted.contains(&(o.asset, o.threshold)) && assets.get(&o.asset).is_some_and(|a| o.traced_from(&a.data))); + let traced: BTreeSet<(AssetId, u8)> = doc.alpha_outlines.iter().map(|o| (o.asset, o.threshold)).collect(); for (asset, threshold) in wanted { - if doc.alpha_outline(asset, threshold).is_some() { + if traced.contains(&(asset, threshold)) { continue; } let Some(a) = doc.assets.get(&asset).filter(|a| a.is_raster()) else { continue }; From b1a514fc51606ba4b26390400f38b6abeff97973 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 22:05:16 -0800 Subject: [PATCH 0984/1349] Paste: ui.paste checks the image's size before decoding it ui.paste {image} refuses base64 longer than the 256 MB file limit before it decodes the data, with the same check edit.pasteImage uses. --- crates/engine/src/cmd.rs | 2 +- crates/engine/src/cmd/paste_image.rs | 25 ++++++++++++++++++++++--- crates/ui-egui/src/control.rs | 3 +++ 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 20260a5ad..739072d78 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -378,6 +378,6 @@ pub use file::{ DOCUMENT_SNIFF_BYTES, RecentPreview, base64_decode, base64_encode, from_bytes, is_document, recent_preview, to_bytes, with_document_extension, }; pub use layout::chapter_numbering; -pub use paste_image::{IMAGE_EXTENSIONS, MAX_PASTED_PIXELS, PASTED_IMAGE_NAME, check_pasted_size, pasted_pixels, pasted_png}; +pub use paste_image::{IMAGE_EXTENSIONS, MAX_PASTED_PIXELS, PASTED_IMAGE_NAME, check_pasted_base64, check_pasted_size, pasted_pixels, pasted_png}; pub use paste_svg::is_svg_markup; pub(crate) use place_text::autoflow as place_text_autoflow; diff --git a/crates/engine/src/cmd/paste_image.rs b/crates/engine/src/cmd/paste_image.rs index b5e1003ac..ec29d78b0 100644 --- a/crates/engine/src/cmd/paste_image.rs +++ b/crates/engine/src/cmd/paste_image.rs @@ -47,6 +47,19 @@ pub fn check_pasted_size(width: u32, height: u32) -> std::result::Result<(), Str Ok(()) } +/// Whether an image file given as base64 is small enough to paste, checked before it is +/// decoded; the error says why not. +pub fn check_pasted_base64(b64: &str) -> std::result::Result<(), String> { + check_pasted_base64_len(b64.len()) +} + +fn check_pasted_base64_len(len: usize) -> std::result::Result<(), String> { + if len / 4 * 3 > MAX_PASTED_BYTES { + return Err(format!("the image is larger than {} MB", MAX_PASTED_BYTES >> 20)); + } + Ok(()) +} + /// Unpremultiplied RGBA pixels from the clipboard, rows top to bottom, as a PNG file for /// [`edit.pasteImage`](specs). pub fn pasted_png(width: u32, height: u32, rgba: Vec) -> std::result::Result, String> { @@ -80,9 +93,7 @@ fn paste_image(s: &mut Session, p: &Value) -> Result { Some(_) => return Err(bad(ID, "`base64` must be a non-empty string")), None => return Err(bad(ID, "missing base64")), }; - if b64.len() / 4 * 3 > MAX_PASTED_BYTES { - return Err(bad(ID, format!("the image is larger than {} MB", MAX_PASTED_BYTES >> 20))); - } + check_pasted_base64(b64).map_err(|e| bad(ID, e))?; let name = match p.get("name") { None | Some(Value::Null) => PASTED_IMAGE_NAME, Some(Value::String(n)) if !n.trim().is_empty() => n.as_str(), @@ -253,6 +264,14 @@ mod tests { assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed"); } + #[test] + fn base64_past_the_file_limit_is_refused_by_its_length() { + let limit = MAX_PASTED_BYTES / 3 * 4; + assert!(check_pasted_base64_len(limit).is_ok()); + let e = check_pasted_base64_len(limit + 4).unwrap_err(); + assert!(e.contains("larger than 256 MB"), "{e}"); + } + #[test] fn a_damaged_image_with_a_whole_header_is_refused() { let mut s = doc(); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 9a8e23900..0b8fbb6d5 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -279,6 +279,9 @@ fn handle_request(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest let event = match (s("text"), s("image")) { (Some(text), None) => egui::Event::Paste(text.to_string()), (None, Some(image)) => { + if let Err(e) = designcraft_engine::cmd::check_pasted_base64(image) { + return err(format!("`image`: {e}")); + } let bytes = designcraft_engine::cmd::base64_decode(image); let Some((w, h, rgba)) = designcraft_engine::cmd::pasted_pixels(&bytes) else { return err("`image` is not an image file that can be pasted"); From 1eda04663b84f2aa87a4f72953b99efa9ed97476 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 22:07:30 -0800 Subject: [PATCH 0985/1349] Recovery: a clean document stops its background writes; a failed folder sync keeps the snapshot tracked - recovery::save cancels the background writes the session queued for a clean document and removes what a finished one left, so an older snapshot is not published after Undo returns the document to its saved state. - Cancelling a document's writes leaves a write another session queued to follow in place. - When the folder sync fails after the rename, the snapshot is reported as published with the error, so it is tracked and Save or Close removes it. --- crates/engine/src/recovery.rs | 45 ++++++++++- crates/engine/src/recovery/tests.rs | 115 ++++++++++++++++++++++++++++ 2 files changed, 156 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index 3b4060763..d6e434a4a 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -580,6 +580,12 @@ pub fn save(s: &Session, dir: &Path) -> Result { for d in &s.docs { // New Document's preview is not a document until Create makes it one. if !d.is_dirty() || s.new_document_preview() == Some(d.uid) { + // A background write this session queued of an older state must not publish after + // this discard, and what one already wrote in another folder is removed too. + #[cfg(not(target_arch = "wasm32"))] + for other in worker::cancel_document(d.uid, s.recovery_owner.0) { + discard(&other, d.uid); + } discard(dir, d.uid); continue; } @@ -762,6 +768,8 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { #[cfg(any(test, feature = "testing"))] testing::gate(&entry.dir); let (doc, meta) = files(&entry.dir, entry.uid); + // Set at the rename: an error after it (syncing the folder) leaves the entry on disk. + let landed = std::cell::Cell::new(false); let published = publish_recovery_written( &doc, entry.own, @@ -774,6 +782,7 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { // and remove (Save and Close must clean up the snapshot they wrote). Recorded with the // rename, so a cleanup after it can remove the entry. || { + landed.set(true); if !entry.own { WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert((entry.key.clone(), entry.uid)); } @@ -785,6 +794,8 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { // reports an error, which is the cancel's and not a failure. Ok(false) => return Written { published: false, error: None }, Err(_) if cancelled() => return Written { published: false, error: None }, + // Renamed into place, then the folder sync failed: the entry is there to track and clean up. + Err(e) if landed.get() => return Written { published: true, error: Some(e) }, Err(e) => return Written { published: false, error: Some(e) }, } let metadata = json!({"path": entry.path, "title": entry.title, "saved": designcraft_doc::vars::now()}); @@ -1048,10 +1059,15 @@ mod worker { let mut dirs = Vec::new(); if let Ok(mut running) = self.running.lock() { let mut keys = Vec::new(); - for (key, q) in running.iter_mut().filter(|((_, u), q)| *u == uid && q.owner == owner) { - keys.push(key.clone()); - dirs.push(q.dir.clone()); - q.next = None; + for (key, q) in running.iter_mut().filter(|((_, u), _)| *u == uid) { + // A write another session queued to follow stays queued. + if q.next.as_ref().is_some_and(|n| n.owner == owner) { + q.next = None; + } + if q.owner == owner { + keys.push(key.clone()); + dirs.push(q.dir.clone()); + } } if let Ok(mut cancelled) = self.cancelled.lock() { cancelled.extend(keys); @@ -1315,6 +1331,23 @@ pub mod testing { w.wait_until_idle(); } } + + static FAIL_SYNC: Mutex> = Mutex::new(None); + + /// Make the next folder sync after a recovery file is renamed into `dir` fail. + pub fn fail_next_sync(dir: &Path) { + *FAIL_SYNC.lock().unwrap_or_else(PoisonError::into_inner) = Some(dir.to_path_buf()); + } + + /// Whether this sync of `dir` is the one [`fail_next_sync`] asked to fail. + pub(super) fn sync_fails(dir: &Path) -> bool { + let mut slot = FAIL_SYNC.lock().unwrap_or_else(PoisonError::into_inner); + if slot.as_deref() == Some(dir) { + *slot = None; + return true; + } + false + } } #[cfg(not(target_arch = "wasm32"))] @@ -1460,6 +1493,10 @@ fn is_link_like(metadata: &std::fs::Metadata) -> bool { #[cfg(not(target_arch = "wasm32"))] fn sync_recovery_dir(dir: &Path) -> Result<()> { validate_recovery_dir(dir)?; + #[cfg(any(test, feature = "testing"))] + if testing::sync_fails(dir) { + return Err(EngineError::Other(format!("{}: sync failed", dir.display()))); + } #[cfg(unix)] { diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index 4534c3c37..d58f31fd6 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -466,6 +466,121 @@ fn a_snapshot_whose_metadata_failed_is_still_the_documents_to_remove() { assert!(s.docs[0].recovery_entries.is_empty()); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_snapshot_whose_folder_sync_failed_is_still_the_documents_to_remove() { + // The rename put the snapshot in place before the folder sync failed: it is tracked, so Save + // removes it. + let root = tempfile::tempdir().unwrap(); + let dir = run_dir(root.path()).unwrap(); + let mut s = dirty_session(); + s.recovery_dir = Some(dir.clone()); + let uid = s.docs[0].uid; + let (document, _) = files(&dir, uid); + testing::fail_next_sync(&dir); + let err = save_tracked(&mut s, &dir).unwrap_err(); + assert!(err.to_string().contains("sync failed"), "{err}"); + assert!(document.exists(), "the snapshot landed"); + assert!(s.docs[0].recovery_entries.iter().any(|(d, u)| *u == uid && same_directory(d, &dir)), "and is tracked"); + let saved = root.path().join("saved.designcraft"); + s.execute("file.saveAs", &json!({"path": saved.to_string_lossy()})).unwrap(); + assert!(!document.exists(), "Save removed the snapshot"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_document_undone_to_its_saved_state_while_its_write_is_held_leaves_no_snapshot() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut s = dirty_session(); + s.recovery_dir = Some(dir.path().to_path_buf()); + let uid = s.docs[0].uid; + let held = testing::hold_next_write(dir.path()); + s.execute("file.recovery.save", &json!({"background": true})).unwrap(); + held.wait_until_held(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!s.docs[0].is_dirty(), "back to the state it had"); + // A save of recovery data now drops the clean document's checkpoint, and the held write of + // the older state must not publish after it. + save(&s, dir.path()).unwrap(); + held.release(); + testing::wait_until_idle(); + assert!(!files(dir.path(), uid).0.exists(), "the older snapshot was not published"); + let _ = s.execute("file.recovery.progress", &json!({})); + assert!(list(dir.path()).is_empty()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_document_undone_to_its_saved_state_loses_the_snapshot_a_finished_write_left_in_another_folder() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let other = tempfile::tempdir().unwrap(); + let mut s = dirty_session(); + s.recovery_dir = Some(other.path().to_path_buf()); + let uid = s.docs[0].uid; + s.execute("file.recovery.save", &json!({"background": true})).unwrap(); + // Written, but its result not yet taken by the session. + testing::wait_until_idle(); + assert!(files(other.path(), uid).0.exists()); + s.execute("edit.undo", &json!({})).unwrap(); + save(&s, dir.path()).unwrap(); + assert!(!files(other.path(), uid).0.exists(), "the snapshot of the older state is removed"); + let _ = s.execute("file.recovery.progress", &json!({})); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_clean_document_leaves_another_sessions_write_queued_behind_its_own() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut a = dirty_session(); + a.recovery_dir = Some(dir.path().to_path_buf()); + let uid = a.docs[0].uid; + let mut b = dirty_session(); + b.recovery_dir = Some(dir.path().to_path_buf()); + b.docs[0].uid = uid; + b.execute("frame.create", &json!({"rect": [20, 20, 60, 60]})).unwrap(); + let held = testing::hold_next_write(dir.path()); + a.execute("file.recovery.save", &json!({"background": true})).unwrap(); + held.wait_until_held(); + // A write now cancels the held one; the other session's write is queued to follow it. + a.execute("file.recovery.save", &json!({"dir": dir.path().to_string_lossy()})).unwrap(); + b.execute("file.recovery.save", &json!({"background": true})).unwrap(); + a.execute("edit.undo", &json!({})).unwrap(); + assert!(!a.docs[0].is_dirty()); + save(&a, dir.path()).unwrap(); + held.release(); + assert_eq!(finished_writes(&mut b), 1, "the other session's write ran"); + let mut reopened = Session::new(); + assert_eq!(open(&mut reopened, dir.path()).unwrap().len(), 1); + assert_eq!(reopened.doc().unwrap().doc.spreads[0].items.len(), 2, "its snapshot was kept"); + discard(dir.path(), uid); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_clean_document_in_another_session_leaves_this_sessions_write_alone() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut queued_by = dirty_session(); + queued_by.recovery_dir = Some(dir.path().to_path_buf()); + let uid = queued_by.docs[0].uid; + // The same uid, clean, in another session. + let mut other = Session::new(); + other.execute("file.new", &json!({})).unwrap(); + other.docs[0].uid = uid; + assert!(!other.docs[0].is_dirty()); + let held = testing::hold_next_write(dir.path()); + queued_by.execute("file.recovery.save", &json!({"background": true})).unwrap(); + held.wait_until_held(); + save(&other, dir.path()).unwrap(); + held.release(); + assert_eq!(finished_writes(&mut queued_by), 1); + assert!(files(dir.path(), uid).0.exists(), "the other session's save did not cancel this write"); + discard(dir.path(), uid); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn a_background_snapshot_whose_metadata_failed_is_still_the_documents_to_remove() { From 61428f05d9b4981755dfdee2ef99c627d3b666b7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 22:15:31 -0800 Subject: [PATCH 0986/1349] Compose: Justify keeps later lines out of an object anchored in an earlier line An object anchored in a line that Justify moves goes down with that line. The lines after it now stop where the object ends up, so the last line no longer runs into it. The Bottom tests also check that a wrap that does not stop the text leaves the last line on the text area's bottom. --- crates/compose/src/lib.rs | 89 +++++++++++++++++++++++++------------ crates/compose/src/tests.rs | 22 ++++++++- crates/compose/src/wrap.rs | 6 ++- 3 files changed, 86 insertions(+), 31 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 9eaafdc5d..009ba6c68 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -364,6 +364,9 @@ pub struct Exclusion { /// An anchored object in the frame's own story: it wraps only lines that start after this /// story byte (its anchor). pub after: Option, + /// For an anchored object in the frame's own story: the baseline of the line holding its + /// anchor when the exclusion was taken from it. + pub anchor_baseline: Option, } impl Exclusion { @@ -531,7 +534,7 @@ fn wrap_exclusion( if let Some(custom) = wrap.path.as_ref().and_then(|p| Contour::of(&p.to_bezpath(), inv * xf, 0.0)) { let rect = custom.bounds(); let contour = matches!(wrap.mode, WrapMode::BoundingBox | WrapMode::Contour).then_some(custom); - return Exclusion { rect, mode: wrap.mode, side, contour, after: None }; + return Exclusion { rect, mode: wrap.mode, side, contour, after: None, anchor_baseline: None }; } let contour = if wrap.mode == WrapMode::Contour { outline() } else { None }.and_then(|(path, frame)| { let c = Contour::of(&path, inv * xf, o[0])?; @@ -541,7 +544,7 @@ fn wrap_exclusion( }) }); let rect = contour.as_ref().map_or_else(|| inv.transform_rect_bbox(r), Contour::bounds); - Exclusion { rect, mode: wrap.mode, side, contour, after: None } + Exclusion { rect, mode: wrap.mode, side, contour, after: None, anchor_baseline: None } } /// The outline a contour wrap of `kind` around frame `it` follows, in the frame's inner space, and @@ -5497,7 +5500,7 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de // Per column (or all lines together). let ncols = if spanned { 1 } else { ft.columns.len().max(1) as u32 }; for c in 0..ncols { - let rooms = wrap_rooms(ft, f, c, spanned, anchors); + let (rooms, follow) = wrap_rooms(ft, f, c, spanned, anchors); // Center and Bottom move the lines together: the nearest text wrap under them is the // bottom of the room they move down into. Justify checks each row's room below. let raised; @@ -5565,7 +5568,20 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de // Each row moves no further than a text wrap under it allows; every row's // shift grows with the space, so the most space that keeps them all clear is // found by bisection. - let clear = |shift: &[f64]| idx.iter().zip(&rows).all(|(&i, &k)| shift[k] <= rooms[i].max(0.0) + 1e-9); + // An object that moves with its anchor's row limits how much further than + // that row a later row moves. + let mut row_of = vec![None; ft.lines.len()]; + for (&i, &k) in idx.iter().zip(&rows) { + row_of[i] = Some(k); + } + let follow: Vec<(usize, usize, f64)> = follow + .iter() + .filter_map(|&(i, a, room)| Some((row_of.get(i).copied().flatten()?, row_of.get(a).copied().flatten()?, room.max(0.0)))) + .collect(); + let clear = |shift: &[f64]| { + idx.iter().zip(&rows).all(|(&i, &k)| shift[k] <= rooms[i].max(0.0) + 1e-9) + && follow.iter().all(|&(k, m, room)| shift[k] - shift[m] <= room + 1e-9) + }; let mut shift = shifts(space); if !clear(&shift) { let (mut lo, mut hi) = (0.0, space); @@ -5627,10 +5643,12 @@ fn wrap_bottom(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, rooms: &[f6 /// contour on its way down (to 0.01 pt). Only wraps that reach into a line's column (or the /// columns it spans) count, as when the lines are set. An anchored object that moves with the /// lines being justified (inline, above the line, or positioned from its anchor and not kept -/// within its column) is skipped, except under Justify. Justify keeps the first row in place, so -/// its room stays infinite. `anchors` holds the story byte of each anchored object's mark, by -/// object index. -fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[usize]) -> Vec { +/// within its column) is skipped, except under Justify, where it moves with the row of its +/// anchor's line: its wrap is taken where the object sits before the lines move, and its rooms go +/// in the second list as (line, anchor's line, room), so a line moves down at most that much +/// further than the anchor's row. Justify keeps the first row in place, so its room stays +/// infinite. `anchors` holds the story byte of each anchored object's mark, by object index. +fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[usize]) -> (Vec, Vec<(usize, usize, f64)>) { const EPS: f64 = 1e-6; // One-sided wraps also block the column on the other side of the object: the x-range wrap // `e` keeps text out of in column `col`, from the object's x-range `a..b` there (None when that @@ -5655,30 +5673,29 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u } }; let in_col = |k: u32| spanned || k == c; + let justify = f.opts.vertical_justification == VerticalJustification::Justify; // An own-story anchored object whose anchor is on one of these lines and whose position - // follows its line moves with the text. Justify moves later lines further than earlier ones, - // so there the object's current top still limits the lines after its anchor. - let moves_with_text = |e: &Exclusion| { - let Some(a) = e.after.filter(|_| f.opts.vertical_justification != VerticalJustification::Justify) else { return false }; + // follows its line moves with the text: the index in `ft.lines` of its anchor's line, and how + // much lower that line was when the wrap was taken (an earlier pass placed the object after + // moving the lines). + let moves_with_text = |e: &Exclusion| -> Option<(usize, f64)> { + let a = e.after?; // The object whose mark is the anchor, placed on one of these lines. - let Some(o) = ft.objects.iter().find(|o| anchors.get(o.index) == Some(&a) && ft.lines.get(o.line).is_some_and(|l| in_col(l.column))) else { - return false; - }; - match &o.object.position { + let o = ft.objects.iter().find(|o| anchors.get(o.index) == Some(&a) && ft.lines.get(o.line).is_some_and(|l| in_col(l.column)))?; + let follows = match &o.object.position { designcraft_doc::AnchorPosition::Inline { .. } | designcraft_doc::AnchorPosition::AboveLine { .. } => true, // Kept within the column, it can stop at the column's edge instead of following. designcraft_doc::AnchorPosition::Custom { y_relative, keep_within_column, .. } => { *y_relative == designcraft_doc::anchored::AnchorRelative::Anchor && !keep_within_column } - } + }; + let now = ft.lines.get(o.line).map_or(0.0, |l| l.baseline); + follows.then(|| (o.line, e.anchor_baseline.map_or(0.0, |b| b - now))) }; // Justify keeps the first row (its segments and a table on them) in place, so wraps under it // set no limit. let first = ft.lines.iter().find(|l| in_col(l.column)).map(|l| l.baseline); - let fixed = |line: usize| { - f.opts.vertical_justification == VerticalJustification::Justify - && ft.lines.get(line).zip(first).is_some_and(|(l, b)| (l.baseline - b).abs() <= 1e-9) - }; + let fixed = |line: usize| justify && ft.lines.get(line).zip(first).is_some_and(|(l, b)| (l.baseline - b).abs() <= 1e-9); // (line, story byte, column, slot x-range, top, bottom) of each line (its band runs from its // top to its baseline) and table fragment. let lines = ft @@ -5689,6 +5706,7 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u .map(|(i, l)| (i, l.range.start, l.column, l.x0, l.x1, l.baseline - l.ascent, l.baseline)); let tables = ft.tables.iter().filter(|t| in_col(t.column)).map(|t| (t.line, t.anchor, t.column, t.rect.x0, t.rect.x1, t.rect.y0, t.rect.y1)); let mut rooms = vec![f64::INFINITY; ft.lines.len()]; + let mut follow = Vec::new(); for (line, start, k, x0, x1, top, bottom) in lines.chain(tables) { let Some(&before) = rooms.get(line) else { continue }; if fixed(line) { @@ -5699,8 +5717,18 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u let col = ft.columns.get(k as usize).copied().unwrap_or(f.area); let col = Rect { x0: col.x0.min(x0), x1: col.x1.max(x1), ..col }; let meets = |(a, b): (f64, f64)| a < x1 - EPS && b > x0 + EPS; - for e in f.exclusions.iter().filter(|e| e.wraps_line(start) && !moves_with_text(e)) { - let r = e.rect; + for e in f.exclusions.iter().filter(|e| e.wraps_line(start)) { + let anchor = moves_with_text(e); + if anchor.is_some() && !justify { + continue; + } + // The wrap where its object sits before the lines move (moved up by `dy`), and how + // far it lets this line move down (relative to its anchor's row for an object that + // moves with the text). + let dy = anchor.map_or(0.0, |(_, dy)| dy); + let cap = if anchor.is_some() { f64::INFINITY } else { room }; + let mut room_e = f64::INFINITY; + let r = Rect { y0: e.rect.y0 - dy, y1: e.rect.y1 - dy, ..e.rect }; if let (WrapMode::BoundingBox | WrapMode::Contour, Some(contour)) = (e.mode, &e.contour) && r.y1 > top && sided(e, col, (r.x0, r.x1)).is_some_and(meets) @@ -5709,8 +5737,8 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u // contour stays inside its box). Moved down by `d`, the line's band sweeps from its // top to its baseline plus `d`; the contour's extent there only grows with `d`, so // the furthest clear move is found by bisection to 0.01 pt. - let hits = |d: f64| contour.band_extent(top, bottom + d).and_then(|x| sided(e, col, x)).is_some_and(meets); - let (mut lo, mut hi) = ((r.y0 - bottom).max(0.0), (r.y1 - top).min(f.area.y1 - bottom).min(room)); + let hits = |d: f64| contour.band_extent(top + dy, bottom + d + dy).and_then(|x| sided(e, col, x)).is_some_and(meets); + let (mut lo, mut hi) = ((r.y0 - bottom).max(0.0), (r.y1 - top).min(f.area.y1 - bottom).min(cap)); if lo < hi && hits(hi) { if hits(lo) { hi = lo; @@ -5726,18 +5754,23 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u lo = mid; } } - room = room.min(lo); + room_e = lo; } } else if r.y0 >= bottom - EPS { // A wrap at or under this line. if blocked(e, col).is_some_and(meets) { - room = room.min(r.y0 - bottom); + room_e = r.y0 - bottom; } } + match anchor { + Some((a, _)) if room_e.is_finite() => follow.push((line, a, room_e)), + Some(_) => {} + None => room = room.min(room_e), + } } rooms[line] = room; } - rooms + (rooms, follow) } // ---------- caret and hit testing (Type tool) ---------- diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 4354aeb47..9d7619c14 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -513,6 +513,7 @@ fn hostile_wrap_geometry_terminates() { side: WrapSide::BothSides, contour: None, after: None, + anchor_baseline: None, }; let f = &mut specs[0]; f.exclusions.push(ex(f64::NAN, f64::NAN, f64::NAN, f64::NAN, WrapMode::JumpObject)); @@ -639,12 +640,12 @@ fn vertical_justification_passes_wraps_that_do_not_stop_the_text() { // Wrap off: the number goes down over the bar. let (lines, area, wrap_top) = bar_chart_lines("42", Bottom, WrapMode::None, WrapSide::BothSides, Rect::new(0.0, 150.0, 60.0, 300.0)); assert!(wrap_top.is_none()); - assert!(lines[0].0 > 150.0 && lines[0].0 <= area.y1 + 1e-6, "{lines:?}"); + assert!((lines[0].0 + lines[0].1 - area.y1).abs() < 1e-6, "{lines:?}, bottom {}", area.y1); // A bar on the right half from the frame's top: the number is set beside it and goes down // beside it. let (lines, area, wrap_top) = bar_chart_lines("42", Bottom, WrapMode::BoundingBox, WrapSide::BothSides, Rect::new(30.0, 0.0, 60.0, 300.0)); assert!(wrap_top.is_some()); - assert!(lines[0].0 > 150.0 && lines[0].0 <= area.y1 + 1e-6, "{lines:?}"); + assert!((lines[0].0 + lines[0].1 - area.y1).abs() < 1e-6, "{lines:?}, bottom {}", area.y1); } /// A one-sided wrap in the second column leaves the first column's lines free to go down, as it @@ -868,6 +869,23 @@ fn vertical_justify_stops_at_an_object_anchored_above_the_lines_it_wraps() { assert!(last > lines[0].baseline + 40.0, "Justify spread the lines: {:?}", lines.iter().map(|l| l.baseline).collect::>()); } +/// Justify moves an object anchored in the second line with that line, so the third line spreads +/// down until it meets the object where it ends up, not where it started. +#[test] +fn vertical_justify_follows_an_object_anchored_in_a_later_line() { + let (mut d, sid, fid) = doc_with("One\nTwo\nSix", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Justify; + anchor_box(&mut d, sid, 5, 0.0, 40.0, true, WrapMode::BoundingBox); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + assert_eq!(lines.len(), 3); + let baselines = lines.iter().map(|l| l.baseline).collect::>(); + let top = cs.frames[0].objects[0].origin.y; + assert!((top - lines[1].baseline - 40.0).abs() < 1e-6, "the object hangs 40 pt under the second line: {top}, {baselines:?}"); + let last = lines[2].baseline; + assert!((top - last).abs() < 1e-6, "Justify moved the last line to {last}, not down to the object at {top}: {baselines:?}"); +} + /// Same As Clipping follows a placed graphic's clipping path: beside a triangle that widens /// downwards, text reaches further in at the narrow top than at the wide bottom. #[test] diff --git a/crates/compose/src/wrap.rs b/crates/compose/src/wrap.rs index f28bba424..a8495bd46 100644 --- a/crates/compose/src/wrap.rs +++ b/crates/compose/src/wrap.rs @@ -46,6 +46,8 @@ pub(crate) struct Obstacle<'a> { xf: Affine, /// Story byte of the anchor, for obstacles in their own story. anchor: Option, + /// Baseline of the line holding the anchor, for obstacles in their own story. + anchor_baseline: Option, } fn wraps(o: &AnchoredObject) -> bool { @@ -126,7 +128,8 @@ pub(crate) fn obstacles<'a>(doc: &Document, story: &'a Story, cs: &ComposedStory } else { None }; - out.push(Obstacle { spread: loc.spread, item: &obj.item, xf, anchor }); + let anchor_baseline = anchor.and_then(|_| ft.lines.get(o.line)).map(|l| l.baseline); + out.push(Obstacle { spread: loc.spread, item: &obj.item, xf, anchor, anchor_baseline }); } } out @@ -157,6 +160,7 @@ pub(crate) fn exclusions(doc: &Document, specs: &[FrameSpec], obs: &[Obstacle]) let r = e.rect; if r.is_finite() && r.x0 < a.x1 && r.x1 > a.x0 && r.y0 < a.y1 && r.y1 > a.y0 { e.after = ob.anchor; + e.anchor_baseline = ob.anchor_baseline; ex.push(e); } } From 23eb593498364037fb7d95a5efc052ae1b07799f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 22:18:21 -0800 Subject: [PATCH 0987/1349] Render: the feather test checks the inner effects still draw inside The edge comparisons pass when a bevel or inner glow is not drawn at all. A pixel inside the bevel and glow bands now has to differ from the same object without the effect, for every feather kind. --- crates/render/src/fx.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index f9b40ba9b..8fd4b0d1d 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -736,6 +736,16 @@ mod tests { ); } } + // Inside the bevel and glow bands the effect still shows, faded with the object + // where the feather reaches. + let inside = px(&plain, threads, 110); + for inner in [1, 2] { + let with = px(&doc(image, feather, inner), threads, 110); + assert!( + diff(with, inside) > 0, + "image {image} feather {feather} inner {inner} threads {threads}: {with:?} at 110, {inside:?} without the effect" + ); + } } } } From d20ffcc055aab088e7c25af259c73f5fdbbfd4db Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 22:23:34 -0800 Subject: [PATCH 0988/1349] Render: satin on an image follows its painted edge Satin on a frame holding an image used the frame's shape. Where the image is transparent, the satin color multiplied over whatever lay behind the frame, so text under a transparent part of the image turned darker. Satin now builds its two offset copies from what the object paints and keeps the result to the painted pixels, as the inner shadow, inner glow and bevel already do. --- crates/render/src/fx.rs | 118 ++++++++++++++++++++++++++++++++-------- 1 file changed, 94 insertions(+), 24 deletions(-) diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index 7c7c91fe1..501333471 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -287,6 +287,7 @@ impl Renderer { } } // Satin: the shape shifted both ways along the angle, blurred, where exactly one covers. + // With a graphic, the shape is what the object paints, as for the inner shadow. if e.satin.on && let Some(c) = doc.resolve_color(&e.satin.color, 1.0) { @@ -295,25 +296,56 @@ impl Renderer { let sigma = bound(st.size).max(0.0) / 2.0; let paint = color_of(&c, st.opacity.clamp(0.0, 1.0)); let invert = st.invert; - self.with_blended_filters(ctx, f, reach, sigma, Mix::Multiply, (bp, xf), |_, c, fr| { + self.with_blended_filters(ctx, f, reach, sigma, Mix::Multiply, (bp, xf), |me, c, fr| { + // One copy of the shape moved by `by`: the shape in the satin colour, or what the + // object paints (coloured below). + let copy = |me: &mut Renderer, c: &mut RenderContext, by: Vec2| match painted { + Some((it, page)) => { + let moved = Frame { view: fr.view * Affine::translate(by), ..*fr }; + me.draw_body(c, &moved, it, bp, xf, page); + } + None => { + c.set_transform(fr.view * Affine::translate(by) * xf); + c.set_paint(paint); + c.fill_path(bp); + } + }; c.set_transform(fr.view); + if painted.is_some() { + c.push_layer(None, None, None, None, None); + } c.push_layer(None, None, None, None, Some(blur(sigma))); + if painted.is_some() { + c.push_layer(None, None, None, None, None); + } if invert { - c.set_transform(fr.view * xf); - c.set_paint(paint); - c.fill_path(bp); + copy(me, c, Vec2::ZERO); } c.set_transform(Affine::IDENTITY); c.push_layer(None, Some(BlendMode::new(Mix::Normal, if invert { Compose::DestOut } else { Compose::SrcOver })), None, None, None); - c.set_transform(fr.view * Affine::translate(off) * xf); - c.set_paint(paint); - c.fill_path(bp); + copy(me, c, off); c.set_transform(Affine::IDENTITY); c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::Xor)), None, None, None); - c.set_transform(fr.view * Affine::translate(-off) * xf); - c.fill_path(bp); + copy(me, c, -off); c.pop_layer(); c.pop_layer(); + if let Some((it, page)) = painted { + // The satin colour where the copies cover, ... + let pad = sigma * 4.0 + off.hypot() + 4.0 * fr.px; + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::SrcIn)), None, None, None); + c.set_transform(fr.view); + c.set_paint(paint); + c.fill_rect(&reach.inflate(pad, pad)); + c.pop_layer(); + c.pop_layer(); + c.pop_layer(); + // ... blurred and kept only where the object paints. + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestIn)), None, None, None); + me.draw_body(c, fr, it, bp, xf, page); + c.pop_layer(); + } c.pop_layer(); }); } @@ -548,8 +580,52 @@ mod tests { /// lines the image's opaque part (its edge in the middle of the frame), not only the frame. #[test] fn an_inner_shadow_follows_a_transparent_images_edge() { + let (d, mut it) = half_image_frame(); + let s = &mut it.effects.inner_shadow; + s.on = true; + s.color = "[Black]".into(); + s.opacity = 1.0; + s.distance = 0.0; + s.size = 20.0; + let lum = render_row(d, it); + // The image's opaque part starts at x = 200: just inside it the shadow darkens it; in its + // middle (x = 250, 50 pt from every edge but the frame's right one) it stays light. + assert!(lum(204) + 60 < lum(250), "shadow at the image's own edge: {} vs {}", lum(204), lum(250)); + // The transparent half shows the page: no shadow painted there. + assert!(lum(150) > 700, "nothing over the transparent part: {}", lum(150)); + } + + /// Satin on a frame holding an image whose left half is transparent multiplies only over the + /// image's opaque part, plain or inverted: the page shows through the transparent half. + #[test] + fn satin_follows_a_transparent_images_edge() { + for invert in [false, true] { + let (d, mut it) = half_image_frame(); + let s = &mut it.effects.satin; + s.on = true; + s.color = "[Black]".into(); + s.opacity = 1.0; + s.angle = 0.0; + s.distance = 100.0; + s.size = 4.0; + s.invert = invert; + let lum = render_row(d, it); + // The copies are 50 pt to each side. Over the frame they leave the satin on 100 to 150 + // (plain) or 150 to 250 (inverted), over the transparent half of the image. + let clear = if invert { 175 } else { 125 }; + assert!(lum(clear) > 700, "invert {invert}: satin over the transparent part at x = {clear}: {}", lum(clear)); + // Over the image's opaque part the copies (150 to 250 and 250 to 350) leave plain satin on + // all of it and inverted satin on none of it. + let shaded = lum(225) < 100; + assert_eq!(shaded, !invert, "invert {invert}: lum at x = 225 is {}", lum(225)); + } + } + + /// A 200 pt frame at (100, 100) holding a 20 × 20 image with a transparent left half and an + /// opaque white right half, in a new document. + fn half_image_frame() -> (designcraft_doc::Document, Item) { + use designcraft_doc::Document; use designcraft_doc::build::NewDocument; - use designcraft_doc::{Document, SpreadRef}; let mut d = Document::new(&NewDocument::default()); let lid = d.default_layer(); // 20 × 20: transparent left half, opaque white right half. @@ -586,25 +662,19 @@ mod tests { wrap: Default::default(), fill: Default::default(), }); - let s = &mut it.effects.inner_shadow; - s.on = true; - s.color = "[Black]".into(); - s.opacity = 1.0; - s.distance = 0.0; - s.size = 20.0; - d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + (d, it) + } + + /// The first page with `it` added, rendered at 100%: the sum of R, G and B at x on row 200. + fn render_row(mut d: designcraft_doc::Document, it: Item) -> impl Fn(u32) -> u32 { + d.insert_item(designcraft_doc::SpreadRef::Doc(0), it, None).unwrap(); let cache = crate::Cache::new(); let mut r = Renderer::new(); r.threads = 0; let page = r.render_page(&d, &cache, 0, 1.0, false, &crate::RenderOptions::default()).unwrap(); - let lum = |x: u32| { + move |x: u32| { let p = page.pixel(x, 200); u32::from(p[0]) + u32::from(p[1]) + u32::from(p[2]) - }; - // The image's opaque part starts at x = 200: just inside it the shadow darkens it; in its - // middle (x = 250, 50 pt from every edge but the frame's right one) it stays light. - assert!(lum(204) + 60 < lum(250), "shadow at the image's own edge: {} vs {}", lum(204), lum(250)); - // The transparent half shows the page: no shadow painted there. - assert!(lum(150) > 700, "nothing over the transparent part: {}", lum(150)); + } } } From c9cc76e6ad2b568981652e96fb4344065f2633e8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 22:45:44 -0800 Subject: [PATCH 0989/1349] CMYK view: the conversion returns the number of bands it converted With more render threads than bands of 32 rows fit evenly, the rows split into fewer bands than requested, and the returned count was the requested one. It is now the number of bands converted. --- crates/render/src/blendspace.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/render/src/blendspace.rs b/crates/render/src/blendspace.rs index 1d992c6fd..4eafc1d89 100644 --- a/crates/render/src/blendspace.rs +++ b/crates/render/src/blendspace.rs @@ -285,7 +285,7 @@ fn srgb_in(table: &[[f32; 3]], cmyk: [f32; 4]) -> [f32; 3] { out } -/// Rows of the ink passes' area one conversion thread takes at least. +/// Rows of the ink passes' area one conversion thread takes at least; the last band can hold fewer. const MIN_BAND_ROWS: usize = 32; /// The blended inks, the C/M/Y complements in `cmy` and the K complement in `black` (`width` @@ -334,7 +334,7 @@ fn inks_to_screen(cmy: &mut [PremulRgba8], black: &[PremulRgba8], width: usize, convert(c, k); } } - bands + parts.len() } impl Renderer { @@ -742,6 +742,18 @@ mod tests { assert_eq!(four.pixels, one.pixels); } + /// The returned count is the number of bands converted: 1,281 rows on 40 threads split into + /// bands of 33 rows, which makes 39 bands. + #[test] + fn ink_conversion_returns_the_bands_it_converted() { + let rows = 1281; + let mut cmy = vec![PremulRgba8 { r: 0, g: 255, b: 255, a: 255 }; rows]; + let black = vec![PremulRgba8 { r: 255, g: 255, b: 255, a: 255 }; rows]; + assert_eq!(inks_to_screen(&mut cmy, &black, 1, false, 40), 39); + assert!(cmy.iter().all(|c| *c == cmy[0]), "every band is converted"); + assert_ne!(cmy[0], PremulRgba8 { r: 0, g: 255, b: 255, a: 255 }); + } + #[test] fn cmyk_nonseparable_modes_use_the_existing_rgb_approximation() { let mut doc = document(); From 7a5924e971b82043b5619dbb212c544d238fbbe0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 22:52:07 -0800 Subject: [PATCH 0990/1349] Render: center inner glow on an image follows its painted edge Inner glow from the center on a frame holding an image filled the frame's shape, so it painted over the transparent parts of the image. It now draws the object's coverage once offscreen, shrinks it by the glow's band, colors and blurs it, and keeps the result to the painted pixels. Partly transparent pixels keep their coverage. --- crates/render/src/fx.rs | 99 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 98 insertions(+), 1 deletion(-) diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index 501333471..6e49577e4 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -265,7 +265,48 @@ impl Renderer { let sigma = if g.technique == designcraft_doc::GlowTechnique::Precise { sigma * 0.4 } else { sigma }; let mix = crate::blend_mode(g.mode).mix; let paint = color_of(&c, g.opacity.clamp(0.0, 1.0)); - if g.center { + if g.center + && let Some((it, page)) = painted + { + // With a graphic, the glow fills what the object paints, shrunk by the band: the + // object's coverage is drawn once offscreen and eroded by the band there. + let band = (bound(g.size) - choke).max(0.5); + self.with_blended_filters(ctx, f, reach, sigma, mix, (bp, xf), |me, c, fr| { + let spread = (sigma * 3.0 + band) / fr.px + 2.0; + let Some(o) = offscreen(fr.view.transform_rect_bbox(reach), spread, c.width(), c.height()) else { return }; + let mut off = RenderContext::new_with(o.width, o.height, vello_cpu::RenderSettings { num_threads: 0, ..Default::default() }); + let view = Affine::scale(1.0 / o.scale) * Affine::translate((-o.x0, -o.y0)) * fr.view; + me.draw_body(&mut off, &Frame { mt: false, view, px: fr.px * o.scale, ..*fr }, it, bp, xf, page); + off.flush(); + let mut pm = vello_cpu::Pixmap::new(o.width, o.height); + off.render(&mut pm, &mut me.resources); + let mask = erode(&pm, band / (fr.px * o.scale)); + // The eroded coverage in the glow color, ... + c.set_transform(fr.view); + c.push_layer(None, None, None, None, None); + c.push_layer(None, None, None, None, Some(blur(sigma))); + c.set_transform(Affine::translate((o.x0, o.y0)) * Affine::scale(o.scale)); + c.set_paint(vello_cpu::Image { + image: vello_cpu::ImageSource::Pixmap(std::sync::Arc::new(mask)), + sampler: peniko::ImageSampler::default(), + }); + c.fill_rect(&Rect::new(0.0, 0.0, f64::from(o.width), f64::from(o.height))); + let pad = sigma * 4.0 + band + 4.0 * fr.px; + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::SrcIn)), None, None, None); + c.set_transform(fr.view); + c.set_paint(paint); + c.fill_rect(&reach.inflate(pad, pad)); + c.pop_layer(); + c.pop_layer(); + // ... blurred and kept only where the object paints. + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestIn)), None, None, None); + me.draw_body(c, fr, it, bp, xf, page); + c.pop_layer(); + c.pop_layer(); + }); + } else if g.center { self.with_blended_filters(ctx, f, reach, sigma, mix, (bp, xf), |_, c, fr| { c.set_transform(fr.view); c.push_layer(None, None, None, None, Some(blur(sigma))); @@ -542,6 +583,30 @@ fn offscreen(reach: Rect, spread: f64, width: u16, height: u16) -> Option= 1.0 && h >= 1.0).then_some(Offscreen { x0, y0, scale, width: w as u16, height: h as u16 }) } +/// `pm`'s coverage shrunk by `r` pixels: each pixel takes the smallest alpha among itself and the +/// points on circles of `r` and `r / 2` around it, as white premultiplied by that alpha. Pixels +/// outside `pm` count as transparent. +fn erode(pm: &vello_cpu::Pixmap, r: f64) -> vello_cpu::Pixmap { + let (w, h) = (i64::from(pm.width()), i64::from(pm.height())); + let src = pm.data(); + let mut taps = vec![(0_i64, 0_i64)]; + for k in 0..16_u8 { + let d = if k % 2 == 0 { r } else { r / 2.0 }; + let a = f64::from(k) * std::f64::consts::PI / 8.0; + taps.push(((a.cos() * d).round() as i64, (a.sin() * d).round() as i64)); + } + taps.dedup(); + let alpha = |x: i64, y: i64| if x < 0 || y < 0 || x >= w || y >= h { 0 } else { src[(y * w + x) as usize].a }; + let mut data = Vec::with_capacity(src.len()); + for y in 0..h { + for x in 0..w { + let a = taps.iter().map(|&(dx, dy)| alpha(x.saturating_add(dx), y.saturating_add(dy))).min().unwrap_or(0); + data.push(vello_cpu::color::PremulRgba8 { r: a, g: a, b: a, a }); + } + } + vello_cpu::Pixmap::from_parts(data, pm.width(), pm.height()) +} + #[cfg(test)] mod tests { #[test] @@ -621,6 +686,38 @@ mod tests { } } + /// An inner glow from the center on a frame holding an image whose left half is transparent + /// fills only the image's opaque part, fading toward that part's own edge. + #[test] + fn a_center_inner_glow_follows_a_transparent_images_edge() { + let (d, mut it) = half_image_frame(); + let g = &mut it.effects.inner_glow; + g.on = true; + g.center = true; + g.color = "[Black]".into(); + g.opacity = 1.0; + g.size = 20.0; + g.mode = Default::default(); + let lum = render_row(d, it); + // The transparent half shows the page: no glow painted there. + assert!(lum(150) > 700, "nothing over the transparent part: {}", lum(150)); + // The opaque part runs from x = 200 to 300: dark in its middle, light at its own left edge. + assert!(lum(250) + 60 < lum(204), "glow fades toward the image's own edge: {} vs {}", lum(250), lum(204)); + } + + /// Eroding keeps a half-transparent area at half coverage away from its edge and clears the + /// band along the edge. + #[test] + fn erosion_keeps_partial_coverage_and_clears_the_edge_band() { + let half = vello_cpu::color::PremulRgba8 { r: 128, g: 128, b: 128, a: 128 }; + let pm = vello_cpu::Pixmap::from_parts(vec![half; 40 * 40], 40, 40); + let out = erode(&pm, 5.0); + assert_eq!(out.sample(20, 20).a, 128); + assert_eq!(out.sample(2, 20).a, 0); + assert_eq!(out.sample(20, 37).a, 0); + assert_eq!(out.sample(6, 20).a, 128); + } + /// A 200 pt frame at (100, 100) holding a 20 × 20 image with a transparent left half and an /// opaque white right half, in a new document. fn half_image_frame() -> (designcraft_doc::Document, Item) { From c4b2d730627ac1e8e1bc8b1f8c14411a66afa663 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 23:02:32 -0800 Subject: [PATCH 0991/1349] Recovery: a shared folder's entry is removed or replaced only by the session that wrote it Entries written or recovered in a recovery folder that is not the run's own were tracked per folder and uid only, so another session in the same process with a document of that uid could replace or remove them; a recovered entry keeps the uid it was written under. Each entry now carries the session that wrote or recovered it, and only that session may replace or remove it. A write queued while its entry was the session's is recorded again when it lands, so a cleanup that dropped the record in between no longer leaves the snapshot on disk after Save. --- crates/engine/src/recovery.rs | 77 ++++++++++++++++++----------- crates/engine/src/recovery/tests.rs | 59 +++++++++++++++++++++- 2 files changed, 104 insertions(+), 32 deletions(-) diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index d6e434a4a..f7f4dcda2 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -272,30 +272,39 @@ fn relock(dir: &Path, created: bool) -> Result { } /// Entries this process wrote or recovered in folders that are not its run's own: (canonical -/// folder, uid). Document uids start at 1 in every process, so a shared folder's entry under -/// one of this run's uids may be another run's. -static WRITTEN: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeSet::new()); +/// folder, uid), with the session that wrote or recovered each ([`Session::recovery_owner`]). +/// Document uids start at 1 in every process, so a shared folder's entry under one of this run's +/// uids may be another run's; and a recovered entry keeps the uid it was written under, which a +/// document of another session can have. +static WRITTEN: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); -/// What this run may do in a recovery folder. +/// What a session may do in a recovery folder. struct Access { /// This run's own folder (`run_dir`): every entry in it is this run's. own: bool, key: PathBuf, + /// The session asking ([`Session::recovery_owner`]). + owner: u64, } impl Access { fn owns(&self, uid: u64) -> bool { - self.own || WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).contains(&(self.key.clone(), uid)) + self.own || WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&(self.key.clone(), uid)) == Some(&self.owner) } fn record(&self, uid: u64) { if !self.own { - WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert((self.key.clone(), uid)); + WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert((self.key.clone(), uid), self.owner); } } + /// Drop the record of an entry this session wrote or recovered; another session's stays. fn forget(&self, uid: u64) { - WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).remove(&(self.key.clone(), uid)); + let mut written = WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let key = (self.key.clone(), uid); + if written.get(&key) == Some(&self.owner) { + written.remove(&key); + } } /// Refuse an entry of another run before anything is written: this run never replaces it. @@ -319,9 +328,9 @@ impl Access { } } -/// Check what this run may do in `dir`. A folder that is not this run's own may be the folder -/// of another running app, whose lock that app holds: this run leaves it alone. -fn access(dir: &Path, created: bool) -> Result { +/// Check what session `owner` may do in `dir`. A folder that is not this run's own may be the +/// folder of another running app, whose lock that app holds: this run leaves it alone. +fn access(dir: &Path, created: bool, owner: u64) -> Result { #[cfg(not(target_arch = "wasm32"))] let own = relock(dir, created)?; #[cfg(not(target_arch = "wasm32"))] @@ -333,7 +342,7 @@ fn access(dir: &Path, created: bool) -> Result { let _ = created; false }; - Ok(Access { own, key: directory_key(dir)? }) + Ok(Access { own, key: directory_key(dir)?, owner }) } #[cfg(not(target_arch = "wasm32"))] @@ -485,13 +494,13 @@ fn read_entry_file(path: &Path) -> std::io::Result> { } /// Remove a document's recovery entry (it was saved or closed). In a folder that is not this -/// run's own, only an entry this run wrote or recovered is removed. -pub fn discard(dir: &Path, uid: u64) { +/// run's own, only an entry session `owner` wrote or recovered is removed. +pub fn discard(dir: &Path, uid: u64, owner: u64) { #[cfg(not(target_arch = "wasm32"))] if validate_recovery_dir(dir).is_err() { return; } - let Ok(access) = access(dir, false) else { return }; + let Ok(access) = access(dir, false, owner) else { return }; if !access.owns(uid) { return; } @@ -504,6 +513,7 @@ pub fn discard(dir: &Path, uid: u64) { /// Consume this document's checkpoint provenance after Save/Close/Revert. A default-directory /// uid may also be another live recovered document's retained source after a failed republish. pub(crate) fn discard_document(s: &mut Session, index: usize, default_dir: Option<&Path>) { + let owner = s.recovery_owner.0; let Some(doc) = s.docs.get_mut(index) else { return }; let uid = doc.uid; // A completed Save/Close/Revert consumes the provenance, even when removal fails. A stale @@ -518,7 +528,7 @@ pub(crate) fn discard_document(s: &mut Session, index: usize, default_dir: Optio // `file.recovery.save {dir}` is not in its entries until the write's result is taken): none // may publish after this point, and what one already published is removed below. #[cfg(not(target_arch = "wasm32"))] - for dir in worker::cancel_document(uid, s.recovery_owner.0) { + for dir in worker::cancel_document(uid, owner) { if !entries.iter().any(|(entry_dir, entry_uid)| *entry_uid == uid && same_directory(entry_dir, &dir)) { entries.push((dir, uid)); } @@ -532,7 +542,7 @@ pub(crate) fn discard_document(s: &mut Session, index: usize, default_dir: Optio // A write of it still running must not publish its snapshot after this point. #[cfg(not(target_arch = "wasm32"))] worker::cancel(&dir, uid); - discard(&dir, uid); + discard(&dir, uid, owner); } } } @@ -563,7 +573,7 @@ fn prepare_save(s: &Session, dir: &Path) -> Result { // coincides with an unrelated live document in a manually configured recovery directory. protect_retained_sources(s, dir)?; let created = secure_recovery_dir(dir)?; - let access = access(dir, created)?; + let access = access(dir, created, s.recovery_owner.0)?; // New Document's preview is never written. let preview = s.new_document_preview(); for document in s.docs.iter().filter(|d| d.is_dirty() && preview != Some(d.uid)) { @@ -584,9 +594,9 @@ pub fn save(s: &Session, dir: &Path) -> Result { // this discard, and what one already wrote in another folder is removed too. #[cfg(not(target_arch = "wasm32"))] for other in worker::cancel_document(d.uid, s.recovery_owner.0) { - discard(&other, d.uid); + discard(&other, d.uid, s.recovery_owner.0); } - discard(dir, d.uid); + discard(dir, d.uid, s.recovery_owner.0); continue; } // The caller asked for this write now: nothing has cancelled it. @@ -676,7 +686,9 @@ struct Snapshot { title: String, /// Whether this run may replace an entry already in the folder. own: bool, - /// The folder's canonical key, for recording that a shared entry is this run's now. + /// The folder is not this run's own: the entry, once written, is recorded as the session's. + shared: bool, + /// The folder's canonical key, for recording that a shared entry is this session's now. key: PathBuf, /// The session that queued a background write ([`Session::recovery_owner`]), which takes its /// result. @@ -716,8 +728,9 @@ impl Snapshot { title: d.title(), // An entry this run did not write is never replaced, even one made since it checked. own: access.owns(d.uid), + shared: !access.own, key: access.key.clone(), - owner: 0, + owner: access.owner, } } } @@ -778,13 +791,15 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { designcraft_format::write(&mut StopWhen { out, cancelled: &cancelled }, &entry.doc, None).map_err(|e| EngineError::Other(e.to_string())) }, &cancelled, - // Written: in a folder that is not this run's own, the entry is now this run's to replace - // and remove (Save and Close must clean up the snapshot they wrote). Recorded with the - // rename, so a cleanup after it can remove the entry. + // Written: in a folder that is not this run's own, the entry is now this session's to + // replace and remove (Save and Close must clean up the snapshot they wrote). Recorded with + // the rename, so a cleanup after it can remove the entry, and recorded even when the + // entry was this session's as the write was queued: a cleanup since may have dropped that + // record. || { landed.set(true); - if !entry.own { - WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert((entry.key.clone(), entry.uid)); + if entry.shared { + WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert((entry.key.clone(), entry.uid), entry.owner); } }, ); @@ -867,6 +882,7 @@ pub(crate) fn start_tracked(s: &mut Session, dir: &Path) -> Result { /// whether a checkpoint was recorded. #[cfg(not(target_arch = "wasm32"))] fn record_checkpoint(s: &mut Session, dir: PathBuf, uid: u64) -> bool { + let owner = s.recovery_owner.0; match s.docs.iter_mut().find(|doc| doc.uid == uid) { Some(doc) if doc.is_dirty() => { if !has_checkpoint(doc, &dir) { @@ -878,7 +894,7 @@ fn record_checkpoint(s: &mut Session, dir: PathBuf, uid: u64) -> bool { // crash, and the timer writes only when a document is dirty, so nothing else would // remove it. Some(_) | None => { - discard(&dir, uid); + discard(&dir, uid, owner); false } } @@ -1604,10 +1620,11 @@ pub fn open(s: &mut Session, dir: &Path) -> Result> { fn open_with_publisher(s: &mut Session, dir: &Path, mut publish: impl FnMut(&Path, &[u8]) -> Result<()>) -> Result> { #[cfg(not(target_arch = "wasm32"))] validate_recovery_dir(dir)?; - let source = access(dir, false)?; + let owner = s.recovery_owner.0; + let source = access(dir, false, owner)?; let destination = s.recovery_dir.clone().unwrap_or_else(|| dir.to_path_buf()); let created = secure_recovery_dir(&destination)?; - let target = access(&destination, created)?; + let target = access(&destination, created, owner)?; let source_key = source.key.clone(); let destination_key = target.key.clone(); let mut opened = Vec::new(); @@ -1665,7 +1682,7 @@ fn open_with_publisher(s: &mut Session, dir: &Path, mut publish: impl FnMut(&Pat let meta = json!({"path": state.path, "title": state.title(), "saved": designcraft_doc::vars::now()}); match publish(&metadata, meta.to_string().as_bytes()) { Ok(()) => { - discard(dir, uid); + discard(dir, uid, owner); state.recovery_entries = vec![(destination.clone(), state.uid)]; } Err(e) => log::warn!("recovery entry {uid} kept: {e}"), diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index d58f31fd6..1a4881a1d 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -1,5 +1,12 @@ use super::*; +/// [`super::discard`] as the session that wrote or recovered the entry, if one did. +fn discard(dir: &Path, uid: u64) { + let key = directory_key(dir).ok().map(|key| (key, uid)); + let owner = key.and_then(|key| WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&key).copied()); + super::discard(dir, uid, owner.unwrap_or(0)); +} + fn dirty_session() -> Session { let mut session = Session::new(); session.execute("file.new", &json!({})).unwrap(); @@ -440,6 +447,51 @@ fn a_snapshot_that_finishes_after_the_save_is_dropped() { assert!(s.docs[0].recovery_entries.iter().any(|(d, u)| *u == uid && d == dir.path())); } +#[test] +fn a_shared_folders_entry_is_only_its_writing_sessions() { + // A recovered entry keeps the uid it was written under, which a document of another session + // in the same process can have. + let dir = tempfile::tempdir().unwrap(); + let writer = dirty_session(); + let uid = writer.docs[0].uid; + assert_eq!(save(&writer, dir.path()).unwrap(), 1); + let (file, _) = files(dir.path(), uid); + let snapshot = std::fs::read(&file).unwrap(); + // Another session's clean document with that uid: its discard leaves the entry alone. + let mut clean = Session::new(); + clean.execute("file.new", &json!({})).unwrap(); + clean.docs[0].uid = uid; + assert_eq!(save(&clean, dir.path()).unwrap(), 0); + assert!(file.exists(), "another session's discard removed the entry"); + // Another session's edited document with that uid: it does not write over the entry. + let mut edited = dirty_session(); + edited.docs[0].uid = uid; + assert!(save(&edited, dir.path()).is_err()); + assert_eq!(std::fs::read(&file).unwrap(), snapshot, "another session wrote over the entry"); + super::discard(dir.path(), uid, writer.recovery_owner.0); + assert!(!file.exists(), "the writing session removes its entry"); +} + +#[test] +fn a_snapshot_queued_as_the_sessions_own_is_recorded_when_it_lands() { + // A write taken while the shared folder's entry was this session's, published after a cleanup + // dropped that record: Save and Close must still remove what it put there. + let dir = tempfile::tempdir().unwrap(); + let s = dirty_session(); + let uid = s.docs[0].uid; + let owner = s.recovery_owner.0; + assert_eq!(save(&s, dir.path()).unwrap(), 1); + let entry = Snapshot::of(&prepare_save(&s, dir.path()).unwrap(), dir.path(), &s.docs[0]); + assert!(entry.own); + super::discard(dir.path(), uid, owner); + let (file, _) = files(dir.path(), uid); + assert!(!file.exists()); + let written = write_snapshot(&entry, || false); + assert!(written.published && written.error.is_none(), "the snapshot landed"); + super::discard(dir.path(), uid, owner); + assert!(!file.exists(), "the snapshot it wrote is the session's to remove"); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn a_snapshot_whose_metadata_failed_is_still_the_documents_to_remove() { @@ -544,12 +596,15 @@ fn a_clean_document_leaves_another_sessions_write_queued_behind_its_own() { let held = testing::hold_next_write(dir.path()); a.execute("file.recovery.save", &json!({"background": true})).unwrap(); held.wait_until_held(); - // A write now cancels the held one; the other session's write is queued to follow it. + // A write now cancels the held one. The other session does not write over the entry it left. a.execute("file.recovery.save", &json!({"dir": dir.path().to_string_lossy()})).unwrap(); - b.execute("file.recovery.save", &json!({"background": true})).unwrap(); + let err = b.execute("file.recovery.save", &json!({"background": true})).unwrap_err(); + assert!(err.to_string().contains("did not write"), "{err}"); a.execute("edit.undo", &json!({})).unwrap(); assert!(!a.docs[0].is_dirty()); save(&a, dir.path()).unwrap(); + // Once that entry is gone, the other session's write is queued to follow the held one. + b.execute("file.recovery.save", &json!({"background": true})).unwrap(); held.release(); assert_eq!(finished_writes(&mut b), 1, "the other session's write ran"); let mut reopened = Session::new(); From b9cba43f89cdaa574a1a1b40248bb3b67225eaa9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 23:09:49 -0800 Subject: [PATCH 0992/1349] Recovery: closing or saving a document cancels only its own session's background writes Discarding a document's recovery entries cancelled every background write of that uid in the folder, so another session's write of a document with the same uid was dropped without a replacement. The cancel now covers only writes the session itself queued. --- crates/engine/src/recovery.rs | 32 ++++++++++++++++++++--------- crates/engine/src/recovery/tests.rs | 24 ++++++++++++++++++++++ 2 files changed, 46 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index f7f4dcda2..2a0422417 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -539,9 +539,10 @@ pub(crate) fn discard_document(s: &mut Session, index: usize, default_dir: Optio if !s.docs.iter().enumerate().any(|(other_index, owner)| { other_index != index && owner.recovery_entries.iter().any(|(entry_dir, entry_uid)| *entry_uid == uid && same_directory(entry_dir, &dir)) }) { - // A write of it still running must not publish its snapshot after this point. + // A write of it this session still runs must not publish its snapshot after this + // point; another session's write of the same uid is its own. #[cfg(not(target_arch = "wasm32"))] - worker::cancel(&dir, uid); + worker::cancel_owned(&dir, uid, owner); discard(&dir, uid, owner); } } @@ -1041,22 +1042,26 @@ mod worker { /// Do not publish the snapshot being written for `dir`/`uid`: the document was saved, /// reverted or closed. Only a write that is queued or running is marked, so the set stays - /// as small as the work in flight. - fn cancel(&self, dir: &Path, uid: u64) { + /// as small as the work in flight. With `owner`, only writes that session queued are + /// marked: another session's write of the same uid stays. + fn cancel(&self, dir: &Path, uid: u64, owner: Option) { let canonical = key(dir, uid); + let mine = |queued_by: u64| owner.is_none_or(|owner| owner == queued_by); // A rename under way finishes first, so the caller's cleanup comes after it; a later // one sees the mark. let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); // The folder's canonical path, or its name as given: a link in the path may lead // elsewhere now than when the write was queued. let Ok(mut running) = self.running.lock() else { return }; - let keys: Vec<(PathBuf, u64)> = - running.iter().filter(|(k, q)| **k == canonical || (k.1 == uid && q.dir == dir)).map(|(k, _)| k.clone()).collect(); - // A write queued to follow it is older than what the caller has now, too. - for k in &keys { - if let Some(q) = running.get_mut(k) { + let mut keys = Vec::new(); + for (k, q) in running.iter_mut().filter(|(k, q)| **k == canonical || (k.1 == uid && q.dir == dir)) { + // A write queued to follow it is older than what the caller has now, too. + if q.next.as_ref().is_some_and(|n| mine(n.owner)) { q.next = None; } + if mine(q.owner) { + keys.push(k.clone()); + } } if let Ok(mut cancelled) = self.cancelled.lock() { cancelled.extend(keys); @@ -1181,7 +1186,14 @@ mod worker { /// Do not publish the snapshot being written for `dir`/`uid` (see [`Writer::cancel`]). pub(super) fn cancel(dir: &Path, uid: u64) { if let Some(w) = started() { - w.cancel(dir, uid); + w.cancel(dir, uid, None); + } + } + + /// [`cancel`] for the writes session `owner` queued. + pub(super) fn cancel_owned(dir: &Path, uid: u64, owner: u64) { + if let Some(w) = started() { + w.cancel(dir, uid, Some(owner)); } } diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index 1a4881a1d..d1d03f162 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -312,6 +312,30 @@ fn saving_in_one_session_leaves_another_sessions_write_alone() { discard(dir.path(), uid); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn saving_in_one_session_leaves_another_sessions_write_to_the_same_folder_alone() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut queued_by = dirty_session(); + queued_by.recovery_dir = Some(dir.path().to_path_buf()); + let uid = queued_by.docs[0].uid; + // The same uid and recovery folder in another session. + let mut other = dirty_session(); + other.recovery_dir = Some(dir.path().to_path_buf()); + other.docs[0].uid = uid; + let held = testing::hold_next_write(dir.path()); + queued_by.execute("file.recovery.save", &json!({"background": true})).unwrap(); + held.wait_until_held(); + let elsewhere = tempfile::tempdir().unwrap(); + other.execute("file.saveAs", &json!({"path": elsewhere.path().join("other.designcraft").to_string_lossy()})).unwrap(); + assert!(!worker::cancelled(dir.path(), uid), "the other session's save cancelled this write"); + held.release(); + assert_eq!(finished_writes(&mut queued_by), 1); + assert!(files(dir.path(), uid).0.exists(), "this session's snapshot was kept"); + discard(dir.path(), uid); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn a_write_now_cancels_a_background_write_to_the_same_folder_spelled_another_way() { From c3a7deb21a34dc119198318049bff119aa32694a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 23:23:50 -0800 Subject: [PATCH 0993/1349] Render: satin on an image compares partial coverage Satin on a frame holding a graphic draws the object's coverage once offscreen and compares the two shifted copies pixel by pixel, taking the difference of their coverages. A partly transparent area that both copies cover equally gets no plain satin, so a uniformly half-transparent image no longer shows satin across its middle. Inverted satin keeps the object's coverage where the copies agree. The offscreen coverage for satin and for a center inner glow on a graphic now covers its whole area at a lower resolution when it would be wider than the largest raster side or hold more than 4096 x 4096 pixels. --- crates/render/src/fx.rs | 204 +++++++++++++++++++++++++++++++--------- 1 file changed, 162 insertions(+), 42 deletions(-) diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index 6e49577e4..ec4e1e60a 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -13,7 +13,8 @@ //! opacity rides on the filter colour's alpha. //! - Inner shadow: the inverse of the offset shape, blurred, clipped to the shape, on top. //! - Inner glow, bevel and emboss, satin: built like the inner shadow (an offset inverse of the -//! shape, blurred and clipped) with screen / multiply blending; satin XORs two offset copies. +//! shape, blurred and clipped) with screen / multiply blending; satin shows where two offset +//! copies' coverages differ. //! - Feather: the object is masked by its shape inset by half the width and blurred, so the //! edge fades from ~0 at the path to full strength `width` inside. @@ -273,7 +274,7 @@ impl Renderer { let band = (bound(g.size) - choke).max(0.5); self.with_blended_filters(ctx, f, reach, sigma, mix, (bp, xf), |me, c, fr| { let spread = (sigma * 3.0 + band) / fr.px + 2.0; - let Some(o) = offscreen(fr.view.transform_rect_bbox(reach), spread, c.width(), c.height()) else { return }; + let Some(o) = mask_offscreen(fr.view.transform_rect_bbox(reach), spread, c.width(), c.height()) else { return }; let mut off = RenderContext::new_with(o.width, o.height, vello_cpu::RenderSettings { num_threads: 0, ..Default::default() }); let view = Affine::scale(1.0 / o.scale) * Affine::translate((-o.x0, -o.y0)) * fr.view; me.draw_body(&mut off, &Frame { mt: false, view, px: fr.px * o.scale, ..*fr }, it, bp, xf, page); @@ -337,41 +338,32 @@ impl Renderer { let sigma = bound(st.size).max(0.0) / 2.0; let paint = color_of(&c, st.opacity.clamp(0.0, 1.0)); let invert = st.invert; - self.with_blended_filters(ctx, f, reach, sigma, Mix::Multiply, (bp, xf), |me, c, fr| { - // One copy of the shape moved by `by`: the shape in the satin colour, or what the - // object paints (coloured below). - let copy = |me: &mut Renderer, c: &mut RenderContext, by: Vec2| match painted { - Some((it, page)) => { - let moved = Frame { view: fr.view * Affine::translate(by), ..*fr }; - me.draw_body(c, &moved, it, bp, xf, page); - } - None => { - c.set_transform(fr.view * Affine::translate(by) * xf); - c.set_paint(paint); - c.fill_path(bp); - } - }; - c.set_transform(fr.view); - if painted.is_some() { + if let Some((it, page)) = painted { + // With a graphic, the object's coverage is drawn once offscreen and the two shifted + // copies are compared there, pixel by pixel, so a partly transparent pixel that + // both copies cover equally gets no satin. + self.with_blended_filters(ctx, f, reach, sigma, Mix::Multiply, (bp, xf), |me, c, fr| { + // The copies' shift on the device. + let shift = fr.view * off.to_point() - fr.view * kurbo::Point::ZERO; + let spread = (sigma * 3.0) / fr.px + shift.hypot() + 2.0; + let Some(o) = mask_offscreen(fr.view.transform_rect_bbox(reach), spread, c.width(), c.height()) else { return }; + let mut off_ctx = RenderContext::new_with(o.width, o.height, vello_cpu::RenderSettings { num_threads: 0, ..Default::default() }); + let view = Affine::scale(1.0 / o.scale) * Affine::translate((-o.x0, -o.y0)) * fr.view; + me.draw_body(&mut off_ctx, &Frame { mt: false, view, px: fr.px * o.scale, ..*fr }, it, bp, xf, page); + off_ctx.flush(); + let mut pm = vello_cpu::Pixmap::new(o.width, o.height); + off_ctx.render(&mut pm, &mut me.resources); + let mask = satin_mask(&pm, shift / o.scale, invert); + // The satin colour where the copies differ, ... + c.set_transform(fr.view); c.push_layer(None, None, None, None, None); - } - c.push_layer(None, None, None, None, Some(blur(sigma))); - if painted.is_some() { - c.push_layer(None, None, None, None, None); - } - if invert { - copy(me, c, Vec2::ZERO); - } - c.set_transform(Affine::IDENTITY); - c.push_layer(None, Some(BlendMode::new(Mix::Normal, if invert { Compose::DestOut } else { Compose::SrcOver })), None, None, None); - copy(me, c, off); - c.set_transform(Affine::IDENTITY); - c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::Xor)), None, None, None); - copy(me, c, -off); - c.pop_layer(); - c.pop_layer(); - if let Some((it, page)) = painted { - // The satin colour where the copies cover, ... + c.push_layer(None, None, None, None, Some(blur(sigma))); + c.set_transform(Affine::translate((o.x0, o.y0)) * Affine::scale(o.scale)); + c.set_paint(vello_cpu::Image { + image: vello_cpu::ImageSource::Pixmap(std::sync::Arc::new(mask)), + sampler: peniko::ImageSampler::default(), + }); + c.fill_rect(&Rect::new(0.0, 0.0, f64::from(o.width), f64::from(o.height))); let pad = sigma * 4.0 + off.hypot() + 4.0 * fr.px; c.set_transform(Affine::IDENTITY); c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::SrcIn)), None, None, None); @@ -380,15 +372,37 @@ impl Renderer { c.fill_rect(&reach.inflate(pad, pad)); c.pop_layer(); c.pop_layer(); - c.pop_layer(); // ... blurred and kept only where the object paints. c.set_transform(Affine::IDENTITY); c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestIn)), None, None, None); me.draw_body(c, fr, it, bp, xf, page); c.pop_layer(); - } - c.pop_layer(); - }); + c.pop_layer(); + }); + } else { + self.with_blended_filters(ctx, f, reach, sigma, Mix::Multiply, (bp, xf), |_, c, fr| { + // One copy of the shape in the satin colour, moved by `by`. + let copy = |c: &mut RenderContext, by: Vec2| { + c.set_transform(fr.view * Affine::translate(by) * xf); + c.set_paint(paint); + c.fill_path(bp); + }; + c.set_transform(fr.view); + c.push_layer(None, None, None, None, Some(blur(sigma))); + if invert { + copy(c, Vec2::ZERO); + } + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, if invert { Compose::DestOut } else { Compose::SrcOver })), None, None, None); + copy(c, off); + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::Xor)), None, None, None); + copy(c, -off); + c.pop_layer(); + c.pop_layer(); + c.pop_layer(); + }); + } } // Bevel and Emboss (inner bevel): highlight from the lit side, shadow from the other. if e.bevel.on { @@ -583,6 +597,26 @@ fn offscreen(reach: Rect, spread: f64, width: u16, height: u16) -> Option= 1.0 && h >= 1.0).then_some(Offscreen { x0, y0, scale, width: w as u16, height: h as u16 }) } +/// The most pixels a coverage mask drawn offscreen ([`mask_offscreen`]) holds: 4096 × 4096. +const MAX_MASK_PIXELS: f64 = 4096.0 * 4096.0; + +/// The offscreen image an object's coverage is drawn in to build an effect's mask: `reach` (device +/// pixels) widened by `spread`, within the window widened the same way, as [`offscreen`] finds it, +/// at a resolution low enough that the whole area fits within [`crate::MAX_SIDE`] a side and +/// [`MAX_MASK_PIXELS`] in all. `None` when none of it shows. +fn mask_offscreen(reach: Rect, spread: f64, width: u16, height: u16) -> Option { + let screen = Rect::new(0.0, 0.0, f64::from(width), f64::from(height)).inflate(spread, spread); + let r = reach.inflate(spread, spread).intersect(screen); + let (x0, y0) = (r.x0.floor(), r.y0.floor()); + let (w, h) = (r.x1.ceil() - x0, r.y1.ceil() - y0); + if !(w >= 1.0 && h >= 1.0) { + return None; + } + let scale = (spread / MAX_BLUR_SPREAD).max(1.0).max(w.max(h) / crate::MAX_SIDE as f64).max((w * h / MAX_MASK_PIXELS).sqrt()); + let side = |len: f64| (len / scale).ceil().clamp(1.0, crate::MAX_SIDE as f64); + Some(Offscreen { x0, y0, scale, width: side(w) as u16, height: side(h) as u16 }) +} + /// `pm`'s coverage shrunk by `r` pixels: each pixel takes the smallest alpha among itself and the /// points on circles of `r` and `r / 2` around it, as white premultiplied by that alpha. Pixels /// outside `pm` count as transparent. @@ -607,6 +641,35 @@ fn erode(pm: &vello_cpu::Pixmap, r: f64) -> vello_cpu::Pixmap { vello_cpu::Pixmap::from_parts(data, pm.width(), pm.height()) } +/// The satin coverage of `pm`'s two copies moved by `shift` and `-shift` pixels: at each pixel, +/// how much the copies' coverages differ, or with `invert`, `pm`'s own coverage where they +/// agree, as white premultiplied by that amount. Copies are sampled bilinearly; pixels outside +/// `pm` count as transparent. +fn satin_mask(pm: &vello_cpu::Pixmap, shift: Vec2, invert: bool) -> vello_cpu::Pixmap { + let (w, h) = (i64::from(pm.width()), i64::from(pm.height())); + let src = pm.data(); + let alpha = |x: i64, y: i64| if x < 0 || y < 0 || x >= w || y >= h { 0.0 } else { f64::from(src[(y * w + x) as usize].a) / 255.0 }; + let sample = |x: f64, y: f64| { + let (fx, fy) = (x.floor(), y.floor()); + let (tx, ty) = (x - fx, y - fy); + let (ix, iy) = (fx as i64, fy as i64); + let top = alpha(ix, iy) * (1.0 - tx) + alpha(ix.saturating_add(1), iy) * tx; + let bottom = alpha(ix, iy.saturating_add(1)) * (1.0 - tx) + alpha(ix.saturating_add(1), iy.saturating_add(1)) * tx; + top * (1.0 - ty) + bottom * ty + }; + let mut data = Vec::with_capacity(src.len()); + for y in 0..h { + for x in 0..w { + let (px, py) = (x as f64, y as f64); + let diff = (sample(px - shift.x, py - shift.y) - sample(px + shift.x, py + shift.y)).abs(); + let v = if invert { alpha(x, y) * (1.0 - diff) } else { diff }; + let a = (v.clamp(0.0, 1.0) * 255.0).round() as u8; + data.push(vello_cpu::color::PremulRgba8 { r: a, g: a, b: a, a }); + } + } + vello_cpu::Pixmap::from_parts(data, pm.width(), pm.height()) +} + #[cfg(test)] mod tests { #[test] @@ -641,6 +704,21 @@ mod tests { assert_eq!(offscreen(object, 15_002.0, 1440, 900), Some(wide)); } + /// A coverage mask covers the whole widened area at a lower resolution when it is wider than + /// `MAX_SIDE` or holds more than `MAX_MASK_PIXELS`; a small one stays at full resolution. + #[test] + fn a_coverage_mask_covers_its_whole_area_within_its_pixel_budget() { + let small = Offscreen { x0: 140.0, y0: 140.0, scale: 1.0, width: 220, height: 220 }; + assert_eq!(mask_offscreen(Rect::new(150.0, 150.0, 350.0, 350.0), 10.0, 1440, 900), Some(small)); + for (reach, w, h) in [(Rect::new(0.0, 0.0, 65_535.0, 100.0), u16::MAX, 100), (Rect::new(0.0, 0.0, 20_000.0, 20_000.0), 20_000, 20_000)] { + let o = mask_offscreen(reach, 10.0, w, h).unwrap(); + assert_eq!((o.x0, o.y0), (-10.0, -10.0)); + assert!(o.x0 + f64::from(o.width) * o.scale >= reach.x1 + 10.0, "{o:?}"); + assert!(o.y0 + f64::from(o.height) * o.scale >= reach.y1 + 10.0, "{o:?}"); + assert!(f64::from(o.width) * f64::from(o.height) <= MAX_MASK_PIXELS + f64::from(o.width) + f64::from(o.height), "{o:?}"); + } + } + /// An inner shadow on a frame holding an image whose left half is transparent: the shadow /// lines the image's opaque part (its edge in the middle of the frame), not only the frame. #[test] @@ -686,6 +764,43 @@ mod tests { } } + /// Satin on a frame holding a uniformly half-transparent image: where both copies cover the + /// same partial coverage (all of the image with a distance of 0, its middle with a short one), + /// plain satin leaves the image as it is; inverted satin shades it. + #[test] + fn satin_leaves_a_uniform_half_transparent_image_plain() { + for (distance, invert) in [(0.0, false), (40.0, false), (0.0, true)] { + let (d, mut it) = image_frame(|_| image::Rgba([255, 255, 255, 128])); + let s = &mut it.effects.satin; + s.on = true; + s.color = "[Black]".into(); + s.opacity = 1.0; + s.angle = 0.0; + s.distance = distance; + s.size = 4.0; + s.invert = invert; + let lum = render_row(d, it); + // The image is white over a white page; satin multiplies black over it. + let shaded = lum(200) < 700; + assert_eq!(shaded, invert, "distance {distance}, invert {invert}: lum at x = 200 is {}", lum(200)); + } + } + + /// The satin mask is the difference of the shifted coverages: none where both copies cover the + /// same half coverage, half along an edge only one copy reaches, and the inverse keeps the + /// pixmap's own coverage where they agree. + #[test] + fn the_satin_mask_compares_partial_coverage() { + let half = vello_cpu::color::PremulRgba8 { r: 128, g: 128, b: 128, a: 128 }; + let pm = vello_cpu::Pixmap::from_parts(vec![half; 40 * 40], 40, 40); + let plain = satin_mask(&pm, Vec2::new(3.0, 0.0), false); + assert_eq!(plain.sample(20, 20).a, 0); + assert_eq!(plain.sample(1, 20).a, 128); + let inverted = satin_mask(&pm, Vec2::new(3.0, 0.0), true); + assert_eq!(inverted.sample(20, 20).a, 128); + assert_eq!(inverted.sample(1, 20).a, 64); + } + /// An inner glow from the center on a frame holding an image whose left half is transparent /// fills only the image's opaque part, fading toward that part's own edge. #[test] @@ -721,12 +836,17 @@ mod tests { /// A 200 pt frame at (100, 100) holding a 20 × 20 image with a transparent left half and an /// opaque white right half, in a new document. fn half_image_frame() -> (designcraft_doc::Document, Item) { + image_frame(|x| if x < 10 { image::Rgba([0, 0, 0, 0]) } else { image::Rgba([255, 255, 255, 255]) }) + } + + /// A 200 pt frame at (100, 100) holding a 20 × 20 image whose pixels in column x are + /// `pixel(x)`, in a new document. + fn image_frame(pixel: impl Fn(u32) -> image::Rgba) -> (designcraft_doc::Document, Item) { use designcraft_doc::Document; use designcraft_doc::build::NewDocument; let mut d = Document::new(&NewDocument::default()); let lid = d.default_layer(); - // 20 × 20: transparent left half, opaque white right half. - let img = image::RgbaImage::from_fn(20, 20, |x, _| if x < 10 { image::Rgba([0, 0, 0, 0]) } else { image::Rgba([255, 255, 255, 255]) }); + let img = image::RgbaImage::from_fn(20, 20, |x, _| pixel(x)); let mut png = Vec::new(); img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); let aid = designcraft_doc::AssetId(d.alloc()); From 8b7fea42fba13445b8f96d9693172f5b8a64bb6d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 23:39:39 -0800 Subject: [PATCH 0994/1349] Recovery: a write now leaves another session's background write of the same uid alone `recovery::save` and the tracked save cancelled every background write of the document's folder and uid, including one another session in the same process had queued. Both now cancel only their own session's writes, refuse while another session's write of that uid is queued or running, and keep other sessions' background writes of it from queuing until the write now is done. --- crates/engine/src/recovery.rs | 122 +++++++++++++++++++++++++--- crates/engine/src/recovery/tests.rs | 52 +++++++++++- 2 files changed, 161 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index 2a0422417..4f774b8d3 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -583,10 +583,33 @@ fn prepare_save(s: &Session, dir: &Path) -> Result { Ok(access) } +/// Refuse a write now while another session's background write of one of the dirty documents' +/// uids to `dir` is queued or running. A write now cancels only this session's writes. +#[cfg(not(target_arch = "wasm32"))] +fn check_no_other_write(s: &Session, dir: &Path) -> Result<()> { + let preview = s.new_document_preview(); + for document in s.docs.iter().filter(|d| d.is_dirty() && preview != Some(d.uid)) { + if worker::queued_by_other(dir, document.uid, s.recovery_owner.0) { + return Err(still_being_written(dir)); + } + } + Ok(()) +} + +#[cfg(not(target_arch = "wasm32"))] +fn still_being_written(dir: &Path) -> EngineError { + EngineError::Other(format!( + "{}: another document's recovery data is still being written here; try again or choose another recovery folder", + dir.display() + )) +} + /// Write recovery entries for dirty documents and drop clean checkpoints. Returns how many /// were written. Command callers use the tracked variant without configuring automatic recovery. pub fn save(s: &Session, dir: &Path) -> Result { let access = prepare_save(s, dir)?; + #[cfg(not(target_arch = "wasm32"))] + check_no_other_write(s, dir)?; let mut n = 0; for d in &s.docs { // New Document's preview is not a document until Create makes it one. @@ -601,9 +624,10 @@ pub fn save(s: &Session, dir: &Path) -> Result { continue; } // The caller asked for this write now: nothing has cancelled it. - // A background write of an older state must not land over this one. + // A background write of an older state this session queued must not land over this one, + // and no other session's write of the uid is queued until it is done. #[cfg(not(target_arch = "wasm32"))] - worker::cancel(dir, d.uid); + let _now = worker::write_now(dir, d.uid, s.recovery_owner.0).ok_or_else(|| still_being_written(dir))?; if let Some(e) = write_snapshot(&Snapshot::of(&access, dir, d), || false).error { return Err(e); } @@ -617,6 +641,8 @@ pub fn save(s: &Session, dir: &Path) -> Result { pub(crate) fn save_tracked(s: &mut Session, dir: &Path) -> Result { reject_overfull_checkpoints(s, dir)?; let access = prepare_save(s, dir)?; + #[cfg(not(target_arch = "wasm32"))] + check_no_other_write(s, dir)?; let mut n = 0; let preview = s.new_document_preview(); for index in 0..s.docs.len() { @@ -629,9 +655,10 @@ pub(crate) fn save_tracked(s: &mut Session, dir: &Path) -> Result { continue; } let Some(document) = s.docs.get(index) else { continue }; - // A background write of an older state must not land over this one. + // A background write of an older state this session queued must not land over this one, + // and no other session's write of the uid is queued until it is done. #[cfg(not(target_arch = "wasm32"))] - worker::cancel(dir, document.uid); + let _now = worker::write_now(dir, document.uid, s.recovery_owner.0).ok_or_else(|| still_being_written(dir))?; let entry = Snapshot::of(&access, dir, document); let written = write_snapshot(&entry, || false); // The primary is the recovery data; its metadata is optional. Track the primary before @@ -980,6 +1007,9 @@ mod worker { /// A document saved, reverted or closed while its write was queued or running: the /// snapshot it is producing must not be published. cancelled: Mutex>, + /// Documents a session is writing now on its own thread, with that session: no background + /// write of one is queued until it is done (see [`write_now`]). + writing_now: Mutex>, /// Notified each time a write finishes and leaves `running`. idle: Condvar, } @@ -1131,6 +1161,48 @@ mod worker { dirs } + /// Whether a session other than `owner` has a write of `dir`/`uid` queued or running that + /// is not cancelled, or queued to follow one. + fn queued_by_other(&self, dir: &Path, uid: u64, owner: u64) -> bool { + let running = self.running.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + self.other_in_flight(&running, dir, uid, owner) + } + + /// [`Writer::queued_by_other`] with `running` held, counting writes now as well. + fn other_in_flight(&self, running: &BTreeMap<(PathBuf, u64), Queued>, dir: &Path, uid: u64, owner: u64) -> bool { + let canonical = key(dir, uid); + running + .iter() + .filter(|(k, q)| **k == canonical || (k.1 == uid && q.dir == dir)) + .any(|(k, q)| (q.owner != owner && !self.cancelled(k)) || q.next.as_ref().is_some_and(|n| n.owner != owner)) + || self.writing_now.lock().is_ok_and(|now| now.get(&canonical).is_some_and(|by| *by != owner)) + } + + /// Start a write now of `dir`/`uid` by session `owner`. Returns `None` while another + /// session's write of it is in flight. Otherwise cancels this session's writes of it (as + /// [`Writer::cancel`]) and records the write now under the returned key, all under one + /// hold of `running`. + fn write_now(&self, dir: &Path, uid: u64, owner: u64) -> Option<(PathBuf, u64)> { + let canonical = key(dir, uid); + let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut running = self.running.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if self.other_in_flight(&running, dir, uid, owner) { + return None; + } + let mut keys = Vec::new(); + for (k, q) in running.iter_mut().filter(|(k, q)| **k == canonical || (k.1 == uid && q.dir == dir)) { + q.next = None; + keys.push(k.clone()); + } + if let Ok(mut cancelled) = self.cancelled.lock() { + cancelled.extend(keys); + } + if let Ok(mut now) = self.writing_now.lock() { + now.insert(canonical.clone(), owner); + } + Some(canonical) + } + /// `key` as in [`Writer::finish`]. fn cancelled(&self, key: &(PathBuf, u64)) -> bool { self.cancelled.lock().is_ok_and(|cancelled| cancelled.contains(key)) @@ -1172,6 +1244,7 @@ mod worker { undelivered: Mutex::new(Vec::new()), running: Mutex::new(BTreeMap::new()), cancelled: Mutex::new(BTreeSet::new()), + writing_now: Mutex::new(BTreeMap::new()), idle: Condvar::new(), }) }) @@ -1183,20 +1256,41 @@ mod worker { WRITER.get().and_then(Option::as_ref) } - /// Do not publish the snapshot being written for `dir`/`uid` (see [`Writer::cancel`]). - pub(super) fn cancel(dir: &Path, uid: u64) { - if let Some(w) = started() { - w.cancel(dir, uid, None); - } - } - - /// [`cancel`] for the writes session `owner` queued. + /// Do not publish the snapshot session `owner` is having written for `dir`/`uid` (see + /// [`Writer::cancel`]). pub(super) fn cancel_owned(dir: &Path, uid: u64, owner: u64) { if let Some(w) = started() { w.cancel(dir, uid, Some(owner)); } } + /// A write now in progress; dropping it lets background writes of its document queue again. + pub(super) struct WriteNow(Option<(PathBuf, u64)>); + + impl Drop for WriteNow { + fn drop(&mut self) { + if let (Some(key), Some(w)) = (self.0.take(), started()) + && let Ok(mut now) = w.writing_now.lock() + { + now.remove(&key); + } + } + } + + /// See [`Writer::write_now`]. `None` while another session's write of `dir`/`uid` is in + /// flight. Without a writer thread there are no background writes to wait for. + pub(super) fn write_now(dir: &Path, uid: u64, owner: u64) -> Option { + match writer() { + Some(w) => w.write_now(dir, uid, owner).map(|key| WriteNow(Some(key))), + None => Some(WriteNow(None)), + } + } + + /// See [`Writer::queued_by_other`]. + pub(super) fn queued_by_other(dir: &Path, uid: u64, owner: u64) -> bool { + started().is_some_and(|w| w.queued_by_other(dir, uid, owner)) + } + /// See [`Writer::pending_folders`]. pub(super) fn pending_folders(uid: u64, owner: u64) -> Vec { started().map(|w| w.pending_folders(uid, owner)).unwrap_or_default() @@ -1238,6 +1332,10 @@ mod worker { let w = writer()?; let mut running = w.running.lock().ok()?; let key = (entry.key.clone(), entry.uid); + // A session is writing this document now: this write waits for a later turn. + if w.writing_now.lock().is_ok_and(|now| now.contains_key(&key)) { + return Some(false); + } if let Some(q) = running.get_mut(&key) { // The write in flight was cancelled (the document was saved since), so it holds // nothing to recover: this one follows it, in place of any that was waiting. diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index d1d03f162..a45cea1ce 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -336,6 +336,56 @@ fn saving_in_one_session_leaves_another_sessions_write_to_the_same_folder_alone( discard(dir.path(), uid); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_write_now_in_one_session_leaves_another_sessions_write_of_the_same_uid_alone() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut queued_by = dirty_session(); + queued_by.recovery_dir = Some(dir.path().to_path_buf()); + let uid = queued_by.docs[0].uid; + // The same uid in another session, with two objects instead of one. + let mut other = dirty_session(); + other.docs[0].uid = uid; + other.execute("frame.create", &json!({"rect": [20, 20, 60, 60]})).unwrap(); + let held = testing::hold_next_write(dir.path()); + queued_by.execute("file.recovery.save", &json!({"background": true})).unwrap(); + held.wait_until_held(); + let err = save(&other, dir.path()).unwrap_err(); + assert!(err.to_string().contains("still being written"), "{err}"); + let err = other.execute("file.recovery.save", &json!({"dir": dir.path().to_string_lossy()})).unwrap_err(); + assert!(err.to_string().contains("still being written"), "{err}"); + assert!(!worker::cancelled(dir.path(), uid), "the other session's write now cancelled this write"); + held.release(); + assert_eq!(finished_writes(&mut queued_by), 1); + let mut reopened = Session::new(); + assert_eq!(open(&mut reopened, dir.path()).unwrap().len(), 1); + assert_eq!(reopened.doc().unwrap().doc.spreads[0].items.len(), 1, "the queued session's snapshot was kept"); + discard(dir.path(), reopened.doc().unwrap().uid); + discard(dir.path(), uid); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn no_other_sessions_write_of_the_uid_is_queued_during_a_write_now() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let writing = dirty_session(); + let uid = writing.docs[0].uid; + let mut other = dirty_session(); + other.recovery_dir = Some(dir.path().to_path_buf()); + other.docs[0].uid = uid; + let now = worker::write_now(dir.path(), uid, writing.recovery_owner.0).expect("nothing else is in flight"); + let queued = other.execute("file.recovery.save", &json!({"background": true})).unwrap(); + assert_eq!(queued["queued"], 0, "another session's write was queued during the write now: {queued}"); + assert!(worker::write_now(dir.path(), uid, other.recovery_owner.0).is_none(), "a second write now of the uid started"); + drop(now); + let queued = other.execute("file.recovery.save", &json!({"background": true})).unwrap(); + assert_eq!(queued["queued"], 1, "{queued}"); + assert_eq!(finished_writes(&mut other), 1); + discard(dir.path(), uid); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn a_write_now_cancels_a_background_write_to_the_same_folder_spelled_another_way() { @@ -733,7 +783,7 @@ fn a_cancel_stops_a_write_before_the_package_is_finished() { fn only_a_queued_write_is_cancelled() { // A mark for a document with no write in flight would stay in the writer's set for ever. let dir = tempfile::tempdir().unwrap(); - worker::cancel(dir.path(), 7); + worker::cancel_owned(dir.path(), 7, 1); assert!(!worker::cancelled(dir.path(), 7), "nothing was queued for it"); } From 7af4d75539a3618ed0fbddabf5e044777101e748 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 00:00:46 -0800 Subject: [PATCH 0995/1349] Render: plain satin with no distance on an image is not drawn Both shifted copies are the same at distance 0, so the coverage mask is empty. The effect is now skipped before the image is drawn offscreen and scanned. --- crates/render/src/fx.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index ec4e1e60a..9fae7d2e1 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -329,8 +329,10 @@ impl Renderer { } } // Satin: the shape shifted both ways along the angle, blurred, where exactly one covers. - // With a graphic, the shape is what the object paints, as for the inner shadow. + // With a graphic, the shape is what the object paints, as for the inner shadow. Plain + // satin on a graphic with no distance compares two equal copies and is not drawn. if e.satin.on + && !(painted.is_some() && !e.satin.invert && e.satin.distance == 0.0) && let Some(c) = doc.resolve_color(&e.satin.color, 1.0) { let st = &e.satin; From 5932810b1f302d2de2f957afd3f7a576aa3038ac Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 00:04:46 -0800 Subject: [PATCH 0996/1349] Render: a center inner glow on an image fades around small transparent holes The coverage was eroded by sampling two rings of points, which could miss a hole smaller than the gaps between them. Erosion now takes the smallest alpha within an octagon of the band's radius, in four passes along the axes and the diagonals. --- crates/render/src/fx.rs | 91 +++++++++++++++++++++++++++++++++-------- 1 file changed, 73 insertions(+), 18 deletions(-) diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index 9fae7d2e1..e74630644 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -619,28 +619,67 @@ fn mask_offscreen(reach: Rect, spread: f64, width: u16, height: u16) -> Option vello_cpu::Pixmap { - let (w, h) = (i64::from(pm.width()), i64::from(pm.height())); - let src = pm.data(); - let mut taps = vec![(0_i64, 0_i64)]; - for k in 0..16_u8 { - let d = if k % 2 == 0 { r } else { r / 2.0 }; - let a = f64::from(k) * std::f64::consts::PI / 8.0; - taps.push(((a.cos() * d).round() as i64, (a.sin() * d).round() as i64)); + let (w, h) = (pm.width() as usize, pm.height() as usize); + let radius = r.max(0.0).round().min(f64::from(u16::MAX)) as usize; + // The octagon is a square of half-width `side` widened by `diag` diagonal steps each way along + // both diagonals, so it reaches `radius` along the axes and about `radius` diagonally. + let diag = (radius as f64 * (1.0 - std::f64::consts::FRAC_1_SQRT_2)).round() as usize; + let side = radius.saturating_sub(2 * diag); + let mut alpha: Vec = pm.data().iter().map(|p| p.a).collect(); + for (step, k) in [((1, 0), side), ((0, 1), side), ((1, 1), diag), ((1, -1), diag)] { + alpha = erode_lines(&alpha, w, h, step, k); } - taps.dedup(); - let alpha = |x: i64, y: i64| if x < 0 || y < 0 || x >= w || y >= h { 0 } else { src[(y * w + x) as usize].a }; - let mut data = Vec::with_capacity(src.len()); - for y in 0..h { - for x in 0..w { - let a = taps.iter().map(|&(dx, dy)| alpha(x.saturating_add(dx), y.saturating_add(dy))).min().unwrap_or(0); - data.push(vello_cpu::color::PremulRgba8 { r: a, g: a, b: a, a }); + let data = alpha.into_iter().map(|a| vello_cpu::color::PremulRgba8 { r: a, g: a, b: a, a }).collect(); + vello_cpu::Pixmap::from_parts(data, pm.width(), pm.height()) +} + +/// `src` (`w` × `h`, row by row) with each value replaced by the smallest within `k` steps of it +/// along the lines that `step` walks. Steps past the edge count as 0. +fn erode_lines(src: &[u8], w: usize, h: usize, step: (isize, isize), k: usize) -> Vec { + if k == 0 { + return src.to_vec(); + } + let inside = |x: isize, y: isize| x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h; + let mut out = vec![0; src.len()]; + let mut line = Vec::new(); + let mut window = std::collections::VecDeque::new(); + for y in 0..h as isize { + for x in 0..w as isize { + // Each line starts at the pixel whose step back leaves the image. + if inside(x - step.0, y - step.1) { + continue; + } + line.clear(); + let (mut cx, mut cy) = (x, y); + while inside(cx, cy) { + line.push(cy as usize * w + cx as usize); + (cx, cy) = (cx + step.0, cy + step.1); + } + // A running minimum over each pixel's window, with the values still in it in rising order. + window.clear(); + let mut next = 0; + for i in 0..line.len() { + while next < line.len() && next <= i + k { + let v = src[line[next]]; + while window.back().is_some_and(|&(_, b)| b >= v) { + window.pop_back(); + } + window.push_back((next, v)); + next += 1; + } + while window.front().is_some_and(|&(j, _)| j + k < i) { + window.pop_front(); + } + let whole = i >= k && i + k < line.len(); + out[line[i]] = if whole { window.front().map_or(0, |&(_, v)| v) } else { 0 }; + } } } - vello_cpu::Pixmap::from_parts(data, pm.width(), pm.height()) + out } /// The satin coverage of `pm`'s two copies moved by `shift` and `-shift` pixels: at each pixel, @@ -835,6 +874,22 @@ mod tests { assert_eq!(out.sample(6, 20).a, 128); } + /// Eroding clears every pixel within the radius of a one-pixel hole, along the axes and the + /// diagonals, and keeps the pixels beyond it. + #[test] + fn erosion_clears_around_a_small_hole() { + let opaque = vello_cpu::color::PremulRgba8 { r: 255, g: 255, b: 255, a: 255 }; + let mut data = vec![opaque; 40 * 40]; + data[20 * 40 + 20] = vello_cpu::color::PremulRgba8 { r: 0, g: 0, b: 0, a: 0 }; + let out = erode(&vello_cpu::Pixmap::from_parts(data, 40, 40), 5.0); + for (x, y) in [(20, 20), (24, 20), (16, 20), (20, 24), (20, 16), (23, 23), (17, 17), (23, 17), (17, 23)] { + assert_eq!(out.sample(x, y).a, 0, "({x}, {y}) is within 5 pixels of the hole"); + } + for (x, y) in [(27, 20), (20, 13), (25, 25), (14, 14)] { + assert_eq!(out.sample(x, y).a, 255, "({x}, {y}) is more than 5 pixels from the hole"); + } + } + /// A 200 pt frame at (100, 100) holding a 20 × 20 image with a transparent left half and an /// opaque white right half, in a new document. fn half_image_frame() -> (designcraft_doc::Document, Item) { From 915be8561e804b9a4dd278cd7a47ca19ad5eb054 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 00:05:58 -0800 Subject: [PATCH 0997/1349] Paste: an image past the size limit is refused before its pixels are copied ClipboardImage::from_color_image checks the size before it copies the pixels, so an image egui delivers with Ctrl/Cmd+V that is over 64 million pixels is not copied before the paste refuses it. --- crates/ui-egui/src/canvas/tests.rs | 20 ++++++++++++++++++++ crates/ui-egui/src/services.rs | 9 +++++++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 5b3f796dc..88a526d9d 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1200,6 +1200,26 @@ fn the_paste_keys_place_an_image_in_the_selected_empty_frame_but_not_in_text() { assert!(h.state().ui.status.contains("stop editing the text"), "{}", h.state().ui.status); } +#[test] +fn a_paste_keys_image_past_the_size_limit_is_refused_without_copying_its_pixels() { + // The size says 72 million pixels; the four pixels it holds are not copied. + let big = egui::ColorImage { size: [9000, 8000], source_size: egui::vec2(9000.0, 8000.0), pixels: vec![egui::Color32::RED; 4] }; + let image = crate::ClipboardImage::from_color_image(&big); + let crate::ClipboardImage::Pixels { width, height, rgba } = &image else { panic!("a bitmap") }; + assert_eq!((*width, *height, rgba.len()), (9000, 8000, 0)); + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let items = app.session.doc().unwrap().doc.spreads[0].items.len(); + assert!(app.paste_clipboard_image(image).is_err()); + assert_eq!(app.session.doc().unwrap().doc.spreads[0].items.len(), items); + assert!(app.ui.status.contains("64 million"), "{}", app.ui.status); + // An image within the limit keeps its pixels. + let small = crate::ClipboardImage::from_color_image(&egui::ColorImage::filled([3, 2], egui::Color32::RED)); + let crate::ClipboardImage::Pixels { width, height, rgba } = small else { panic!("a bitmap") }; + assert_eq!((width, height), (3, 2)); + assert_eq!(rgba, [255, 0, 0, 255].repeat(6)); +} + #[test] fn selected_merged_owners_paint_the_same_row_and_column_targets() { for column in [true, false] { diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index fd529ac42..c2a181be1 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -21,10 +21,15 @@ pub enum ClipboardImage { } impl ClipboardImage { - /// An image egui delivered with Ctrl/Cmd+V (`Event::PasteImage`). + /// An image egui delivered with Ctrl/Cmd+V (`Event::PasteImage`). The pixels of an image + /// past the paste limit are not copied, and pasting it is refused by its size. pub fn from_color_image(image: &egui::ColorImage) -> Self { - let rgba = image.pixels.iter().flat_map(|c| c.to_srgba_unmultiplied()).collect(); let [w, h] = image.size.map(|n| u32::try_from(n).unwrap_or(u32::MAX)); + let rgba = if designcraft_engine::cmd::check_pasted_size(w, h).is_ok() { + image.pixels.iter().flat_map(|c| c.to_srgba_unmultiplied()).collect() + } else { + Vec::new() + }; ClipboardImage::Pixels { width: w, height: h, rgba } } } From 3efde54ae9354f02adf61de979697931a49d1d24 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 00:08:50 -0800 Subject: [PATCH 0998/1349] Recovery: opening the recovery folder leaves this session's unfinished background writes alone A background write that is running, or that finished before the session took its result, is not in the document's entries yet. Opening recovery from that folder reopened it as a second copy of the live document. It is now skipped. The PUBLISH doc comment names the functions that take the lock. --- crates/engine/src/recovery.rs | 8 +++++++- crates/engine/src/recovery/tests.rs | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index 4f774b8d3..d045b2415 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -1532,7 +1532,7 @@ fn publish_recovery_file(path: &Path, bytes: &[u8], replace: bool) -> Result<()> } /// Serializes the last check for a cancelled write with the rename that publishes it, and with -/// [`worker::cancel`]. +/// [`worker::cancel_owned`] and [`worker::cancel_document`]. #[cfg(not(target_arch = "wasm32"))] static PUBLISH: std::sync::Mutex<()> = std::sync::Mutex::new(()); @@ -1755,6 +1755,12 @@ fn open_with_publisher(s: &mut Session, dir: &Path, mut publish: impl FnMut(&Pat }) { continue; } + // A background write of this session that is running, or finished with its result not + // taken yet, is a live document's checkpoint, not an entry to recover. + #[cfg(not(target_arch = "wasm32"))] + if worker::pending_folders(uid, owner).iter().any(|pending| directory_key(pending).is_ok_and(|key| key == source_key)) { + continue; + } #[cfg(not(target_arch = "wasm32"))] validate_recovery_dir(dir)?; let (doc, _) = files(dir, uid); diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index a45cea1ce..f66d28879 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -242,6 +242,24 @@ fn saving_removes_a_finished_write_to_a_named_folder_whose_result_was_not_taken( assert!(list(named.path()).is_empty()); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn opening_recovery_leaves_a_finished_background_write_whose_result_was_not_taken() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut s = dirty_session(); + s.recovery_dir = Some(dir.path().to_path_buf()); + let uid = s.docs[0].uid; + s.execute("file.recovery.save", &json!({"background": true})).unwrap(); + testing::wait_until_idle(); + assert!(files(dir.path(), uid).0.exists(), "the write finished"); + assert!(open(&mut s, dir.path()).unwrap().is_empty(), "the live document's own snapshot is not recovered"); + assert_eq!(s.docs.len(), 1); + assert_eq!(finished_writes(&mut s), 1); + assert_eq!(list(dir.path()).len(), 1); + discard(dir.path(), uid); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn an_edit_after_a_save_is_written_after_the_cancelled_write_stops() { From 346a0b24a291b41c4d68f8aa35fda234fd1e630e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 00:12:21 -0800 Subject: [PATCH 0999/1349] Paste: objects copied over empty clipboard text paste from the menu With a native menu, Copy saved the clipboard's empty text as the copy's text, so the next Paste took the older image, which the paste then skipped, and nothing was pasted. Empty text now counts as no text at the copy, as it does at the paste. --- crates/ui-egui/src/app/commands.rs | 3 ++- crates/ui-egui/src/canvas/tests.rs | 8 ++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index dc0326172..0255bd189 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -53,7 +53,8 @@ impl DesignApp { self.object_clip_text.clone() } None => { - self.object_clip_text = self.services.clipboard_text.as_mut().and_then(|f| f()); + // Empty text counts as no text, as Paste reads it. + self.object_clip_text = self.services.clipboard_text.as_mut().and_then(|f| f()).filter(|t| !t.is_empty()); self.object_clip_change = self.services.clipboard_change.as_mut().and_then(|f| f()); None } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 88a526d9d..7bca97710 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1152,6 +1152,14 @@ fn objects_copied_here_still_paste_as_objects_until_another_image_is_copied() { copy_elsewhere(&clip, Some(url), Some((5, 5))); crate::menus::activate(&mut app, "edit.paste", &Value::Null); assert_eq!(pasted_image(&app).map(|(px, _)| px), Some((5, 5)), "the image copied again with the same address"); + // Empty text beside the older image counts as no text at the copy too. + copy_elsewhere(&clip, Some(""), Some((7, 7))); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + crate::menus::activate(&mut app, "edit.copy", &Value::Null); + let items = app.session.doc().unwrap().doc.spreads[0].items.len(); + crate::menus::activate(&mut app, "edit.paste", &Value::Null); + assert_eq!(app.session.doc().unwrap().doc.spreads[0].items.len(), items + 1, "the copied text frame is pasted"); + assert_eq!(pasted_image(&app), None); } #[test] From ed9980fec243e286368011f7fff16c9a55dd6bd2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 00:39:11 -0800 Subject: [PATCH 1000/1349] Paste: params text gives the pasted image's size as one point per pixel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit edit.pasteImage sizes a new frame as File › Place does, which reads a raster at one point per pixel and does not read a stored resolution. The params text and the comment said otherwise. --- crates/engine/src/cmd/paste_image.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/paste_image.rs b/crates/engine/src/cmd/paste_image.rs index ec29d78b0..6040d1b9e 100644 --- a/crates/engine/src/cmd/paste_image.rs +++ b/crates/engine/src/cmd/paste_image.rs @@ -28,7 +28,7 @@ pub fn specs() -> Vec { "Paste Image", [], None, - "{base64: an image file (PNG/JPEG/GIF/WebP/TIFF/BMP) as base64, name?: its name in the Links panel ending in an image extension (default \"Pasted image.png\"), spread?, at?: [x, y] (spread coords of the image's center; default the first page's center)} → {id, asset} — embedded; a selected empty frame takes the image, otherwise a new frame holds it at its stored resolution (72 ppi when none) and at most 60% of the page width", + "{base64: an image file (PNG/JPEG/GIF/WebP/TIFF/BMP) as base64, name?: its name in the Links panel ending in an image extension (default \"Pasted image.png\"), spread?, at?: [x, y] (spread coords of the image's center; default the first page's center)} → {id, asset} — embedded; a selected empty frame takes the image, otherwise a new frame holds it at one point per pixel, as File › Place sizes an image, and at most 60% of the page width", has_doc, paste_image )] @@ -140,8 +140,8 @@ fn paste_image(s: &mut Session, p: &Value) -> Result { Some(at) => at, None => sp.pages.first().map_or(Point::ZERO, |pg| pg.bounds().center()), }; - // The size File › Place gives it: the stored resolution (72 ppi when none), at most 60% of - // the page width. + // The size File › Place gives it: one point per pixel (`designcraft_images::natural_size`), at + // most 60% of the page width. let (nw, nh) = designcraft_render::natural_size(&bytes, 0).unwrap_or((f64::from(pw), f64::from(ph))); let w = nw.min(d.settings.page_width * 0.6); let h = nh * w / nw; From f87c24a1cda25c64ac49b575548e40fca9585065 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:27:18 -0500 Subject: [PATCH 1001/1349] PPTX export: bound the retained glyph-to-character maps * PPTX export: keep only the last four faces' glyph-to-character maps --- crates/pptx/src/fonts.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/crates/pptx/src/fonts.rs b/crates/pptx/src/fonts.rs index 27c976aaf..ed02ff297 100644 --- a/crates/pptx/src/fonts.rs +++ b/crates/pptx/src/fonts.rs @@ -15,6 +15,9 @@ pub struct RunFont { pub italic: bool, } +/// Faces whose glyph-to-character map is kept at once. +const MAX_REVERSE_MAPS: usize = 4; + #[derive(Default)] pub struct Fonts { names: HashMap, @@ -116,6 +119,11 @@ impl Fonts { /// The character a glyph shows (the lowest code point mapping to it). pub fn char_of(&mut self, face: &FontFace, gid: u32) -> Option { + // A face's reverse map can hold over a million entries; keeping one per face a bundle uses + // is unbounded, so only the last few stay (a rebuilt map answers the same). + if !self.reverse.contains_key(&face.id()) && self.reverse.len() >= MAX_REVERSE_MAPS { + self.reverse.clear(); + } let map = self.reverse.entry(face.id()).or_insert_with(|| { let mut m = HashMap::new(); for (c, g) in face.chars() { @@ -216,3 +224,26 @@ pub fn eot(face: &FontFace) -> Result, NoEmbed> { h.extend_from_slice(data); Ok(h) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_a_few_reverse_maps_are_kept_and_answers_do_not_change() { + let db = designcraft_fonts::FontDb::global(); + let mut fonts = Fonts::default(); + let mut last = None; + for style in ["Regular", "Bold", "Italic", "Bold Italic", "Semibold", "Light", "Black", "ExtraLight", "Medium", "SemiBold Italic"] { + let face = db.face("Source Serif 4", style); + let gid = face.glyph_for('A'); + assert_eq!(fonts.char_of(&face, gid), Some('A'), "{style}"); + assert!(fonts.reverse.len() <= MAX_REVERSE_MAPS); + last = Some((face, gid)); + } + // The map evicted earlier is rebuilt on demand with the same answer. + if let Some((face, gid)) = last { + assert_eq!(fonts.char_of(&face, gid), Some('A')); + } + } +} From 23465223bc655a4177282f8c3a33a55693751226 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:27:24 -0500 Subject: [PATCH 1002/1349] xtask: refuse an oversized corpus archive before extracting it * xtask: refuse a corpus archive that expands past the cap before extracting it * address review: a within-cap answer needs tar to exit successfully * Apply review fixes - xtask/src/main.rs --------- Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com> --- xtask/src/main.rs | 52 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 19f8557ad..0ce6b1974 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -273,6 +273,30 @@ fn dir_bytes(dir: &std::path::Path) -> u64 { total } +/// Whether the file bytes of the tar.gz at `tgz` add up to at most `max`, found by streaming them +/// through `tar -xzOf` and counting: nothing is written to disk, and a decompression bomb is cut +/// off (the child is killed) as soon as it passes `max`. +fn expands_within(tgz: &Path, max: u64) -> Result { + use std::io::Read; + let mut child = Command::new("tar") + .arg("-xzOf") + .arg(tgz) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .map_err(|e| format!("tar -xzOf: failed to spawn: {e}"))?; + let Some(out) = child.stdout.take() else { return Err("tar -xzOf: no stdout".into()) }; + let n = std::io::copy(&mut out.take(max.saturating_add(1)), &mut std::io::sink()).map_err(|e| format!("tar -xzOf: {e}"))?; + if n > max { + let _ = child.kill(); + let _ = child.wait(); + return Ok(false); + } + // Within the cap only counts when tar read the whole archive: an early exit proves nothing. + let status = child.wait().map_err(|e| format!("tar -xzOf: {e}"))?; + if status.success() { Ok(true) } else { Err(format!("tar -xzOf {} failed ({status}); archive refused", tgz.display())) } +} + fn cmd_corpus(download: bool) -> Result<(), String> { let corpus = root().join("corpus"); println!( @@ -309,6 +333,11 @@ Tests that use a corpus skip cleanly when it is absent. if !listing.status.success() || listing.stdout.iter().filter(|b| **b == b'\n').count() > PNGSUITE_MAX_ENTRIES { return refuse(format!("the PngSuite download isn't a tar.gz of at most {PNGSUITE_MAX_ENTRIES} entries")); } + match expands_within(&tgz, PNGSUITE_MAX_EXTRACTED) { + Ok(true) => {} + Ok(false) => return refuse(format!("the PngSuite archive expands to more than {PNGSUITE_MAX_EXTRACTED} bytes; nothing was extracted")), + Err(e) => return refuse(e), + } let mut tar = Command::new("tar"); tar.arg("-xzf").arg(&tgz).arg("-C").arg(&dest); if let Err(e) = run(tar, "tar -xzf PngSuite-2017jul19.tgz") { @@ -324,3 +353,26 @@ Tests that use a corpus skip cleanly when it is absent. println!("PngSuite: {n} PNG files in {}", dest.display()); if n == 0 { Err("no PNG files extracted".into()) } else { Ok(()) } } + +#[cfg(test)] +mod corpus_tests { + use super::*; + + #[test] + fn a_tarball_that_expands_past_the_cap_is_refused_without_extracting() { + let dir = std::env::temp_dir().join(format!("dc-xtask-corpus-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("big"), vec![0u8; 100_000]).unwrap(); + let tgz = dir.join("a.tgz"); + let made = Command::new("tar").arg("-czf").arg(&tgz).arg("-C").arg(&dir).arg("big").status(); + if made.is_ok_and(|s| s.success()) { + assert_eq!(expands_within(&tgz, 100_000), Ok(true)); + assert_eq!(expands_within(&tgz, 99_999), Ok(false)); + // A truncated archive makes tar fail: not a within-cap answer. + let bytes = std::fs::read(&tgz).unwrap(); + std::fs::write(&tgz, &bytes[..bytes.len() / 2]).unwrap(); + assert!(expands_within(&tgz, 1 << 20).is_err()); + } + let _ = std::fs::remove_dir_all(&dir); + } +} From eb0ea78d9ad8fbea22361c1812f55303fbabe550 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:27:29 -0500 Subject: [PATCH 1003/1349] Images: a WebP with an ICC chunk longer than the file is read without its profile * Images: a WebP whose ICC chunk declares more than the file holds is read without it --- crates/images/src/lib.rs | 23 +++++++++++++++++++++++ crates/images/src/tests.rs | 27 +++++++++++++++++++++++++++ crates/pdf/src/export/images.rs | 6 ++++++ 3 files changed, 56 insertions(+) diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 83c540e6e..98c058aa6 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -433,9 +433,32 @@ pub fn decode_rgba(bytes: &[u8]) -> Option { to_display_rgba(px, Some(&icc), &DisplayColour::active()) } +/// False when `bytes` is a WebP whose `ICCP` chunk declares more bytes than the file holds or than +/// [`colour::MAX_ICC_BYTES`]. The decoder sizes its buffer from the declared length before it reads +/// anything, so such a file must not reach `icc_profile()`; its pixels decode without it. +pub fn webp_icc_is_sane(bytes: &[u8]) -> bool { + if bytes.get(0..4) != Some(b"RIFF") || bytes.get(8..12) != Some(b"WEBP") { + return true; + } + let mut pos = 12usize; + while let Some(head) = bytes.get(pos..pos.saturating_add(8)) { + let size = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as usize; + let body = pos + 8; + if &head[..4] == b"ICCP" { + return size <= colour::MAX_ICC_BYTES && body.saturating_add(size) <= bytes.len(); + } + // Chunks are padded to an even size. + pos = body.saturating_add(size).saturating_add(size & 1); + } + true +} + /// The ICC profile embedded in a PNG, JPEG, TIFF or WebP. fn embedded_icc(bytes: &[u8]) -> Option> { use image::ImageDecoder; + if !webp_icc_is_sane(bytes) { + return None; + } let mut d = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?; d.icc_profile().ok().flatten() } diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index 3e5daf8ab..cd577f09a 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -534,3 +534,30 @@ fn gif_tone_and_cmyk_inks_check_the_rgba_budget() { assert!(too_large_to_decode(&tiff)); assert_eq!(decode_cmyk_tiff(&tiff), None); } + +fn webp_with(chunks: &[(&[u8; 4], u32, &[u8])]) -> Vec { + let mut v = b"RIFF\0\0\0\0WEBP".to_vec(); + for (id, declared, body) in chunks { + v.extend_from_slice(*id); + v.extend_from_slice(&declared.to_le_bytes()); + v.extend_from_slice(body); + if body.len() % 2 == 1 { + v.push(0); + } + } + v +} + +/// A WebP that declares an `ICCP` chunk larger than the file (or than the ICC cap) never reaches the +/// decoder's profile read, which would size a buffer from the declared length. +#[test] +fn a_webp_icc_chunk_that_declares_more_than_it_holds_is_refused_before_decoding() { + assert!(webp_icc_is_sane(&webp_with(&[(b"VP8X", 10, &[0; 10]), (b"ICCP", 4, &[1; 4])]))); + // An odd-sized chunk before it is padded to even. + assert!(webp_icc_is_sane(&webp_with(&[(b"EXIF", 3, &[0; 3]), (b"ICCP", 4, &[1; 4])]))); + assert!(!webp_icc_is_sane(&webp_with(&[(b"VP8X", 10, &[0; 10]), (b"ICCP", u32::MAX, &[1; 4])]))); + assert!(!webp_icc_is_sane(&webp_with(&[(b"ICCP", 100, &[1; 4])]))); + assert!(embedded_icc(&webp_with(&[(b"ICCP", u32::MAX, &[1; 4])])).is_none()); + assert!(webp_icc_is_sane(b"\x89PNG not a webp")); + assert!(webp_icc_is_sane(&webp_with(&[(b"VP8L", 6, &[0; 6])]))); +} diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index ec7c76fd6..b50c6b20a 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -47,6 +47,9 @@ pub(super) struct RasterMode { /// The ICC profile embedded in an image file, if it has one. pub(super) fn embedded_icc(data: &[u8]) -> Option> { use image::ImageDecoder; + if !designcraft_images::webp_icc_is_sane(data) { + return None; + } let mut dec = image::ImageReader::new(std::io::Cursor::new(data)).with_guessed_format().ok()?.into_decoder().ok()?; dec.icc_profile().ok().flatten() } @@ -89,6 +92,9 @@ pub(super) fn jpeg(data: krilla::Data, icc: impl FnOnce() -> Option>, mo /// its own. fn untagged_rgb(data: &[u8]) -> bool { use image::ImageDecoder; + if !designcraft_images::webp_icc_is_sane(data) { + return false; + } let Some(mut dec) = image::ImageReader::new(std::io::Cursor::new(data)).with_guessed_format().ok().and_then(|r| r.into_decoder().ok()) else { return false; }; From a41fc046f395696df98c2cce6524177c2cd31d9f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:27:35 -0500 Subject: [PATCH 1004/1349] Data merge: a record range stops expanding once the limit is met * Data merge: a record range stops expanding once the limit or the record count is met --- crates/engine/src/cmd/datamerge/parse.rs | 15 ++++++++++++--- crates/engine/src/cmd/datamerge/tests.rs | 10 ++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/datamerge/parse.rs b/crates/engine/src/cmd/datamerge/parse.rs index dfc49e842..20b57e39a 100644 --- a/crates/engine/src/cmd/datamerge/parse.rs +++ b/crates/engine/src/cmd/datamerge/parse.rs @@ -159,7 +159,11 @@ pub fn select_records(count: usize, records: &str, one: u32, range: &str, limit: let i = record_index(one, count)?; idx.push(i); } - "range" => select_range(range, count, &mut idx, &mut seen)?, + "range" => { + // Past this many records nothing more can be kept, so later ranges are only validated. + let keep = limit.filter(|l| *l > 0).map_or(count, |l| count.min(l as usize)); + select_range(range, count, keep, &mut idx, &mut seen)? + } other => return Err(format!("unknown records value \"{other}\"")), } if let Some(limit) = limit { @@ -175,7 +179,9 @@ pub fn select_records(count: usize, records: &str, one: u32, range: &str, limit: } /// Expand a comma-separated list of record numbers and `a-b` ranges into `idx`, skipping repeats. -fn select_range(range: &str, count: usize, idx: &mut Vec, seen: &mut std::collections::HashSet) -> Result<(), String> { +/// Every token is still checked, but once `idx` holds `keep` records no more are expanded, so +/// repeated or overlapping ranges cost nothing past that point. +fn select_range(range: &str, count: usize, keep: usize, idx: &mut Vec, seen: &mut std::collections::HashSet) -> Result<(), String> { if range.trim().is_empty() { return Err("no records".into()); } @@ -194,8 +200,11 @@ fn select_range(range: &str, count: usize, idx: &mut Vec, seen: &mut std: if a > b { return Err(format!("range {a}-{b} is reversed")); } + // Both ends in range means every record between them is. + record_index(a, count)?; + record_index(b, count)?; let mut n = a; - while n <= b { + while n <= b && idx.len() < keep { let i = record_index(n, count)?; if seen.insert(i) { idx.push(i); diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index 4793aac17..bcad97bb5 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -1310,3 +1310,13 @@ fn merged_records_give_anchored_objects_their_own_ids() { doc.check().unwrap(); designcraft_format::load(&designcraft_format::save(doc).unwrap()).unwrap(); } + +#[test] +fn select_records_stops_expanding_once_the_limit_is_met_but_still_checks_every_range() { + // 4 billion records in a range would not finish if it were expanded; the limit stops it. + let idx = parse::select_records(u32::MAX as usize, "range", 1, "1-3,1-4294967295,2-4294967295", Some(5)).unwrap(); + assert_eq!(idx, vec![0, 1, 2, 3, 4]); + // A later token that is out of range is still an error. + assert!(parse::select_records(10, "range", 1, "1-10,5-11", Some(2)).is_err()); + assert!(parse::select_records(10, "range", 1, "1-2,0", Some(2)).is_err()); +} From 26d5c8941c4d8b7dd6e013ce02c4aef407f360f2 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:27:41 -0500 Subject: [PATCH 1005/1349] IDML: story export and object-style overlay in linear time, embedded image budget * idml: story runs and marker offsets found once, object-style overlay by position, embedded image budget * address review: saturating embedded-bytes counter * address review: IDML export past the embed limit succeeds and warns for each image written as a link * address review: an unlinked image is always embedded, only linked ones fall back to their link --- crates/engine/src/cmd/interchange.rs | 14 +++-- crates/idml/src/export.rs | 26 ++++++++- crates/idml/src/export/item.rs | 12 +++- crates/idml/src/export/story.rs | 76 +++++++++++++++++++++----- crates/idml/src/import/object_style.rs | 30 ++++++---- crates/idml/src/lib.rs | 2 +- crates/idml/src/tests/assets.rs | 39 +++++++++++++ 7 files changed, 165 insertions(+), 34 deletions(-) diff --git a/crates/engine/src/cmd/interchange.rs b/crates/engine/src/cmd/interchange.rs index 47b36b776..e84c28103 100644 --- a/crates/engine/src/cmd/interchange.rs +++ b/crates/engine/src/cmd/interchange.rs @@ -17,7 +17,7 @@ use crate::{DocState, EngineError, Result, Session}; pub fn specs() -> Vec { vec![ cmd!(query "file.exportIdml", "Export IDML…", [], None, - "{path?, embedImages?: true} — writes an IDML package to `path`, or returns {base64} without a path", + "{path?, embedImages?: true} — writes an IDML package to `path`, or returns {base64} without a path; `warnings` names each image written as a link because the embedded-image limit was reached", has_doc, export_idml), cmd!(noundo "file.openIdml", "Open IDML", [], None, "{path | base64, name?} — opens an IDML package, or an InDesign document or template (.indd, .indt: converted to IDML first; its conversion warnings join `warnings`), as a new document (linked images are read next to the file or from its Links/ folder; the fonts in a `Document Fonts` folder beside it load first) → {index, documentFonts, warnings: conversion warnings, package parts missing, font files skipped, GREP styles whose pattern can't compile}", @@ -29,15 +29,19 @@ fn export_idml(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; let opts = designcraft_idml::ExportOptions { embed_images: p.get("embedImages").and_then(Value::as_bool).unwrap_or(true) }; let layer_doc = with_pdf_layer_variants(&st.doc, opts.embed_images)?; - let bytes = designcraft_idml::export_idml_with(layer_doc.as_ref().unwrap_or(&st.doc), &opts); - match str_param(p, "path") { + let (bytes, warnings) = designcraft_idml::export_idml_report(layer_doc.as_ref().unwrap_or(&st.doc), &opts); + let mut out = match str_param(p, "path") { Some(path) => { #[cfg(not(target_arch = "wasm32"))] crate::io::write_file(path, &bytes).map_err(EngineError::Other)?; - Ok(json!({"path": path, "bytes": bytes.len()})) + json!({"path": path, "bytes": bytes.len()}) } - None => Ok(json!({"base64": base64_encode(&bytes), "bytes": bytes.len()})), + None => json!({"base64": base64_encode(&bytes), "bytes": bytes.len()}), + }; + if !warnings.is_empty() { + out["warnings"] = json!(warnings); } + Ok(out) } /// Whether a placement holds an Object Layer Options choice an export can still apply: a graphic diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs index 717bb5d6c..fccbc7c2f 100644 --- a/crates/idml/src/export.rs +++ b/crates/idml/src/export.rs @@ -65,9 +65,20 @@ pub fn export_idml(doc: &Document) -> Vec { /// Export with options, using the index sort-key conflict policy of [`export_idml`]. pub fn export_idml_with(doc: &Document, opts: &ExportOptions) -> Vec { + export_idml_report(doc, opts).0 +} + +/// [`export_idml_with`] and its warnings: an image written as a link only because the export's +/// embedded-image limit was reached is named in one, so the package is not silently incomplete. +pub fn export_idml_report(doc: &Document, opts: &ExportOptions) -> (Vec, Vec) { + export_with_limit(doc, opts, MAX_EMBEDDED_BYTES) +} + +pub(crate) fn export_with_limit(doc: &Document, opts: &ExportOptions, embed_limit: usize) -> (Vec, Vec) { let mut ex = Ex::new(doc, opts); + ex.embed_limit = embed_limit; let parts = ex.build(); - zip_parts(&parts) + (zip_parts(&parts), ex.warnings) } fn zip_parts(parts: &[(String, Vec)]) -> Vec { @@ -106,8 +117,18 @@ struct Ex<'a> { /// Index topic path → first serialized sort key; See / See also cross-references. index_topics: BTreeMap, String>, index_xrefs: Vec<(Vec, &'static str, String)>, + /// Bytes of image data written into `` so far (see [`MAX_EMBEDDED_BYTES`]). + embedded: usize, + embed_limit: usize, + /// Images written as links because the embed limit was reached (one line per placement). + warnings: Vec, } +/// Image bytes one export embeds, counting each placement (IDML holds a copy per placement): past +/// it a graphic that has a link of its own is written as that link without its contents (an +/// image with no link is always embedded: it has nowhere else to live). +const MAX_EMBEDDED_BYTES: usize = 512 * 1024 * 1024; + impl<'a> Ex<'a> { fn new(d: &'a Document, opts: &'a ExportOptions) -> Self { let mut ex = Ex { @@ -121,6 +142,9 @@ impl<'a> Ex<'a> { link_text_sources: Vec::new(), index_topics: BTreeMap::new(), index_xrefs: Vec::new(), + embedded: 0, + embed_limit: MAX_EMBEDDED_BYTES, + warnings: Vec::new(), }; ex.assign_swatch_ids(); for s in d.stories.values() { diff --git a/crates/idml/src/export/item.rs b/crates/idml/src/export/item.rs index 457172253..ca27a8ca0 100644 --- a/crates/idml/src/export/item.rs +++ b/crates/idml/src/export/item.rs @@ -268,9 +268,19 @@ impl<'a> Ex<'a> { el.set("FillColor", id.clone()); el.set("FillTint", pct(g.fill.tint as f64)); } - let embed = !asset.data.is_empty() && (self.opts.embed_images || asset.link.is_none()); + let wanted = !asset.data.is_empty() && (self.opts.embed_images || asset.link.is_none()); + // An image with no link of its own has nowhere else to live, so it is always embedded + // (dropping its data would lose it); only an image with a real link can fall back to it. + let embed = wanted && (asset.link.is_none() || self.embedded.saturating_add(asset.data.len()) <= self.embed_limit); + if wanted && !embed { + self.warnings.push(format!( + "image {} is written as a link, not embedded: the package already holds {} bytes of images (limit {})", + asset.name, self.embedded, self.embed_limit + )); + } let mut props = Vec::new(); if embed { + self.embedded = self.embedded.saturating_add(asset.data.len()); let mut c = El::new("Contents"); c.children.push(Node::CData(base64_encode(&asset.data))); props.push(c); diff --git a/crates/idml/src/export/story.rs b/crates/idml/src/export/story.rs index 437376190..7ca41e231 100644 --- a/crates/idml/src/export/story.rs +++ b/crates/idml/src/export/story.rs @@ -278,7 +278,14 @@ impl<'a> Ex<'a> { None } - fn apply_tracked_changes(&mut self, s: &Story, f: &CharFormat, csrs: &mut [El], para_br: bool, para_end: usize) { + fn apply_tracked_changes( + &mut self, + f: &CharFormat, + csrs: &mut [El], + para_br: bool, + runs: &[(std::ops::Range, &CharFormat)], + para_end: usize, + ) { // Tracked changes wrap the text they mark. if let Some(kind) = change_type(f.over.change) { for c in csrs.iter_mut().filter(|c| c.name == "CharacterStyleRange" && !c.children.is_empty()) { @@ -288,7 +295,10 @@ impl<'a> Ex<'a> { } } if para_br && let Some(c) = csrs.last_mut() { - let nl = s.runs().find(|(rr, _)| rr.contains(¶_end)).and_then(|(_, nf)| change_type(nf.over.change)); + let nl = runs + .get(runs.partition_point(|(rr, _)| rr.end <= para_end)) + .filter(|(rr, _)| rr.start <= para_end) + .and_then(|(_, nf)| change_type(nf.over.change)); match nl { None => c.push(El::new("Br")), Some(kind) => match c.children.last_mut() { @@ -307,17 +317,27 @@ impl<'a> Ex<'a> { pub(super) fn story_paras(&mut self, s: &Story) -> Vec { let ranges = s.para_ranges(); let n = ranges.len(); - ranges.into_iter().enumerate().map(|(pi, r)| self.story_para(s, pi, r, pi + 1 == n)).collect() + // The runs and the marker offsets, once: each paragraph (and each marker) searched them from the start. + let runs: Vec<(std::ops::Range, &CharFormat)> = s.runs().collect(); + let marks = Marks::of(s); + ranges.into_iter().enumerate().map(|(pi, r)| self.story_para(s, pi, r, pi + 1 == n, &runs, &marks)).collect() } - fn paragraph_runs(s: &Story, r: &std::ops::Range) -> Vec<(std::ops::Range, CharFormat)> { - // Character runs intersecting the paragraph. + fn paragraph_runs( + s: &Story, + r: &std::ops::Range, + runs: &[(std::ops::Range, &CharFormat)], + ) -> Vec<(std::ops::Range, CharFormat)> { + // Character runs intersecting the paragraph (they ascend: the first is a search away). let mut segs: Vec<(std::ops::Range, CharFormat)> = Vec::new(); - for (rr, f) in s.runs() { + for (rr, f) in &runs[runs.partition_point(|(rr, _)| rr.end <= r.start)..] { + if rr.start >= r.end { + break; + } let a = rr.start.max(r.start); let b = rr.end.min(r.end); if a < b { - segs.push((a..b, f.clone())); + segs.push((a..b, (*f).clone())); } } if segs.is_empty() { @@ -354,11 +374,19 @@ impl<'a> Ex<'a> { } } - fn story_para(&mut self, s: &Story, pi: usize, r: std::ops::Range, last: bool) -> El { + fn story_para( + &mut self, + s: &Story, + pi: usize, + r: std::ops::Range, + last: bool, + runs: &[(std::ops::Range, &CharFormat)], + marks: &Marks, + ) -> El { let pf = s.paras.get(pi).cloned().unwrap_or_default(); let mut psr = self.psr_el(&pf); let ends_with_break = s.text.get(r.clone()).and_then(|t| t.chars().next_back()).is_some_and(st::is_break_char); - let segs = Self::paragraph_runs(s, &r); + let segs = Self::paragraph_runs(s, &r, runs); // A hyperlink on a run of text is written as a `HyperlinkTextSource` around the // ranges it covers, so the runs are cut at its edges first (#1446). let (links, segs) = self.cut_runs_at_links(s, &r, segs); @@ -414,7 +442,7 @@ impl<'a> Ex<'a> { } else if ch == designcraft_doc::ANCHOR_MARK { flush_text(&mut cur, &mut pending); flush_content(&mut pending, &mut out); - let k = s.text[..seg_start + ci].matches(designcraft_doc::ANCHOR_MARK).count(); + let k = marks.anchor.partition_point(|&at| at < seg_start + ci); if let Some(a) = s.anchors.get(k) { out.push(Node::El( El::new("HyperlinkTextDestination") @@ -428,14 +456,14 @@ impl<'a> Ex<'a> { // An anchored object: the item inside the range with its anchoring settings. flush_text(&mut cur, &mut pending); flush_content(&mut pending, &mut out); - let k = s.text[..seg_start + ci].matches(designcraft_doc::OBJECT_MARK).count(); + let k = marks.object.partition_point(|&at| at < seg_start + ci); if let Some(el) = self.anchored_object(s, k) { out.push(Node::El(el)); } } else if ch == designcraft_doc::INDEX_MARK { flush_text(&mut cur, &mut pending); flush_content(&mut pending, &mut out); - let k = s.text[..seg_start + ci].matches(designcraft_doc::INDEX_MARK).count(); + let k = marks.index.partition_point(|&at| at < seg_start + ci); if let Some(el) = self.index_reference(s, k) { out.push(Node::El(el)); } @@ -448,7 +476,7 @@ impl<'a> Ex<'a> { c.children.append(&mut out); csrs.push(c); } - let k = s.text[..seg_start + ci].matches(designcraft_doc::XREF_MARK).count(); + let k = marks.xref.partition_point(|&at| at < seg_start + ci); if let Some(x) = s.xrefs.get(k) { let me = self.fresh(); let fmt = self.d.xref_formats.iter().position(|ff| ff.name == x.format).map_or("n".to_string(), xref_format_self); @@ -525,7 +553,7 @@ impl<'a> Ex<'a> { c.children.extend(out); csrs.push(c); } - self.apply_tracked_changes(s, &f, &mut csrs, para_br, r.end); + self.apply_tracked_changes(&f, &mut csrs, para_br, runs, r.end); let link = links.iter().find(|(_, l)| l.contains(&seg_start) || (l.start == seg_start && l.start == l.end)).map(|(i, _)| *i); for c in csrs { psr_csrs.push((link, c)); @@ -655,3 +683,23 @@ pub(super) fn with_list_tab(mut a: ParaAttrs, resolved: impl FnOnce() -> (design a.tabs = Some(tabs); a } + +/// Byte offsets of a story's anchor, object, index and cross-reference markers, in text order. +pub(super) struct Marks { + anchor: Vec, + object: Vec, + index: Vec, + xref: Vec, +} + +impl Marks { + fn of(s: &Story) -> Self { + let at = |c: char| s.text.match_indices(c).map(|(i, _)| i).collect::>(); + Marks { + anchor: at(designcraft_doc::ANCHOR_MARK), + object: at(designcraft_doc::OBJECT_MARK), + index: at(designcraft_doc::INDEX_MARK), + xref: at(designcraft_doc::XREF_MARK), + } + } +} diff --git a/crates/idml/src/import/object_style.rs b/crates/idml/src/import/object_style.rs index 343e67211..6af6f845e 100644 --- a/crates/idml/src/import/object_style.rs +++ b/crates/idml/src/import/object_style.rs @@ -242,9 +242,11 @@ fn overlay(base: &mut El, top: &El, depth: usize) { *base = top.clone(); return; } + // Where `base`'s Properties child is, once (a search per attribute otherwise). + let props = base.children.iter().position(|n| matches!(n, Node::El(p) if p.local() == "Properties")); for (k, v) in &top.attrs { base.set(k, v); - if let Some(Node::El(p)) = base.children.iter_mut().find(|n| matches!(n, Node::El(p) if p.local() == "Properties")) { + if let Some(Node::El(p)) = props.and_then(|at| base.children.get_mut(at)) { p.children.retain(|n| !matches!(n, Node::El(x) if x.local() == k)); } } @@ -259,22 +261,26 @@ fn overlay(base: &mut El, top: &El, depth: usize) { // The k-th child of a name merges with the k-th child of that name in `base` (repeated elements // such as gradient stops pair up in order). let mut seen: HashMap<&str, usize> = HashMap::new(); + // Positions in `base.children` of its elements, by name, in order: the k-th is a lookup, not a + // scan from the first child (many repeated names made the scans quadratic). + let mut at: HashMap> = HashMap::new(); + for (i, b) in base.children.iter().enumerate() { + if let Node::El(b) = b { + at.entry(b.local().to_string()).or_default().push(i); + } + } for n in &top.children { match n { Node::El(c) => { let k = seen.entry(c.local()).or_insert(0); - let slot = base - .children - .iter_mut() - .filter_map(|b| match b { - Node::El(b) if b.local() == c.local() => Some(b), - _ => None, - }) - .nth(*k); + let slot = at.get(c.local()).and_then(|v| v.get(*k)).copied(); *k += 1; - match slot { - Some(b) => overlay(b, c, depth + 1), - None => base.children.push(n.clone()), + match slot.and_then(|i| base.children.get_mut(i)) { + Some(Node::El(b)) => overlay(b, c, depth + 1), + _ => { + at.entry(c.local().to_string()).or_default().push(base.children.len()); + base.children.push(n.clone()); + } } } Node::Text(_) | Node::CData(_) if has_text => base.children.push(n.clone()), diff --git a/crates/idml/src/lib.rs b/crates/idml/src/lib.rs index 8f7b22ff9..0c024dfab 100644 --- a/crates/idml/src/lib.rs +++ b/crates/idml/src/lib.rs @@ -57,7 +57,7 @@ mod xml; #[cfg(test)] mod tests; -pub use export::{ExportOptions, export_idml, export_idml_with}; +pub use export::{ExportOptions, export_idml, export_idml_report, export_idml_with}; pub use import::{Imported, import_idml, import_idml_report, import_idml_report_with_previews, import_idml_with}; /// The IDML package mimetype (content of the first, stored `mimetype` entry). diff --git a/crates/idml/src/tests/assets.rs b/crates/idml/src/tests/assets.rs index 48875c256..265183540 100644 --- a/crates/idml/src/tests/assets.rs +++ b/crates/idml/src/tests/assets.rs @@ -393,3 +393,42 @@ fn the_swatch_applied_to_an_image_is_kept() { assert!(!images.iter().any(|e| e.contains("Swatch/None")), "{images:?}"); assert_eq!(fills(&import_idml_with(&out, &reader).unwrap()), want); } + +/// Past the embedded-image limit an export still succeeds: the images that no longer fit are +/// written as links, and each is named in a warning. +#[test] +fn export_past_the_embed_limit_warns_for_each_image_written_as_a_link() { + let bytes = vec![42u8; 300]; + let reader = |p: &str| p.ends_with("couple.jpg").then(|| bytes.clone()); + let frames = vec![ + frame(1, 0.0, 1.0, &image(1, PHOTO, None)), + frame(2, 100.0, 2.0, &image(2, PHOTO, None)), + frame(3, 200.0, 3.0, &image(3, PHOTO, None)), + frame(4, 300.0, 4.0, &image(4, "file:/elsewhere/copy.jpg", Some(&bytes))), + ]; + let d = import_idml_with(&package(&frames), &reader).unwrap(); + let opts = ExportOptions { embed_images: true }; + // Four placements of 300 bytes each; the limit holds two. + let (out, warnings) = crate::export::export_with_limit(&d, &opts, 700); + assert_eq!(warnings.len(), 2, "{warnings:?}"); + assert!(warnings.iter().all(|w| w.contains("written as a link")), "{warnings:?}"); + assert_eq!(import_idml_with(&out, &reader).unwrap().assets.len(), 2); + assert!(crate::export::export_with_limit(&d, &opts, 1200).1.is_empty()); +} + +/// An image with no link of its own is embedded even past the limit: it has no other home, and +/// dropping its data would lose it. +#[test] +fn an_unlinked_image_is_embedded_past_the_embed_limit() { + let bytes = vec![42u8; 300]; + let reader = |p: &str| p.ends_with("couple.jpg").then(|| bytes.clone()); + let frames = vec![frame(1, 0.0, 1.0, &image(1, PHOTO, None)), frame(2, 100.0, 2.0, &image(2, PHOTO, None))]; + let mut d = import_idml_with(&package(&frames), &reader).unwrap(); + for a in d.assets.values_mut() { + std::sync::Arc::make_mut(a).link = None; + } + let (out, warnings) = crate::export::export_with_limit(&d, &ExportOptions { embed_images: true }, 100); + assert!(warnings.is_empty(), "{warnings:?}"); + let back = import_idml_with(&out, &|_: &str| None).unwrap(); + assert!(!back.assets.is_empty() && back.assets.values().all(|a| a.data.as_slice() == bytes.as_slice())); +} From 665fe2a8e42a97c881d8d80dd2bf37d34f168b70 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:27:47 -0500 Subject: [PATCH 1006/1349] Format: a failed entry read counts against the archive budget * format: bytes a failed entry read inflated count against the archive budget * address review: mutate the payload bytes explicitly in the checksum test * address review: charge a failed read to the budget it belongs to (stored vs deflated) --- crates/format/src/lib.rs | 11 +++++++++-- crates/format/src/tests.rs | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 8f9d8856e..a03667209 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -224,10 +224,17 @@ fn read_entry( return Err(too_big()); } let mut v = Vec::new(); - if f.take(limit.saturating_add(1)).read_to_end(&mut v).is_err() { + let read = f.take(limit.saturating_add(1)).read_to_end(&mut v); + let n = v.len() as u64; + // What a failed read produced was inflated all the same: it counts against the archive's budget. + if read.is_err() { + if stored { + *stored_left = stored_left.saturating_sub(n); + } else { + *left = left.saturating_sub(n); + } return Ok(None); } - let n = v.len() as u64; if n > limit { return Err(too_big()); } diff --git a/crates/format/src/tests.rs b/crates/format/src/tests.rs index ca57c7770..0e6f613cd 100644 --- a/crates/format/src/tests.rs +++ b/crates/format/src/tests.rs @@ -3,6 +3,25 @@ use designcraft_doc::build::NewDocument; use designcraft_doc::geom::Rect; use designcraft_doc::{Asset, ParaFormat, SpreadRef}; +/// An entry that fails after inflating (a bad checksum) still uses up the archive's byte budget. +#[test] +fn a_failed_read_is_charged_to_the_budget() { + let mut z = zip::ZipWriter::new(Cursor::new(Vec::new())); + let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); + z.start_file("a", stored).unwrap(); + z.write_all(&[7u8; 1000]).unwrap(); + let mut bytes = z.finish().unwrap().into_inner(); + // Flip a data byte: the entry reads in full, then fails its checksum. + // The payload is the only run of 1,000 consecutive 7s in the archive. + let start = bytes.windows(1000).position(|w| w.iter().all(|b| *b == 7)).expect("payload"); + bytes[start] = 8; + let mut archive = zip::ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap(); + let (mut left, mut stored_left) = (5000, 5000); + assert_eq!(read_entry(&mut archive, "a", 4000, &mut left, &mut stored_left).unwrap(), None); + // A failed stored read is charged to the stored budget only. + assert_eq!((left, stored_left), (5000, 4000)); +} + fn png_asset(d: &mut Document, data: &[u8]) -> AssetId { let aid = AssetId(d.alloc()); let a = From 568f25fa9f2b2e50097bb1f76499f24355b18fa1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:27:53 -0500 Subject: [PATCH 1007/1349] Fonts: cap decoded names, bound outline flattening, cache fallback coverage * fonts: cap decoded names, outline flatten tolerance by size, coverage cache for system fallback * Apply review fixes - crates/fonts/src/fontdb/system.rs - crates/fonts/src/fontdb/names.rs * Apply review fixes - crates/fonts/src/fontdb/system.rs * address review: cap flattened edges in has_serifs * address review: check alias blankness before capping --------- Co-authored-by: aiongg <67543387+aiongg@users.noreply.github.com> --- crates/fonts/src/fontdb/fallback.rs | 9 +++ crates/fonts/src/fontdb/names.rs | 40 +++++++++++++- crates/fonts/src/fontdb/outline.rs | 26 ++++++++- crates/fonts/src/fontdb/system.rs | 85 +++++++++++++++++++++++++++-- 4 files changed, 150 insertions(+), 10 deletions(-) diff --git a/crates/fonts/src/fontdb/fallback.rs b/crates/fonts/src/fontdb/fallback.rs index 73a2e0a25..7291cb343 100644 --- a/crates/fonts/src/fontdb/fallback.rs +++ b/crates/fonts/src/fontdb/fallback.rs @@ -10,8 +10,17 @@ pub(super) struct SysFallback { pub(super) misses: std::collections::HashSet, /// CJK chain families already looked up in the catalog (loaded, or not installed). pub(super) chain_tried: std::collections::HashSet<&'static str>, + /// The code points each installed file covers (as ranges), by path, valid for the file's + /// stamp: one character after another is looked up without reading every file again. + pub(super) coverage: std::collections::HashMap>)>, + /// Ranges held in `coverage` (it stops growing at [`MAX_COVERAGE_RANGES`]). + pub(super) coverage_ranges: usize, } +/// Most coverage ranges kept across all files (8 bytes each). +#[cfg(not(target_arch = "wasm32"))] +pub(super) const MAX_COVERAGE_RANGES: usize = 4 * 1024 * 1024; + #[cfg(all(test, target_os = "linux"))] pub(super) struct FallbackSnapshotHook { pub(super) reached: std::sync::mpsc::SyncSender<()>, diff --git a/crates/fonts/src/fontdb/names.rs b/crates/fonts/src/fontdb/names.rs index af5f14cc3..6c2610824 100644 --- a/crates/fonts/src/fontdb/names.rs +++ b/crates/fonts/src/fontdb/names.rs @@ -3,16 +3,42 @@ use super::face::FontFace; use super::system::CatalogEntry; use super::{Arc, MetadataProvider, StringId}; +/// Characters kept of one decoded name: a name record can be 64 KB, and a font has many of them, +/// kept for every face (a real family or style name is far shorter). +const MAX_NAME_CHARS: usize = 256; + +fn capped(name: impl std::fmt::Display) -> String { + use std::fmt::Write as _; + let mut out = String::new(); + // Stops decoding at the cap: the name is never built in full. + let mut room = MAX_NAME_CHARS; + struct Cap<'a>(&'a mut String, &'a mut usize); + impl std::fmt::Write for Cap<'_> { + fn write_str(&mut self, s: &str) -> std::fmt::Result { + for c in s.chars() { + if *self.1 == 0 { + return Err(std::fmt::Error); + } + *self.1 -= 1; + self.0.push(c); + } + Ok(()) + } + } + let _ = write!(Cap(&mut out, &mut room), "{name}"); + out +} + pub(super) fn aliases(font: &skrifa::FontRef<'_>, ids: &[StringId]) -> Vec { let mut names: Vec = - ids.iter().flat_map(|id| font.localized_strings(*id)).take(256).map(|name| name.to_string()).filter(|name| !name.trim().is_empty()).collect(); + ids.iter().flat_map(|id| font.localized_strings(*id)).take(256).filter(|name| !name.chars().all(char::is_whitespace)).map(capped).collect(); names.sort(); names.dedup(); names } pub(super) fn name(font: &skrifa::FontRef<'_>, ids: &[StringId]) -> Option { - ids.iter().find_map(|id| font.localized_strings(*id).english_or_first().map(|s| s.to_string()).filter(|s| !s.is_empty())) + ids.iter().find_map(|id| font.localized_strings(*id).english_or_first().map(capped).filter(|s| !s.is_empty())) } /// A face's family and style names (the default instance's style for a variable font). @@ -116,3 +142,13 @@ pub(super) fn style_italic(style: &str) -> bool { let s = norm(style); s.contains("italic") || s.contains("oblique") || s == "it" } + +#[cfg(test)] +mod tests { + #[test] + fn decoded_names_are_capped() { + assert_eq!(super::capped("Arial"), "Arial"); + let long = "é".repeat(10_000); + assert_eq!(super::capped(&long).chars().count(), super::MAX_NAME_CHARS); + } +} diff --git a/crates/fonts/src/fontdb/outline.rs b/crates/fonts/src/fontdb/outline.rs index 30e328be4..0b07f3b3f 100644 --- a/crates/fonts/src/fontdb/outline.rs +++ b/crates/fonts/src/fontdb/outline.rs @@ -11,28 +11,48 @@ pub(super) fn has_serifs(face: &FontFace) -> Option { if bbox.height().is_nan() || bbox.height() <= 1.0 { return None; } + // Flattened segments kept: an "l" has a few dozen; a hostile outline has no such limit of its own. + const MAX_EDGES: usize = 1 << 20; let mut edges = Vec::new(); + let mut over = false; let mut last = None; let mut start = None; - kurbo::flatten(&path, 1.0, |el| match el { + // A tolerance of one unit is fine for outlines of normal size; a transform that blows one up + // gets a tolerance in proportion, so the subdivision stays bounded (4096 units stay at 1). + let tol = (bbox.width().max(bbox.height()) / 4096.0).max(1.0); + if !tol.is_finite() { + return None; + } + kurbo::flatten(&path, tol, |el| match el { kurbo::PathEl::MoveTo(p) => { last = Some(p); start = Some(p); } kurbo::PathEl::LineTo(p) => { if let Some(a) = last { - edges.push((a, p)); + if edges.len() < MAX_EDGES { + edges.push((a, p)); + } else { + over = true; + } } last = Some(p); } kurbo::PathEl::ClosePath => { if let (Some(a), Some(b)) = (last, start) { - edges.push((a, b)); + if edges.len() < MAX_EDGES { + edges.push((a, b)); + } else { + over = true; + } } last = start; } _ => {} }); + if over { + return None; + } // The outline is y-down: the foot is near bbox.y1 (the baseline). let width_at = |y: f64| { let xs: Vec = edges diff --git a/crates/fonts/src/fontdb/system.rs b/crates/fonts/src/fontdb/system.rs index 2a367b894..84916807e 100644 --- a/crates/fonts/src/fontdb/system.rs +++ b/crates/fonts/src/fontdb/system.rs @@ -38,6 +38,60 @@ fn file_stamp(path: &std::path::Path) -> Option { std::fs::metadata(path).ok().map(|m| (m.len(), m.modified().ok())) } +/// The code points any face of a font file maps, as sorted inclusive ranges. +#[cfg(not(target_arch = "wasm32"))] +fn coverage_ranges(data: &[u8]) -> Vec<(u32, u32)> { + // One bit per code point: memory stays fixed however many faces (or named instances of one face) map however much. + let mut bits = vec![0u64; 0x110000 / 64]; + let mut last = None; + for (i, _, _, _) in enumerate_faces(data) { + if last.replace(i) == Some(i) { + continue; + } + if let Ok(f) = skrifa::FontRef::from_index(data, i) { + for (cp, _) in f.charmap().mappings() { + if let Some(w) = bits.get_mut((cp / 64) as usize) { + *w |= 1u64 << (cp % 64); + } + } + } + } + let mut out: Vec<(u32, u32)> = Vec::new(); + for (wi, &w) in bits.iter().enumerate() { + if w == 0 { + continue; + } + for b in 0..64u32 { + if (w >> b) & 1 == 0 { + continue; + } + let cp = wi as u32 * 64 + b; + match out.last_mut() { + Some(last) if last.1 + 1 == cp => last.1 = cp, + _ => out.push((cp, cp)), + } + } + } + out +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod coverage_tests { + #[test] + fn coverage_ranges_match_the_charmap() { + let data = include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf"); + let ranges = super::coverage_ranges(data); + let f = skrifa::FontRef::new(data).unwrap(); + use skrifa::MetadataProvider as _; + let in_ranges = |c: char| ranges.iter().any(|&(lo, hi)| (lo..=hi).contains(&u32::from(c))); + assert!(in_ranges('a') && !in_ranges('\u{10FFFE}')); + for c in ['a', 'Z', 'é', '\u{4E2D}', '\u{1F600}'] { + assert_eq!(in_ranges(c), f.charmap().map(c).is_some(), "{c:?}"); + } + assert!(ranges.windows(2).all(|w| w[0].1 + 1 < w[1].0), "sorted and merged"); + } +} + /// What [`FontDb::reload_fonts`] did: the faces cataloged by the rescan, and the installed font /// files that changed or were removed since they were read (their faces are read again, from the /// new file, the next time they are looked up). @@ -272,6 +326,8 @@ impl FontDb { sys.generation = sys.generation.wrapping_add(1); sys.misses.clear(); sys.chain_tried.clear(); + sys.coverage.clear(); + sys.coverage_ranges = 0; count } @@ -564,13 +620,32 @@ impl FontDb { } } for p in paths { - if std::fs::metadata(&p).map(|m| m.len() > 40 << 20).unwrap_or(true) { + let Some(stamp) = file_stamp(&p).filter(|s| s.0 <= 40 << 20) else { continue }; + let cached = + self.sys.lock().unwrap_or_else(PoisonError::into_inner).coverage.get(&p).filter(|(s, _)| *s == stamp).map(|(_, r)| r.clone()); + let mut data = None; + let ranges = match cached { + Some(r) => r, + None => { + let Some(d) = self.read_installed(&p) else { continue }; + let r = Arc::new(coverage_ranges(&d)); + let mut sys = self.sys.lock().unwrap_or_else(PoisonError::into_inner); + if sys.coverage_ranges + r.len() <= super::fallback::MAX_COVERAGE_RANGES { + sys.coverage_ranges += r.len(); + if let Some((_, old)) = sys.coverage.insert(p.clone(), (stamp, r.clone())) { + sys.coverage_ranges -= old.len(); + } + } + data = Some(d); + r + } + }; + let cp = u32::from(c); + if !ranges.iter().any(|&(lo, hi)| (lo..=hi).contains(&cp)) { continue; } - let Some(data) = self.read_installed(&p) else { continue }; - let hit = - enumerate_faces(&data).iter().any(|(i, _, _, _)| skrifa::FontRef::from_index(&data, *i).is_ok_and(|f| f.charmap().map(c).is_some())); - if hit && self.add_faces(data, FontSource::Installed(p)) > 0 && covered(self) { + let Some(data) = data.or_else(|| self.read_installed(&p)) else { continue }; + if self.add_faces(data, FontSource::Installed(p)) > 0 && covered(self) { return true; } } From b7174dc92dca0129ae82969bbf7cf4c5dbc0128e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:27:59 -0500 Subject: [PATCH 1008/1349] Engine: bounded DTD validation, compound-path hole orientation * dtd: bounded matching steps, element depth and problem count * address review: stop DTD matching when a step charge fails; refuse hole orientation past its budget * Apply review fixes - crates/engine/src/dtd.rs --------- Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com> --- crates/engine/src/cmd/paths.rs | 62 ++++++++++++++-- crates/engine/src/dtd.rs | 130 +++++++++++++++++++++++++++++---- 2 files changed, 174 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/paths.rs b/crates/engine/src/cmd/paths.rs index 7800b3189..946da4215 100644 --- a/crates/engine/src/cmd/paths.rs +++ b/crates/engine/src/cmd/paths.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use designcraft_doc::{Content, Document, Fill, Item, ItemId, Selection, Shape, SpreadRef, Stroke}; -use designcraft_geom::{Affine, BezPath, PathData, SubPath}; +use designcraft_geom::{Affine, BezPath, PathData, Shape as _, SubPath}; use serde_json::{Value, json}; use super::{CommandSpec, bad, cmd, has_selection, point_param, targets}; @@ -75,20 +75,40 @@ fn spread_xf(d: &Document, id: ItemId) -> Option<(SpreadRef, Affine)> { Some((loc.spread, d.parent_xf(&loc) * d.item_at(&loc)?.xf)) } +/// Containment tests `orient_holes` makes at most (after the bounding-box filter). A compound path +/// of thousands of nested contours would otherwise take quadratic time; past this the command is +/// refused rather than leave later subpaths with the wrong direction. +const MAX_HOLE_TESTS: usize = 4_000_000; + /// Orient subpaths so those nested an odd number of times run against the others: with the /// non-zero rule they become holes. -fn orient_holes(path: &mut PathData) { +fn orient_holes(path: &mut PathData, command: &str) -> Result<()> { + orient_holes_within(path, command, MAX_HOLE_TESTS) +} + +fn orient_holes_within(path: &mut PathData, command: &str, max_tests: usize) -> Result<()> { let beziers: Vec = path.subpaths.iter().map(|s| PathData::single(s.clone()).to_bezpath()).collect(); + // A point outside a contour's box is outside the contour: most pairs are skipped without a winding count. + let boxes: Vec<_> = beziers.iter().map(BezPath::bounding_box).collect(); let n = path.subpaths.len(); + let mut tests = 0usize; for i in 0..n { let Some(p) = path.subpaths[i].anchors.first().map(|a| a.p) else { continue }; - let depth = (0..n).filter(|&j| j != i && designcraft_geom::hit::fill_contains(&beziers[j], designcraft_geom::FillRule::NonZero, p)).count(); + let mut depth = 0; + for j in (0..n).filter(|&j| j != i && boxes[j].inflate(1e-6, 1e-6).contains(p)) { + tests += 1; + if tests > max_tests { + return Err(bad(command, "too many nested contours to tell holes from fills")); + } + depth += usize::from(designcraft_geom::hit::fill_contains(&beziers[j], designcraft_geom::FillRule::NonZero, p)); + } let sp = &mut path.subpaths[i]; let cw = sp.area() > 0.0; if cw == (depth % 2 == 1) { sp.reverse(); } } + Ok(()) } fn make_compound(s: &mut Session, p: &Value) -> Result { @@ -115,7 +135,7 @@ fn make_compound(s: &mut Session, p: &Value) -> Result { } let it = d.item_mut(base_id).ok_or(designcraft_doc::DocError::NoItem(base_id))?; it.path = PathData::new(subpaths); - orient_holes(&mut it.path); + orient_holes(&mut it.path, "object.makeCompoundPath")?; it.shape = Shape::Path; *sel = Selection::items(vec![base_id]); Ok(json!({"id": base_id.0})) @@ -159,7 +179,7 @@ fn pathfinder(s: &mut Session, p: &Value) -> Result { } let it = d.item_mut(keep).ok_or(designcraft_doc::DocError::NoItem(keep))?; it.path = result.transformed(kxf.inverse()); - orient_holes(&mut it.path); + orient_holes(&mut it.path, "object.pathfinder")?; it.shape = Shape::Path; it.corners = Default::default(); *sel = Selection::items(vec![keep]); @@ -409,6 +429,38 @@ mod tests { s.doc().unwrap().doc.check().unwrap(); } + #[test] + fn orient_holes_alternates_nested_contours_and_skips_distant_ones() { + use designcraft_geom::{Rect, shapes::rectangle}; + let mut subs: Vec = Vec::new(); + for k in 0..3 { + let o = 10.0 * f64::from(k); + subs.extend(rectangle(Rect::new(o, o, 100.0 - o, 100.0 - o)).subpaths); + } + // Thousands of separate contours cost no winding counts (their boxes miss each other). + for k in 0..3000 { + let x = 200.0 + 20.0 * f64::from(k); + subs.extend(rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)).subpaths); + } + let mut path = PathData::new(subs); + orient_holes(&mut path, "test").unwrap(); + let cw: Vec = path.subpaths.iter().map(|s| s.area() > 0.0).collect(); + assert_eq!(cw[..3], [true, false, true]); + assert!(cw[3..].iter().all(|c| *c)); + } + + #[test] + fn orient_holes_refuses_past_its_budget_instead_of_half_orienting() { + use designcraft_geom::{Rect, shapes::rectangle}; + let mut subs: Vec = Vec::new(); + for k in 0..4 { + let o = 10.0 * f64::from(k); + subs.extend(rectangle(Rect::new(o, o, 100.0 - o, 100.0 - o)).subpaths); + } + assert!(orient_holes_within(&mut PathData::new(subs.clone()), "test", 3).is_err()); + assert!(orient_holes_within(&mut PathData::new(subs), "test", 100).is_ok()); + } + #[test] fn pathfinder_subtracts_front_from_back() { let mut s = Session::new(); diff --git a/crates/engine/src/dtd.rs b/crates/engine/src/dtd.rs index 6b48ba3ab..7128ba84e 100644 --- a/crates/engine/src/dtd.rs +++ b/crates/engine/src/dtd.rs @@ -309,7 +309,39 @@ pub fn parse(src: &str) -> Result { /// What `ends` has worked out for one sequence of children: the end positions of a group (by the /// address of its node, which lives as long as the model) from a position. -type EndsMemo = HashMap<(usize, usize), Vec>; +struct EndsMemo { + map: HashMap<(usize, usize), Vec>, + /// Matching steps left (shared by a whole validation); at zero `ends` stops and `over` is set. + left: usize, + /// End positions held in `map`; past [`MAX_STORED_ENDS`] results are no longer kept. + stored: usize, + over: bool, +} + +/// Matching steps one validation may take across all its elements (a step is a position handled or +/// compared). Valid documents with thousands of children per element use a small fraction. +const MAX_MATCH_STEPS: usize = 8 * 1024 * 1024; +/// End positions the memo may hold at once (8 bytes each). +const MAX_STORED_ENDS: usize = 4 * 1024 * 1024; +/// Element nesting depth: `check` recurses and keeps each level's full path. +const MAX_XML_DEPTH: usize = 256; +/// Elements in the document being validated. +const MAX_XML_NODES: usize = 4 * 1024 * 1024; +/// Problems reported before the list stops. +const MAX_PROBLEMS: usize = 10_000; + +impl EndsMemo { + /// Spend `n` steps; false once the budget is gone. + fn spend(&mut self, n: usize) -> bool { + if self.over || n > self.left { + self.left = 0; + self.over = true; + return false; + } + self.left -= n; + true + } +} /// End positions after `cp` matches a prefix of `seq[i..]`. /// @@ -321,8 +353,16 @@ fn ends(cp: &Cp, seq: &[&str], i: usize, memo: &mut EndsMemo) -> Vec { return if seq.get(i) == Some(&n.as_str()) { vec![i + 1] } else { vec![] }; } let key = (std::ptr::from_ref(cp) as usize, i); - if let Some(done) = memo.get(&key) { - return done.clone(); + if let Some(done) = memo.map.get(&key) { + // Charged before the clone, and a failed charge ends the match. + let len = done.len(); + if !memo.spend(len) { + return vec![]; + } + return memo.map.get(&key).cloned().unwrap_or_default(); + } + if !memo.spend(1) { + return vec![]; } let mut out: Vec = match cp { Cp::Name(_) => vec![], @@ -334,6 +374,9 @@ fn ends(cp: &Cp, seq: &[&str], i: usize, memo: &mut EndsMemo) -> Vec { for p in at { next.extend(ends(c, seq, p, memo)); } + if !memo.spend(next.len()) { + return vec![]; + } next.sort_unstable(); next.dedup(); at = next; @@ -349,16 +392,21 @@ fn ends(cp: &Cp, seq: &[&str], i: usize, memo: &mut EndsMemo) -> Vec { } Cp::Rep(c, r) => { let mut all = if *r == '+' { vec![] } else { vec![i] }; + // `all` as a set too: a list search per position made long repeats quadratic. + let mut have: std::collections::HashSet = all.iter().copied().collect(); let mut frontier = ends(c, seq, i, memo); if *r == '?' { all.extend(frontier); } else { while !frontier.is_empty() { - let new: Vec = frontier.iter().copied().filter(|p| !all.contains(p)).collect(); + if !memo.spend(frontier.len()) { + break; + } + let new: Vec = frontier.iter().copied().filter(|p| have.insert(*p)).collect(); all.extend(&new); let mut next = Vec::new(); for p in new.into_iter().filter(|&p| p > i) { - next.extend(ends(c, seq, p, memo).into_iter().filter(|p| !all.contains(p))); + next.extend(ends(c, seq, p, memo).into_iter().filter(|p| !have.contains(p))); } // Two paths to one position are one position: kept apart they multiply per round. next.sort_unstable(); @@ -371,7 +419,10 @@ fn ends(cp: &Cp, seq: &[&str], i: usize, memo: &mut EndsMemo) -> Vec { }; out.sort_unstable(); out.dedup(); - memo.insert(key, out.clone()); + if !memo.over && memo.stored + out.len() <= MAX_STORED_ENDS { + memo.stored += out.len(); + memo.map.insert(key, out.clone()); + } out } @@ -396,6 +447,7 @@ fn read_tree(xml: &str) -> Result { use quick_xml::events::Event; let mut r = quick_xml::Reader::from_str(xml); let mut stack: Vec = Vec::new(); + let mut count = 0usize; let node = |e: &quick_xml::events::BytesStart| Node { name: String::from_utf8_lossy(e.name().as_ref()).to_string(), attrs: e.attributes().flatten().map(|a| String::from_utf8_lossy(a.key.as_ref()).to_string()).collect(), @@ -403,8 +455,20 @@ fn read_tree(xml: &str) -> Result { text: false, }; loop { - match r.read_event().map_err(|e| e.to_string())? { - Event::Start(e) => stack.push(node(&e)), + let event = r.read_event().map_err(|e| e.to_string())?; + if matches!(event, Event::Start(_) | Event::Empty(_)) { + count += 1; + if count > MAX_XML_NODES { + return Err(format!("more than {MAX_XML_NODES} elements")); + } + } + match event { + Event::Start(e) => { + if stack.len() >= MAX_XML_DEPTH { + return Err(format!("elements nested more than {MAX_XML_DEPTH} deep")); + } + stack.push(node(&e)); + } Event::Empty(e) => { let n = node(&e); match stack.last_mut() { @@ -437,8 +501,15 @@ fn read_tree(xml: &str) -> Result { } } -fn check(dtd: &Dtd, n: &Node, path: &str, out: &mut Vec) { - let mut problem = |m: String| out.push(Problem { path: path.to_string(), message: m }); +fn check(dtd: &Dtd, n: &Node, path: &str, out: &mut Vec, steps: &mut usize) { + if out.len() >= MAX_PROBLEMS { + return; + } + let mut problem = |m: String| { + if out.len() < MAX_PROBLEMS { + out.push(Problem { path: path.to_string(), message: m }); + } + }; match dtd.model(&n.name) { None => problem(format!("`{}` isn't declared in the DTD", n.name)), Some(Model::Any) => {} @@ -459,7 +530,12 @@ fn check(dtd: &Dtd, n: &Node, path: &str, out: &mut Vec) { problem(format!("`{}` can't contain text", n.name)); } let seq: Vec<&str> = n.children.iter().map(|c| c.name.as_str()).collect(); - if !ends(cp, &seq, 0, &mut EndsMemo::new()).contains(&seq.len()) { + let mut memo = EndsMemo { map: HashMap::new(), left: *steps, stored: 0, over: false }; + let matched = ends(cp, &seq, 0, &mut memo).contains(&seq.len()); + *steps = memo.left; + if memo.over { + problem(format!("`{}` has too many children to check against its content model", n.name)); + } else if !matched { let got = if seq.is_empty() { "nothing".to_string() } else { seq.join(", ") }; problem(format!("`{}` contains {got}; the DTD asks for {}", n.name, show(cp))); } @@ -474,7 +550,7 @@ fn check(dtd: &Dtd, n: &Node, path: &str, out: &mut Vec) { for c in &n.children { let k = seen.entry(c.name.as_str()).or_default(); *k += 1; - check(dtd, c, &format!("{path}/{}[{k}]", c.name), out); + check(dtd, c, &format!("{path}/{}[{k}]", c.name), out, steps); } } @@ -484,7 +560,10 @@ pub fn validate(dtd: &Dtd, xml: &str) -> Vec { Ok(root) => { let mut out = Vec::new(); let path = root.name.clone(); - check(dtd, &root, &path, &mut out); + check(dtd, &root, &path, &mut out, &mut { MAX_MATCH_STEPS }); + if out.len() >= MAX_PROBLEMS { + out.push(Problem { path: String::new(), message: "further problems are not listed".into() }); + } out } Err(e) => vec![Problem { path: String::new(), message: format!("not well-formed XML: {e}") }], @@ -743,4 +822,29 @@ mod tests { assert_eq!(problems.len(), 1, "{problems:?}"); assert!(problems[0].message.starts_with("`r` contains a, a, a"), "{problems:?}"); } + + #[test] + fn nested_repeats_over_many_children_stop_at_the_step_budget() { + let dtd = parse("").unwrap(); + assert_eq!(validate(&dtd, &format!("{}", "".repeat(1000))), vec![]); + let problems = validate(&dtd, &format!("{}", "".repeat(20_000))); + assert_eq!(problems.len(), 1, "{problems:?}"); + assert!(problems[0].message.contains("too many children"), "{problems:?}"); + } + + #[test] + fn xml_nesting_is_bounded() { + let dtd = parse("").unwrap(); + let deep = |n: usize| format!("{}{}", "".repeat(n), "".repeat(n)); + assert_eq!(validate(&dtd, &deep(MAX_XML_DEPTH)), vec![]); + let problems = validate(&dtd, &deep(MAX_XML_DEPTH + 1)); + assert!(problems[0].message.contains("nested more than"), "{problems:?}"); + } + + #[test] + fn problems_are_capped() { + let dtd = parse("").unwrap(); + let problems = validate(&dtd, &format!("{}", "".repeat(MAX_PROBLEMS + 50))); + assert!(problems.len() <= MAX_PROBLEMS + 1, "{}", problems.len()); + } } From ff0463e299c65a74c0191909cdadc6f16f8092be Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:28:07 -0500 Subject: [PATCH 1009/1349] Exports: leave out text the page doesn't show (inherited conditions, deletions, hidden layers) * fix(export): leave out text hidden by inherited conditions or deletion in every exporter * address review: skip hidden frames in page text and hidden article items; first visible paragraph as nav label; read table anchor's own format * address review: skip nonprinting frames and non-printable layers in fixed-layout page text * Apply review fixes - crates/epub/src/html.rs - crates/engine/src/cmd/export/formats.rs * Apply review fixes - crates/epub/src/html.rs - crates/engine/src/cmd/export/formats.rs * address review: fixed-layout page text skips frames in inactive object states * address review: place a threaded story at its first shown frame; skip it only when every frame is hidden --------- Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com> --- crates/doc/src/lib.rs | 46 +++++++++++++ crates/engine/src/cmd/export/formats.rs | 21 +++++- crates/engine/src/cmd/export/text_tests.rs | 19 +++++ crates/epub/src/chapters.rs | 5 +- crates/epub/src/html.rs | 51 ++++++++++++-- crates/epub/src/story_writer.rs | 32 +++++++-- crates/epub/src/tests.rs | 69 +++++++++++++++++++ crates/epub/tests/it/grouped_reading_order.rs | 5 +- crates/textimport/src/export.rs | 62 ++++++++++++----- crates/textimport/src/tagged.rs | 4 +- 10 files changed, 281 insertions(+), 33 deletions(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index d9ee6d3e9..4ebcd665b 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -251,6 +251,52 @@ impl Document { pub fn conditions_hide(&self, conds: &[String]) -> bool { !conds.is_empty() && conds.iter().all(|c| self.conditions.iter().any(|x| x.name == *c && !x.visible)) } + + /// Is text with character format `f`, in a paragraph whose base character attributes are + /// `base` (`Styles::resolve_para`), left off the page: hidden by its effective conditions + /// (the paragraph's and character style's included) or marked deleted? Exports leave it out + /// as composition does. + pub fn hides_run(&self, base: &CharProps, f: &CharFormat) -> bool { + let props = self.styles.resolve_char(base, f); + props.change == ChangeMark::Deleted || self.conditions_hide(&props.conditions) + } + + /// The byte ranges of `st` that show, in order: the runs [`Self::hides_run`] hides left out. + /// Paragraphs and runs are walked together, once; take it once per story. + pub fn visible_spans(&self, st: &Story) -> Vec> { + let mut out: Vec> = Vec::new(); + let runs: Vec<(std::ops::Range, &CharFormat)> = st.runs().collect(); + let mut k = 0; + for (pi, pr) in st.para_ranges().iter().enumerate() { + let base = st.paras.get(pi).map(|pf| self.styles.resolve_para(pf).1).unwrap_or_default(); + while runs.get(k).is_some_and(|(rr, _)| rr.end <= pr.start) { + k += 1; + } + for (rr, f) in runs.iter().skip(k).take_while(|(rr, _)| rr.start < pr.end) { + let (a, b) = (rr.start.max(pr.start), rr.end.min(pr.end)); + if a >= b || self.hides_run(&base, f) { + continue; + } + match out.last_mut() { + Some(last) if last.end == a => last.end = b, + _ => out.push(a..b), + } + } + } + out + } + + /// The text of `st` within `range` that lies in `spans` ([`Self::visible_spans`] of `st`). + pub fn visible_text(st: &Story, spans: &[std::ops::Range], range: std::ops::Range) -> String { + let first = spans.partition_point(|s| s.end <= range.start); + let mut out = String::new(); + for s in spans.iter().skip(first).take_while(|s| s.start < range.end) { + if let Some(t) = st.text.get(s.start.max(range.start)..s.end.min(range.end)) { + out.push_str(t); + } + } + out + } } /// Ink Manager settings for output, by swatch name. Output applies them through a diff --git a/crates/engine/src/cmd/export/formats.rs b/crates/engine/src/cmd/export/formats.rs index a25553d69..4474d8ae7 100644 --- a/crates/engine/src/cmd/export/formats.rs +++ b/crates/engine/src/cmd/export/formats.rs @@ -142,7 +142,7 @@ pub(super) fn export_text(s: &mut Session, p: &Value) -> Result { let text = match format { "rtf" => designcraft_textimport::export::rtf(doc, story), "tagged" => designcraft_textimport::tagged::tagged_text(doc, story), - _ => designcraft_textimport::export::plain_text(story), + _ => designcraft_textimport::export::plain_text(doc, story), }; match path { Some(path) => { @@ -159,13 +159,30 @@ fn page_text(d: &designcraft_doc::Document, cache: &designcraft_compose::Cache, let mut out = String::new(); for st in d.stories.values() { let cs = cache.get(d, st.id, None); + let spans = d.visible_spans(st); for ft in &cs.frames { if d.page_of_item(ft.frame) != Some(abs) { continue; } + // Pages render printing-only: a hidden or nonprinting frame or group around it, or a top-level item on a hidden or non-printable layer (members draw on its layer), isn't on the rendered page. + // Inside a multi-state object only the active state is drawn. + if d.find(ft.frame).is_some_and(|loc| { + (1..=loc.path.len()).any(|n| { + d.item_at(&designcraft_doc::ItemLoc { spread: loc.spread, path: loc.path[..n].to_vec() }).is_some_and(|it| { + it.hidden + || it.nonprinting + || n == 1 && d.layers.iter().any(|l| (!l.visible || !l.printable) && l.id == it.layer) + || n < loc.path.len() && !it.states.is_empty() && loc.path[n] != it.active_state + }) + }) + }) { + continue; + } for l in &ft.lines { let r = l.range.start.min(st.text.len())..l.range.end.min(st.text.len()); - let t: String = st.text[r].chars().filter(|c| !('\u{E000}'..='\u{F8FF}').contains(c)).collect(); + // The line's text as it shows: hidden conditional text and deletions left out. + let t: String = + designcraft_doc::Document::visible_text(st, &spans, r).chars().filter(|c| !('\u{E000}'..='\u{F8FF}').contains(c)).collect(); if !t.trim().is_empty() { out.push_str(t.trim_end_matches('\n')); out.push('\n'); diff --git a/crates/engine/src/cmd/export/text_tests.rs b/crates/engine/src/cmd/export/text_tests.rs index b1b791d3b..48e255ef7 100644 --- a/crates/engine/src/cmd/export/text_tests.rs +++ b/crates/engine/src/cmd/export/text_tests.rs @@ -92,6 +92,25 @@ fn epub_cover_and_fixed_layout() { assert!(p1.contains("width=612, height=792") && p1.contains("Page one words"), "{p1}"); } +/// Fixed-layout page text leaves out frames in a multi-state object's inactive states. +#[test] +fn fixed_epub_text_skips_inactive_states() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let a = s.execute("frame.create", &json!({"rect": [72, 72, 200, 100], "content": "text", "text": "Active words", "caret": false})).unwrap()["id"] + .as_u64() + .unwrap(); + let b = + s.execute("frame.create", &json!({"rect": [72, 300, 200, 100], "content": "text", "text": "Inactive words", "caret": false})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("states.create", &json!({"ids": [a, b]})).unwrap(); + let r = s.execute("file.exportFixedEpub", &json!({})).unwrap(); + let mut z = unzip(r["base64"].as_str().unwrap()); + let p1 = read(&mut z, "OEBPS/page1.xhtml"); + assert!(p1.contains("Active words") && !p1.contains("Inactive words"), "{p1}"); +} + /// #775: the fallback follows the font's class, and embedFonts packages the stylesheet's fonts /// (and reports those it can't). #[test] diff --git a/crates/epub/src/chapters.rs b/crates/epub/src/chapters.rs index ede96f390..b9b6e6183 100644 --- a/crates/epub/src/chapters.rs +++ b/crates/epub/src/chapters.rs @@ -99,7 +99,8 @@ pub(crate) fn toc_entries(doc: &Document, order: &[Block]) -> Vec<(String, Strin continue; } let Some(st) = doc.story(*sid) else { continue }; - let first = label(st.text.split('\n').next().unwrap_or("")); + let spans = doc.visible_spans(st); + let first = st.para_ranges().into_iter().map(|r| label(&Document::visible_text(st, &spans, r))).find(|t| !t.is_empty()).unwrap_or_default(); if !first.is_empty() { firsts.push((format!("s{k}"), first, 1)); } @@ -107,7 +108,7 @@ pub(crate) fn toc_entries(doc: &Document, order: &[Block]) -> Vec<(String, Strin let Some(pf) = st.paras.get(pi) else { continue }; let (tag, _) = export_mapping(&doc.styles, &pf.style, false, &pc); let Some(level) = heading_level(tag).filter(|l| *l <= 3) else { continue }; - let text = label(st.text.get(r.clone()).unwrap_or("")); + let text = label(&Document::visible_text(st, &spans, r.clone())); if !text.is_empty() { headings.push((format!("s{k}-p{pi}"), text, level)); } diff --git a/crates/epub/src/html.rs b/crates/epub/src/html.rs index 6442d5045..233c2764e 100644 --- a/crates/epub/src/html.rs +++ b/crates/epub/src/html.rs @@ -14,11 +14,22 @@ pub enum Block { pub fn reading_order(doc: &Document) -> Vec { // Articles, when there are any to export, decide the order (and what's included). if doc.articles.iter().any(|a| a.export) { + let hidden_layers: Vec<_> = doc.layers.iter().filter(|l| !l.visible).map(|l| l.id).collect(); let mut out = Vec::new(); let mut seen = Vec::new(); for a in doc.articles.iter().filter(|a| a.export) { for id in &a.items { let Some(top) = doc.item(*id) else { continue }; + // A hidden item or group hides everything in it. The layer that counts is the + // top-level item's: pages draw a group's members on the group's layer. + if doc.find(*id).is_some_and(|loc| { + (1..=loc.path.len()).any(|n| { + doc.item_at(&designcraft_doc::ItemLoc { spread: loc.spread, path: loc.path[..n].to_vec() }) + .is_some_and(|g| g.hidden || n == 1 && hidden_layers.contains(&g.layer)) + }) + }) { + continue; + } let mut push = |it: &Item| match &it.content { Content::Text(tf) if !seen.contains(&tf.story) => { seen.push(tf.story); @@ -27,11 +38,21 @@ pub fn reading_order(doc: &Document) -> Vec { Content::Graphic(_) => out.push(Block::Image(it.id)), _ => {} }; - top.walk(&mut |i| push(i)); + // Hidden items (with everything in them) aren't on the page. + let mut stack = vec![top]; + while let Some(it) = stack.pop() { + if it.hidden { + continue; + } + push(it); + stack.extend(it.children().iter().rev().map(|c| &**c)); + } } } return out; } + let hidden_layers: Vec<_> = doc.layers.iter().filter(|l| !l.visible).map(|l| l.id).collect(); + let shown = shown_items(doc, &hidden_layers); let mut keyed: Vec<((usize, i64, i64), Block)> = Vec::new(); let mut seen_stories = Vec::new(); for (si, sp) in doc.spreads.iter().enumerate() { @@ -45,7 +66,8 @@ pub fn reading_order(doc: &Document) -> Vec { continue; }; let xf = *parent * it.xf; - if it.hidden { + // Hidden items, and top-level items on hidden layers (with everything in them), aren't on the page. + if it.hidden || stack.len() == 1 && hidden_layers.contains(&it.layer) { continue; } let children = it.children(); @@ -55,8 +77,13 @@ pub fn reading_order(doc: &Document) -> Vec { let block = match &it.content { Content::Text(tf) => { let Some(story) = doc.story(tf.story) else { continue }; - // A story is placed where its first frame is. - if story.frames.first() != Some(&it.id) || seen_stories.contains(&tf.story) || story.text.trim().is_empty() { + // A story is placed where its first frame on the page is: a story is left out + // only when every frame of it is hidden, and a hidden first frame does not hide + // the rest of the thread. + if story.frames.iter().find(|f| shown.contains(f)) != Some(&it.id) + || seen_stories.contains(&tf.story) + || story.text.trim().is_empty() + { continue; } seen_stories.push(tf.story); @@ -78,6 +105,22 @@ pub fn reading_order(doc: &Document) -> Vec { keyed.into_iter().map(|(_, b)| b).collect() } +/// The items the page shows: not hidden themselves, in a hidden group, or (top level) on a hidden layer. +fn shown_items(doc: &Document, hidden_layers: &[designcraft_doc::LayerId]) -> std::collections::HashSet { + let mut shown = std::collections::HashSet::new(); + for sp in &doc.spreads { + let mut stack: Vec<(&Item, bool)> = sp.items.iter().map(|i| (&**i, true)).collect(); + while let Some((it, top)) = stack.pop() { + if it.hidden || top && hidden_layers.contains(&it.layer) { + continue; + } + shown.insert(it.id); + stack.extend(it.children().iter().map(|c| (&**c, false))); + } + } + shown +} + /// Package path of an asset: `{dir}/{name}-{id}.{ext}`, the name from its original file name /// (lowercase ASCII, so the package stays readable) and the id keeping two assets of the same /// name apart. diff --git a/crates/epub/src/story_writer.rs b/crates/epub/src/story_writer.rs index d6fb05159..31ca17ebc 100644 --- a/crates/epub/src/story_writer.rs +++ b/crates/epub/src/story_writer.rs @@ -120,9 +120,15 @@ impl<'a, 'f> StoryWriter<'a, 'f> { let mut lead = lead; let mut list: Option<&str> = None; let mut pre: Option<(String, bool)> = None; + let runs: Vec<(std::ops::Range, &story::CharFormat)> = st.runs().collect(); for (pi, (r, pf)) in st.para_ranges().into_iter().zip(&st.paras).enumerate() { let Some(text) = st.text.get(r.clone()) else { continue }; - let table = pf.table.and_then(|id| st.tables.get(&id)).filter(|_| text.contains(story::TABLE_ANCHOR)); + let base = doc.styles.resolve_para(pf).1; + // A table whose anchor is hidden or deleted is off the page, so it stays out. + let table = pf + .table + .and_then(|id| st.tables.get(&id)) + .filter(|_| text.find(story::TABLE_ANCHOR).is_some_and(|at| !doc.hides_run(&base, st.char_format_of(r.start + at)))); let only_table = table.is_some() && text.chars().all(|c| c == story::TABLE_ANCHOR || c.is_whitespace()); if !only_table || !lead.is_empty() { // Export Tagging: the style's element and class. @@ -167,7 +173,7 @@ impl<'a, 'f> StoryWriter<'a, 'f> { lead = ""; let mut after = String::new(); if !only_table { - self.runs(st, r, depth, out, &mut after); + self.runs(st, &runs, r, &base, depth, out, &mut after); } if tag == "pre" { // Closed when the next paragraph isn't a line of the same block. @@ -224,17 +230,29 @@ impl<'a, 'f> StoryWriter<'a, 'f> { t } - /// The runs of paragraph `para` of `st`; footnotes go to `after`. - fn runs(&mut self, st: &Story, para: std::ops::Range, depth: usize, out: &mut String, after: &mut String) { + /// The runs of paragraph `para` of `st` (`runs`: the story's, collected once; `base`: the + /// paragraph's base character attributes); footnotes go to `after`. + #[allow(clippy::too_many_arguments)] + fn runs( + &mut self, + st: &Story, + runs: &[(std::ops::Range, &story::CharFormat)], + para: std::ops::Range, + base: &designcraft_doc::CharProps, + depth: usize, + out: &mut String, + after: &mut String, + ) { let doc = self.doc; - for (rr, f) in st.runs() { + let first = runs.partition_point(|(rr, _)| rr.end <= para.start); + for (rr, f) in runs.iter().skip(first).take_while(|(rr, _)| rr.start < para.end).map(|(rr, f)| (rr.clone(), *f)) { let a = rr.start.max(para.start); let b = rr.end.min(para.end); if a >= b { continue; } - // Hidden conditional text isn't exported. - if f.over.conditions.as_deref().is_some_and(|c| doc.conditions_hide(c)) || f.over.change == Some(designcraft_doc::ChangeMark::Deleted) { + // Hidden conditional text (the styles' conditions included) and deletions aren't exported. + if doc.hides_run(base, f) { continue; } let Some(raw) = st.text.get(a..b) else { continue }; diff --git a/crates/epub/src/tests.rs b/crates/epub/src/tests.rs index 62683f91a..62195aec0 100644 --- a/crates/epub/src/tests.rs +++ b/crates/epub/src/tests.rs @@ -1025,3 +1025,72 @@ fn hidden_group_children_are_not_exported() { assert!(html::reading_order(&grouped_text(true)).is_empty()); assert_eq!(html::reading_order(&grouped_text(false)).len(), 1); } + +/// Text hidden by a condition the paragraph style carries, and text marked deleted, are off the +/// page: neither the HTML body nor the navigation labels show them. A frame on a hidden layer +/// isn't exported at all. +#[test] +fn text_hidden_by_inherited_conditions_or_deletion_is_not_exported() { + use designcraft_doc::{ChangeMark, CharAttrs, Condition, ParagraphStyle}; + let mut d = Document::new(&NewDocument::default()); + d.conditions.push(Condition { name: "Secret".into(), color: [0, 0, 0], visible: false }); + d.styles_mut().paragraph.push(ParagraphStyle { + name: "Classified".into(), + based_on: None, + next_style: None, + para: Default::default(), + chars: CharAttrs { conditions: Some(vec!["Secret".into()]), ..Default::default() }, + shortcut: String::new(), + }); + let lid = d.default_layer(); + let (_, sid) = d + .add_text_frame( + SpreadRef::Doc(0), + Rect::new(36.0, 36.0, 300.0, 100.0), + lid, + "Public heading\nclassified line\nkept dropped", + ParaFormat::default(), + ) + .unwrap(); + let st = d.story_mut(sid).unwrap(); + let c = st.text.find("classified").unwrap(); + st.format_paras(c..c + 1, |p| p.style = "Classified".into()); + let g = st.text.find(" dropped").unwrap(); + st.format_chars(g..g + 8, |f| f.over = CharAttrs { change: Some(ChangeMark::Deleted), ..Default::default() }); + let hidden_layer = designcraft_doc::LayerId(d.alloc()); + d.layers.push(designcraft_doc::Layer { + id: hidden_layer, + name: "Hidden".into(), + color: [0, 0, 0], + visible: false, + locked: false, + printable: true, + show_guides: true, + suppress_wrap_when_hidden: false, + }); + d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 200.0, 300.0, 300.0), hidden_layer, "On a hidden layer", ParaFormat::default()).unwrap(); + let html = html::export_html(&d, &html::HtmlOptions::default()); + assert!(html.contains("Public heading") && html.contains("kept"), "{html}"); + for gone in ["classified line", "dropped", "On a hidden layer"] { + assert!(!html.contains(gone), "{gone} must not be exported: {html}"); + } + let labels: Vec = chapters::toc_entries(&d, &html::reading_order(&d)).into_iter().map(|(_, label, _)| label).collect(); + assert_eq!(labels, ["Public heading"]); +} + +/// A threaded story is left out only when every one of its frames is hidden: a hidden first +/// frame does not hide the frames after it. +#[test] +fn a_threaded_story_is_skipped_only_when_every_frame_is_hidden() { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let (a, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 100.0), lid, "first", ParaFormat::default()).unwrap(); + let (b, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 200.0, 300.0, 300.0), lid, "second", ParaFormat::default()).unwrap(); + d.thread(a, b).unwrap(); + let story = |d: &Document| html::reading_order(d).iter().filter(|x| **x == html::Block::Story(sid)).count(); + assert_eq!(story(&d), 1); + d.item_mut(a).unwrap().hidden = true; + assert_eq!(story(&d), 1, "the visible second frame keeps the story"); + d.item_mut(b).unwrap().hidden = true; + assert_eq!(story(&d), 0); +} diff --git a/crates/epub/tests/it/grouped_reading_order.rs b/crates/epub/tests/it/grouped_reading_order.rs index c4689cf20..eb820883a 100644 --- a/crates/epub/tests/it/grouped_reading_order.rs +++ b/crates/epub/tests/it/grouped_reading_order.rs @@ -145,10 +145,13 @@ fn articles_keep_their_explicit_order_and_exclusions() { let (c, _) = text(&mut doc, 0, 36.0, 10.0, "Article third"); let (omitted, _) = text(&mut doc, 0, 36.0, 5.0, "Excluded story"); doc.articles.push(Article { name: "Unused".into(), items: vec![omitted], export: false }); - doc.articles.push(Article { name: "Chosen".into(), items: vec![grouped, c, grouped], export: true }); + let (hidden, _) = text(&mut doc, 0, 36.0, 1.0, "Hidden in article"); + doc.item_mut(hidden).unwrap().hidden = true; + doc.articles.push(Article { name: "Chosen".into(), items: vec![grouped, c, grouped, hidden], export: true }); assert_output_order(&doc, &["Article first", "Article second", "Article third"]); for output in outputs(&doc) { assert!(!output.contains("Excluded story")); + assert!(!output.contains("Hidden in article")); } } diff --git a/crates/textimport/src/export.rs b/crates/textimport/src/export.rs index 2493f7f98..8d38780d1 100644 --- a/crates/textimport/src/export.rs +++ b/crates/textimport/src/export.rs @@ -20,33 +20,35 @@ fn plain_char(c: char) -> Option<&'static str> { } } -fn table_text(story: &Story, id: u64, nl: &str) -> String { +/// Cells of table `id` as rows of tab-separated cell text (the cells' visible text, nested +/// tables and notes left out), `nl` between rows. +fn table_text(doc: &Document, story: &Story, id: u64, nl: &str) -> String { let Some(t) = story.tables.get(&id) else { return String::new() }; (0..t.nrows()) - .map(|r| (0..t.ncols()).map(|c| t.cell(r, c).map(|x| x.text.text.replace('\n', " ")).unwrap_or_default()).collect::>().join("\t")) + .map(|r| { + (0..t.ncols()) + .map(|c| t.cell(r, c).map(|x| plain_text(doc, &x.text).replace("\r\n", " ").replace('\n', " ")).unwrap_or_default()) + .collect::>() + .join("\t") + }) .collect::>() .join(nl) } -/// Text Only: the story's text, CRLF between paragraphs. -pub fn plain_text(story: &Story) -> String { - // Tracked deletions aren't part of the text. - let deleted: Vec> = - story.runs().filter(|(_, f)| f.over.change == Some(designcraft_doc::ChangeMark::Deleted)).map(|(r, _)| r).collect(); +/// Text Only: the story's text as it shows (hidden conditional text and tracked deletions left +/// out), CRLF between paragraphs. +pub fn plain_text(doc: &Document, story: &Story) -> String { let mut out = String::with_capacity(story.text.len() + 16); + let spans = doc.visible_spans(story); for (i, r) in story.para_ranges().into_iter().enumerate() { if i > 0 { out.push_str("\r\n"); } - let start = r.start; - for (ci, c) in story.text[r].char_indices() { - if deleted.iter().any(|d| d.contains(&(start + ci))) { - continue; - } + for c in Document::visible_text(story, &spans, r).chars() { match (c, plain_char(c)) { (TABLE_ANCHOR, _) => { if let Some(id) = story.paras.get(i).and_then(|p| p.table) { - out.push_str(&table_text(story, id, "\r\n")); + out.push_str(&table_text(doc, story, id, "\r\n")); } } (_, Some("")) => out.push(c), @@ -178,7 +180,7 @@ pub fn rtf(doc: &Document, story: &Story) -> String { match c { TABLE_ANCHOR => { if let Some(id) = table { - for ch in table_text(story, *id, "\u{2028}").chars() { + for ch in table_text(doc, story, *id, "\u{2028}").chars() { rtf_escape(&mut out, ch); } } @@ -214,14 +216,42 @@ mod tests { #[test] fn text_variable_markers_are_dropped() { let st = Story::with_text(StoryId(1), "Page \u{E100} of", Default::default()); - assert_eq!(plain_text(&st), "Page of"); + assert_eq!(plain_text(&Document::new(&NewDocument::default()), &st), "Page of"); let r = rtf(&Document::new(&NewDocument::default()), &st); assert!(!r.contains("\\u-7936") && r.contains("Page of"), "{r}"); } #[test] fn text_only() { - assert_eq!(plain_text(&story()), "Plain bold {x}\r\nCafé\ntwo"); + assert_eq!(plain_text(&Document::new(&NewDocument::default()), &story()), "Plain bold {x}\r\nCafé\ntwo"); + } + + /// Text hidden by a condition set on the paragraph style, and text marked deleted, don't + /// reach Text Only: not in the story and not in a table cell. + #[test] + fn text_only_leaves_out_hidden_and_deleted_text() { + let mut doc = Document::new(&NewDocument::default()); + doc.conditions.push(designcraft_doc::Condition { name: "Secret".into(), color: [0, 0, 0], visible: false }); + doc.styles_mut().paragraph.push(designcraft_doc::ParagraphStyle { + name: "Hidden".into(), + based_on: None, + next_style: None, + para: Default::default(), + chars: CharAttrs { conditions: Some(vec!["Secret".into()]), ..Default::default() }, + shortcut: String::new(), + }); + let mut st = Story::with_text(StoryId(1), "shown\nhidden by style\nkept gone", Default::default()); + let h = st.text.find("hidden").unwrap(); + st.format_paras(h..h + 1, |p| p.style = "Hidden".into()); + let g = st.text.find(" gone").unwrap(); + st.format_chars(g..g + 5, |f| f.over = CharAttrs { change: Some(designcraft_doc::ChangeMark::Deleted), ..Default::default() }); + assert_eq!(plain_text(&doc, &st), "shown\r\n\r\nkept"); + let mut outer = Story::with_text(StoryId(2), &TABLE_ANCHOR.to_string(), Default::default()); + let mut t = designcraft_doc::Table::new(7, 1, 1, 0, 0, 100.0); + t.cells[0].text = st.clone(); + outer.tables.insert(7, std::sync::Arc::new(t)); + outer.paras[0].table = Some(7); + assert_eq!(plain_text(&doc, &outer), "shown kept"); } #[test] diff --git a/crates/textimport/src/tagged.rs b/crates/textimport/src/tagged.rs index c3668614d..572c732c8 100644 --- a/crates/textimport/src/tagged.rs +++ b/crates/textimport/src/tagged.rs @@ -74,13 +74,15 @@ pub fn tagged_text(doc: &Document, story: &Story) -> String { out.push_str("\r\n"); } let pf = story.paras.get(i).cloned().unwrap_or_default(); + let base = doc.styles.resolve_para(&pf).1; let _ = write!(out, "", escape_value(&pf.style)); for (rr, f) in story.runs() { let (a, b) = (rr.start.max(r.start), rr.end.min(r.end)); if a >= b { continue; } - if doc.conditions_hide(f.over.conditions.as_deref().unwrap_or(&[])) || f.over.change == Some(designcraft_doc::ChangeMark::Deleted) { + // Hidden conditional text (the styles' conditions included) and deletions aren't exported. + if doc.hides_run(&base, f) { continue; } let mut open = Vec::new(); From 027bbae9cb3b157750e9213254f03e7192dc10c9 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:28:15 -0500 Subject: [PATCH 1010/1349] Engine: index style, tag, swatch and run lookups; bound polygon sides, Change All and spelling candidates * fix(engine): index lookups that were quadratic in a document's styles, tags, swatches and runs * address review: first swatch per name in book sync; bound spelling input before collecting * address review: keep the last source style per name in book sync; bound GREP replacement bytes while generating them * address review: write GREP replacements into a byte-bounded buffer; gate keep_last test off wasm * merge main into fix/sec-engine-linear-lookups * address review: make the suggestion length-cap test deterministic --- crates/compose/src/grep.rs | 58 ++++++++++++++++++++++++--- crates/engine/src/cmd/book.rs | 51 ++++++++++++++++++----- crates/engine/src/cmd/find.rs | 26 +++++++----- crates/engine/src/cmd/find/tests.rs | 18 +++++++++ crates/engine/src/cmd/paste_svg.rs | 51 ++++++++++++++++++----- crates/engine/src/cmd/select.rs | 3 +- crates/engine/src/cmd/spelling.rs | 20 +++++++++ crates/engine/src/cmd/table/styles.rs | 7 +++- crates/engine/src/cmd/text/edit.rs | 7 +++- crates/engine/src/cmd/xml.rs | 17 +++++--- crates/engine/src/dtd.rs | 14 ++++++- 11 files changed, 229 insertions(+), 43 deletions(-) diff --git a/crates/compose/src/grep.rs b/crates/compose/src/grep.rs index b387384f9..5a56920dc 100644 --- a/crates/compose/src/grep.rs +++ b/crates/compose/src/grep.rs @@ -432,15 +432,36 @@ impl Grep { Ok((out, more)) } - /// Matches in `text` and their replacements, `template` expanded per match (`$1`…; see - /// [`translate_replacement`]). Stops after the first match when `first_only`. - pub fn replacements(&self, text: &str, template: &str, first_only: bool) -> Result, String)>, GrepError> { + /// Matches in `text` that `keep` accepts and their replacements, `template` expanded per match + /// (`$1`…; see [`translate_replacement`]). Stops after the first kept match when `first_only`, + /// and with an error once the expanded replacements pass `max_bytes` in all (before any more + /// are made). + pub fn replacements( + &self, + text: &str, + template: &str, + first_only: bool, + max_bytes: usize, + keep: impl Fn(&Range) -> bool, + ) -> Result, String)>, GrepError> { let exp = fancy_regex::Expander::default(); let mut out = Vec::new(); + let mut bytes = 0usize; for caps in self.re.captures_iter(text) { let caps = caps.map_err(run_err)?; let Some(m) = caps.get(0) else { continue }; - out.push((m.range(), exp.expansion(template, &caps))); + if !keep(&m.range()) { + continue; + } + // Written into a buffer that refuses bytes past the budget, so an oversized + // expansion is rejected before it is allocated. + let mut w = BoundedBuf { buf: Vec::new(), left: max_bytes.saturating_sub(bytes) }; + if exp.write_expansion(&mut w, template, &caps).is_err() { + return Err(err(format!("the replacements would put more than {max_bytes} bytes in"))); + } + bytes += w.buf.len(); + let expanded = String::from_utf8(w.buf).map_err(|_| err("the replacement is not valid UTF-8".to_string()))?; + out.push((m.range(), expanded)); if first_only { break; } @@ -449,6 +470,27 @@ impl Grep { } } +/// A byte sink that fails a write that would pass its remaining budget (nothing is copied then). +struct BoundedBuf { + buf: Vec, + left: usize, +} + +impl std::io::Write for BoundedBuf { + fn write(&mut self, data: &[u8]) -> std::io::Result { + if data.len() > self.left { + return Err(std::io::ErrorKind::OutOfMemory.into()); + } + self.left -= data.len(); + self.buf.extend_from_slice(data); + Ok(data.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + fn run_err(e: fancy_regex::Error) -> GrepError { err(format!("GREP search stopped: {e}")) } @@ -520,7 +562,13 @@ mod tests { assert_eq!(g.find_all("axb A.B a.b", 1).unwrap().first(), Some(&(4..7))); let g = grep(r"(\d+)\h(\l+)"); let tpl = translate_replacement(r"$2~S$1x\r\$$"); - assert_eq!(g.replacements("5 kg", &tpl, false).unwrap(), [(0..4, "kg\u{A0}5x\n$$".to_string())]); + assert_eq!(g.replacements("5 kg", &tpl, false, usize::MAX, |_| true).unwrap(), [(0..4, "kg\u{A0}5x\n$$".to_string())]); + // The total expanded size is bounded while the replacements are made, over the matches kept. + let g = grep("a"); + assert!(g.replacements("aaaa", "xxxx", false, 15, |_| true).is_err()); + assert_eq!(g.replacements("aaaa", "xxxx", false, 16, |_| true).unwrap().len(), 4); + assert_eq!(g.replacements("aaaa", "xxxx", false, 8, |m| m.start < 2).unwrap().len(), 2); + assert_eq!(g.replacements("aaaa", "xxxx", true, 4, |m| m.start >= 2).unwrap(), [(2..3, "xxxx".to_string())]); } #[test] diff --git a/crates/engine/src/cmd/book.rs b/crates/engine/src/cmd/book.rs index a4217f825..29f95741d 100644 --- a/crates/engine/src/cmd/book.rs +++ b/crates/engine/src/cmd/book.rs @@ -1,6 +1,8 @@ //! Books (File › New / Open Book): an ordered list of documents with continuous page numbers, //! styles synchronised from a style source, and one PDF for the whole book. Saved as `.dcbook`. +use std::collections::{HashMap, HashSet}; + use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -177,6 +179,15 @@ fn paginate(s: &Session) -> Result { Ok(json!({"pages": next - 1, "chapters": chapters})) } +/// `list` with only the last entry of each name, in the order of those last entries. +#[cfg(not(target_arch = "wasm32"))] +fn keep_last(list: &[T], name: impl Fn(&T) -> &str) -> Vec<&T> { + let mut seen = HashSet::new(); + let mut out: Vec<&T> = list.iter().rev().filter(|x| seen.insert(name(x))).collect(); + out.reverse(); + out +} + #[cfg(not(target_arch = "wasm32"))] fn sync_styles(s: &Session) -> Result { let b = s.book.as_ref().ok_or_else(no_book)?; @@ -187,6 +198,11 @@ fn sync_styles(s: &Session) -> Result { let styles = src.styles.clone(); let swatches = src.swatches.clone(); drop(src); + // A name the source defines twice keeps its last definition, at its last position. + let paragraph = keep_last(&styles.paragraph, |x| x.name.as_str()); + let character = keep_last(&styles.character, |x| x.name.as_str()); + let (paragraph_names, character_names): (HashSet<&str>, HashSet<&str>) = + (paragraph.iter().map(|x| x.name.as_str()).collect(), character.iter().map(|x| x.name.as_str()).collect()); let mut n = 0; for (i, path) in paths.iter().enumerate() { if i == b.style_source { @@ -195,21 +211,27 @@ fn sync_styles(s: &Session) -> Result { writable_chapter(s, path, "book.syncStyles")?; let mut d = load(path)?; { + // The source's styles replace the chapter's of the same names and go last, in the + // source's order (one pass over each list, not one per style). let st = d.styles_mut(); - for ps in &styles.paragraph { - st.paragraph.retain(|x| x.name != ps.name); - st.paragraph.push(ps.clone()); - } - for cs in &styles.character { - st.character.retain(|x| x.name != cs.name); - st.character.push(cs.clone()); - } + st.paragraph.retain(|x| !paragraph_names.contains(x.name.as_str())); + st.paragraph.extend(paragraph.iter().map(|x| (*x).clone())); + st.character.retain(|x| !character_names.contains(x.name.as_str())); + st.character.extend(character.iter().map(|x| (*x).clone())); + } + // First index per name, as Document::swatch resolves colours. + let mut at: HashMap = HashMap::new(); + for (i, w) in d.swatches.iter().enumerate() { + at.entry(w.name.clone()).or_insert(i); } for sw in &swatches { - match d.swatches.iter_mut().find(|w| w.name == sw.name) { + match at.get(&sw.name).and_then(|i| d.swatches.get_mut(*i)) { Some(w) if !w.locked => *w = sw.clone(), Some(_) => {} - None => d.swatches.push(sw.clone()), + None => { + at.insert(sw.name.clone(), d.swatches.len()); + d.swatches.push(sw.clone()); + } } } batch.stage(path, &d)?; @@ -431,4 +453,13 @@ mod tests { assert_eq!(t.execute("book.open", &json!({"path": p("book.dcbook")})).unwrap()["documents"], 2); std::fs::remove_dir_all(&dir).ok(); } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_source_style_defined_twice_keeps_its_last_definition() { + let list = [("a", 1), ("b", 2), ("a", 3), ("c", 4)]; + let kept: Vec<_> = super::keep_last(&list, |x| x.0).into_iter().copied().collect(); + // As the one-style-at-a-time loop left them: each name once, at its last position. + assert_eq!(kept, [("b", 2), ("a", 3), ("c", 4)]); + } } diff --git a/crates/engine/src/cmd/find.rs b/crates/engine/src/cmd/find.rs index b9ab42550..63a1debb9 100644 --- a/crates/engine/src/cmd/find.rs +++ b/crates/engine/src/cmd/find.rs @@ -316,19 +316,27 @@ impl Search { ) -> Result, String)>> { let limit = if first_only { 1 } else { usize::MAX }; match (&self.re, self.spans(d, sid, cell, r)) { - (Some(re), None) if grep => re.replacements(text, rep, first_only).map_err(|e| bad("find.change", e)), - (Some(re), Some(spans)) if grep => Ok(re - .replacements(text, rep, false) - .map_err(|e| bad("find.change", e))? - .into_iter() - .filter(|(m, _)| within(&spans, m)) - .take(limit) - .collect()), - _ => Ok(self.find_all(d, sid, cell, r, text, limit)?.into_iter().map(|m| (m, rep.to_string())).collect()), + (Some(re), spans) if grep => re + .replacements(text, rep, first_only, MAX_CHANGE_BYTES, |m| spans.as_ref().is_none_or(|s| within(s, m))) + .map_err(|e| bad("find.change", e)), + _ => { + let found = self.find_all(d, sid, cell, r, text, limit)?; + // Every match gets its own copy of the change: bounded before any is made. + if found.len().saturating_mul(rep.len()) > MAX_CHANGE_BYTES { + return Err(bad( + "find.change", + format!("changing {} matches to {} bytes each would put more than {MAX_CHANGE_BYTES} bytes in", found.len(), rep.len()), + )); + } + Ok(found.into_iter().map(|m| (m, rep.to_string())).collect()) + } } } } +/// The most text one Change All may put into a story: the matches times the change's length. +const MAX_CHANGE_BYTES: usize = 64 << 20; + #[derive(Clone, Debug, PartialEq, Eq)] enum Domain { Document, diff --git a/crates/engine/src/cmd/find/tests.rs b/crates/engine/src/cmd/find/tests.rs index 348acd294..edea872ad 100644 --- a/crates/engine/src/cmd/find/tests.rs +++ b/crates/engine/src/cmd/find/tests.rs @@ -959,3 +959,21 @@ fn change_takes_any_selection_find_next_made() { assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, if grep { "a" } else { "ab" }); } } + +/// Change All with a long change and many matches is refused before any copy of the change is +/// made, not after the memory for all of them has gone. +#[test] +fn change_all_is_bounded_by_what_it_would_put_in() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let text = "x ".repeat(2048); + s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": text})).unwrap(); + let huge = "y".repeat(40_000); + let e = s.execute("find.change", &json!({"find": "x", "change": huge})).unwrap_err().to_string(); + assert!(e.contains("would put more than"), "{e}"); + // GREP replacements are held to the same total while they are made. + let e = s.execute("find.change", &json!({"find": "x", "change": huge, "grep": true})).unwrap_err().to_string(); + assert!(e.contains("would put more than"), "{e}"); + let r = s.execute("find.change", &json!({"find": "x", "change": "yy"})).unwrap(); + assert_eq!(r["count"], 2048); +} diff --git a/crates/engine/src/cmd/paste_svg.rs b/crates/engine/src/cmd/paste_svg.rs index a5d738cef..fa3c1cffc 100644 --- a/crates/engine/src/cmd/paste_svg.rs +++ b/crates/engine/src/cmd/paste_svg.rs @@ -3,6 +3,8 @@ //! clipboard as SVG markup; each path becomes a DesignCraft path with its fill and stroke, groups //! stay groups, and text comes in as outlines. +use std::collections::{HashMap, HashSet}; + use designcraft_doc::{Content, Fill, Item, ItemId, Selection, Shape, Stroke, StrokeType}; use designcraft_geom::{Affine, BezPath, PathData, Point, Rect}; use designcraft_images::usvg; @@ -201,16 +203,46 @@ fn bounds(art: &[Art]) -> Option { .reduce(|a, b| a.union(b)) } +/// The document's RGB colour swatches by colour and its swatch names, looked up once per paste +/// (a pasted SVG can hold tens of thousands of colours). +struct PasteSwatches { + by_rgb: HashMap<[u32; 3], String>, + names: HashSet, +} + +impl PasteSwatches { + /// An RGB colour as a key: equal colours, equal keys (`+ 0.0` makes -0 and 0 one key). + fn key(r: f32, g: f32, b: f32) -> [u32; 3] { + [(r + 0.0).to_bits(), (g + 0.0).to_bits(), (b + 0.0).to_bits()] + } + + fn new(d: &designcraft_doc::Document) -> Self { + use designcraft_color::swatch::SwatchValue; + let mut by_rgb = HashMap::new(); + for w in &d.swatches { + if let SwatchValue::Color { color: designcraft_color::Color::Rgb { r, g, b }, .. } = &w.value { + // The first swatch of a colour is the one, as a search from the start finds it. + by_rgb.entry(Self::key(*r, *g, *b)).or_insert_with(|| w.name.clone()); + } + } + Self { by_rgb, names: d.swatches.iter().map(|w| w.name.clone()).collect() } + } +} + /// The swatch holding exactly `rgb`: an existing process colour, else a new unnamed one (hidden /// from the Swatches panel until Add to Swatches), as InDesign does for pasted colours. -fn swatch_for(d: &mut designcraft_doc::Document, rgb: [u8; 3]) -> String { +fn swatch_for(d: &mut designcraft_doc::Document, known: &mut PasteSwatches, rgb: [u8; 3]) -> String { use designcraft_color::swatch::{Swatch, SwatchValue}; let color = designcraft_color::Color::rgb8(rgb[0], rgb[1], rgb[2]); - if let Some(w) = d.swatches.iter().find(|w| matches!(&w.value, SwatchValue::Color { color: c, .. } if *c == color)) { - return w.name.clone(); + let designcraft_color::Color::Rgb { r, g, b } = color else { return String::new() }; + let key = PasteSwatches::key(r, g, b); + if let Some(name) = known.by_rgb.get(&key) { + return name.clone(); } let base = format!("R={} G={} B={}", rgb[0], rgb[1], rgb[2]); - let name = designcraft_doc::Styles::unique_name(|n| d.swatch(n).is_some(), &base); + let name = designcraft_doc::Styles::unique_name(|n| known.names.contains(n), &base); + known.names.insert(name.clone()); + known.by_rgb.insert(key, name.clone()); d.swatches.push(Swatch { name: name.clone(), value: SwatchValue::Color { color, color_type: designcraft_color::ColorType::Process }, @@ -221,7 +253,7 @@ fn swatch_for(d: &mut designcraft_doc::Document, rgb: [u8; 3]) -> String { name } -fn build(d: &mut designcraft_doc::Document, art: Vec, layer: designcraft_doc::LayerId, shift: Affine) -> Vec { +fn build(d: &mut designcraft_doc::Document, known: &mut PasteSwatches, art: Vec, layer: designcraft_doc::LayerId, shift: Affine) -> Vec { let mut out = Vec::new(); for a in art { match a { @@ -239,12 +271,12 @@ fn build(d: &mut designcraft_doc::Document, art: Vec, layer: designcraft_do let paint = fill.map(|f| f.opacity).or(stroke.as_ref().map(|(c, _)| c.opacity)).unwrap_or(1.0); let mut it = Item::new(ItemId(d.alloc()), layer, if line { Shape::GraphicLine } else { Shape::Path }, data); it.fill = match fill { - Some(f) => Fill::swatch(&swatch_for(d, f.rgb)), + Some(f) => Fill::swatch(&swatch_for(d, known, f.rgb)), None => Fill::none(), }; it.stroke = match stroke { Some((c, s)) => Stroke { - swatch: swatch_for(d, c.rgb), + swatch: swatch_for(d, known, c.rgb), weight: s.width, cap: s.cap, join: s.join, @@ -258,7 +290,7 @@ fn build(d: &mut designcraft_doc::Document, art: Vec, layer: designcraft_do out.push(it); } Art::Group(items, opacity) => { - let children = build(d, items, layer, shift); + let children = build(d, known, items, layer, shift); if children.is_empty() { continue; } @@ -312,7 +344,8 @@ fn paste_svg(s: &mut Session, p: &Value) -> Result { warnings.push(format!("{} embedded image(s) left out (place images with File › Place)", notes.images)); } s.edit(|d, sel| { - let items = build(d, art, layer, shift); + let mut known = PasteSwatches::new(d); + let items = build(d, &mut known, art, layer, shift); let mut ids = Vec::new(); for it in items { ids.push(it.id); diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 0f77d5372..e351fe837 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -133,7 +133,8 @@ fn convert_shape(s: &mut Session, p: &Value) -> Result { const ID: &str = "object.convertShape"; let to = str_param(p, "to").ok_or_else(|| bad(ID, "`to` required"))?.to_string(); let ids = targets(s, p)?; - let sides = s.prefs.polygon_sides; + // The preference as object.polygon takes it: 3–100 sides, whatever prefs.set was given. + let sides = s.prefs.polygon_sides.clamp(3, 100); let inset = s.prefs.star_inset; s.edit(|d, _| { let mut changed = 0; diff --git a/crates/engine/src/cmd/spelling.rs b/crates/engine/src/cmd/spelling.rs index 4a43ab752..8ff9ac94d 100644 --- a/crates/engine/src/cmd/spelling.rs +++ b/crates/engine/src/cmd/spelling.rs @@ -161,6 +161,9 @@ const COMMON: &[&str] = &[ "yay", ]; +/// Longest word [`suggest`] makes candidates for. +pub const MAX_SUGGEST_CHARS: usize = 40; + /// Is `w` (lowercase) a known word, allowing common inflections of dictionary stems? pub fn known(dict: &Dictionary, user: &[String], w: &str) -> bool { // A typographer's apostrophe (don’t, we’re) is the word list's straight one. @@ -207,6 +210,11 @@ pub fn known(dict: &Dictionary, user: &[String], w: &str) -> bool { /// Up to 6 suggestions at edit distance 1, ranked: transpositions, replacements, deletions, insertions. pub fn suggest(dict: &Dictionary, w: &str) -> Vec { + // Each candidate is a copy of the word: 53 per position, quadratic in its length. No word of + // a dictionary is this long, so no edit of such a "word" is one either. Checked before collecting. + if w.chars().take(MAX_SUGGEST_CHARS + 1).count() > MAX_SUGGEST_CHARS { + return Vec::new(); + } let chars: Vec = w.chars().collect(); let mut out: Vec = Vec::new(); let mut push = |c: Vec| { @@ -325,6 +333,18 @@ mod tests { assert!(known(d, &["designcraft".into()], "designcraft")); } + /// A "word" longer than any in the dictionary gets no candidates: there would be more than + /// fifty copies of it per character. + #[test] + fn very_long_words_get_no_suggestions() { + // The dictionary holds the longest allowed word, so deleting one letter of the 41-letter + // input would be a hit if the length cap were not applied. + let d = Dictionary::from_entries(vec![("a".repeat(MAX_SUGGEST_CHARS), 0)]); + assert_eq!(suggest(&d, &"a".repeat(MAX_SUGGEST_CHARS)), Vec::::new()); + assert_eq!(suggest(&d, &"a".repeat(MAX_SUGGEST_CHARS - 1)), vec!["a".repeat(MAX_SUGGEST_CHARS)]); + assert!(suggest(&d, &"a".repeat(MAX_SUGGEST_CHARS + 1)).is_empty()); + } + #[test] fn user_dictionary_replaces_and_counts() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/table/styles.rs b/crates/engine/src/cmd/table/styles.rs index fa3717977..046904fef 100644 --- a/crates/engine/src/cmd/table/styles.rs +++ b/crates/engine/src/cmd/table/styles.rs @@ -133,6 +133,11 @@ fn reapply_cell_styles(d: &mut Document, names: &[String]) { /// Include descendants when editing an inherited style, with the resolver's depth limit. fn dependent_styles<'a>(name: &str, styles: impl Iterator)>) -> Vec { let styles: Vec<_> = styles.collect(); + // The first style of a name is the one, as the resolver's lookup finds it. + let mut based_on: std::collections::HashMap<&str, Option<&str>> = std::collections::HashMap::new(); + for (n, base) in &styles { + based_on.entry(n).or_insert(*base); + } styles .iter() .filter(|(candidate, _)| { @@ -142,7 +147,7 @@ fn dependent_styles<'a>(name: &str, styles: impl Iterator Result { let mut changes = Vec::new(); for seg in segs.iter().rev() { let old = st.slice(seg.clone()).to_string(); - let new: String = starts.iter().zip(&mapped).filter(|(b, _)| seg.contains(b)).map(|(_, m)| m.as_str()).collect(); + // The characters in this run: `starts` is sorted, so a search finds the slice. + let (from, to) = (starts.partition_point(|b| *b < seg.start), starts.partition_point(|b| *b < seg.end)); + let new: String = mapped.get(from..to).unwrap_or_default().iter().map(String::as_str).collect(); if new != old { delta += new.len() as isize - old.len() as isize; st.replace(seg.clone(), &new); // Per-character changes (back to front), so ranges inside the run keep their boundaries. - for (i, (b, m)) in starts.iter().zip(&mapped).enumerate().rev().filter(|(_, (b, _))| seg.contains(b)) { + for i in (from..to.min(mapped.len())).rev() { + let (b, m) = (&starts[i], &mapped[i]); let ce = starts.get(i + 1).copied().unwrap_or(r.end); if m.len() != ce - b { changes.push((*b..ce, m.len())); diff --git a/crates/engine/src/cmd/xml.rs b/crates/engine/src/cmd/xml.rs index 81b57b5b3..949d96436 100644 --- a/crates/engine/src/cmd/xml.rs +++ b/crates/engine/src/cmd/xml.rs @@ -60,10 +60,13 @@ fn plain(t: &str) -> String { } /// A paragraph's text with inline-tagged runs as elements. -fn para_xml(st: &designcraft_doc::Story, r: std::ops::Range) -> String { +/// `runs` are the story's runs in order (collected once per story): only those reaching the +/// paragraph are visited, found by binary search. +fn para_xml(st: &designcraft_doc::Story, runs: &[(std::ops::Range, &designcraft_doc::CharFormat)], r: std::ops::Range) -> String { let mut out = String::new(); let mut open: Option = None; - for (rr, f) in st.runs() { + let first = runs.partition_point(|(rr, _)| rr.end <= r.start); + for (rr, f) in runs.iter().skip(first).take_while(|(rr, _)| rr.start < r.end) { let (a, b) = (rr.start.max(r.start), rr.end.min(r.end)); if a >= b { continue; @@ -97,8 +100,10 @@ pub fn export_xml(d: &Document) -> String { let Some(st) = d.story(tf.story) else { continue }; let mapped = |style: &str| d.xml.style_map.iter().find(|(s, _)| s == style).map(|(_, t)| t.clone()); // Paragraph text with inline tags already escaped. - let paras: Vec<(Option, String)> = - st.para_ranges().into_iter().enumerate().map(|(i, r)| (mapped(&st.paras[i].style), para_xml(st, r))).collect(); + let paras: Vec<(Option, String)> = { + let runs: Vec<_> = st.runs().collect(); + st.para_ranges().into_iter().enumerate().map(|(i, r)| (mapped(&st.paras[i].style), para_xml(st, &runs, r))).collect() + }; if paras.iter().any(|(m, _)| m.is_some()) { out.push_str(&format!(" <{tag}>\n")); for (m, text) in paras { @@ -341,8 +346,10 @@ pub fn specs() -> Vec { let dtd = crate::dtd::parse(&text).map_err(|e| bad("xml.loadDtd", e))?; let names: Vec = dtd.element_names().map(str::to_string).collect(); s.edit(|d, _| { + // The tags there are, then those added: one set, not a search per element. + let mut known: std::collections::HashSet = d.xml.tags.iter().map(|t| t.name.clone()).collect(); for n in &names { - if valid_name(n) && !d.xml.tags.iter().any(|t| t.name == *n) { + if valid_name(n) && known.insert(n.clone()) { let color = COLORS[d.xml.tags.len() % COLORS.len()]; d.xml.tags.push(XmlTag { name: n.clone(), color }); } diff --git a/crates/engine/src/dtd.rs b/crates/engine/src/dtd.rs index 7128ba84e..c0d45d820 100644 --- a/crates/engine/src/dtd.rs +++ b/crates/engine/src/dtd.rs @@ -29,6 +29,8 @@ enum Model { #[derive(Clone, Debug, Default)] pub struct Dtd { elements: Vec<(String, Model)>, + /// Each declared name's first declaration (which wins), by name. + index: HashMap, /// Element → its `#REQUIRED` attributes. required: HashMap>, } @@ -47,7 +49,7 @@ impl Dtd { } fn model(&self, name: &str) -> Option<&Model> { - self.elements.iter().find(|(n, _)| n == name).map(|(_, m)| m) + self.elements.get(*self.index.get(name)?).map(|(_, m)| m) } } @@ -252,6 +254,7 @@ pub fn parse(src: &str) -> Result { let rest = rest.trim_start(); let name: String = rest.chars().take_while(|c| !c.is_whitespace()).collect(); let model = parse_model(&rest[name.len()..]).map_err(|e| format!(": {e}"))?; + dtd.index.entry(name.clone()).or_insert(dtd.elements.len()); dtd.elements.push((name, model)); } else if let Some(rest) = d.strip_prefix("ATTLIST") { // name (attr type default)*; only `#REQUIRED` matters here. @@ -609,6 +612,15 @@ mod tests { assert!(parse("just text").is_err()); } + /// An element declared twice keeps its first model (the index points there). + #[test] + fn the_first_declaration_of_an_element_wins() { + let dtd = parse("\n\n").unwrap(); + assert_eq!(dtd.element_names().collect::>(), ["a", "b", "a"]); + assert_eq!(validate(&dtd, ""), vec![]); + assert!(!validate(&dtd, "").is_empty()); + } + /// A few hundred bytes of nested parameter entities used to inflate multiplicatively across /// the eight wholly-string-replacing passes (#713); expansion is capped. #[test] From 95fdb96680e8133af05b90c3dd329126e206d858 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 05:19:22 -0800 Subject: [PATCH 1011/1349] Text wrap: a clipped contour visits only the edges in each line band A clipped contour now looks only at the edges of the outline and its clips that reach a line band, and charges its work budget for those alone. An outline with thousands of points elsewhere no longer exhausts the budget and falls back to the projections' common part. The Text wrap row of docs/typography-parity.md notes that an image over 40 megapixels, or one that can't be decoded, follows the frame's path. --- crates/compose/src/lib.rs | 150 ++++++++++++++++++++---------------- crates/compose/src/tests.rs | 30 ++++++++ docs/typography-parity.md | 2 +- 3 files changed, 115 insertions(+), 67 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 76df87568..4224b793f 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -406,10 +406,6 @@ impl Region<'_> { fn fills(self, winding: i32) -> bool { if self.even_odd { winding % 2 != 0 } else { winding != 0 } } - - fn edges(self) -> usize { - self.rings.iter().map(Vec::len).sum() - } } /// Points a contour outline may have; a larger outline wraps around its bounding box. @@ -545,19 +541,56 @@ fn intersect_spans(a: &[(f64, f64)], b: &[(f64, f64)]) -> Vec<(f64, f64)> { /// one shape that lies inside the others. The spans are the middle slice of all the shapes and /// the parts of each shape's edges in the band that lie inside the others, so a part of the /// outline outside a clip blocks nothing, even where it shares x positions with the clip in the -/// same band. None when that takes more than [`MAX_CLIPPED_WORK`] edge visits. +/// same band. Only the edges that reach the band are visited. None when that takes more than +/// [`MAX_CLIPPED_WORK`] edge visits. fn clipped_band_spans(shapes: &[Region], y0: f64, y1: f64) -> Option> { let middle = y0 * 0.5 + y1 * 0.5; let mut slices = shapes.iter().map(|s| merge_spans(middle_spans(*s, middle))); let first = slices.next()?; let mut spans = slices.fold(first, |a, b| intersect_spans(&a, &b)); + let banded: Vec = shapes.iter().map(|s| BandEdges::of(*s, y0, y1)).collect(); let mut budget = MAX_CLIPPED_WORK; - for k in 0..shapes.len() { - edges_inside(shapes, k, y0, y1, &mut budget, &mut spans)?; + for k in 0..banded.len() { + edges_inside(&banded, k, y0, y1, &mut budget, &mut spans)?; } Some(merge_spans(spans)) } +/// The edges of a shape that reach a line band, with a margin above and below. Every point +/// [`segment_inside`] tests lies within the margin, and an edge that doesn't reach a point's y +/// neither crosses the ray from it nor passes within a hair of it, so these edges give the same +/// inside and on-edge answers as the whole shape for those points. +struct BandEdges { + edges: Vec<(Point, Point)>, + even_odd: bool, +} + +impl BandEdges { + /// Margin added above and below the band; well above the side step in [`segment_inside`]. + const MARGIN: f64 = 1e-3; + + fn of(shape: Region, y0: f64, y1: f64) -> BandEdges { + let (lo, hi) = (y0 - Self::MARGIN, y1 + Self::MARGIN); + let mut edges = Vec::new(); + for ring in shape.rings { + let Some(&last) = ring.last() else { continue }; + let mut a = last; + for &b in ring { + if a.y.max(b.y) >= lo && a.y.min(b.y) <= hi { + edges.push((a, b)); + } + a = b; + } + } + BandEdges { edges, even_odd: shape.even_odd } + } + + /// Is a point with this winding number filled? + fn fills(&self, winding: i32) -> bool { + if self.even_odd { winding % 2 != 0 } else { winding != 0 } + } +} + /// Takes `n` edge visits from `budget`; None when it doesn't hold that many. fn spend(budget: &mut usize, n: usize) -> Option<()> { *budget = budget.checked_sub(n)?; @@ -567,25 +600,19 @@ fn spend(budget: &mut usize, n: usize) -> Option<()> { /// Pushes to `out` the x-ranges of the parts of the edges of `shapes[k]` within the band `y0..y1` /// that bound the part of the plane inside all of `shapes` ([`segment_inside`]). None when /// `budget` runs out. -fn edges_inside(shapes: &[Region], k: usize, y0: f64, y1: f64, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { - let n = shapes.iter().map(|o| o.edges()).sum::().max(1); - let rings = shapes.get(k)?.rings; - for ring in rings { - let Some(&last) = ring.last() else { continue }; - let mut a = last; - for &b in ring { - let dy = b.y - a.y; - if a.y.max(b.y) >= y0 && a.y.min(b.y) <= y1 { - let (t0, t1) = if dy.abs() < 1e-12 { - (0.0, 1.0) - } else { - let (u, v) = ((y0 - a.y) / dy, (y1 - a.y) / dy); - (u.min(v).clamp(0.0, 1.0), u.max(v).clamp(0.0, 1.0)) - }; - let (p, q) = (a + (b - a) * t0, a + (b - a) * t1); - segment_inside(p, q, shapes, k, n, budget, out)?; - } - a = b; +fn edges_inside(shapes: &[BandEdges], k: usize, y0: f64, y1: f64, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { + let n = shapes.iter().map(|o| o.edges.len()).sum::().max(1); + for &(a, b) in &shapes.get(k)?.edges { + let dy = b.y - a.y; + if a.y.max(b.y) >= y0 && a.y.min(b.y) <= y1 { + let (t0, t1) = if dy.abs() < 1e-12 { + (0.0, 1.0) + } else { + let (u, v) = ((y0 - a.y) / dy, (y1 - a.y) / dy); + (u.min(v).clamp(0.0, 1.0), u.max(v).clamp(0.0, 1.0)) + }; + let (p, q) = (a + (b - a) * t0, a + (b - a) * t1); + segment_inside(p, q, shapes, k, n, budget, out)?; } } Some(()) @@ -597,14 +624,14 @@ fn edges_inside(shapes: &[Region], k: usize, y0: f64, y1: f64, budget: &mut usiz /// the points just beside it on one side are inside all the shapes. Where `shapes[k]` has no area /// on either side (an open path), it counts when it is inside the other shapes or on their /// boundary. Each pass over the edges takes `n` from `budget`; None when it runs out. -fn segment_inside(p: Point, q: Point, shapes: &[Region], k: usize, n: usize, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { +fn segment_inside(p: Point, q: Point, shapes: &[BandEdges], k: usize, n: usize, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { let r = q - p; let len2 = r.hypot2(); if !len2.is_finite() { return Some(()); } let at = |t: f64| p + r * t; - let in_others = |pt: Point| shapes.iter().enumerate().all(|(i, s)| i == k || inside_or_on(*s, pt)); + let in_others = |pt: Point| shapes.iter().enumerate().all(|(i, s)| i == k || inside_or_on(s, pt)); spend(budget, n)?; if len2 < 1e-24 { if in_others(p) { @@ -615,7 +642,7 @@ fn segment_inside(p: Point, q: Point, shapes: &[Region], k: usize, n: usize, bud // A step to either side of the segment, well above rounding at page coordinates. let side = r.turn_90() * (1e-6 / len2.sqrt()); let bounds_the_part = |m: Point| { - let own = shapes.get(k).copied(); + let own = shapes.get(k); let in_own = |pt: Point| own.is_some_and(|s| inside_or_on(s, pt)); let (a, b) = (m + side, m - side); match (in_own(a), in_own(b)) { @@ -625,29 +652,24 @@ fn segment_inside(p: Point, q: Point, shapes: &[Region], k: usize, n: usize, bud }; let (ylo, yhi) = (p.y.min(q.y), p.y.max(q.y)); let mut ts = vec![0.0, 1.0]; - for ring in shapes.iter().enumerate().filter(|(i, _)| *i != k).flat_map(|(_, s)| s.rings) { - let Some(&last) = ring.last() else { continue }; - let mut c = last; - for &d in ring { - if c.y.max(d.y) >= ylo - 1e-9 && c.y.min(d.y) <= yhi + 1e-9 { - let e = d - c; - let denom = r.cross(e); - let w = c - p; - if denom.abs() > 1e-12 * (len2 * e.hypot2()).sqrt() { - let (t, u) = (w.cross(e) / denom, w.cross(r) / denom); - if (-1e-9..=1.0 + 1e-9).contains(&u) && (0.0..=1.0).contains(&t) { + for &(c, d) in shapes.iter().enumerate().filter(|(i, _)| *i != k).flat_map(|(_, s)| &s.edges) { + if c.y.max(d.y) >= ylo - 1e-9 && c.y.min(d.y) <= yhi + 1e-9 { + let e = d - c; + let denom = r.cross(e); + let w = c - p; + if denom.abs() > 1e-12 * (len2 * e.hypot2()).sqrt() { + let (t, u) = (w.cross(e) / denom, w.cross(r) / denom); + if (-1e-9..=1.0 + 1e-9).contains(&u) && (0.0..=1.0).contains(&t) { + ts.push(t); + } + } else if w.cross(r).abs() <= 1e-9 * len2.sqrt() { + // Collinear: the edge's ends split the segment. + for t in [w.dot(r) / len2, (d - p).dot(r) / len2] { + if (0.0..=1.0).contains(&t) { ts.push(t); } - } else if w.cross(r).abs() <= 1e-9 * len2.sqrt() { - // Collinear: the edge's ends split the segment. - for t in [w.dot(r) / len2, (d - p).dot(r) / len2] { - if (0.0..=1.0).contains(&t) { - ts.push(t); - } - } } } - c = d; } } ts.sort_by(f64::total_cmp); @@ -663,26 +685,22 @@ fn segment_inside(p: Point, q: Point, shapes: &[Region], k: usize, n: usize, bud Some(()) } -/// Is `pt` inside `shape` or within a hair of one of its edges? -fn inside_or_on(shape: Region, pt: Point) -> bool { +/// Is `pt`, a point within the band of `shape`'s edges, inside the shape or within a hair of one +/// of its edges? +fn inside_or_on(shape: &BandEdges, pt: Point) -> bool { let mut winding = 0i32; - for ring in shape.rings { - let Some(&last) = ring.last() else { continue }; - let mut a = last; - for &b in ring { - let e = b - a; - let len2 = e.hypot2(); - let t = if len2 > 0.0 { ((pt - a).dot(e) / len2).clamp(0.0, 1.0) } else { 0.0 }; - if (a + e * t - pt).hypot2() < 1e-18 { - return true; + for &(a, b) in &shape.edges { + let e = b - a; + let len2 = e.hypot2(); + let t = if len2 > 0.0 { ((pt - a).dot(e) / len2).clamp(0.0, 1.0) } else { 0.0 }; + if (a + e * t - pt).hypot2() < 1e-18 { + return true; + } + if (a.y <= pt.y && pt.y < b.y) || (b.y <= pt.y && pt.y < a.y) { + let x = a.x + (pt.y - a.y) / e.y * e.x; + if x > pt.x { + winding += if e.y > 0.0 { 1 } else { -1 }; } - if (a.y <= pt.y && pt.y < b.y) || (b.y <= pt.y && pt.y < a.y) { - let x = a.x + (pt.y - a.y) / e.y * e.x; - if x > pt.x { - winding += if e.y > 0.0 { 1 } else { -1 }; - } - } - a = b; } } shape.fills(winding) diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index e8fb2aac8..8ea0fe3cc 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -8612,6 +8612,36 @@ fn a_clipped_contour_blocks_only_what_its_frame_shows() { assert_eq!(c.within(&poly(&detailed), id).band_spans(0.0, 10.0), vec![(20.0, 40.0)]); } +/// Edges far above or below a line band cost a clipped contour nothing there: an outline with +/// 7,000 points well below the band still gets the exact spans, not the projections' common part. +#[test] +fn a_clipped_contours_budget_counts_only_edges_in_the_band() { + let poly = |pts: &[(f64, f64)]| { + let mut p = designcraft_geom::BezPath::new(); + p.move_to(pts[0]); + for &q in &pts[1..] { + p.line_to(q); + } + p.close_path(); + p + }; + let id = designcraft_geom::Affine::IDENTITY; + // The L-shaped frame of the test above, with its notch at x 10..40 above y = 6. + let frame = poly(&[(0.0, 0.0), (10.0, 0.0), (10.0, 6.0), (40.0, 6.0), (40.0, 10.0), (0.0, 10.0)]); + // An outline in the notch and to the right of the frame, with 40 teeth along its top in the + // band and a 7,000-point zigzag along its bottom at y = 200. + let mut pts = vec![(20.0, 0.0)]; + for i in 0..40 { + let x = 40.0 + 0.5 * f64::from(i); + pts.extend([(x, 0.0), (x + 0.25, 0.5)]); + } + pts.push((60.0, 0.0)); + pts.extend((0..7000).map(|i| (60.0 - 10.0 * f64::from(i) / 6999.0, if i % 2 == 0 { 200.0 } else { 201.0 }))); + pts.extend([(50.0, 4.0), (20.0, 4.0)]); + let c = Contour::of(&poly(&pts), id, 0.0).unwrap(); + assert_eq!(c.within(&frame, id).band_spans(0.0, 10.0), Vec::<(f64, f64)>::new(), "the frame shows none of it"); +} + /// Rule Above's offset runs from the first line's baseline up to the rule's bottom edge, as in /// InDesign: a rule set clear of the cap height sits between the rows, not across the row above /// (an INDD project list whose rules crossed the previous paragraph's text). diff --git a/docs/typography-parity.md b/docs/typography-parity.md index 0b3c030cf..323e028dc 100644 --- a/docs/typography-parity.md +++ b/docs/typography-parity.md @@ -59,7 +59,7 @@ Fidelity: **unmeasured** unless stated. | Paragraph rules, borders, shading | ✓ | ✓ | ✓ | | | Balance ragged lines | ✓ | ✓ | ✓ | | | Optical margin alignment | per story with a size, Ignore Optical Margin per paragraph and style | ✓ (hang table of our own, scaled by the story's size; Story panel; IDML `StoryPreference`, `IgnoreEdgeAlignment`) | ~ | hang amounts are ours, InDesign's unknown (#947) | -| Text wrap | bounding box, shape, jump object/column, wrap sides (text on both sides of an object), contour options, on page items and anchored objects | ✓ | ~ | Alpha Channel contours follow the outline of the image's visible pixels; Detect Edges and Photoshop Path contours follow the frame's path | +| Text wrap | bounding box, shape, jump object/column, wrap sides (text on both sides of an object), contour options, on page items and anchored objects | ✓ | ~ | Alpha Channel contours follow the outline of the image's visible pixels (an image over 40 megapixels, or one that can't be decoded, follows the frame's path); Detect Edges and Photoshop Path contours follow the frame's path | | Anchored objects | inline, above line, custom | ✓ | ~ | anchored objects in table cells not drawn (#163) | | Footnotes, endnotes | ✓ | ✓ | ~ | footnotes don't split across columns yet | | Type on a path | ✓ | ✓ | ✓ | | From fad00dd646298479046accd3102ee21e776f3914 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 05:55:38 -0800 Subject: [PATCH 1012/1349] Data merge: an image field in a table cell or a note is refused by name With the insertion point in a table cell or a note, data.placeholder.add with an image field returned "a hyperlink field can't go in a table cell or a note". It now returns a message about image fields that names the two ways on: bind the field to a frame, or pass role text to merge its path. Nothing is inserted on the error, and role text still puts the marker in the cell. Docs: docs/agents.md and the command's params text. --- crates/engine/src/cmd/datamerge.rs | 10 +++++++++- crates/engine/src/cmd/datamerge/tests.rs | 19 +++++++++++++++++++ docs/agents.md | 4 +++- 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/datamerge.rs b/crates/engine/src/cmd/datamerge.rs index 213b3d1cb..e03da2d05 100644 --- a/crates/engine/src/cmd/datamerge.rs +++ b/crates/engine/src/cmd/datamerge.rs @@ -58,7 +58,7 @@ pub fn specs() -> Vec { "Insert Field", [], None, - "{field, role?: text|image|qr|hyperlink, story?, at?, end?, item?} → {id}; an image field at a text insertion point merges as an inline image; with the insertion point in a table cell or a note → {cell: true, marker} (a typed marker, not an anchored placeholder)", + "{field, role?: text|image|qr|hyperlink, story?, at?, end?, item?} → {id}; an image field at a text insertion point merges as an inline image; with the insertion point in a table cell or a note → {cell: true, marker} (a typed marker, not an anchored placeholder; an image field there is an error unless role is text)", has_doc, placeholder_add ), @@ -535,6 +535,14 @@ fn add_placeholder(d: &mut Document, sel: &mut Selection, p: &Value, name: &str) && let Some(t) = sel.text && let Some(pressed) = t.cell { + // The merge fills such a text with the record's value as text, so an image there + // would merge as its path. + if role == PlaceholderRole::Image { + return Err(bad( + "data.placeholder.add", + "an image field can't go in a table cell or a note; bind it to a frame, or insert it with role text to merge its path", + )); + } if role != PlaceholderRole::Text { return Err(bad("data.placeholder.add", "a hyperlink field can't go in a table cell or a note; insert it as text")); } diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index e5cf28497..5f5c4a118 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -1605,6 +1605,25 @@ fn a_field_named_with_angle_brackets_is_refused_in_a_cell() { let _ = made; } +/// An image field with the insertion point in a table cell is refused with a message about image +/// fields, and nothing is inserted; with role text its marker goes into the cell. +#[test] +fn an_image_field_in_a_cell_is_refused_unless_its_role_is_text() { + let mut s = Session::new(); + table_with_caret_in_cell(&mut s, "Name,@Photo\nAda,pics/a.png\n"); + for params in [json!({"field": "Photo"}), json!({"field": "Photo", "role": "image"})] { + let e = s.execute("data.placeholder.add", ¶ms).expect_err("refused").to_string(); + assert!(e.contains("an image field can't go in a table cell or a note"), "{e}"); + assert!(!e.contains("hyperlink"), "{e}"); + assert_eq!(cell_texts(&s), ["Who", "Where"], "nothing inserted"); + } + let r = exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "role": "text"})); + assert_eq!(r["marker"], "<>", "{r}"); + assert_eq!(cell_texts(&s), ["Who", "<>Where"]); + exec(&mut s, "data.preview", json!({"record": 1})); + assert_eq!(cell_texts(&s), ["Who", "pics/a.pngWhere"], "the text role merges the path"); +} + /// Endnote text is filled too: it is a text inside its story, like a footnote's. #[test] fn a_field_in_an_endnote_is_filled() { diff --git a/docs/agents.md b/docs/agents.md index 13977d2af..b2ec4c156 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -90,7 +90,9 @@ external PDF/X certification. `data.source.remove` drops it); `data.fields` lists its fields. `data.placeholder.add {field, role?, story?, at?, end?, item?}` marks text or a frame as a field (`role`: text, image, qr, hyperlink). An image field (a `@` column) inserted at a text insertion point, or typed there as `<>`, merges as an inline image at its natural size, scaled down to fit the -frame. A QR field (a `#` column) inserted at a text insertion point is refused; bind it to a frame instead. An image +frame. The merge writes only text into a table cell or a note: an image field inserted there is refused unless `role` +is `text`, and its `<>` marker, inserted or typed, merges as the path. A QR field (a `#` column) inserted at a +text insertion point is refused; bind it to a frame instead. An image path is absolute or relative to the data file's folder, then the document's; a path that starts with one separator (`\Photos\a.jpg`) is tried from the drive's root first. `data.options` sets records, tiling and image fitting; `data.preview {record}` / `data.preview.stop` show one record without saving it. From 767c0a542b23118c2ebdbf3a0363a544005be950 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 05:51:33 -0800 Subject: [PATCH 1013/1349] Canvas: an idle frame paints and looks up only the spreads in view Every frame, the canvas painted the page shadow, paper, edges, guides, margins and frame edges of every spread in the document, and looked up the composed story of every text frame that ends a story to place its overset mark. Each lookup walks the document, so an idle frame cost more with every page added, and faster than the page count grew. Those shapes are now painted only where they reach into the canvas view: spreads by their bounds, bleed and slug outlines, page grids and guides by their own rectangles, and frames by a rectangle around their anchors, handles and nested objects. A story is looked up only for a frame in view. What shows in the view is the same. In a 400-page document with two frames a page, an idle canvas frame painted 5,099 shapes and looked up 400 stories; it now paints 311 and looks up 1, the same as in a 4-page document. Part of #1343. Refs #1411, #2298. --- ROADMAP.md | 1 + crates/ui-egui/src/canvas.rs | 20 ++++-- crates/ui-egui/src/canvas/frames.rs | 51 +++++++++++--- crates/ui-egui/src/canvas/page_decor.rs | 40 ++++++++--- crates/ui-egui/src/canvas/tests.rs | 93 +++++++++++++++++++++---- 5 files changed, 170 insertions(+), 35 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 006396b1d..16b009a80 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -413,6 +413,7 @@ Newest first. - **2026-10-30** · macOS: a file dragged in from the Finder fills the frame it is dropped on. winit sends no pointer events during such a drag, so the drop asks the system where the pointer is (`Services::pointer`, from `NSEvent.mouseLocation`), at any UI scale. No readiness percentage change. - **2026-10-30** · File > Package opens a dialog, as the reference app's: a Summary of fonts, links and images and inks, pages for each, a Printing Instructions step, and a PDF made with the options of a preset (#1514, #1515). - **2026-10-30** · IDML import reads TOC separators and entry styles written with the `$ID/` prefix or as `Properties` children, and the TOC separator notation (`^t`, `^y`, `^m`, `^>`) is shared by the dialog and IDML, with a special-character menu on the separator field (#1249, #1255). +- **2026-11-12** · An idle canvas frame no longer does work for the spreads out of view (part of #1343): page shadows, paper, guides, margins, frame edges and overset marks are painted for the spreads and objects in view, and only their stories are looked up. In a 400-page document with two frames a page, an idle frame painted 5,099 shapes and looked up 400 stories; it now paints 311 and looks up 1, the same as in a 4-page document. No readiness percentage change. - **2026-10-30** · Spreads show a line at each edge where two of their pages meet, on the canvas only (it isn't printed or exported), so the page boundaries inside a spread are visible while laying out across them, in the spread edge's colour. Right-to-left spreads and pages of different sizes put it on the edge the pages share; pages that don't touch, as an imported spread can keep them, get none (#1838). No readiness percentage change. - **2026-10-29** · Inserting text with many returns no longer takes time that grows with their square (part of #1588): each return copied its paragraph's format with its own insert, moving every format after it. Splitting 20,000 returns into paragraphs took 15.8 s; placing a text file of them now takes 0.2 s, and one of a million returns 5.5 s. No readiness percentage change. - **2026-10-28** · A placed image whose pixels would decode past 1 GiB of RGBA (256 Mpx) is refused from its header, before decoding (#1586). A 288 KB 23,000 px gray PNG used to hang the first draw for 9 s and take the app to 4.5 GB; it now draws as an empty frame, and PDF export skips it with a warning. A 300 ppi A0 scan still fits. No readiness percentage change. diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 4ce86d083..50652ffe6 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -133,6 +133,13 @@ impl Xf { } } +/// Whether the canvas rectangle `r`, grown by `margin` screen points, reaches into `clip`. A +/// rectangle with a coordinate that is not finite counts as in view. +fn in_view(xf: &Xf, clip: Rect, r: DRect, margin: f32) -> bool { + let s = xf.rect(r); + !s.is_finite() || s.expand(margin).intersects(clip) +} + /// A guide being dragged out or moved: its line, what caught it, and where it is beside the pointer (#1282). fn draw_guide_drag(app: &DesignApp, painter: &egui::Painter, xf: &Xf, g: &GuideDrag, p: Pos2, rect: Rect, t: &Tokens) { let col = Color32::from_rgb(74, 227, 255); @@ -188,7 +195,9 @@ fn paint_render(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc: &Documen // Preview: only the shown area of each spread keeps its content. for slot in &layout.slots { let r = shown_area(app, doc, xf, slot); - painter.with_clip_rect(r.intersect(screen)).add(egui::Shape::mesh(mesh.clone())); + if r.intersects(screen) { + painter.with_clip_rect(r.intersect(screen)).add(egui::Shape::mesh(mesh.clone())); + } } } else { painter.add(egui::Shape::mesh(mesh)); @@ -252,8 +261,11 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { let preview = app.ui.screen_mode != ScreenMode::Normal; let bg = if app.ui.screen_mode == ScreenMode::Presentation { Color32::BLACK } else { t.pasteboard }; painter.rect_filled(screen, 0.0, bg); + // The spreads whose pages, shadow or edge reach into the view: the others paint none of them. + let clip = painter.clip_rect(); + let in_sight: Vec<&SpreadSlot> = layout.slots.iter().filter(|slot| in_view(&xf, clip, slot.bounds, 2.0)).collect(); // Page shadow: a hard 1.5 pt black offset on the right and bottom (InDesign 2026). - for slot in &layout.slots { + for slot in &in_sight { let r = xf.rect(slot.bounds); painter.rect_filled(r.translate(vec2(1.5, 1.5)), 0.0, Color32::BLACK); } @@ -261,7 +273,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { // not the shadow's black, until its render arrives. let [r, g, b, _] = doc.resolve_color(designcraft_color::swatch::PAPER, 1.0).unwrap_or(designcraft_color::Color::WHITE).to_rgba8(1.0); let paper = Color32::from_rgb(r, g, b); - for slot in &layout.slots { + for slot in &in_sight { for page in doc.spread(slot.spread).map(|sp| sp.pages.as_slice()).unwrap_or_default() { painter.rect_filled(xf.rect(slot.xf.transform_rect_bbox(page.bounds())), 0.0, paper); } @@ -271,7 +283,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { paint_render(app, &painter, &xf, &doc, &layout, screen, preview); crate::separations::paint(app, ui.ctx(), &painter, &xf, &layout, screen); let hair = 1.0 / ui.ctx().pixels_per_point(); - for slot in &layout.slots { + for slot in &in_sight { painter.rect_stroke(xf.rect(slot.bounds), 0.0, Stroke::new(hair, page_decor::PAGE_EDGE), StrokeKind::Outside); } if !preview { diff --git a/crates/ui-egui/src/canvas/frames.rs b/crates/ui-egui/src/canvas/frames.rs index 0c92c3c6c..e557c9b1d 100644 --- a/crates/ui-egui/src/canvas/frames.rs +++ b/crates/ui-egui/src/canvas/frames.rs @@ -3,8 +3,8 @@ use super::render::c32; use super::rulers::hair; use super::text_overlay::draw_text_selection; use super::{ - Affine, CanvasLayout, Color32, Content, DRect, DesignApp, Document, Item, Point, Pos2, Rect, Selection, Stroke, StrokeKind, Xf, compose, pos2, - vec2, + Affine, CanvasLayout, Color32, Content, DRect, DesignApp, Document, Item, Point, Pos2, Rect, Selection, Stroke, StrokeKind, Xf, compose, in_view, + pos2, vec2, }; /// Spread-space → canvas transform for an item at `loc`. @@ -51,22 +51,31 @@ pub(super) fn draw_frames(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc return; } let ported = ported_frames(app, doc); + // Only the objects that reach into the view are drawn, and only their stories are looked up: + // an object out of view adds no shapes and no work on its story. + let clip = painter.clip_rect(); + let parent_items = doc.parents.iter().any(|p| !p.items.is_empty()); for slot in &layout.slots { let Some(sp) = doc.spread(slot.spread) else { continue }; let a = slot.xf; // Parent items on document pages, and base parents' items on a parent spread: dotted edges. - for (pi, page) in sp.pages.iter().enumerate() { - let overridden = doc.overridden_parent_items(slot.spread, pi); + for (pi, page) in sp.pages.iter().enumerate().filter(|_| parent_items) { + let mut overridden = None; for (ppi, ppg) in doc.shown_parent_pages(slot.spread, pi) { let Some(parent) = doc.parents.get(ppi) else { continue }; let Some(ppage) = parent.pages.get(ppg) else { continue }; let dx = page.x - ppage.x; + let shifted = a * Affine::translate((dx, 0.0)); for it in &parent.items { - if (parent.pages.len() > 1 && parent.page_at_x(it.bounds().center().x) != Some(ppg)) || overridden.contains(&it.id) { + let bounds = it.bounds(); + if (parent.pages.len() > 1 && parent.page_at_x(bounds.center().x) != Some(ppg)) + || !in_view(xf, clip, shifted.transform_rect_bbox(bounds), EDGE_MARGIN) + || overridden.get_or_insert_with(|| doc.overridden_parent_items(slot.spread, pi)).contains(&it.id) + { continue; } let col = doc.layer(it.layer).map(|l| c32(l.color)).unwrap_or(Color32::LIGHT_BLUE); - for poly in path_screen(it, xf, a * Affine::translate((dx, 0.0))) { + for poly in path_screen(it, xf, shifted) { for w in poly.windows(2) { dashed(painter, w[0], w[1], Stroke::new(hair(painter), col.gamma_multiply(0.8)), 2.0, 2.0); } @@ -74,13 +83,15 @@ pub(super) fn draw_frames(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc } } } - for it in &sp.items { + let seen: Vec<&std::sync::Arc> = + sp.items.iter().filter(|it| reach(it, 0).is_none_or(|r| in_view(xf, clip, a.transform_rect_bbox(r), EDGE_MARGIN))).collect(); + for it in &seen { draw_item_edges(painter, xf, doc, it, a); } // Every overset frame, selected or not and inside groups too, shows its red mark at the // out port (InDesign shows it only on the selected frame; a report in Preflight is easy // to miss while laying out). - for (it, c) in overset_marks(app, doc, layout, &sp.items, xf.zoom, &ported) { + for (it, c) in seen.iter().flat_map(|it| overset_marks(app, doc, layout, std::slice::from_ref(*it), xf.zoom, &ported)) { let c = xf.to_screen(c); let s = designcraft_tools::thread::PORT_SIZE_PX as f32; painter.rect_filled(Rect::from_center_size(c, vec2(s, s)), 0.0, Color32::WHITE); @@ -93,7 +104,7 @@ pub(super) fn draw_frames(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc if app.ui.tagged_frames { for top in &sp.items { top.walk(&mut |it: &Item| { - if it.xml_tag.is_empty() { + if it.xml_tag.is_empty() || !in_view(xf, clip, (a * it.xf).transform_rect_bbox(it.inner_bounds()), EDGE_MARGIN) { return; } let Some(t) = doc.xml.tags.iter().find(|t| t.name == it.xml_tag) else { return }; @@ -109,6 +120,28 @@ pub(super) fn draw_frames(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc } } +/// How far, in screen points, an object's edges and port marks paint past its bounds: the 8.5 pt +/// port square is centred on the frame's edge. +const EDGE_MARGIN: f32 = 8.0; + +/// A rectangle around `it` and everything nested in it, in its parent's space: every anchor and +/// handle of its path, and those of the objects grouped or pasted into it, which can lie outside +/// its own outline. None when the nesting is deeper than [`PORT_GROUP_DEPTH`]. +fn reach(it: &Item, depth: usize) -> Option { + if depth > PORT_GROUP_DEPTH { + return None; + } + let mut all: Option = None; + let mut add = |r: DRect| all = Some(all.map_or(r, |a| a.union(r))); + for p in it.path.subpaths.iter().flat_map(|sp| &sp.anchors).flat_map(|a| [a.p, a.h_in, a.h_out]) { + add(DRect::from_points(p, p)); + } + for c in it.children() { + add(reach(c, depth + 1)?); + } + Some(it.xf.transform_rect_bbox(all.unwrap_or(DRect::ZERO))) +} + fn draw_item_edges(painter: &egui::Painter, xf: &Xf, doc: &Document, it: &Item, a: Affine) { if it.hidden || doc.layer(it.layer).is_some_and(|l| !l.visible) { return; diff --git a/crates/ui-egui/src/canvas/page_decor.rs b/crates/ui-egui/src/canvas/page_decor.rs index 39df15a78..a42cb6386 100644 --- a/crates/ui-egui/src/canvas/page_decor.rs +++ b/crates/ui-egui/src/canvas/page_decor.rs @@ -3,7 +3,7 @@ use super::render::c32; use super::rulers::hair; use super::{ CanvasLayout, Color32, DRect, DesignApp, Document, GuideSel, Item, Point, Pos2, Rect, ScreenMode, SpreadRef, SpreadSlot, Stroke, StrokeKind, - Tokens, Xf, + Tokens, Xf, in_view, }; pub(super) fn dashed(painter: &egui::Painter, a: Pos2, b: Pos2, stroke: Stroke, dash: f32, gap: f32) { @@ -52,11 +52,16 @@ pub(super) fn draw_guides( ) { let selection: std::collections::HashSet = app.session.active().map(|st| st.selection.guides.iter().copied().collect()).unwrap_or_default(); + // Only what reaches into the view is painted: a spread or a page out of view adds no shapes. + let clip = painter.clip_rect(); for slot in &layout.slots { let Some(sp) = doc.spread(slot.spread) else { continue }; + let shows = |r: DRect| in_view(xf, clip, slot.xf.transform_rect_bbox(r), GUIDE_MARGIN); if app.ui.guides { - draw_bleed_and_slug(painter, xf, doc, slot, sp); - draw_spine(painter, xf, slot, sp); + draw_bleed_and_slug(painter, xf, doc, slot, sp, clip); + if shows(sp.bounds()) { + draw_spine(painter, xf, slot, sp); + } } let pasteboard = slot.xf.inverse().transform_rect_bbox(layout.pasteboard); for (pi, p) in sp.pages.iter().enumerate() { @@ -65,22 +70,28 @@ pub(super) fn draw_guides( if !app.ui.guides { continue; } - draw_page_grids(painter, xf, doc, slot, p, pr, app.ui.baseline_grid); - let cx = GuideCtx { painter, xf, doc, slot, sp, pasteboard }; + if shows(pr.union(p.margin_rect())) { + draw_page_grids(painter, xf, doc, slot, p, pr, app.ui.baseline_grid); + } + let cx = GuideCtx { painter, xf, doc, slot, sp, pasteboard, clip }; draw_page_guides(&cx, (pi, p, pr), moving, &selection); } } let _ = t; } +/// How far, in screen points, a guide, margin or outline paints past its own rectangle: half of +/// a selected guide's 2 pt line, rounded up. +const GUIDE_MARGIN: f32 = 2.0; + /// The bleed and slug outlines of a spread, in their own colours. -fn draw_bleed_and_slug(painter: &egui::Painter, xf: &Xf, doc: &Document, slot: &SpreadSlot, sp: &designcraft_doc::Spread) { +fn draw_bleed_and_slug(painter: &egui::Painter, xf: &Xf, doc: &Document, slot: &SpreadSlot, sp: &designcraft_doc::Spread, clip: Rect) { let s = &doc.settings; let rect = |r: DRect| xf.rect(slot.xf.transform_rect_bbox(r)); // Bleed, then slug: one rectangle each around the spread (the inside offset only applies // at the spread's outer edges). for (r, color) in [(sp.bleed_rect(s.bleed), s.bleed_color), (sp.slug_rect(s.slug), s.slug_color)] { - if let Some(r) = r { + if let Some(r) = r.filter(|r| in_view(xf, clip, slot.xf.transform_rect_bbox(*r), GUIDE_MARGIN)) { painter.rect_stroke(rect(r), 0.0, Stroke::new(hair(painter), c32(color)), StrokeKind::Middle); } } @@ -105,6 +116,9 @@ fn draw_parent_overlay(painter: &egui::Painter, xf: &Xf, doc: &Document, slot: & && let Some(pp) = doc.parents.get(ppi).and_then(|ps| ps.pages.get(ppg)) { let r = rect(DRect::new(pr.x0, pr.y0, pr.x0 + pp.width, pr.y0 + pp.height)); + if r.is_finite() && !r.expand(GUIDE_MARGIN).intersects(painter.clip_rect()) { + return; + } painter.rect_filled(r, 0.0, Color32::from_rgba_unmultiplied(110, 110, 230, 28)); painter.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::from_rgb(110, 110, 230)), StrokeKind::Middle); } @@ -150,6 +164,8 @@ struct GuideCtx<'a> { slot: &'a SpreadSlot, sp: &'a designcraft_doc::Spread, pasteboard: DRect, + /// The painter's clip rectangle: a guide outside it is not painted. + clip: Rect, } /// The page's own guides, then those it shows from its parent page. `moving` draws dragged @@ -182,7 +198,7 @@ fn draw_page_guides( /// One guide as a line: across the pasteboard for a spread guide, across its page otherwise. fn draw_guide(cx: &GuideCtx, pr: DRect, g: &designcraft_doc::Guide, selected: bool) { - let GuideCtx { painter, xf, doc, slot, sp, pasteboard } = *cx; + let GuideCtx { painter, xf, doc, slot, sp, pasteboard, clip } = *cx; let pt = |q: Point| xf.to_screen(slot.xf * q); // Spread guides cross the pasteboard; page guides their page. let span = if g.spread { pasteboard } else { pr }; @@ -193,6 +209,9 @@ fn draw_guide(cx: &GuideCtx, pr: DRect, g: &designcraft_doc::Guide, selected: bo (Point::new(g.position, span.y0), Point::new(g.position, span.y1)) } }; + if !in_view(xf, clip, slot.xf.transform_rect_bbox(DRect::from_points(a, bb)), GUIDE_MARGIN) { + return; + } let stroke = if selected { let color = g.layer.and_then(|l| doc.layer(l)).map_or(Color32::from_rgb(79, 153, 255), |l| c32(l.color)); Stroke::new(2.0, color) @@ -218,7 +237,10 @@ pub(super) fn draw_flattener_preview(painter: &egui::Painter, xf: &Xf, doc: &Doc let Some(sp) = doc.spread(slot.spread) else { continue }; for it in sp.items.iter().filter(|it| !it.hidden && transparent(it)) { let r = it.bounds().inflate(designcraft_render::effect_outset(it), designcraft_render::effect_outset(it)); - painter.rect_filled(xf.rect(slot.xf.transform_rect_bbox(r)), 0.0, red); + let r = slot.xf.transform_rect_bbox(r); + if in_view(xf, painter.clip_rect(), r, 0.0) { + painter.rect_filled(xf.rect(r), 0.0, red); + } } } } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 62064ea79..069dce96d 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -71,19 +71,28 @@ fn a_press_after_a_drag_is_not_a_double_click() { assert_eq!(press(Some(up), 0.0, 1.0), 1); } -/// The shapes the canvas paints for a new document, after two frames (the first lays out). +/// The shapes the canvas paints for a new document with every spread in view, after two frames +/// (the first lays out). fn canvas_shapes(app: &mut DesignApp) -> Vec { let ctx = egui::Context::default(); let mut shapes = Vec::new(); for _ in 0..2 { - let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| show(app, ui)); - out.textures_delta.clear(); - shapes = out.shapes; + shapes = canvas_frame_shapes(app, &ctx); + if let Some(rect) = app.canvas_rect { + fit(app, rect, "all"); + } } shapes } +/// One frame of the canvas alone in a 1440 by 900 window: the shapes it paints. +fn canvas_frame_shapes(app: &mut DesignApp, ctx: &egui::Context) -> Vec { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + out.shapes +} + /// The spine-coloured vertical hairlines at screen x `x` that run the full height of `page` /// (the spine of one spread shares its x with the pages of the spreads above and below it). fn vertical_lines_at(shapes: &[egui::epaint::ClippedShape], x: f32, page: Rect) -> usize { @@ -172,14 +181,7 @@ fn the_spine_line_hides_with_the_other_guides() { fn pages_show_paper_under_their_render() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); app.run("file.new", serde_json::json!({"pages": 3, "facingPages": true})).unwrap(); - let ctx = egui::Context::default(); - let mut shapes = Vec::new(); - for _ in 0..2 { - let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| show(&mut app, ui)); - out.textures_delta.clear(); - shapes = out.shapes; - } + let shapes = canvas_shapes(&mut app); let st = app.session.active().unwrap(); let layout = CanvasLayout::new(&st.doc, false); let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); @@ -1272,6 +1274,71 @@ fn overset_mark_sits_on_the_out_port_once() { assert!(marks.is_empty()); } +/// An idle frame of the canvas paints the spreads in view and looks up their stories: a document +/// ten times as long adds no shape and no story lookup, and the view shows the same shapes. +#[test] +fn an_idle_canvas_frame_does_the_same_work_for_a_longer_document() { + // Every page holds an empty frame and an overset text frame with a story of its own. + let work = |pages: usize| { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": pages, "facingPages": false})).unwrap(); + let text = "far too much text for a frame this small, over and over again ".repeat(8); + for page in 0..pages { + app.run("frame.create", json!({"spread": page, "rect": [36, 36, 300, 200]})).unwrap(); + app.run("frame.create", json!({"spread": page, "rect": [36, 300, 200, 340], "content": "text", "text": text})).unwrap(); + } + app.run("edit.deselectAll", json!({})).unwrap(); + let ctx = egui::Context::default(); + canvas_frame_shapes(&mut app, &ctx); + go_to_page(&mut app, 0); + canvas_frame_shapes(&mut app, &ctx); + assert_eq!(current_page(&app), Some(0)); + // With nothing composed, the stories composed after one more frame are the ones it looked up. + app.session.cache.clear(); + let shapes = canvas_frame_shapes(&mut app, &ctx); + let showing = shapes.iter().filter(|s| s.clip_rect.intersects(s.shape.visual_bounding_rect())).count(); + let doc = &app.session.active().unwrap().doc; + let composed = doc.stories.keys().filter(|id| app.session.cache.composed_for(doc, **id).is_some()).count(); + (shapes.len(), showing, composed) + }; + let (short, long) = (work(4), work(40)); + assert_eq!(long.1, short.1, "shapes in view"); + assert_eq!(long.0, short.0, "shapes painted"); + assert_eq!(long.2, short.2, "stories looked up"); + assert!((1..4).contains(&long.2), "the stories in view, not all 40: {}", long.2); +} + +/// A frame on the pasteboard keeps its edges while its page is out of view, in a rotated view +/// too, and a view that shows none of it paints none of them. +#[test] +fn frame_edges_are_painted_for_the_frames_in_view() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [-300, 100, -200, 200], "content": "text", "text": "a"})).unwrap()["id"].as_u64().unwrap(); + app.run("edit.deselectAll", json!({})).unwrap(); + let doc = app.session.doc().unwrap().doc.clone(); + let layout = CanvasLayout::new(&doc, false); + let it = out_frame(&doc, id); + let (a, _) = item_canvas_xf(&doc, &layout, it.id).unwrap(); + let frame = a.transform_rect_bbox(it.bounds()); + assert!(frame.x1 < layout.slots[0].bounds.x0 - 150.0, "the frame is on the pasteboard, left of the page"); + let window = Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)); + let edges = |xf: Xf| { + let ctx = egui::Context::default(); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(window), ..Default::default() }, |ui| { + draw_frames(&app, &ui.painter_at(window), &xf, &doc, &layout); + }); + out.textures_delta.clear(); + out.shapes.iter().filter(|s| matches!(s.shape, egui::Shape::Path(_))).count() + }; + // The frame 20 points inside a window too small to reach the page. + let near = Xf { min: Pos2::ZERO, origin: Point::new(frame.x0 - 20.0, frame.y0 - 20.0), zoom: 1.0, rot: 0, pivot: window.center() }; + assert_eq!(edges(near), 1); + assert_eq!(edges(Xf { rot: 1, ..near }), 1); + // The same window over the page: the frame is out of view. + assert_eq!(edges(Xf { origin: Point::new(layout.slots[0].bounds.x0, frame.y0 - 20.0), ..near }), 0); +} + #[test] fn right_clicking_a_ruler_sets_that_rulers_units() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); From ba81cb05e91fa01e242c43836661275e0c12d387 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 06:21:26 -0800 Subject: [PATCH 1014/1349] Compose: an edit composes only the paragraphs it can change Every edit of a story composed it from its first paragraph, so a typed character in a long threaded story cost as much as laying out the whole story: 456 ms in a story threaded over 300 pages. A composition that lays every paragraph once keeps its state before each paragraph. After an edit, composing starts one paragraph above the first changed one, in the kept state and with the lines above copied. It stops at the first unchanged paragraph it reaches in the state kept for that paragraph, and copies the lines from there on with their story offsets moved by the length of the edit. - The cache does this when only the story differs from its entry. - Composed whole as before: stories with footnotes, endnotes, tables, anchored objects, named lists, tracked deletions, balanced columns, vertical justification other than Top, column rules, type on a path, spanning or split paragraphs, paragraph borders or shading, and a layout that goes back over a paragraph (keep options). - An edit that moves lines into other frames is composed to the end of the story. In a 240-paragraph story a typed character composes 3 paragraphs (240 before). Docs: docs/architecture.md, docs/gaps.md (gap 20), ROADMAP. Refs #2298 --- ROADMAP.md | 1 + crates/compose/src/cache.rs | 49 ++- crates/compose/src/lib.rs | 87 ++++- crates/compose/src/reuse.rs | 713 ++++++++++++++++++++++++++++++++++++ crates/compose/src/wrap.rs | 24 +- docs/architecture.md | 10 +- docs/gaps.md | 9 +- 7 files changed, 861 insertions(+), 32 deletions(-) create mode 100644 crates/compose/src/reuse.rs diff --git a/ROADMAP.md b/ROADMAP.md index 006396b1d..87daec8b7 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -387,6 +387,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log +- **2026-11-12** · An edit of a long threaded story composes the paragraphs it can change and copies the other lines from the composition before the edit; every typed character composed the whole story. In a 240-paragraph story a typed character composes 3 paragraphs (240 before). An edit that moves lines into other frames is composed to the story's end, and stories with footnotes, tables, anchored objects, balanced columns or keep options that move lines are composed whole (#2298). No readiness percentage change. - **2026-11-04** · Striped strokes retain out-and-back cubic segments whose second control point is away from the coincident endpoints and first control point. A geometry regression checks the offset extent and both stripe bands. No readiness percentage change. - **2026-11-04** · Esperanto is a text language (Character › Language, `type.char {language: "Esperanto"}`, IDML `$ID/Esperanto`): tag `eo`, English-style quotes; not hyphenated yet (#1201). No readiness percentage change. diff --git a/crates/compose/src/cache.rs b/crates/compose/src/cache.rs index 5e4cb0911..ba55e0d86 100644 --- a/crates/compose/src/cache.rs +++ b/crates/compose/src/cache.rs @@ -6,12 +6,17 @@ //! its text ([`crate::wrap::neighbours`]). An anchored frame's entry also records where its host //! story's composition places it. Entries hold clones of those `Arc`s, so the pointers //! can't be reused by other allocations while the entry lives. +//! +//! When only the story itself differs from an entry's (an edit of its text or formatting), the +//! new composition starts from the entry's and composes the paragraphs the edit can change +//! ([`crate::reuse`]). use std::collections::{HashMap, HashSet}; use std::sync::{Arc, Mutex, PoisonError}; use designcraft_doc::{Document, Item, Story, StoryId, Styles}; +use crate::reuse::{Reuse, Trace}; use crate::vars::RunningIndex; use crate::{ComposeOptions, ComposedStory}; @@ -50,6 +55,25 @@ struct Entry { _keep: (Arc, Arc, Vec>, Vec>), out: Arc, stamp: u64, + /// For composing the story again after an edit ([`crate::reuse`]). + trace: Option>, +} + +/// The story an entry was composed from, its composition and that composition's trace. +type Before = (Arc, Arc, Arc); + +/// How many leading values of a [`signature`] identify the story's own allocation and revision; +/// the rest is everything else the composition was made from. +const STORY_SIG: usize = 2; + +impl Entry { + /// What composing for `sig` can take from this entry: set when only the story itself differs + /// (an edit of its text or formatting) and the entry's composition left a trace. + fn before(&self, sig: &[usize]) -> Option { + let trace = self.trace.as_ref()?; + (self.sig.len() == sig.len() && self.sig.get(STORY_SIG..) == sig.get(STORY_SIG..)) + .then(|| (self._keep.0.clone(), self.out.clone(), trace.clone())) + } } #[derive(Default)] @@ -244,33 +268,38 @@ impl Cache { std::hash::Hash::hash(&doc.list_start(sid, &l.name), &mut h); sig.push(std::hash::Hasher::finish(&h) as usize); } - { + let before = { let mut g = self.map.lock().unwrap_or_else(PoisonError::into_inner); g.1 += 1; let stamp = g.1; - if let Some(e) = g.0.get_mut(&key) - && e.sig == sig - { - e.stamp = stamp; - return e.out.clone(); + match g.0.get_mut(&key) { + Some(e) if e.sig == sig => { + e.stamp = stamp; + return e.out.clone(); + } + Some(e) => e.before(&sig), + None => None, } - } + }; // Parent-page items are composed per page: markers show its name, variables need its index. let page = page.filter(|_| with_vars); let running = running.then(|| self.running_index(doc)); let others: Vec> = neighbours.iter().map(|n| self.neighbour(doc, *n, depth, resolved)).collect(); - let out = Arc::new(crate::wrap::compose_among( + let (out, trace) = crate::wrap::compose_among_traced( doc, sid, &ComposeOptions { page_name, section_marker, page, running, label: None, xrefs: with_xrefs.then(|| self.xref_index(doc)), placed }, &others.iter().map(|o| &**o).collect::>(), - )); + before.as_ref().map(|(story, composed, trace)| Reuse { story, composed, trace }), + ); + let (out, trace) = (Arc::new(out), trace.map(Arc::new)); let mut g = self.map.lock().unwrap_or_else(PoisonError::into_inner); let stamp = g.1; if g.0.len() > 4096 { g.0.retain(|_, e| stamp - e.stamp < 64); } - let replaced = g.0.insert(key, Entry { sig, _keep: (story.clone(), doc.styles.clone(), keep_items, keep_stories), out: out.clone(), stamp }); + let replaced = + g.0.insert(key, Entry { sig, _keep: (story.clone(), doc.styles.clone(), keep_items, keep_stories), out: out.clone(), stamp, trace }); drop(g); // Only the composition that is shown (not one made for another story's wrap). if key.1 == ShownOn::Own diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index abac72985..8a86b87c0 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -24,6 +24,7 @@ mod outline; mod overlay; mod parabox; mod placed; +mod reuse; mod ruby; pub mod shape; pub mod shatai; @@ -1028,6 +1029,9 @@ fn frame_columns_and_text(frames: &[FrameSpec], direction: designcraft_doc::Text } struct ParagraphProgressInput<'a> { + /// Nothing is left to lay: the rest of the story is in place, or the pass is abandoned + /// ([`reuse::Pass::step`]). + done: bool, paragraph: usize, count: usize, balance_frames: usize, @@ -1047,7 +1051,10 @@ enum ParagraphProgress { } fn paragraph_progress(input: ParagraphProgressInput<'_>) -> ParagraphProgress { - let ParagraphProgressInput { paragraph, count, balance_frames, trial, limits, cursor, columns, frames, out, may_retry } = input; + let ParagraphProgressInput { done, paragraph, count, balance_frames, trial, limits, cursor, columns, frames, out, may_retry } = input; + if done { + return ParagraphProgress::Complete; + } if paragraph < count { return ParagraphProgress::Continue; } @@ -2671,6 +2678,40 @@ fn finish_paragraph(input: ParagraphFinishInput<'_>) -> ParagraphFinish { } fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &ComposeOptions, db: &FontDb) -> ComposedStory { + compose_run(doc, story, frames, opts, db, None, false).map(|(out, _)| out).unwrap_or_default() +} + +/// [`compose`], leaving a trace for composing the story again after an edit when it can +/// ([`reuse`]). With `before` (the story before an edit, its composition and trace), only the +/// paragraphs the edit can change are composed, when the trace covers the edit. +pub(crate) fn compose_traced( + doc: &Document, + story: &Story, + frames: &[FrameSpec], + opts: &ComposeOptions, + before: Option>, +) -> (ComposedStory, Option) { + let db = FontDb::global(); + if before.is_some() + && let Some(done) = compose_run(doc, story, frames, opts, db, before.as_ref(), true) + { + return done; + } + compose_run(doc, story, frames, opts, db, None, true).unwrap_or_default() +} + +/// Compose `story` into `frames`, from its start or from what `before` holds for it; with +/// `traced`, also give the trace when the composition can leave one. `None` only with `before`: +/// its trace does not cover the edit, so the story has to be composed from its start. +fn compose_run( + doc: &Document, + story: &Story, + frames: &[FrameSpec], + opts: &ComposeOptions, + db: &FontDb, + before: Option<&reuse::Reuse<'_>>, + traced: bool, +) -> Option<(ComposedStory, Option)> { let db = &db.scoped(doc.font_scope); let mut out = ComposedStory { story: story.id, rev: story.rev, text_len: story.text.len(), ..Default::default() }; let mut styles_tab: Vec = Vec::new(); @@ -2737,6 +2778,14 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C // and in split columns. let mut span_paras = vec![false; np]; let mut split_paras = vec![false; np]; + // Composing again after an edit starts at the paragraph above it ([`reuse`]). The entries + // for the paragraphs before that one are never read: going back over a paragraph abandons the + // pass. + let plain = traced && reuse::plain(story, frames, opts, &named_labels, &deleted); + let (mut pass, start) = reuse::Pass::new(before, story, plain, reuse::Start { pi, cur, list_counter, info }, &mut out, &mut styles_tab); + (pi, cur, list_counter, info) = (start.pi, start.cur, start.list_counter, start.info); + snaps.extend((0..pi).map(|_| Snapshot::take(&out, &cur, &list_counter))); + note_snaps.resize(pi, (notes.num, notes.key, 0)); 'paras: while pi <= np { cur.pi = pi; cur.limits = Rc::clone(&limits); @@ -2747,8 +2796,12 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C note_snaps.truncate(pi); note_snaps.push((notes.num, notes.key, notes.placed.len())); info.truncate(pi); + // Whether nothing is left to lay: the rest of the story is in place, copied from its + // composition before an edit, or that composition turned out not to hold for this one. + let done = pass.step((pi, np), snaps.last(), &mut out, &mut styles_tab, &mut info); // A balancing trial whose band ran past its frame: re-lay the band with more room. - if trial.as_ref().is_some_and(|t| cur.fi > t.key.0) + if !done + && trial.as_ref().is_some_and(|t| cur.fi > t.key.0) && let Some(j) = trial_failed(&mut trial, &mut limits, balance_runs < balance_budget) { balance_runs += 1; @@ -2757,6 +2810,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C continue 'paras; } match paragraph_progress(ParagraphProgressInput { + done, paragraph: pi, count: np, balance_frames, @@ -2843,6 +2897,8 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C var_cache: &mut var_cache, notes: &mut notes, }); + #[cfg(test)] + reuse::SHAPED.with(|n| n.set(n.get() + 1)); let shaped = shape_paragraph(ParagraphShapeInput { db, doc, @@ -3114,17 +3170,20 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C cur.pending += if spans_in_current_frame || ends_split { pp.space_after.max(pp.span_space_after) } else { pp.space_after }; pi += 1; } - finish_composition(FinishInput { - doc, - story, - frames, - cols: &cols, - notes: &mut notes, - out: &mut out, - boxes: &boxes, - span_paras: &span_paras, - split_paras: &split_paras, - styles_tab, + pass.trace(reuse::plain_end(&span_paras, &split_paras, &boxes), &snaps, info).map(|trace| { + let out = finish_composition(FinishInput { + doc, + story, + frames, + cols: &cols, + notes: &mut notes, + out: &mut out, + boxes: &boxes, + span_paras: &span_paras, + split_paras: &split_paras, + styles_tab, + }); + (out, trace) }) } @@ -3568,7 +3627,7 @@ pub fn deleted_paras(story: &Story, ranges: &[Range]) -> Vec { } /// Where a placed paragraph sits (for keep resolution). -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] struct ParaInfo { start: (usize, usize), /// Started at the top of a column (moving it can't help). diff --git a/crates/compose/src/reuse.rs b/crates/compose/src/reuse.rs new file mode 100644 index 000000000..67a7d6314 --- /dev/null +++ b/crates/compose/src/reuse.rs @@ -0,0 +1,713 @@ +//! Composing an edited story from the composition it had before the edit. +//! +//! A composition that laid every paragraph once leaves a [`Trace`]: the state it had before each +//! paragraph. Composing the story again after an edit starts at the paragraph before the first +//! changed one, in the state the trace holds for it and with the lines above it copied. It stops +//! at the first paragraph after the edit that it reaches in the state the trace holds for that +//! paragraph, and copies the lines from there on with their story offsets moved by the length of +//! the edit. The result is the composition a full pass over the edited story gives. +//! +//! Only plain stories are traced ([`plain`]): the features left out carry state between +//! paragraphs that the trace does not hold, or move lines after they are set. A composition that +//! goes back over a paragraph (keep options, column balancing, hyphenation across columns) +//! leaves no trace, and one that does so while it reuses a trace is abandoned for a full pass. + +use std::rc::Rc; + +use designcraft_doc::{CharRun, ListCounter, Story, VerticalJustification}; + +use crate::{Above, Band, ComposeOptions, ComposedStory, Cursor, FrameSpec, Line, ParaInfo, RunStyle, Snapshot}; + +#[cfg(test)] +thread_local! { + /// Paragraphs shaped on this thread (tests count the work an edit causes). + pub(crate) static SHAPED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The composition's state before a paragraph: the cursor, the list numbering, and how much of +/// the cursor's frame and of the run style table is filled. +#[derive(Clone, Debug)] +struct Mark { + fi: usize, + col: usize, + last_baseline: Option, + last_descent: f64, + last_reference: f64, + aki_below: Option, + pending: f64, + band: Band, + grid_next: Option<(f64, f64)>, + list_counter: ListCounter, + lines: usize, + decos: usize, + styles: usize, +} + +fn bits(v: Option) -> Option { + v.map(f64::to_bits) +} + +fn above_bits(a: Option) -> Option<[Option; 6]> { + a.map(|a| { + [ + Some(a.top.to_bits()), + Some(a.baseline.to_bits()), + Some(a.descent.to_bits()), + Some(a.reference.to_bits()), + bits(a.aki_below), + Some(a.pending.to_bits()), + ] + }) +} + +impl Mark { + /// The state `snap` holds with `styles` run styles in the table, or `None` when it has state + /// a mark does not hold (a split-column block, balanced column bottoms, tables). + fn of(snap: &Snapshot, styles: usize) -> Option { + let c = &snap.cur; + if c.split.is_some() || !c.limits.is_empty() || !c.split_limits.is_empty() || snap.tables != 0 { + return None; + } + Some(Mark { + fi: c.fi, + col: c.col, + last_baseline: c.last_baseline, + last_descent: c.last_descent, + last_reference: c.last_reference, + aki_below: c.aki_below, + pending: c.pending, + band: c.band, + grid_next: c.grid_next, + list_counter: snap.list_counter.clone(), + lines: snap.lines, + decos: snap.decos, + styles, + }) + } + + fn cursor(&self, pi: usize) -> Cursor { + Cursor { + fi: self.fi, + col: self.col, + last_baseline: self.last_baseline, + last_descent: self.last_descent, + last_reference: self.last_reference, + aki_below: self.aki_below, + pending: self.pending, + pi, + band: self.band, + limits: Rc::default(), + split: None, + split_limits: Rc::default(), + grid_next: self.grid_next, + } + } + + /// The mark with its paragraph numbers after the edit. + fn moved(&self, plan: &Plan) -> Mark { + let band = Band { para: plan.moved(self.band.para), tail: self.band.tail.map(|(p, c)| (plan.moved(p), c)), ..self.band }; + Mark { band, ..self.clone() } + } + + /// Whether composing on from `self` and from `other` sets the same lines. Numbers are + /// compared by their bits: a difference too small to show still changes what follows. + fn same(&self, other: &Mark) -> bool { + let (a, b) = (&self.band, &other.band); + self.fi == other.fi + && self.col == other.col + && bits(self.last_baseline) == bits(other.last_baseline) + && self.last_descent.to_bits() == other.last_descent.to_bits() + && self.last_reference.to_bits() == other.last_reference.to_bits() + && bits(self.aki_below) == bits(other.aki_below) + && self.pending.to_bits() == other.pending.to_bits() + && a.para == b.para + && a.line0 == b.line0 + && above_bits(a.above) == above_bits(b.above) + && a.tail == b.tail + && self.grid_next.map(|(x, y)| (x.to_bits(), y.to_bits())) == other.grid_next.map(|(x, y)| (x.to_bits(), y.to_bits())) + && self.list_counter == other.list_counter + && self.lines == other.lines + && self.decos == other.decos + && self.styles == other.styles + } +} + +/// What a composition leaves for composing the story again after an edit: its state before each +/// paragraph it laid (and after the last one), and where each paragraph sits. +#[derive(Debug)] +pub(crate) struct Trace { + marks: Vec, + info: Vec, +} + +/// A story as it was before an edit, its composition and that composition's trace. +#[derive(Clone, Copy)] +pub(crate) struct Reuse<'a> { + pub story: &'a Story, + pub composed: &'a ComposedStory, + pub trace: &'a Trace, +} + +/// How much of the composition before an edit holds for the edited story. +pub(crate) struct Plan { + /// The paragraph composing starts at. + pub resume: usize, + /// The first paragraph (numbered as in the edited story) that may take the lines it had + /// before the edit: the one before it is unchanged too. + pub rejoin: usize, + /// Paragraphs and bytes the edit added. + paras: isize, + bytes: isize, + /// The first paragraph the edit left as it was, numbered as before the edit. + old_tail: usize, +} + +impl Plan { + /// The number after the edit of paragraph `p` of the story before it. + fn moved(&self, p: usize) -> usize { + if p >= self.old_tail { p.wrapping_add_signed(self.paras) } else { p } + } + + /// The number before the edit of paragraph `pi` of the edited story's unchanged end. + fn before(&self, pi: usize) -> Option { + pi.checked_add_signed(self.paras.checked_neg()?) + } +} + +/// Whether a composition of `story` in `frames` can leave a trace, or use one. Footnotes, +/// endnotes, tables and anchored objects carry state of their own; named lists and tracked +/// deletions reach across paragraphs; vertical justification and column rules change a frame +/// after its lines are set; type on a path sizes its frame from the story; balanced columns are +/// laid more than once. +pub(crate) fn plain(story: &Story, frames: &[FrameSpec], opts: &ComposeOptions, labels: &[Option], deleted: &[bool]) -> bool { + story.notes.is_empty() + && story.endnotes.is_empty() + && story.objects.is_empty() + && story.tables.is_empty() + && opts.label.is_none() + && labels.iter().all(Option::is_none) + && !deleted.contains(&true) + && frames.iter().all(|f| { + let o = &f.opts; + o.vertical_justification == VerticalJustification::Top && !o.column_rule && o.path.is_none() && !(o.balance_columns && o.columns > 1) + }) +} + +/// Whether the paragraphs a composition laid are ones a trace covers: none spans or splits +/// columns (`span`, `split`, by paragraph) or has a border or shading (`boxes`), which are drawn +/// once every line is set. +pub(crate) fn plain_end(span: &[bool], split: &[bool], boxes: &[Option]) -> bool { + !span.contains(&true) && !split.contains(&true) && boxes.iter().all(Option::is_none) +} + +/// Bytes of text from the start of both run lists (in the order given) that have the same +/// character formats. +fn same_formats<'a>(mut old: impl Iterator, mut new: impl Iterator) -> usize { + let mut same = 0usize; + let (mut a, mut b): (Option<(&CharRun, usize)>, Option<(&CharRun, usize)>) = (None, None); + loop { + if a.is_none_or(|(_, left)| left == 0) { + a = old.find(|r| r.len > 0).map(|r| (r, r.len)); + } + if b.is_none_or(|(_, left)| left == 0) { + b = new.find(|r| r.len > 0).map(|r| (r, r.len)); + } + let (Some((ra, la)), Some((rb, lb))) = (a, b) else { return same }; + if ra.format != rb.format { + return same; + } + let step = la.min(lb); + same += step; + (a, b) = (Some((ra, la - step)), Some((rb, lb - step))); + } +} + +fn returns(text: &str) -> usize { + text.bytes().filter(|b| *b == b'\n').count() +} + +impl Reuse<'_> { + /// Where composing `new` (the story after the edit) starts and may stop, or `None` when the + /// edit changed something a trace does not cover. + pub(crate) fn plan(&self, new: &Story) -> Option { + let old = self.story; + if old.frames != new.frames + || old.direction != new.direction + || old.vertical != new.vertical + || old.optical_margin != new.optical_margin + || old.anchors != new.anchors + || old.xrefs != new.xrefs + || old.index_refs != new.index_refs + || old.editorial != new.editorial + { + return None; + } + let (o, n) = (old.text.as_bytes(), new.text.as_bytes()); + if old.paras.len() != returns(&old.text) + 1 || new.paras.len() != returns(&new.text) + 1 { + return None; + } + // The unchanged start: the same text in the same character formats, then whole paragraphs + // with the same paragraph formats. + let mut head = o.iter().zip(n).take_while(|(a, b)| a == b).count().min(same_formats(old.chars.iter(), new.chars.iter())); + while !new.text.is_char_boundary(head) { + head -= 1; + } + let whole = returns(new.text.get(..head)?); + let first = old.paras.iter().zip(&new.paras).take(whole).take_while(|(a, b)| a == b).count(); + if first < whole { + // A paragraph format changed above the first changed character. + head = match first.checked_sub(1) { + Some(k) => n.iter().enumerate().filter(|(_, b)| **b == b'\n').nth(k).map(|(i, _)| i + 1)?, + None => 0, + }; + } + // The unchanged end, which the unchanged start does not overlap. + let room = o.len().min(n.len()).checked_sub(head)?; + let mut tail = o + .iter() + .rev() + .zip(n.iter().rev()) + .take_while(|(a, b)| a == b) + .count() + .min(same_formats(old.chars.iter().rev(), new.chars.iter().rev())) + .min(room); + while !new.text.is_char_boundary(n.len() - tail) { + tail -= 1; + } + let after = returns(new.text.get(n.len() - tail..)?); + let after = old.paras.iter().rev().zip(new.paras.iter().rev()).take(after).take_while(|(a, b)| a == b).count(); + let (old_paras, new_paras) = (old.paras.len(), new.paras.len()); + Some(Plan { + // One paragraph above the first changed one: setting a paragraph reads the one after it. + resume: first.saturating_sub(1).min(self.trace.marks.len().checked_sub(1)?), + rejoin: new_paras.checked_sub(after)? + 1, + paras: isize::try_from(new_paras).ok()?.checked_sub(isize::try_from(old_paras).ok()?)?, + bytes: isize::try_from(n.len()).ok()?.checked_sub(isize::try_from(o.len()).ok()?)?, + old_tail: old_paras.checked_sub(after)?, + }) + } + + /// Put `out` and `styles` back as they were before paragraph `plan.resume`, and give the + /// cursor, list numbering and paragraph positions of that moment. `None` when the composition + /// before the edit does not match `out`'s frames. + pub(crate) fn restore(&self, plan: &Plan, out: &mut ComposedStory, styles: &mut Vec) -> Option<(Cursor, ListCounter, Vec)> { + let mark = self.trace.marks.get(plan.resume)?; + let before = self.composed; + if before.frames.len() != out.frames.len() || before.frames.iter().zip(&out.frames).any(|(a, b)| a.frame != b.frame) { + return None; + } + let info = self.trace.info.get(..plan.resume)?.to_vec(); + *styles = before.styles.get(..mark.styles)?.to_vec(); + for (i, (to, from)) in out.frames.iter_mut().zip(&before.frames).enumerate().take(mark.fi.saturating_add(1)) { + let (lines, decos) = if i < mark.fi { (from.lines.len(), from.decos.len()) } else { (mark.lines, mark.decos) }; + to.lines = from.lines.get(..lines)?.iter().map(|l| moved_line(l, 0, 0)).collect(); + to.decos = from.decos.get(..decos)?.to_vec(); + } + Some((mark.cursor(plan.resume), mark.list_counter.clone(), info)) + } + + /// At paragraph `pi` of the edited story, in the state `snap` with `styles` and `info` as + /// they are: when the composition before the edit was in that state before the same + /// paragraph, copy what it set from there on into `out`, `styles` and `info`, and say so. + pub(crate) fn rejoin( + &self, + plan: &Plan, + pi: usize, + snap: &Snapshot, + out: &mut ComposedStory, + styles: &mut Vec, + info: &mut Vec, + ) -> bool { + let before = self.composed; + let Some(k) = plan.before(pi) else { return false }; + let (Some(old), Some(new)) = (self.trace.marks.get(k), Mark::of(snap, styles.len())) else { return false }; + // The paragraph above is where it was, and no chain of keep-with-next paragraphs reaches + // back through it into the changed text. + let last = |v: &[ParaInfo], i: usize| i.checked_sub(1).and_then(|i| v.get(i).cloned()); + let same_above = matches!((last(&self.trace.info, k), last(info, pi)), (Some(a), Some(b)) if a == b && a.keep_with_next == 0); + if !same_above || info.len() != pi || !old.moved(plan).same(&new) || before.styles.get(..old.styles) != Some(styles.as_slice()) { + return false; + } + for (i, (to, from)) in out.frames.iter_mut().zip(&before.frames).enumerate().skip(old.fi) { + let (lines, decos) = if i == old.fi { (old.lines, old.decos) } else { (0, 0) }; + to.lines.extend(from.lines.get(lines..).unwrap_or_default().iter().map(|l| moved_line(l, plan.bytes, plan.paras))); + to.decos.extend(from.decos.get(decos..).unwrap_or_default().iter().cloned()); + } + out.overset_at = before.overset_at.map(|b| b.wrapping_add_signed(plan.bytes)); + styles.clone_from(&before.styles); + info.extend(self.trace.info.get(k..).unwrap_or_default().iter().cloned()); + true + } +} + +/// `line` with its story offsets and paragraph number moved, and without the keep-violation +/// flag, which is set again for the whole story once it is composed. +fn moved_line(line: &Line, bytes: isize, paras: isize) -> Line { + let at = |b: usize| b.wrapping_add_signed(bytes); + let mut l = Line { keep_violation: false, ..line.clone() }; + l.range = at(l.range.start)..at(l.range.end); + l.para = l.para.wrapping_add_signed(paras); + if bytes != 0 { + for g in &mut l.glyphs { + g.byte = at(g.byte); + } + } + if let Some(cap) = &mut l.drop_cap { + cap.end = at(cap.end); + } + l +} + +/// What one composition keeps for its trace, and what it reuses of the composition before an +/// edit. +pub(crate) struct Pass<'a> { + before: Option<(&'a Reuse<'a>, Plan)>, + /// The composition was to reuse the one before an edit and cannot: its result is not used. + abandoned: bool, + /// A trace is wanted and nothing rules one out so far. + traced: bool, + /// Run styles in the table before each paragraph. + styles: Vec, + /// The paragraph the next step should be at: another one means the layout went back over a + /// paragraph. + next: usize, + /// The paragraph the lines copied from before the edit start at. + rejoined: Option, +} + +/// Where a composition starts: the paragraph, the cursor, the list numbering and the positions +/// of the paragraphs above. +pub(crate) struct Start { + pub pi: usize, + pub cur: Cursor, + pub list_counter: ListCounter, + pub info: Vec, +} + +impl<'a> Pass<'a> { + /// The bookkeeping for composing `story`, and where to start. `traced`: a trace is wanted and + /// the story is [`plain`]. `fresh` is the start of the story. With `before`, `out` and + /// `styles` are filled with what holds from before the edit and the start is the paragraph + /// above the edit; when `before` cannot be used the pass is abandoned at its first step. + pub(crate) fn new( + before: Option<&'a Reuse<'a>>, + story: &Story, + traced: bool, + fresh: Start, + out: &mut ComposedStory, + styles: &mut Vec, + ) -> (Pass<'a>, Start) { + let mut pass = Pass { before: None, abandoned: false, traced, styles: Vec::with_capacity(story.paras.len() + 1), next: 0, rejoined: None }; + let Some(b) = before else { return (pass, fresh) }; + let resumed = traced.then(|| b.plan(story)).flatten().and_then(|plan| Some((b.restore(&plan, out, styles)?, plan))); + let Some(((cur, list_counter, info), plan)) = resumed else { + pass.abandoned = true; + return (pass, fresh); + }; + let pi = plan.resume; + // The counts for the paragraphs above are never read: their marks are kept as they are. + pass.styles.resize(pi, 0); + pass.next = pi; + pass.before = Some((b, plan)); + (pass, Start { pi, cur, list_counter, info }) + } + + /// Before paragraph `pi` of `count` is laid, in the state `snap`: whether nothing is left to + /// lay, because the rest of the story is in place (copied from the composition before the + /// edit into `out`, `styles` and `info`) or because the pass is abandoned. + pub(crate) fn step( + &mut self, + (pi, count): (usize, usize), + snap: Option<&Snapshot>, + out: &mut ComposedStory, + styles: &mut Vec, + info: &mut Vec, + ) -> bool { + self.styles.truncate(pi); + self.styles.push(styles.len()); + if pi != self.next { + // The layout went back over a paragraph. + self.traced = false; + self.abandoned |= self.before.is_some(); + } + self.next = pi + 1; + if self.abandoned { + return true; + } + if pi < count + && let (Some((before, plan)), Some(snap)) = (&self.before, snap) + && pi >= plan.rejoin + && before.rejoin(plan, pi, snap, out, styles, info) + { + self.rejoined = Some(pi); + return true; + } + false + } + + /// The trace of the finished composition, when it laid every paragraph once and `plain_end` + /// (no paragraph it laid uses something a trace does not cover): `snaps` holds the state + /// before each paragraph it laid itself, `info` every paragraph's position. The paragraphs + /// above the one a reusing composition started at keep the marks they had, and those after + /// the one it rejoined at the marks that followed before the edit. The outer `None` is for an + /// abandoned pass and for a reusing one that leaves no trace: the story has to be composed + /// from its start. + pub(crate) fn trace(self, plain_end: bool, snaps: &[Snapshot], info: Vec) -> Option> { + if self.abandoned { + return None; + } + let trace = if self.traced && plain_end { self.marks(snaps).map(|marks| Trace { marks, info }) } else { None }; + if self.before.is_some() && trace.is_none() { + return None; + } + Some(trace) + } + + fn marks(&self, snaps: &[Snapshot]) -> Option> { + let reused = self.before.as_ref(); + let start = reused.map_or(0, |(_, plan)| plan.resume); + let mut marks = Vec::with_capacity(snaps.len()); + if let Some((before, _)) = reused { + marks.extend(before.trace.marks.get(..start)?.iter().cloned()); + } + for (snap, styles) in snaps.iter().zip(&self.styles).skip(start) { + marks.push(Mark::of(snap, *styles)?); + } + if let (Some((before, plan)), Some(pi)) = (reused, self.rejoined) { + let k = plan.before(pi)?; + marks.extend(before.trace.marks.get(k + 1..)?.iter().map(|m| m.moved(plan))); + } + // Lines are only ever added to the cursor's frame, so the frames above it are complete. + marks.windows(2).all(|w| w[0].fi <= w[1].fi).then_some(marks) + } +} + +#[cfg(test)] +mod tests { + use designcraft_doc::build::NewDocument; + use designcraft_doc::{Align, Document, ItemId, ListType, ParaFormat, SpreadRef, StartParagraph, Story, StoryId, VerticalJustification}; + use designcraft_geom::Rect; + + use super::SHAPED; + use crate::Cache; + + const SENTENCE: &str = "The quick brown fox jumps over the lazy dog while the workbook keeps growing page by page."; + + /// A story of `paras` paragraphs of two to five lines, threaded through `frames` frames of 31 + /// lines each. + fn threaded(paras: usize, frames: usize) -> (Document, StoryId, Vec) { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let text = (0..paras).map(|i| vec![SENTENCE; 2 + i % 4].join(" ")).collect::>().join("\n"); + let rect = |i: usize| Rect::new(i as f64 * 600.0, 0.0, i as f64 * 600.0 + 540.0, 456.0); + let (first, sid) = d.add_text_frame(SpreadRef::Doc(0), rect(0), lid, &text, ParaFormat::default()).unwrap(); + let mut ids = vec![first]; + for i in 1..frames { + let (next, _) = d.add_text_frame(SpreadRef::Doc(0), rect(i), lid, "", ParaFormat::default()).unwrap(); + d.thread(ids[i - 1], next).unwrap(); + ids.push(next); + } + (d, sid, ids) + } + + /// What `f` returns and the paragraphs it shaped. + fn shaped(f: impl FnOnce() -> T) -> (T, usize) { + SHAPED.with(|n| n.set(0)); + let out = f(); + (out, SHAPED.with(|n| n.get())) + } + + /// Compose the edited story through `cache`, which holds its composition before the edit, and + /// check the result against composing it whole. Gives the paragraphs the cache shaped. + fn check(cache: &Cache, d: &Document, sid: StoryId, what: &str) -> usize { + let (cached, n) = shaped(|| cache.get(d, sid, None)); + let whole = Cache::new().get(d, sid, None); + assert_eq!(cached.frames.len(), whole.frames.len(), "{what}"); + for (fi, (a, b)) in cached.frames.iter().zip(&whole.frames).enumerate() { + assert_eq!(a.lines.len(), b.lines.len(), "{what}: lines in frame {fi}"); + for (li, (x, y)) in a.lines.iter().zip(&b.lines).enumerate() { + assert_eq!(format!("{x:?}"), format!("{y:?}"), "{what}: frame {fi} line {li}"); + } + } + assert!(format!("{cached:?}") == format!("{whole:?}"), "{what}: the composition differs from composing the story whole"); + n + } + + #[test] + fn a_typed_character_composes_the_paragraphs_around_it() { + for paras in [60, 240] { + let (mut d, sid, _) = threaded(paras, paras / 4); + let cache = Cache::new(); + let (first, whole) = shaped(|| cache.get(&d, sid, None)); + assert!(!first.is_overset()); + assert!(first.frames.iter().filter(|f| !f.lines.is_empty()).count() > paras / 12); + assert_eq!(whole, paras); + let len = d.story(sid).unwrap().len(); + for at in [10, len / 2, len - 1] { + d.story_mut(sid).unwrap().insert(at, "x"); + let n = check(&cache, &d, sid, "a typed character"); + assert!(n <= 3, "{n} of {paras} paragraphs composed for a character typed at {at}"); + } + } + } + + #[test] + fn characters_typed_one_after_another_each_compose_the_paragraphs_around_them() { + let (mut d, sid, _) = threaded(80, 20); + let cache = Cache::new(); + cache.get(&d, sid, None); + let at = d.story(sid).unwrap().len() / 2; + for (i, c) in "one two\nthree".chars().enumerate() { + d.story_mut(sid).unwrap().insert(at + i, &c.to_string()); + let n = check(&cache, &d, sid, "typing"); + // A return adds a line, which moves the paragraphs below it in their frame: they are + // composed up to the end of the story. + assert!(c == '\n' || n <= 4, "{n} of 80 paragraphs composed for {c:?}"); + } + } + + #[test] + fn an_edit_that_moves_lines_composes_up_to_the_next_frame_the_text_starts_in() { + let (mut d, sid, _) = threaded(100, 24); + // Chapters of five paragraphs, each starting in the next frame. + let starts: Vec = + d.story(sid).unwrap().para_ranges().iter().enumerate().filter(|(i, _)| *i > 0 && i % 5 == 0).map(|(_, r)| r.start).collect(); + for at in starts { + d.story_mut(sid).unwrap().format_paras(at..at, |p| p.para.start_paragraph = Some(StartParagraph::NextFrame)); + } + let cache = Cache::new(); + let (first, whole) = shaped(|| cache.get(&d, sid, None)); + assert!(!first.is_overset()); + assert_eq!(whole, 100); + let at = d.story(sid).unwrap().para_ranges()[52].start + 20; + d.story_mut(sid).unwrap().insert(at, &format!(" {SENTENCE} {SENTENCE}")); + let n = check(&cache, &d, sid, "two more lines in a chapter"); + assert!(n <= 6, "{n} of 100 paragraphs composed for lines added to one chapter"); + } + + #[test] + fn edits_give_the_composition_of_the_edited_story() { + let (mut d, sid, _) = threaded(40, 12); + let original = d.clone(); + let cache = Cache::new(); + cache.get(&d, sid, None); + let edits: [(&str, fn(&mut Story)); 15] = [ + ("a character", |s| s.insert(s.len() / 2, "x")), + ("a return", |s| s.insert(s.len() / 2, "\n")), + ("a long insertion", |s| s.insert(s.len() / 3, &format!(" {SENTENCE} {SENTENCE} {SENTENCE}"))), + ("several paragraphs", |s| s.insert(s.len() / 3, &format!("\n{SENTENCE}\n{SENTENCE}\n"))), + ("a deleted character", |s| s.delete(s.len() / 2..s.len() / 2 + 1)), + ("a deleted return", |s| { + let at = s.text[..s.len() / 2].rfind('\n').unwrap(); + s.delete(at..at + 1); + }), + ("a deletion across paragraphs", |s| s.delete(s.len() / 4..s.len() / 4 + 900)), + ("a replacement", |s| s.replace(s.len() / 2..s.len() / 2 + 40, "replaced")), + ("larger type", |s| s.format_chars(s.len() / 2..s.len() / 2 + 60, |f| f.over.size = Some(18.0))), + ("a centered paragraph", |s| s.format_paras(s.len() / 2..s.len() / 2, |p| p.para.align = Some(Align::Center))), + ("text at the start", |s| s.insert(0, "Start. ")), + ("text at the end", |s| s.insert(s.len(), " End.")), + ("a two-byte character", |s| s.insert(s.len() / 2, "\u{e9}")), + ("everything deleted", |s| s.delete(0..s.len())), + ("text in an empty story", |s| s.insert(0, "Again.")), + ]; + for (what, edit) in edits { + edit(d.story_mut(sid).unwrap()); + check(&cache, &d, sid, what); + } + // Undo puts an earlier story back. + check(&cache, &original, sid, "the story before the edits"); + } + + #[test] + fn edits_in_and_above_overset_text_compose_right() { + let (mut d, sid, _) = threaded(60, 3); + let cache = Cache::new(); + assert!(cache.get(&d, sid, None).is_overset()); + let len = d.story(sid).unwrap().len(); + d.story_mut(sid).unwrap().insert(len - 10, "x"); + let n = check(&cache, &d, sid, "a character in overset text"); + assert!(n <= 1, "{n} paragraphs composed for a character typed in overset text"); + d.story_mut(sid).unwrap().insert(200, &format!(" {SENTENCE}")); + check(&cache, &d, sid, "a line added above overset text"); + d.story_mut(sid).unwrap().delete(100..len / 2); + check(&cache, &d, sid, "a deletion that brings overset text into the frames"); + } + + /// Stories with features a trace does not cover are composed whole after an edit. + #[test] + fn edits_of_stories_a_trace_does_not_cover_compose_right() { + let setups: [(&str, fn(&mut Document, StoryId, &[ItemId])); 6] = [ + ("keep options", |d, sid, _| { + let s = d.story_mut(sid).unwrap(); + s.format_paras(0..s.len(), |p| { + p.para.keep_with_next = Some(1); + p.para.keep_lines_together = Some(true); + }); + }), + ("balanced columns", |d, _, frames| { + for f in frames { + let o = &mut d.item_mut(*f).unwrap().text_frame_mut().unwrap().options; + (o.columns, o.balance_columns) = (2, true); + } + }), + ("vertical justification", |d, _, frames| { + for f in frames { + d.item_mut(*f).unwrap().text_frame_mut().unwrap().options.vertical_justification = VerticalJustification::Center; + } + }), + ("a numbered list", |d, sid, _| { + let s = d.story_mut(sid).unwrap(); + s.format_paras(0..s.len(), |p| p.para.list_type = Some(ListType::Numbers)); + }), + ("a footnote", |d, sid, _| { + d.story_mut(sid).unwrap().insert_note(300, "A synthetic footnote.", ParaFormat::default()); + }), + ("a column rule", |d, _, frames| { + for f in frames { + let o = &mut d.item_mut(*f).unwrap().text_frame_mut().unwrap().options; + (o.columns, o.column_rule) = (2, true); + } + }), + ]; + for (what, setup) in setups { + let (mut d, sid, frames) = threaded(30, 10); + setup(&mut d, sid, &frames); + let cache = Cache::new(); + cache.get(&d, sid, None); + let mid = d.story(sid).unwrap().len() / 2; + d.story_mut(sid).unwrap().insert(mid, "x"); + check(&cache, &d, sid, what); + d.story_mut(sid).unwrap().insert(mid, &format!("\n{SENTENCE} {SENTENCE}\n")); + check(&cache, &d, sid, what); + d.story_mut(sid).unwrap().delete(mid / 2..mid); + check(&cache, &d, sid, what); + } + } + + #[test] + fn a_run_of_mixed_edits_composes_right_after_each() { + let (mut d, sid, _) = threaded(40, 14); + let cache = Cache::new(); + cache.get(&d, sid, None); + let texts = ["x", " word", "\n", " several words in a row here", "\n\n", "A sentence. "]; + let mut seed = 0x2545_f491_u64; + let mut next = |below: usize| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (seed >> 33) as usize % below.max(1) + }; + for step in 0..60 { + let s = d.story_mut(sid).unwrap(); + let at = next(s.len() + 1); + match next(4) { + 0 | 1 => s.insert(at, texts[next(texts.len())]), + 2 => s.delete(at..(at + next(120)).min(s.len())), + _ => { + let size = 9.0 + next(10) as f64; + s.format_chars(at..(at + next(60)).min(s.len()), |f| f.over.size = Some(size)); + } + } + check(&cache, &d, sid, &format!("step {step}")); + } + } +} diff --git a/crates/compose/src/wrap.rs b/crates/compose/src/wrap.rs index f28bba424..70675eab5 100644 --- a/crates/compose/src/wrap.rs +++ b/crates/compose/src/wrap.rs @@ -21,6 +21,7 @@ use designcraft_doc::{AnchorPosition, AnchoredObject, Document, Item, OBJECT_MARK, PageSide, SpreadRef, Story, StoryId, WrapMode}; use designcraft_geom::Affine; +use crate::reuse::{Reuse, Trace}; use crate::{ComposeOptions, ComposedStory, Exclusion, FrameSpec}; /// Most extra compositions of a story with its own anchored objects' wrap, however many objects @@ -192,7 +193,22 @@ fn settled(a: &[Vec], b: &[Vec]) -> bool { /// Compose story `sid` with the wrapping anchored objects of `others` (compositions of its /// [`neighbours`]) and of its own. pub(crate) fn compose_among(doc: &Document, sid: StoryId, opts: &ComposeOptions, others: &[&ComposedStory]) -> ComposedStory { - let Some(st) = doc.story(sid) else { return ComposedStory { story: sid, ..Default::default() } }; + compose_among_traced(doc, sid, opts, others, None).0 +} + +/// [`compose_among`], also giving the trace for composing the story again after an edit, when +/// the composition leaves one ([`crate::reuse`]). `before` is the story before an edit with its +/// composition among the same `others` and that composition's trace: the paragraphs the edit +/// cannot change are taken from it. A story with wrapping anchored objects of its own is +/// composed whole and leaves no trace. +pub(crate) fn compose_among_traced( + doc: &Document, + sid: StoryId, + opts: &ComposeOptions, + others: &[&ComposedStory], + before: Option>, +) -> (ComposedStory, Option) { + let Some(st) = doc.story(sid) else { return (ComposedStory { story: sid, ..Default::default() }, None) }; let mut specs = crate::frame_specs_placed(doc, sid, &opts.placed); if !others.is_empty() { let mut obs = Vec::new(); @@ -206,10 +222,10 @@ pub(crate) fn compose_among(doc: &Document, sid: StoryId, opts: &ComposeOptions, specs = with_exclusions(&specs, &added); } } - let mut out = crate::compose(doc, st, &specs, opts); if !has_wrapping_objects(st) { - return out; + return crate::compose_traced(doc, st, &specs, opts, before); } + let mut out = crate::compose(doc, st, &specs, opts); let own = st.objects.iter().filter(|o| wraps(o) && !matches!(o.position, AnchorPosition::Inline { .. })).count(); let mut prev = vec![Vec::new(); specs.len()]; for _ in 0..(own + 1).clamp(MIN_PASSES, MAX_PASSES) { @@ -220,5 +236,5 @@ pub(crate) fn compose_among(doc: &Document, sid: StoryId, opts: &ComposeOptions, out = crate::compose(doc, st, &with_exclusions(&specs, &added), opts); prev = added; } - out + (out, None) } diff --git a/docs/architecture.md b/docs/architecture.md index 7b86388a9..4fede8ca4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -70,7 +70,15 @@ AppKit callback never runs the confirmation dialogs inside a modal termination l ## Composition and rendering The compose cache is keyed by story revision, frame geometry, style revision and font database -revision; stories compose in parallel (rayon) on native targets. Composition produces per-frame +revision; stories compose in parallel (rayon) on native targets. After an edit of a story's text +or formatting, composing starts at the paragraph before the first changed one and stops at the +first unchanged paragraph it reaches in the state it had before the edit; the lines above and +below are copied from the composition before the edit (`crates/compose/src/reuse.rs`). An edit +that moves lines into other frames is composed to the story's end. A story is composed whole +when it has footnotes, endnotes, tables, anchored objects, named lists, tracked deletions, +balanced columns, vertical justification other than Top, column rules, type on a path, spanning +or split paragraphs, or paragraph borders or shading, and when its layout goes back over a +paragraph (keep options). Composition produces per-frame lines with positioned glyph runs, decorations, anchors and overset. The canvas renders on a background worker with vello_cpu into tiles; after an edit only frames whose composition changed are re-rendered and patched (damage regions, pixel-identical to a full render). The GPU (wgpu: diff --git a/docs/gaps.md b/docs/gaps.md index addb0b679..df396e9f6 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -231,10 +231,13 @@ Kind: **F** feature · **U** UI/UX · **T** typography · **FF** file format · - **Estimate:** 30–60 h (PostScript interpreter is a large separate project: +80–150 h). ### 20. Performance on large documents (P) -- **Missing:** incremental composition (recompose from the edited paragraph; 8 ms keystroke - budget), benchmarks against InDesign on long books and image-heavy catalogues. +- **Missing:** the 8 ms keystroke budget in long stories: an edit that moves lines into other + frames composes the story to its end, the lines an edit keeps are copied, and stories with + footnotes, tables, anchored objects or keep options that move lines compose whole; benchmarks + against InDesign on long books and image-heavy catalogues. - **Have:** compose 300k characters ~38 ms warm, damage-region repaint (< 1 ms while typing), - parallel story composition. + parallel story composition, and an edit composes only the paragraphs it can change in a plain + story (240 paragraphs: 3 composed for a typed character). - **Estimate:** 40–80 h. ### 26. Autoflow flows into the primary text frame of the pages that follow (F) From 5858ccfec1e467459c7498d1190315bd135bf825 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 06:28:18 -0800 Subject: [PATCH 1015/1349] ROADMAP: the idle canvas frame entry moves to the top of the progress log The progress log is newest first, and the 2026-11-12 entry sat among the 2026-10-30 entries. --- ROADMAP.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index 16b009a80..b029e87bf 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -400,6 +400,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-11-12** · An idle canvas frame no longer does work for the spreads out of view (part of #1343): page shadows, paper, guides, margins, frame edges and overset marks are painted for the spreads and objects in view, and only their stories are looked up. In a 400-page document with two frames a page, an idle frame painted 5,099 shapes and looked up 400 stories; it now paints 311 and looks up 1, the same as in a 4-page document. No readiness percentage change. - **2026-11-06** · Preflight warns about white or [Paper] set to overprint (#2401): a fill, stroke or stroke gap, or ruby and kenten, in [Paper] or a colour that lays down no ink (C=0 M=0 Y=0 K=0, a 0% tint; a spot ink, such as a white ink or a varnish, prints whatever colour stands in for it), is reported as `whiteOverprint`, since it disappears on press. Text itself has no overprint, so white text in a frame set to Overprint Fill still knocks out and prints, and is not reported. Preflight no longer says PDF export drops ruby and kenten overprint, which it writes. No readiness percentage change. - **2026-11-04** · Interface Language › Português (Brasil) translates the whole interface: 996 strings the catalog lacked (tool names, window and guide commands, Keyboard Shortcuts sets, panel docking, Edit › Menus paths, the Japanese typesetting dialogs, special characters, Load Styles, Data Merge, Preflight, font replacement, the Package summary, OpenType features, page presets, About) and File › New's unit names, and a path is "demarcador" throughout. `cargo xtask i18n-report` counts 2,936 of 2,939 strings for pt-BR (1,933 before); only the Control panel's `IT`, `VA` and `Y:` captions stay English, as in every language. No readiness percentage change. - **2026-11-03** · `type.char` says when the font it applies isn't available (#2189): it returns `{"warnings": ["Missing font: Courier Prime (using Source Sans 3)"]}`, or `Missing font style: …` for a style the family doesn't have, in preflight's words. The font is still applied, as before, so Find Font and preflight list it. A script that asked for a font the machine doesn't have exported in the substitute with no word about it. No readiness percentage change. @@ -413,7 +414,6 @@ Newest first. - **2026-10-30** · macOS: a file dragged in from the Finder fills the frame it is dropped on. winit sends no pointer events during such a drag, so the drop asks the system where the pointer is (`Services::pointer`, from `NSEvent.mouseLocation`), at any UI scale. No readiness percentage change. - **2026-10-30** · File > Package opens a dialog, as the reference app's: a Summary of fonts, links and images and inks, pages for each, a Printing Instructions step, and a PDF made with the options of a preset (#1514, #1515). - **2026-10-30** · IDML import reads TOC separators and entry styles written with the `$ID/` prefix or as `Properties` children, and the TOC separator notation (`^t`, `^y`, `^m`, `^>`) is shared by the dialog and IDML, with a special-character menu on the separator field (#1249, #1255). -- **2026-11-12** · An idle canvas frame no longer does work for the spreads out of view (part of #1343): page shadows, paper, guides, margins, frame edges and overset marks are painted for the spreads and objects in view, and only their stories are looked up. In a 400-page document with two frames a page, an idle frame painted 5,099 shapes and looked up 400 stories; it now paints 311 and looks up 1, the same as in a 4-page document. No readiness percentage change. - **2026-10-30** · Spreads show a line at each edge where two of their pages meet, on the canvas only (it isn't printed or exported), so the page boundaries inside a spread are visible while laying out across them, in the spread edge's colour. Right-to-left spreads and pages of different sizes put it on the edge the pages share; pages that don't touch, as an imported spread can keep them, get none (#1838). No readiness percentage change. - **2026-10-29** · Inserting text with many returns no longer takes time that grows with their square (part of #1588): each return copied its paragraph's format with its own insert, moving every format after it. Splitting 20,000 returns into paragraphs took 15.8 s; placing a text file of them now takes 0.2 s, and one of a million returns 5.5 s. No readiness percentage change. - **2026-10-28** · A placed image whose pixels would decode past 1 GiB of RGBA (256 Mpx) is refused from its header, before decoding (#1586). A 288 KB 23,000 px gray PNG used to hang the first draw for 9 s and take the app to 4.5 GB; it now draws as an empty frame, and PDF export skips it with a warning. A 300 ppi A0 scan still fits. No readiness percentage change. From e22a6362ccab4088e1b9be2ca7d9c577aea99d3e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 06:53:12 -0800 Subject: [PATCH 1016/1349] Compose: list every case that composes a story whole in gap 20 docs/gaps.md now lists the same cases as docs/architecture.md and reuse::plain. A doc comment on rejoin says that a run style an edit uses for the first time stops the reuse until the old composition reaches the same style at the same index. --- crates/compose/src/reuse.rs | 5 +++++ docs/gaps.md | 5 ++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/compose/src/reuse.rs b/crates/compose/src/reuse.rs index 67a7d6314..d3f570ebe 100644 --- a/crates/compose/src/reuse.rs +++ b/crates/compose/src/reuse.rs @@ -309,6 +309,11 @@ impl Reuse<'_> { /// At paragraph `pi` of the edited story, in the state `snap` with `styles` and `info` as /// they are: when the composition before the edit was in that state before the same /// paragraph, copy what it set from there on into `out`, `styles` and `info`, and say so. + /// + /// The copied lines keep their run-style indexes, so this needs `styles` to equal the old + /// table up to that point. A run style that the edit uses for the first time takes a new + /// index, and the story then composes on until the old composition added the same style at + /// the same index, or to its end. The result is the same; only the time differs. pub(crate) fn rejoin( &self, plan: &Plan, diff --git a/docs/gaps.md b/docs/gaps.md index df396e9f6..02f02a33b 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -233,7 +233,10 @@ Kind: **F** feature · **U** UI/UX · **T** typography · **FF** file format · ### 20. Performance on large documents (P) - **Missing:** the 8 ms keystroke budget in long stories: an edit that moves lines into other frames composes the story to its end, the lines an edit keeps are copied, and stories with - footnotes, tables, anchored objects or keep options that move lines compose whole; benchmarks + footnotes, endnotes, tables, anchored objects, named lists, tracked deletions, balanced + columns, vertical justification other than Top, column rules, type on a path, spanning or + split paragraphs, paragraph borders or shading, or keep options that move lines compose + whole; benchmarks against InDesign on long books and image-heavy catalogues. - **Have:** compose 300k characters ~38 ms warm, damage-region repaint (< 1 ms while typing), parallel story composition, and an edit composes only the paragraphs it can change in a plain From 92043b4c4892224a14d1441160ad25bf4508e523 Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:39:39 +0530 Subject: [PATCH 1017/1349] =?UTF-8?q?Automation=20roots:=20refuse=20COM?= =?UTF-8?q?=C2=B9=20to=20LPT=C2=B3=20and=20a=20device=20name=20before=20a?= =?UTF-8?q?=20colon=20(#2383)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Automation roots: refuse COM¹ to LPT³ and a device name before a colon is_device_name missed COM¹, COM², COM³ and LPT¹, LPT², LPT³, which Windows reserves as it does COM1. It also cut the name only at a period, so COM1: and NUL:x were not seen as device names. * Credit my name in the About window * Automation roots: document the device-name tests CodeRabbit's docstring check counts the touched tests. same_component stays without a doc comment, because #2205 deletes that function and a doc line above it conflicts. * Automation roots: record the device-name refusal The MCP roots description and the roadmap now name COM¹ to LPT³ and a device name before a colon. --- ROADMAP.md | 3 ++- contributors/people.toml | 4 ++++ crates/engine/src/cmd/export_batch.rs | 6 +++++- crates/engine/src/file_access.rs | 17 ++++++++++++----- docs/mcp.md | 2 +- 5 files changed, 24 insertions(+), 8 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 006396b1d..3a5feac4b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -4,7 +4,7 @@ - 2026-10-23: placed-artwork layer options survive IDML and native round trips per placement, independently of shared assets. Unsupported visibility overrides are explicit import/preflight/PDF warnings; format 4 prevents older native readers from silently discarding them. Rendering parity is still open; see [graphic-layer-options.md](docs/graphic-layer-options.md). - FID1: PDF export normalizes mixed emitted gradient color spaces to RGB with an explicit warning; homogeneous device-space gradients retain their components. Linear/radial, midpoint, archival and print policies have synthetic regression coverage. -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-04 · **Change:** minor (Pages panel parents and alternate layouts; File ▸ Export Layouts and Versions; placed graphic layer-option preservation and explicit rendering warnings; File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill; Based on Parent; object styles carry effects; table anchors keep their own paragraphs; grouped HTML/EPUB reading order; Links source paths; XLSX cached cell values retain numeric precision and text) · **Target:** Adobe InDesign 2026 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-06 · **Change:** minor (Pages panel parents and alternate layouts; File ▸ Export Layouts and Versions; placed graphic layer-option preservation and explicit rendering warnings; File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill; Based on Parent; object styles carry effects; table anchors keep their own paragraphs; grouped HTML/EPUB reading order; Links source paths; XLSX cached cell values retain numeric precision and text; automation roots refuse superscript COM/LPT names and a device name before a colon) · **Target:** Adobe InDesign 2026 - AR1.1: Kashida justification tests verify space fallback without Tatweel fonts using an isolated font database, while retaining elongation assertions when fonts support it. - AR1: Arabic IDML controls now retain character direction, kashida switches, diacritic offsets/forms, paragraph policy values and independent story/table directions. Shaping preserves joining context and script/language selection; paragraph-level bidi, contextual digit conversion, mark-safe elongation, RTL columns/tables and physical column insertion have regression coverage. Vendor-specific justification and diacritic presets remain explicit preflight warnings; see docs/arabic-typography.md. @@ -12,6 +12,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, open (documented JSON format + IDML), scriptable by agents (MCP), and available on the web. +- **2026-11-06** · Automation roots refuse `COM¹` to `LPT³` and a device name before a colon (`COM1:`, `NUL:x`). A batch-export layout of that name is written with a leading `_` on every platform. No readiness percentage change. - **2026-10-30** · Document Fonts lookup treats a bare document filename's empty parent as the current directory (#2014), preserving case-insensitive discovery and automation read-root checks. No readiness percentage change. - **2026-10-28** · Inline table rows leave room for column and spanning footnotes, continuing in the next column or frame when needed (#1901). Cell-local footnotes contribute to row height diff --git a/contributors/people.toml b/contributors/people.toml index 5049c9493..617091888 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -87,3 +87,7 @@ sync_github_name = true [people.JonRC] real_name = "Jonathan Cardoso" display_name = "Jonathan Cardoso" + +[people.adikshan11] +real_name = "Adithya Shankaran" +sync_github_name = true diff --git a/crates/engine/src/cmd/export_batch.rs b/crates/engine/src/cmd/export_batch.rs index 8e685475b..3b24f60c9 100644 --- a/crates/engine/src/cmd/export_batch.rs +++ b/crates/engine/src/cmd/export_batch.rs @@ -557,13 +557,17 @@ mod tests { assert!(pdf.starts_with(b"%PDF-")); } + /// An export name drops reserved characters, and a Windows device name (`CON`, `COM¹`, `LPT³`) + /// is written with a leading `_`. Two files built from one name stay distinct. #[test] fn names_are_made_safe_and_unique() { assert_eq!(safe_name("../a/b:c*?"), "a b c"); assert_eq!(safe_name(" ... "), "Untitled"); assert_eq!(safe_name(&"x".repeat(500)).chars().count(), MAX_NAME); // Windows device names name no file. - for (name, safe) in [("CON", "_CON"), ("nul", "_nul"), ("com1.x", "_com1.x"), ("Console", "Console")] { + for (name, safe) in + [("CON", "_CON"), ("nul", "_nul"), ("com1.x", "_com1.x"), ("COM¹", "_COM¹"), ("lpt³.x", "_lpt³.x"), ("Console", "Console")] + { assert_eq!(safe_name(name), safe); } let mut s = two_layouts(); diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 69edeaca1..e1127dd5f 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -265,10 +265,11 @@ fn inside(path: &Path, root: &Path) -> bool { root.components().all(|r| path.next() == Some(r)) } -/// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file. +/// A Windows device name (`CON`, `NUL`, `COM1`, `COM¹`… also with an extension or a colon), which names no file. pub(crate) fn is_device_name(component: &str) -> bool { - let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase(); - let numbered = |prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9")); + let stem = component.split(['.', ':']).next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase(); + let numbered = + |prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³")); matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT") } @@ -526,6 +527,8 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + /// On Windows an existing file spelled in another case is still inside its root, and `NUL`, + /// `COM1` and `COM¹` are refused. #[cfg(windows)] #[test] fn windows_ignores_case_and_refuses_devices() { @@ -536,6 +539,8 @@ mod tests { let e = roots.check(s(base.join("out/NUL")), Access::Write).unwrap_err(); assert!(e.contains("reserved device names"), "{e}"); assert!(roots.check(s(base.join("out/com1.txt")), Access::Write).is_err()); + let e = roots.check(s(base.join("out/COM¹.txt")), Access::Write).unwrap_err(); + assert!(e.contains("reserved device names"), "{e}"); assert_eq!(roots.check(s(base.join("out/console.txt")), Access::Write), Ok(())); let _ = std::fs::remove_dir_all(base); } @@ -561,6 +566,8 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + /// `COM¹` to `LPT³`, and a device name before a colon, are reserved. `COM⁴`, `com¹0`, `lpt¹x` + /// and `console:x` are file names. #[test] fn inside_compares_components_exactly() { assert!(inside(Path::new("/work/in/a"), Path::new("/work/in"))); @@ -571,10 +578,10 @@ mod tests { #[test] fn device_names() { - for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.designcraft", "NUL "] { + for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.designcraft", "NUL ", "COM¹", "Lpt²", "lpt³.txt", "COM1:", "nul:x", "COM¹:"] { assert!(is_device_name(d), "{d}"); } - for f in ["console", "com10", "COM0", "lpt", "a.designcraft", "nul-x"] { + for f in ["console", "com10", "COM0", "lpt", "a.designcraft", "nul-x", "COM⁴", "com¹0", "lpt¹x", "console:x"] { assert!(!is_device_name(f), "{f}"); } } diff --git a/docs/mcp.md b/docs/mcp.md index f7e0b8187..3c190317d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -143,7 +143,7 @@ config works across the suite) keep the agent to the folders you give it: folder that doesn't exist is refused, as is a link that leads nowhere (writing through it would create its target). The result is compared with each root by whole folder names: `/work2/x` is not inside `/work`. On Windows case is ignored, UNC paths (`\\server\share\...`) are resolved like - drive-letter ones, and device names (`CON`, `NUL`, `COM1`...) are refused. + drive-letter ones, and device names (`CON`, `NUL`, `COM1`, `COM¹`, including before a colon) are refused. - A refused path is an ordinary tool error the agent can read and correct, for example `automation path rejected: outside the write root /work/project/out: /etc/x.designcraft` (with several, `outside the write roots /work/project/out, /tmp/scratch: ...`) or From 092c46c1487203f3711fab335d7ba4b0aaaf1f09 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 07:39:06 -0800 Subject: [PATCH 1018/1349] Render: list layers among the kept shadow image's dependencies The doc comment on with_kept_filters now names the document's layers next to its colors, styles and images, as Deps holds them. --- crates/render/src/fx.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index c6cbd532e..0cfe63661 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -491,7 +491,7 @@ impl Renderer { /// [`Renderer::with_filters`] for a drop shadow or an outer glow of `it`, keeping its image /// between renders. While the object, its effect, the view's scale and rotation, the render - /// options and the document's colours, styles and images stay the same, a move of the object + /// options and the document's colors, styles, layers and images stay the same, a move of the object /// or of the view by whole device pixels places the kept image again instead of drawing and /// blurring it. Only multithreaded contexts (the canvas) keep images, and only of objects /// without text or nested items. From c2a15435285a1c6d02a2293529a3949a3ccced4e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 07:40:29 -0800 Subject: [PATCH 1019/1349] Copy: mark the renumber results as must-use renumber and its helpers return false when a copy nests deeper than MAX_COPY_DEPTH and must not be inserted. They now carry #[must_use], so a caller that drops the result fails to build under -D warnings. --- crates/engine/src/cmd/object.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 149a4eab1..a9da97458 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -1112,12 +1112,14 @@ fn adopt_or_dangle(dst: &mut Document, src: &Document, id: AssetId) -> AssetId { /// the stories of `src` copied so far to their copies. False when its groups, or the tables and notes in the table cells /// of its stories, nest deeper than [`MAX_COPY_DEPTH`]: the items and tables below that keep their ids, and the copy /// must not be used. +#[must_use = "false means the copy is incomplete and must not be inserted"] pub(crate) fn renumber(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut HashMap) -> bool { renumber_in(dst, src, it, stories, 0, true) } /// [`renumber`] for an item `depth` groups deep. `adopt` is false inside a story copy, whose asset references the copy /// has already adopted. +#[must_use = "false means the copy is incomplete and must not be inserted"] fn renumber_in(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut HashMap, depth: usize, adopt: bool) -> bool { it.id = ItemId(dst.alloc()); let my_id = it.id; @@ -1190,6 +1192,7 @@ fn renumber_in(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut /// levels. Cross-references in `st` and in the copies `stories` already lists point at the copies of their /// destinations where those are copied, and the copy's paragraphs follow its tables. False when tables or notes in /// table cells nest deeper than [`MAX_COPY_DEPTH`]: the tables below that keep their ids, and the copy must not be used. +#[must_use = "false means the copy is incomplete and must not be inserted"] fn renumber_marks(dst: &mut Document, src: &Document, stories: &HashMap, st: &mut Story) -> bool { let base = st.id.0 << 24; let mut anchors = HashMap::new(); @@ -1243,6 +1246,7 @@ fn retarget_copies(dst: &mut Document, src: &Document, stories: &HashMap bool { let mut tables = HashMap::new(); for (old, mut table) in std::mem::take(&mut st.tables) { @@ -1320,6 +1324,7 @@ fn retarget_xrefs(copy: &mut Story, orig: &Story, map: &HashMap, depth /// Fresh ids for the objects anchored in story copy `st`, its table cells, footnotes and endnotes (#1522), each `depth` /// levels deep. False when one of them nests groups deeper than [`MAX_COPY_DEPTH`]. +#[must_use = "false means the copy is incomplete and must not be inserted"] fn renumber_anchored(dst: &mut Document, src: &Document, st: &mut Story, stories: &mut HashMap, depth: usize) -> bool { let mut complete = true; let mut fresh = |t: &mut Story| { From 3ff65a381a308267eecc14a8f7ba36c476f2c522 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 07:42:44 -0800 Subject: [PATCH 1020/1349] Layers: compare frame paths in the duplicate thread-order test Both text frames in the test start with an identity transform, so comparing transforms passed even when the copied thread was reversed. The assertion now compares the frames' paths, which differ. --- crates/engine/src/cmd/layout/layers.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/layout/layers.rs b/crates/engine/src/cmd/layout/layers.rs index a527df660..b696653b4 100644 --- a/crates/engine/src/cmd/layout/layers.rs +++ b/crates/engine/src/cmd/layout/layers.rs @@ -538,8 +538,8 @@ mod layer_tests { assert_eq!(st.text, orig.text, "the copy holds the whole text"); // Thread order as in the original (a's copy first, though b's copy was made first), without c. let pos = |id: designcraft_doc::ItemId| d.find(id).map(|l| l.path.clone()); - let order: Vec<_> = st.frames.iter().map(|f| d.item(*f).unwrap().xf).collect(); - let want: Vec<_> = [a, b].iter().map(|f| d.item(designcraft_doc::ItemId(*f)).unwrap().xf).collect(); + let order: Vec<_> = st.frames.iter().map(|f| d.item(*f).unwrap().path.clone()).collect(); + let want: Vec<_> = [a, b].iter().map(|f| d.item(designcraft_doc::ItemId(*f)).unwrap().path.clone()).collect(); assert_eq!(order, want); assert!(st.frames.iter().all(|f| pos(*f).is_some())); } From 329806477e0bd05f7bf05f16e44d06fdb9cfb5f8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 07:45:10 -0800 Subject: [PATCH 1021/1349] Data merge: an explicit QR role in text is refused, and the caret follows each field data.placeholder.add with role qr and the insertion point in text bound the QR code to the first selected frame, which the caret was not in. It now returns "qr placeholders bind to a frame", as a QR field there does. A field inserted at the insertion point left the caret before its marker, so a second field went in front of the first. The caret now moves past the marker, as after typing. Docs: docs/agents.md. --- crates/engine/src/cmd/datamerge.rs | 9 +++++- crates/engine/src/cmd/datamerge/tests.rs | 38 ++++++++++++++++++++++++ docs/agents.md | 5 ++-- 3 files changed, 49 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/datamerge.rs b/crates/engine/src/cmd/datamerge.rs index e03da2d05..c57d507fb 100644 --- a/crates/engine/src/cmd/datamerge.rs +++ b/crates/engine/src/cmd/datamerge.rs @@ -485,7 +485,9 @@ fn add_placeholder(d: &mut Document, sel: &mut Selection, p: &Value, name: &str) } else if explicit_story || role_param == Some("text") { false } else if role_param == Some("qr") { - true + // A QR role with the insertion point in text is refused below rather than bound to a + // selected frame the caret is not in. + sel.text.is_none() } else if role_param == Some("image") { // An image role with the insertion point in text places an inline image there. sel.text.is_none() @@ -585,6 +587,11 @@ fn add_placeholder(d: &mut Document, sel: &mut Selection, p: &Value, name: &str) st.replace(at..at, &marker); } d.adjust_text_ranges(story, at..at, marker.len()); + // The caret moves past the field, as after typing, so the next field goes after it. + if let Some(t) = sel.text.as_mut().filter(|t| t.story == story && t.cell.is_none()) { + let shift = |pos: usize| if pos >= at { pos + marker.len() } else { pos }; + (t.anchor, t.focus) = (shift(t.anchor), shift(t.focus)); + } PlaceholderAnchor::Text { story, start: at, end: at.saturating_add(marker.len()) } } else { let text = d.story(story).map(|st| st.text.clone()).unwrap_or_default(); diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index 5f5c4a118..9180964c2 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -831,6 +831,44 @@ fn a_qr_field_at_the_insertion_point_is_refused() { assert!(s.documents()[0].doc.data_merge.placeholders.is_empty()); } +/// An explicit QR role at a text insertion point is refused too, rather than binding the QR code +/// to a selected frame the caret is not in. +#[test] +fn an_explicit_qr_role_at_the_insertion_point_is_refused() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name,#Code\nAda,hello\n"); + let made = text_frame(&mut s, [36.0, 36.0, 300.0, 300.0], "Hi ", None); + let other = text_frame(&mut s, [36.0, 400.0, 300.0, 600.0], "", None); + let other_id = designcraft_doc::ItemId(other["id"].as_u64().unwrap()); + let sid = StoryId(made["story"].as_u64().unwrap()); + let doc = s.doc_mut().unwrap(); + doc.selection = Selection::text(TextSel { story: sid, anchor: 3, focus: 3, frame: None, cell: None }); + doc.selection.items = vec![other_id]; + let msg = err(&mut s, "data.placeholder.add", json!({"field": "Code", "role": "qr"})); + assert!(msg.contains("bind to a frame"), "{msg}"); + let doc = &s.documents()[0].doc; + assert!(doc.data_merge.placeholders.is_empty()); + assert_eq!(doc.item(other_id).unwrap().label, "", "the other frame is not bound"); +} + +/// Fields inserted one after another at the insertion point keep their order: the caret moves +/// past each marker, as after typing. +#[test] +fn fields_inserted_at_the_insertion_point_keep_their_order() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name,City,@Photo\nAda,Paris,/x.png\n"); + let made = text_frame(&mut s, [36.0, 36.0, 300.0, 300.0], "Hi ", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 3, "focus": 3})); + exec(&mut s, "data.placeholder.add", json!({"field": "Name", "role": "text"})); + exec(&mut s, "data.placeholder.add", json!({"field": "City", "role": "text"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo"})); + assert_eq!(texts(&s), vec!["Hi <><><>".to_string()]); + let t = s.documents()[0].selection.text.unwrap(); + assert_eq!((t.anchor, t.focus), (28, 28)); +} + /// A typed `<>` marker for an image column places the image too, from an absolute path; /// an explicit text role still writes the path as text. #[test] diff --git a/docs/agents.md b/docs/agents.md index b2ec4c156..8058510e6 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -91,8 +91,9 @@ external PDF/X certification. marks text or a frame as a field (`role`: text, image, qr, hyperlink). An image field (a `@` column) inserted at a text insertion point, or typed there as `<>`, merges as an inline image at its natural size, scaled down to fit the frame. The merge writes only text into a table cell or a note: an image field inserted there is refused unless `role` -is `text`, and its `<>` marker, inserted or typed, merges as the path. A QR field (a `#` column) inserted at a -text insertion point is refused; bind it to a frame instead. An image +is `text`, and its `<>` marker, inserted or typed, merges as the path. A QR field (a `#` column) or `role: "qr"` +at a text insertion point is refused; bind it to a frame with `item` instead. A field inserted at the insertion point +puts the caret after its marker. An image path is absolute or relative to the data file's folder, then the document's; a path that starts with one separator (`\Photos\a.jpg`) is tried from the drive's root first. `data.options` sets records, tiling and image fitting; `data.preview {record}` / `data.preview.stop` show one record without saving it. From 72475633c20751b433a705268d4c9a6e87f3c6fd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 07:49:45 -0800 Subject: [PATCH 1022/1349] Layers: point copied live captions at copied anchored objects Duplicate Layer pointed copied live captions at the copied objects before anchored objects in the copied stories had their ids, so a caption whose source is anchored kept the original object as its source. Anchored objects in copied stories also kept their captions and parent-item overrides unchanged. The copies now take their links after every anchored object has its id, and anchored objects get the same remapping as the other copies. --- crates/engine/src/cmd/layout/layers.rs | 53 +++++++++++++++++++++++--- 1 file changed, 48 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/layout/layers.rs b/crates/engine/src/cmd/layout/layers.rs index b696653b4..26e3545d1 100644 --- a/crates/engine/src/cmd/layout/layers.rs +++ b/crates/engine/src/cmd/layout/layers.rs @@ -91,11 +91,6 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { copies.push((r, copy)); } } - // Every copy has its id before overrides are pointed at the copied parent items. - for (r, mut copy) in copies { - move_copy(&mut copy, new_id, &ids); - d.insert_item(r, copy, None)?; - } // A story copy holds the same anchored objects as the original: they get ids of their own, and the stories of // anchored text frames get copies in turn. The story copies are taken in story order. let mut pending: Vec = stories.values().copied().collect(); @@ -106,6 +101,17 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { renumber_anchored(d, &mut st, new_id, &mut stories, &mut ids, &mut pending); d.stories.insert(new, Arc::new(st)); } + // Every copy, anchored objects included, has its id before overrides are pointed at the copied parent items and + // live captions at the copied objects. + for (r, mut copy) in copies { + move_copy(&mut copy, new_id, &ids); + d.insert_item(r, copy, None)?; + } + for new in stories.values() { + if let Some(st) = d.story_mut(*new) { + move_anchored(st, new_id, &ids); + } + } // Each story copy gets its frames in the original order, text anchors of its own, which its cross-references // and those of the other copies point at, and tables with ids of their own, the tables in its cells and notes // included, allocated in story order. @@ -375,6 +381,22 @@ fn move_copy(it: &mut Item, to: LayerId, ids: &HashMap) { } } +/// Run [`move_copy`] on the anchored objects of `st` and of the stories of its table cells and notes. [`too_deep`] bounds +/// the nesting. +fn move_anchored(st: &mut Story, to: LayerId, ids: &HashMap) { + for o in &mut st.objects { + move_copy(&mut Arc::make_mut(o).item, to, ids); + } + for t in st.tables.values_mut() { + for c in &mut Arc::make_mut(t).cells { + move_anchored(&mut c.text, to, ids); + } + } + for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + move_anchored(&mut Arc::make_mut(n).text, to, ids); + } +} + #[cfg(test)] mod layer_tests { use serde_json::json; @@ -695,6 +717,27 @@ mod layer_tests { assert_ne!(frame.id.0, a); } + #[test] + fn duplicate_layer_points_copied_live_captions_at_copied_anchored_objects() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let a = s.execute("frame.create", &json!({"rect": [450, 450, 474, 490]})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.caption", &json!({"ids": [a], "text": "{name}", "live": true})).unwrap(); + let text = json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Before after."}); + let f = s.execute("frame.create", &text).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + // The caption's source moves into the story and keeps its id. + s.execute("anchored.insert", &json!({"ids": [a], "story": sid.0, "pos": 7})).unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let anchored = d.anchored_items().into_iter().map(|(_, i)| i).find(|i| i.layer.0 == copy).unwrap(); + assert_ne!(anchored.id.0, a); + let copies = on_layer(d, copy); + let caption = copies.iter().find_map(|i| i.live_caption.as_ref()).unwrap(); + assert_eq!(caption.source, anchored.id, "the caption's copy follows the anchored object's copy"); + } + #[test] fn duplicate_layer_copies_the_hyperlinks_of_its_objects_and_text() { use designcraft_doc::{HyperlinkDest, HyperlinkSource}; From 5c484618ca37c1fa3b923d529d8c4b3269e387e0 Mon Sep 17 00:00:00 2001 From: jayzed80 <121670721+jayzed80@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:53:23 +0000 Subject: [PATCH 1023/1349] Save: a TIFF, BMP or PSD too big for opening to inflate is stored as is, so the document reopens (#2283) (#2701) save deflated every asset that isn't PNG, JPEG, GIF or WebP, with no size cap, while opening refuses a deflated asset over 1 GiB or deflated entries over 4 GiB together. An asset past either cap is now stored as is, which opening reads at any size. Smaller assets are deflated as before, and the zip bomb guard on load is unchanged. --- crates/format/src/lib.rs | 25 +++++++++++++++++++++---- crates/format/src/tests.rs | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 4 deletions(-) diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index a03667209..52ce74860 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -86,6 +86,11 @@ fn required_version(doc: &Document) -> u32 { } fn save_with_large_entries_from(doc: &Document, preview: Option<&[u8]>, large_entry: usize) -> Result, FormatError> { + save_within(doc, preview, large_entry, Limits::DEFAULT) +} + +/// [`save_with_large_entries_from`], deflating only what a reader with `limits` inflates. +fn save_within(doc: &Document, preview: Option<&[u8]>, large_entry: usize, limits: Limits) -> Result, FormatError> { // JSON writes infinity and NaN as null, which no load accepts: the file would not open. if let Some(id) = doc.non_finite_item() { return Err(FormatError::Unsaveable(format!("object {} has a position or size that is not a finite number", id.0))); @@ -103,8 +108,8 @@ fn save_with_large_entries_from(doc: &Document, preview: Option<&[u8]>, large_en z.write_all(MIME.as_bytes()).map_err(|e| FormatError::Io(e.to_string()))?; z.start_file("meta.json", deflate).map_err(io)?; let version = required_version(doc); - let meta = json!({"format": "designcraft", "version": version, "generator": concat!("DesignCraft ", env!("CARGO_PKG_VERSION"))}); - z.write_all(meta.to_string().as_bytes()).map_err(|e| FormatError::Io(e.to_string()))?; + let meta = json!({"format": "designcraft", "version": version, "generator": concat!("DesignCraft ", env!("CARGO_PKG_VERSION"))}).to_string(); + z.write_all(meta.as_bytes()).map_err(|e| FormatError::Io(e.to_string()))?; if let Some(png) = preview { z.start_file(PREVIEW, stored).map_err(io)?; z.write_all(png).map_err(|e| FormatError::Io(e.to_string()))?; @@ -112,12 +117,23 @@ fn save_with_large_entries_from(doc: &Document, preview: Option<&[u8]>, large_en z.start_file("document.json", deflate).map_err(io)?; let json = serde_json::to_vec_pretty(doc).map_err(|e| FormatError::Io(e.to_string()))?; z.write_all(&json).map_err(|e| FormatError::Io(e.to_string()))?; + // Opening caps what deflated entries expand to, one asset and all of them together, while a + // stored entry opens at any size. An asset deflated past those caps would save but never + // open again (#2283), so it is stored as is instead. + let mut deflate_left = limits.total.saturating_sub(meta.len() as u64).saturating_sub(json.len() as u64); for (id, a) in &doc.assets { if a.data.is_empty() { continue; } + let len = a.data.len() as u64; // Already-compressed images are stored as-is. - let opts = if matches!(a.mime.as_str(), "image/png" | "image/jpeg" | "image/gif" | "image/webp") { stored } else { deflate }; + let compressed = matches!(a.mime.as_str(), "image/png" | "image/jpeg" | "image/gif" | "image/webp"); + let opts = if compressed || len > limits.asset || len > deflate_left { + stored + } else { + deflate_left = deflate_left.saturating_sub(len); + deflate + }; let opts = opts.large_file(a.data.len() >= large_entry); z.start_file(format!("assets/{}.{}", id.0, ext_for(&a.mime)), opts).map_err(io)?; z.write_all(&a.data).map_err(|e| FormatError::Io(e.to_string()))?; @@ -183,7 +199,8 @@ const MAX_ENTRIES: usize = 100_000; /// bytes in the archive, which is already in memory, and all stored entries read together are /// held to the archive's own size), so a placed image — stored as is by [`save`] — opens whatever /// its size and doesn't count against the budget. Saving has no cap, and this keeps every saved -/// document openable (#2166). +/// document openable (#2166): [`save`] deflates an asset only while it stays within these limits, +/// and stores the rest as is (#2283). #[derive(Clone, Copy, Debug)] struct Limits { /// Most bytes `meta.json` or `document.json` may expand to. diff --git a/crates/format/src/tests.rs b/crates/format/src/tests.rs index 0e6f613cd..5b73801ea 100644 --- a/crates/format/src/tests.rs +++ b/crates/format/src/tests.rs @@ -152,6 +152,44 @@ fn stored_assets_open_at_any_size_while_deflated_ones_stay_capped() { assert!(!doc.assets.is_empty() && doc.assets.values().all(|x| x.data.len() == 50_000), "every saved image is back"); } +fn tiff_asset(d: &mut Document, data: Vec) -> AssetId { + let aid = AssetId(d.alloc()); + let a = Asset { id: aid, name: "x.tif".into(), mime: "image/tiff".into(), data: Arc::new(data), pixels: Some((1, 1)), ..Default::default() }; + d.assets.insert(aid, Arc::new(a)); + place(d, aid, 0.0); + aid +} + +fn is_deflated(bytes: &[u8], aid: AssetId) -> bool { + let mut z = zip::ZipArchive::new(Cursor::new(bytes)).unwrap(); + z.by_name(&format!("assets/{}.tif", aid.0)).unwrap().compression() == zip::CompressionMethod::Deflated +} + +/// #2283: `save` deflates a TIFF, BMP or PSD, and opening caps what a deflated asset (and all of +/// them together) may expand to. One past either cap is stored as is, so the document opens again. +#[test] +fn assets_too_big_to_inflate_are_stored_so_the_document_reopens() { + let mut d = Document::new(&NewDocument::default()); + let big = tiff_asset(&mut d, noise(5_000)); + let b = tiff_asset(&mut d, noise(3_000)); + let c = tiff_asset(&mut d, noise(3_000).into_iter().rev().collect()); + let small = tiff_asset(&mut d, vec![0; 500]); + // Room for the JSON, the small asset and one 3 000-byte asset, not two. + let json_len = serde_json::to_vec_pretty(&d).unwrap().len() as u64; + let tight = Limits { json: 256 << 20, asset: 4_000, total: json_len + 500 + 500 + 4_000 }; + + let saved = save_within(&d, None, LARGE_ENTRY, tight).unwrap(); + let back = load_zip_within(&saved, tight).expect("a saved document opens under the limits it was saved for"); + for aid in [big, b, c, small] { + assert_eq!(back.assets[&aid].data, d.assets[&aid].data, "asset {} round-trips", aid.0); + } + assert!(!is_deflated(&saved, big), "an asset over the per-asset cap is stored"); + assert!(!(is_deflated(&saved, b) && is_deflated(&saved, c)), "the two together would pass the total budget"); + // Within the limits nothing changes: everything still deflates under the defaults. + let normal = save(&d).unwrap(); + assert!([big, b, c, small].iter().all(|a| is_deflated(&normal, *a))); +} + #[test] fn explicit_all_on_pdf_layers_require_a_capable_reader_only_when_needed() { let mut d = Document::new(&NewDocument::default()); From 7604db695f5fd9b8c238986d27ca8f63df0f2bad Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 07:57:27 -0800 Subject: [PATCH 1024/1349] Copy: point copied cross-references at copied anchors in one pass Each copied story with text anchors walked every story copied before it to retarget their cross-references, so copying many such frames took time quadratic in their number. The copies' cross-references are now pointed at the copied anchors once, after the last item is copied. --- crates/engine/src/cmd/edit.rs | 1 + crates/engine/src/cmd/object.rs | 75 ++++++++------------------------- 2 files changed, 18 insertions(+), 58 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 00e197514..958c7c511 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -117,6 +117,7 @@ fn paste_text(s: &mut Session, text: Option, formatted: bool) -> Result< Ok(i) }) .collect::>()?; + super::object::retarget_copied_xrefs(d, &items, &stories); let end = super::anchored::anchor_items(d, t.story, r.start, fresh, &Default::default())?; sel.text = Some(designcraft_doc::TextSel { anchor: end, focus: end, ..t }); Ok(json!({"pos": end, "anchored": list.len()})) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index a9da97458..481385952 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -1095,6 +1095,7 @@ pub fn duplicate_from(dst: &mut Document, src: &Document, ids: &[ItemId], to: Sp dst.insert_item(to, copy, None)?; out.push(nid); } + retarget_copied_xrefs(dst, src, &story_map); Ok(out) } @@ -1109,9 +1110,10 @@ fn adopt_or_dangle(dst: &mut Document, src: &Document, id: AssetId) -> AssetId { } /// Give `it` (an item of `src`) fresh ids from `dst`, with copies of its stories and the assets it uses. `stories` maps -/// the stories of `src` copied so far to their copies. False when its groups, or the tables and notes in the table cells -/// of its stories, nest deeper than [`MAX_COPY_DEPTH`]: the items and tables below that keep their ids, and the copy -/// must not be used. +/// the stories of `src` copied so far to their copies. After the last call with the same `stories`, +/// [`retarget_copied_xrefs`] points the copies' cross-references at the copied anchors. False when its groups, or the +/// tables and notes in the table cells of its stories, nest deeper than [`MAX_COPY_DEPTH`]: the items and tables below +/// that keep their ids, and the copy must not be used. #[must_use = "false means the copy is incomplete and must not be inserted"] pub(crate) fn renumber(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut HashMap) -> bool { renumber_in(dst, src, it, stories, 0, true) @@ -1138,7 +1140,7 @@ fn renumber_in(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut let n = StoryId(dst.alloc()); let mut st = src.story(tf.story).cloned().unwrap_or_else(|| Story::new(n)); st.id = n; - let marked = renumber_marks(dst, src, stories, &mut st); + let marked = renumber_marks(dst, &mut st); let mut assets = HashMap::new(); for a in designcraft_doc::story_asset_refs(&st) { let na = adopt_or_dangle(dst, src, a); @@ -1150,14 +1152,8 @@ fn renumber_in(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut st.frames.clear(); // Mapped first: the map is the seen-set that stops story recursion. stories.insert(tf.story, n); - let copied = stories.len(); complete = renumber_anchored(dst, src, &mut st, stories, depth + 1) && marked; dst.stories.insert(n, Arc::new(st)); - // The stories anchored in this one were copied while it was not yet in `dst`. - if stories.len() > copied { - let anchors = copied_anchors(dst, src, stories); - retarget_copies(dst, src, stories, &anchors); - } n } }; @@ -1187,39 +1183,26 @@ fn renumber_in(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut true } -/// Give the text anchors and tables of `st`, a new copy of a story of `src`, ids of their own (anchors from the story's -/// id, tables from `dst`), as do the tables in the stories of its table cells and notes down to [`MAX_COPY_DEPTH`] -/// levels. Cross-references in `st` and in the copies `stories` already lists point at the copies of their -/// destinations where those are copied, and the copy's paragraphs follow its tables. False when tables or notes in -/// table cells nest deeper than [`MAX_COPY_DEPTH`]: the tables below that keep their ids, and the copy must not be used. +/// Give the text anchors and tables of `st`, a new copy of a story, ids of their own (anchors from the story's id, +/// tables from `dst`), as do the tables in the stories of its table cells and notes down to [`MAX_COPY_DEPTH`] levels. +/// The copy's paragraphs follow its tables. False when tables or notes in table cells nest deeper than +/// [`MAX_COPY_DEPTH`]: the tables below that keep their ids, and the copy must not be used. #[must_use = "false means the copy is incomplete and must not be inserted"] -fn renumber_marks(dst: &mut Document, src: &Document, stories: &HashMap, st: &mut Story) -> bool { +fn renumber_marks(dst: &mut Document, st: &mut Story) -> bool { let base = st.id.0 << 24; - let mut anchors = HashMap::new(); for (k, a) in (1..).zip(st.anchors.iter_mut()) { - anchors.insert(a.id, base + k); Arc::make_mut(a).id = base + k; } - // Earlier copies change only when this story brings anchors, and this story only when it holds cross-references. - let own = !anchors.is_empty(); - if own || has_xrefs(st, 0) { - anchors.extend(copied_anchors(dst, src, stories)); - if own { - retarget_copies(dst, src, stories, &anchors); - } - remap_xrefs(st, &anchors, 0); - } renumber_tables(dst, st, 0) } -/// Whether `st`, or a story of its table cells and notes down to [`MAX_COPY_DEPTH`] levels, holds a cross-reference. -fn has_xrefs(st: &Story, depth: usize) -> bool { - if !st.xrefs.is_empty() { - return true; +/// Point the cross-references in the story copies in `dst` that `stories` maps at the copies of their destinations +/// where [`renumber`] copied those, in one pass after the last copy. Other cross-references keep their destination. +pub(crate) fn retarget_copied_xrefs(dst: &mut Document, src: &Document, stories: &HashMap) { + let anchors = copied_anchors(dst, src, stories); + if !anchors.is_empty() { + retarget_copies(dst, src, stories, &anchors); } - depth < MAX_COPY_DEPTH - && (st.tables.values().any(|t| t.cells.iter().any(|c| has_xrefs(&c.text, depth + 1))) - || st.notes.iter().chain(&st.endnotes).any(|n| has_xrefs(&n.text, depth + 1))) } /// The anchor ids of the stories of `src` that `stories` maps, each to the id of its copy's anchor in `dst`. @@ -1275,30 +1258,6 @@ fn renumber_tables(dst: &mut Document, st: &mut Story, depth: usize) -> bool { complete } -/// Point the cross-references in `st`, and in the stories of its table cells and notes down to [`MAX_COPY_DEPTH`] -/// levels, at the anchors `map` gives for their targets. -fn remap_xrefs(st: &mut Story, map: &HashMap, depth: usize) { - if map.is_empty() { - return; - } - for x in &mut st.xrefs { - if let Some(n) = map.get(&x.target) { - Arc::make_mut(x).target = *n; - } - } - if depth >= MAX_COPY_DEPTH { - return; - } - for t in st.tables.values_mut() { - for c in &mut Arc::make_mut(t).cells { - remap_xrefs(&mut c.text, map, depth + 1); - } - } - for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { - remap_xrefs(&mut Arc::make_mut(n).text, map, depth + 1); - } -} - /// Point the cross-references in `copy`, a copy of `orig`, and in the stories of its table cells and notes down to /// [`MAX_COPY_DEPTH`] levels, at the anchors `map` gives for the targets of the matching references in `orig`. fn retarget_xrefs(copy: &mut Story, orig: &Story, map: &HashMap, depth: usize) { From 812c7c4fd8319203906b8c6d5f2fe30e95127c21 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 08:01:00 -0800 Subject: [PATCH 1025/1349] Layers: give copied text anchors ids no other anchor has Duplicate Layer gave each copied text anchor the id story id << 24 | n without checking it, so a document holding an anchor with that id, such as one loaded from a file, got two anchors with one id, and cross-references could find the wrong one. A copied anchor now takes a new id when another anchor has that one or when the story id does not fit in the high bits. --- crates/engine/src/cmd/layout/layers.rs | 42 +++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/layout/layers.rs b/crates/engine/src/cmd/layout/layers.rs index 26e3545d1..2f423e676 100644 --- a/crates/engine/src/cmd/layout/layers.rs +++ b/crates/engine/src/cmd/layout/layers.rs @@ -129,7 +129,18 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { } st.frames = src.story(*old).map(|o| o.frames.iter().filter_map(|f| ids.get(f).copied()).collect()).unwrap_or_default(); for (k, a) in (1..).zip(st.anchors.iter_mut()) { - let id = (new.0 << 24) + k; + // `story id << 24 | n`, as anchors are made, or a new id when another anchor has that one or the story id + // does not fit. + let made = new.0.checked_mul(1 << 24).and_then(|base| base.checked_add(k)).filter(|id| !used.contains(id)); + let id = match made { + Some(id) => id, + None => loop { + let id = d.alloc(); + if !used.contains(&id) { + break id; + } + }, + }; anchors.insert(a.id, id); used.insert(id); Arc::make_mut(a).id = id; @@ -800,6 +811,35 @@ mod layer_tests { assert_eq!(d.find_anchor(st.anchors[0].id).map(|a| a.0), Some(copied)); } + #[test] + fn duplicate_layer_gives_copied_text_anchors_ids_no_other_anchor_has() { + use std::sync::Arc; + + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Head"})).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + s.execute("layer.new", &json!({"name": "Art"})).unwrap(); + let g = s.execute("frame.create", &json!({"rect": [72, 450, 400, 600], "content": "text", "text": "Other"})).unwrap()["id"].as_u64().unwrap(); + let other = s.doc().unwrap().doc.item(designcraft_doc::ItemId(g)).unwrap().text_frame().unwrap().story; + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + d.story_mut(sid).unwrap().insert_anchor(0, "Heading"); + // A story on another layer holds the ids the copy's first anchor would take, as anchors loaded from a file can. + let next = d.next_id; + let st = d.story_mut(other).unwrap(); + for k in 1..=64 { + st.insert_anchor(0, "Taken"); + Arc::make_mut(&mut st.anchors[0]).id = ((next + k) << 24) + 1; + } + s.execute("layer.duplicate", &json!({"id": base})).unwrap(); + let d = &s.doc().unwrap().doc; + let all: Vec = d.stories.values().flat_map(|st| st.anchors.iter().map(|a| a.id)).collect(); + assert_eq!(all.len(), 66); + let unique: std::collections::HashSet<_> = all.iter().collect(); + assert_eq!(unique.len(), all.len(), "the copied anchor has an id no other anchor has"); + } + #[test] fn duplicate_layer_remaps_anchors_in_cells_and_notes() { use designcraft_doc::Story; From 20319e991e049862f15da16632dffa3ff3fc265e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 08:07:12 -0800 Subject: [PATCH 1026/1349] Text Frame Options: link the insets only when every selected frame has even sides The dialog turned the inset link on when the first selected frame had the same inset on all four sides. With a second frame whose sides differ, typing one side then set all four sides of every selected frame, so the second frame lost its other insets. The link is now on only when every frame the dialog changes has even sides: the selected items, else the caret's frame, else every frame of the caret's story. --- crates/ui-egui/src/dialogs.rs | 21 +++++++++++- crates/ui-egui/src/dialogs/tests.rs | 51 +++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a6400054d..1499b37e5 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1005,6 +1005,24 @@ fn selected_frame_options(app: &DesignApp) -> Option bool { + let Some(st) = app.session.active() else { + return true; + }; + let mut ids = st.selection.items.clone(); + if ids.is_empty() + && let Some(t) = st.selection.text + { + ids = match t.frame { + Some(f) => vec![f], + None => st.doc.story(t.story).map(|s| s.frames.clone()).unwrap_or_default(), + }; + } + ids.iter().filter_map(|id| st.doc.item(*id)?.text_frame()).all(|t| t.options.inset.iter().all(|v| (v - t.options.inset[0]).abs() < 1e-9)) +} + /// Object › Text Frame Options shows the selected frame's options. `_shown` keeps what it showed, /// so OK sends only the fields the user changed. Fields given when the dialog opened count as /// changed. @@ -1056,7 +1074,8 @@ fn seed_text_frame_options(app: &DesignApp, d: &mut Dialog) { d.fields.entry(k.clone()).or_insert_with(|| v.clone()); } } - d.fields.entry("insetLinked".to_string()).or_insert_with(|| json!(o.inset.iter().all(|v| (v - o.inset[0]).abs() < 1e-9))); + // Linked only when no selected frame has uneven sides, so a typed side cannot overwrite them. + d.fields.entry("insetLinked".to_string()).or_insert_with(|| json!(selected_frames_have_even_insets(app))); // The frame's width: Fixed Number shows each column's width from it as the fields change. if let Some(w) = selected_frame_width(app) { d.fields.insert("_frameWidth".into(), json!(w)); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 272165b08..5c2cf749e 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1485,6 +1485,57 @@ fn text_frame_options_change_only_what_was_edited() { assert_eq!(opts(&app), before); } +#[test] +fn text_frame_options_link_the_insets_only_when_every_selected_frame_has_even_sides() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let frame = |app: &mut DesignApp, rect: [u32; 4], inset: Value| { + let r = app.run("frame.create", json!({"rect": rect, "content": "text", "text": "Hello"})).unwrap(); + let id = r["id"].as_u64().unwrap(); + app.run("object.textFrameOptions", json!({"ids": [id], "inset": inset})).unwrap(); + (designcraft_doc::ItemId(id), r["story"].clone()) + }; + let (even, _) = frame(&mut app, [36, 36, 236, 236], json!(6)); + let (uneven, uneven_story) = frame(&mut app, [300, 36, 500, 236], json!([1, 2, 3, 4])); + let (other_even, other_even_story) = frame(&mut app, [36, 300, 236, 500], json!(9)); + let inset = |app: &DesignApp, id| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.inset; + let seeded = |app: &DesignApp| { + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(app, &mut d); + d + }; + // The frame with even sides is selected first: the uneven one still turns the link off. + app.run("selection.set", json!({"ids": [even.0, uneven.0]})).unwrap(); + let mut d = seeded(&app); + assert_eq!(d.s("insetTop"), "0p6"); + assert!(!d.b("insetLinked"), "a selected frame with uneven sides leaves the link off"); + // Top edited while unlinked: only Top changes, and each frame keeps its other sides. + d.fields.insert("insetTop".into(), json!("1p0")); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + assert_eq!(inset(&app, even), [12.0, 6.0, 6.0, 6.0]); + assert_eq!(inset(&app, uneven), [12.0, 2.0, 3.0, 4.0]); + // A frame with even sides alone keeps the link on; selected with the uneven one, the link is off. + app.run("selection.set", json!({"ids": [other_even.0]})).unwrap(); + assert!(seeded(&app).b("insetLinked")); + app.run("selection.set", json!({"ids": [other_even.0, uneven.0]})).unwrap(); + assert!(!seeded(&app).b("insetLinked")); + // A caret: the frames the dialog changes decide. + app.run("text.select", json!({"story": uneven_story, "anchor": 0, "focus": 0})).unwrap(); + assert!(!seeded(&app).b("insetLinked")); + app.run("text.select", json!({"story": other_even_story, "anchor": 0, "focus": 0})).unwrap(); + assert!(seeded(&app).b("insetLinked")); + // A story threaded on into the uneven frame: a caret placed in the first frame changes only + // that frame, and a caret with no frame changes every frame of the story. + let (first, story) = frame(&mut app, [300, 300, 500, 500], json!(6)); + let (last, _) = frame(&mut app, [300, 520, 500, 700], json!([1, 2, 3, 4])); + app.run("text.thread", json!({"from": first.0, "to": last.0})).unwrap(); + app.run("text.placeCaret", json!({"frame": first.0, "point": [310, 310]})).unwrap(); + assert!(seeded(&app).b("insetLinked")); + app.run("text.select", json!({"story": story, "anchor": 0, "focus": 0})).unwrap(); + assert!(!seeded(&app).b("insetLinked")); +} + #[test] fn toc_dialog_adds_a_style_and_ok_makes_the_table_of_contents() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); From 5e60c4d8fe56a8265123bac2eef45aec161b9c0b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 08:54:29 -0800 Subject: [PATCH 1027/1349] Compose: vertical justification stays finite with an extreme grid increment A grid increment so small that the room holds more steps than an f64 can count made the grid step count infinite, and Bottom, Center and Justify then moved the grid-aligned lines to an infinite baseline. Such an increment now leaves the lines placed as they are without a grid. A Center step so large that doubling it overflows no longer turns a zero step count into a NaN shift; the lines stay where they are. --- crates/compose/src/lib.rs | 6 +++++- crates/compose/src/tests.rs | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index f43caad84..84da4a148 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -5604,6 +5604,9 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de }); let shift = match step { None => shifts(most_room(space)), + // A step so small that the room holds more steps than an f64 can count: the lines take + // the room as they do without a grid, and stay within one step of a grid line. + Some(inc) if !(space / inc).is_finite() => shifts(most_room(space)), Some(inc) => { // The room one grid step takes: Center moves the lines by half the room. let unit = if center { 2.0 * inc } else { inc }; @@ -5615,7 +5618,8 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de if steps > 0.0 && !fits(&shifts(steps * unit)) { steps -= 1.0; } - shifts(steps * unit) + // With no step taken the lines stay put, even when Center's doubled step overflows. + shifts(if steps > 0.0 { steps * unit } else { 0.0 }) } }; let before: Vec = idx.iter().map(|&i| ft.lines[i].baseline).collect(); diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 0f7b54da2..aca4ab07c 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -2435,6 +2435,43 @@ fn vertical_justification_keeps_grid_aligned_lines_on_the_grid() { assert!((free[2] - area.y1).abs() < 1e-6, "Bottom without the grid: {free:?}"); } +/// A grid increment too small for the room to be counted in steps, or too large to double, leaves +/// a grid-aligned line at a finite place inside the text area with Bottom, Center and Justify. +#[test] +fn vertical_justification_with_an_extreme_grid_increment_stays_finite() { + use designcraft_doc::GridAlign; + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify, Top}; + // The grid starts at the line's natural baseline, so the line sits on it before it moves. + let (natural, grid) = grid_doc("One", ParaAttrs { grid_align: Some(GridAlign::None), ..Default::default() }, |_, _| {}); + let natural = natural[0].baseline; + let start = natural - grid.0; + let compose_with = |mode: VerticalJustification, inc: f64| { + let mut area = Rect::ZERO; + let (lines, _) = grid_doc("One", ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }, |d, sid| { + let spec = frame_specs(d, sid).remove(0); + area = spec.area; + let opts = &mut d.item_mut(spec.id).unwrap().text_frame_mut().unwrap().options; + opts.baseline_grid = Some(designcraft_doc::FrameBaselineGrid::new(start, inc)); + opts.vertical_justification = mode; + }); + (area, lines[0].baseline) + }; + for inc in [1e-310, 1e308] { + let (_, top) = compose_with(Top, inc); + assert!((top - natural).abs() < 1e-6, "Top with increment {inc:e}: baseline {top}, natural {natural}"); + for mode in [Bottom, Center, Justify] { + let (area, b) = compose_with(mode, inc); + assert!(b.is_finite() && b >= top - 1e-6 && b <= area.y1 + 1e-6, "{mode:?} with increment {inc:e}: baseline {b}, text area {area:?}"); + } + } + // A step far smaller than the room: Bottom takes the room as it does without a grid. + let (area, b) = compose_with(Bottom, 1e-310); + assert!((b - area.y1).abs() < 1e-6, "Bottom with a tiny increment: baseline {b}, text area {area:?}"); + // A step far larger than the room: the line does not move. + let (_, b) = compose_with(Center, 1e308); + assert!((b - natural).abs() < 1e-6, "Center with a huge increment: baseline {b}, natural {natural}"); +} + /// A corner radius leaves a Cap Height first line where it sits in a rectangular frame, with Top /// and with Center: a line's band above the text area isn't held to the frame's outline (#1999). /// Center puts the last baseline halfway between where Top sets it and the bottom inset, also in From f0f609a3ba9c1e5b8ed14dacf634e96500036e7f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 08:55:00 -0800 Subject: [PATCH 1028/1349] Canvas: a scaled object's hardened shadow or glow stays in its damage The spread of a drop shadow or outer glow is stroked through the item's transform, so on a scaled item it reaches that much farther. Damage now grows the effect outset by the item's largest scale factor, and the multithreaded renderer crops the effect's offscreen image to the scaled reach, so the outer part of the glow is no longer cut off. --- crates/render/src/damage.rs | 42 +++++++++++++++-------- crates/render/src/fx.rs | 68 ++++++++++++++++++++++++++++++++++--- 2 files changed, 92 insertions(+), 18 deletions(-) diff --git a/crates/render/src/damage.rs b/crates/render/src/damage.rs index bacd3864c..aa1780014 100644 --- a/crates/render/src/damage.rs +++ b/crates/render/src/damage.rs @@ -11,6 +11,8 @@ use std::sync::Arc; use designcraft_doc::{Document, Item, ItemId, SpreadRef, Story, StoryId}; use designcraft_geom::Rect; +use crate::fx::max_scale; + /// Changed regions in spread coordinates, or `None` when the whole view must be repainted. pub fn damage(old: &Document, new: &Document) -> Option> { damage_with(old, new, None) @@ -167,23 +169,18 @@ fn item_area(it: &Item) -> Option { if !ok { return None; } - // The stroke is drawn through the item's transform. The item's own drop shadow and outer glow - // reach `fx::outset` past what it paints; its inner effects and feathers stay inside the shape. - let stroke = it.stroke.extent().max(0.0) * max_scale(it.xf)?; - let pad = stroke + 2.0 + if it.is_text_frame() { 24.0 } else { 0.0 } + crate::fx::outset(it); + // The stroke and the effects' spread are drawn through the item's transform. The item's own + // drop shadow and outer glow reach `fx::outset_scaled` past what it paints; its inner effects + // and feathers stay inside the shape. + let scale = max_scale(it.xf)?; + let stroke = it.stroke.extent().max(0.0) * scale; + let pad = stroke + 2.0 + if it.is_text_frame() { 24.0 } else { 0.0 } + crate::fx::outset_scaled(it, scale); + if !pad.is_finite() { + return None; + } Some(painted_bounds(it)?.inflate(pad, pad)) } -/// The largest factor `m` stretches a length by (its linear part's largest singular value), or -/// None when that is not finite. -fn max_scale(m: designcraft_geom::Affine) -> Option { - let [a, b, c, d, _, _] = m.as_coeffs(); - let s = a * a + b * b + c * c + d * d; - let det = a * d - b * c; - let v = ((s + (s * s - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt(); - v.is_finite().then_some(v) -} - /// An item's bounds, grown to its text: text is composed in the box around the frame's path in /// the frame's own coordinates, which a sheared then rotated frame turns past its path's bounds. /// Its children's bounds include their strokes. None when a child's transform is not finite. @@ -427,6 +424,23 @@ mod tests { let changed = changed_pixels_in_damage(&old, &d); assert!(changed.iter().any(|p| !Rect::new(98.0, 98.0, 312.0, 242.0).contains(*p)), "glow {glow}: the effect paints outside the object"); } + // A hardened glow on a scaled object: its growth is stroked through the transform, so it + // reaches three times as far on the spread as the glow's size says. + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let lid = d.default_layer(); + let id = ItemId(d.alloc()); + let mut it = Item::new(id, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(50.0, 50.0, 90.0, 90.0))); + it.xf = designcraft_geom::Affine::scale(3.0); + it.fill = designcraft_doc::Fill::swatch(designcraft_color::swatch::BLACK); + let g = &mut it.effects.outer_glow; + (g.on, g.color, g.opacity, g.size, g.spread) = (true, designcraft_color::swatch::BLACK.into(), 1.0, 20.0, 100.0); + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let old = d.clone(); + let it = d.item_mut(id).unwrap(); + it.xf = designcraft_geom::Affine::translate((60.0, 40.0)) * it.xf; + // The square covers 150..270 before the move; its glow reaches 60 pt past that. + let changed = changed_pixels_in_damage(&old, &d); + assert!(changed.iter().any(|p| p.x < 110.0), "the hard glow grows with the object's scale"); // An effect on an object inside a group is drawn through the group's transform: unbounded. let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); let lid = d.default_layer(); diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index 7c7c91fe1..26a87dacd 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -35,17 +35,37 @@ pub(crate) fn offset(angle: f64, distance: f64) -> Vec2 { /// How far (points) the effects of `it` reach outside its geometry. pub(crate) fn outset(it: &Item) -> f64 { + outset_scaled(it, 1.0) +} + +/// [`outset`] for an item whose transform stretches lengths by up to `scale`: the blur and the +/// shadow's distance are spread lengths, but the spread's growth is stroked through the item's +/// transform and grows with it. +pub(crate) fn outset_scaled(it: &Item, scale: f64) -> f64 { let e = &it.effects; + let extra = |size: f64, pct: f64| split(size, pct).1 * (scale - 1.0).max(0.0); let mut o: f64 = 0.0; if e.drop_shadow.on { - o = o.max(bound(e.drop_shadow.distance).abs() + bound(e.drop_shadow.size).abs() * 1.6 + 1.0); + let s = &e.drop_shadow; + o = o.max(bound(s.distance).abs() + bound(s.size).abs() * 1.6 + 1.0 + extra(s.size, s.spread)); } if e.outer_glow.on { - o = o.max(bound(e.outer_glow.size).abs() * 1.6 + 1.0); + let g = &e.outer_glow; + o = o.max(bound(g.size).abs() * 1.6 + 1.0 + extra(g.size, g.spread)); } o } +/// The largest factor `m` stretches a length by (its linear part's largest singular value), or +/// None when that is not finite. +pub(crate) fn max_scale(m: Affine) -> Option { + let [a, b, c, d, _, _] = m.as_coeffs(); + let s = a * a + b * b + c * c + d * d; + let det = a * d - b * c; + let v = ((s + (s * s - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt(); + v.is_finite().then_some(v) +} + /// (blur σ, growth) in points for an effect `size` with `pct` percent hardened. fn split(size: f64, pct: f64) -> (f64, f64) { let size = bound(size).max(0.0); @@ -104,7 +124,9 @@ impl Renderer { pub(crate) fn draw_item_fx(&mut self, ctx: &mut RenderContext, f: &Frame, it: &Item, bp: &BezPath, xf: Affine, page: ShownOn) { let doc = f.doc; let e = &it.effects; - let sw = if it.stroke.is_none() { 0.0 } else { it.stroke.extent() }; + // The stroke and the effects' growth are drawn through `xf`, which stretches them. + let scale = max_scale(xf).unwrap_or(1.0); + let sw = if it.stroke.is_none() { 0.0 } else { it.stroke.extent() * scale }; // Spread-space reach of what the object paints. let reach = xf.transform_rect_bbox(bp.bounding_box()).inflate(sw + 1.0, sw + 1.0); // The silhouette is the shape when the object paints its area (fill / image); text frames @@ -125,7 +147,7 @@ impl Renderer { let filter = shadow(sigma, color_of(&c, opacity.clamp(0.0, 1.0))); // The offset moves the geometry, not the filter: vello drops layer content that lies // entirely outside the viewport before filtering. - let r = (reach + off).inflate(grow, grow); + let r = (reach + off).inflate(grow * scale, grow * scale); // The effect's blend sees what's behind the object: a layer around the filtered one. let mix = crate::blend_mode(mode).mix; if mix != Mix::Normal { @@ -607,4 +629,42 @@ mod tests { // The transparent half shows the page: no shadow painted there. assert!(lum(150) > 700, "nothing over the transparent part: {}", lum(150)); } + + /// A hardened outer glow is stroked through the item's transform, so a scaled item's glow + /// grows with it. The multithreaded renderer draws the glow offscreen, cropped to its reach, + /// and that reach scales too. + #[test] + fn a_scaled_items_hard_glow_is_not_cropped() { + use designcraft_doc::build::NewDocument; + use designcraft_doc::{Document, SpreadRef}; + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let mut it = Item::new( + designcraft_doc::ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(50.0, 50.0, 90.0, 90.0)), + ); + it.xf = Affine::scale(3.0); + it.fill = designcraft_doc::Fill::swatch(designcraft_color::swatch::BLACK); + let g = &mut it.effects.outer_glow; + (g.on, g.color, g.opacity, g.size, g.spread) = (true, designcraft_color::swatch::BLACK.into(), 1.0, 20.0, 100.0); + // max_scale's own cases: a plain scale, a rotation and a shear. + assert_eq!(max_scale(it.xf), Some(3.0)); + assert!((max_scale(Affine::rotate(0.7)).unwrap() - 1.0).abs() < 1e-12); + assert!((max_scale(Affine::skew(1.0, 0.0)).unwrap() - (1.0 + 5f64.sqrt()) / 2.0).abs() < 1e-12); + assert_eq!(max_scale(Affine::scale(f64::INFINITY)), None); + // The 20 pt growth is 60 pt on the spread: the glow covers 90..330. + assert_eq!(outset_scaled(&it, 3.0), outset(&it) + 40.0); + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let cache = crate::Cache::new(); + for threads in [0, 2] { + let mut r = Renderer::new(); + r.threads = threads; + let page = r.render_page(&d, &cache, 0, 1.0, false, &crate::RenderOptions::default()).unwrap(); + let p = page.pixel(100, 210); + let lum = u32::from(p[0]) + u32::from(p[1]) + u32::from(p[2]); + assert!(lum < 200, "{threads} threads: the glow 50 pt left of the scaled square is drawn, luminance {lum}"); + } + } } From 49792c9ad5d25d499b5c34f63a64294f3ade8f28 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 09:04:11 -0800 Subject: [PATCH 1029/1349] Text wrap: look up Alpha Channel outlines by binary search The document keeps its outlines sorted by image and threshold, and the lookup uses a binary search. The data merge test now checks that the merged document has the image's outline, and that a bounding box wrap leaves the same caption overset. --- crates/doc/src/lib.rs | 6 +++-- crates/engine/src/cmd/alpha_wrap.rs | 30 ++++++++++++++++++++++++ crates/engine/src/cmd/datamerge/tests.rs | 24 +++++++++++++++---- 3 files changed, 54 insertions(+), 6 deletions(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 5e18186da..f4c8a25b6 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -803,7 +803,8 @@ pub struct Document { pub sections: Vec
, #[serde(default)] pub assets: BTreeMap>, - /// Alpha Channel contour outlines of placed images (see [`AlphaOutline`]). Not saved. + /// Alpha Channel contour outlines of placed images (see [`AlphaOutline`]), sorted by asset + /// and then threshold, at most one for each pair. Not saved. #[serde(skip)] pub alpha_outlines: Vec>, /// Hyperlinks (Window → Interactive → Hyperlinks). @@ -1118,7 +1119,8 @@ impl Document { /// The Alpha Channel outline of `asset` at `threshold`, once the engine has traced it. pub fn alpha_outline(&self, asset: AssetId, threshold: u8) -> Option<&AlphaOutline> { - self.alpha_outlines.iter().map(|o| &**o).find(|o| o.asset == asset && o.threshold == threshold) + let i = self.alpha_outlines.binary_search_by_key(&(asset, threshold), |o| (o.asset, o.threshold)).ok()?; + self.alpha_outlines.get(i).map(|o| &**o) } pub fn layer(&self, id: LayerId) -> Option<&Layer> { diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs index 86b864a61..ea9801f79 100644 --- a/crates/engine/src/cmd/alpha_wrap.rs +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -49,6 +49,7 @@ pub(crate) fn sync(doc: &mut Document) { let assets = &doc.assets; doc.alpha_outlines.retain(|o| wanted.contains(&(o.asset, o.threshold)) && assets.get(&o.asset).is_some_and(|a| o.traced_from(&a.data))); let traced: BTreeSet<(AssetId, u8)> = doc.alpha_outlines.iter().map(|o| (o.asset, o.threshold)).collect(); + let kept = doc.alpha_outlines.len(); for (asset, threshold) in wanted { if traced.contains(&(asset, threshold)) { continue; @@ -59,6 +60,10 @@ pub(crate) fn sync(doc: &mut Document) { let o = trace(&a.data, asset, threshold).unwrap_or_else(|| no_outline(&a.data, asset, threshold)); doc.alpha_outlines.push(Arc::new(o)); } + // `Document::alpha_outline` finds an outline by binary search. + if doc.alpha_outlines.len() > kept { + doc.alpha_outlines.sort_by_key(|o| (o.asset, o.threshold)); + } } /// The empty outline standing for an image `trace` found none in: zero-size, which composition @@ -443,6 +448,31 @@ mod tests { assert_eq!((b.x0, b.x1), (24.0, 40.0), "the new image's outline"); } + /// An outline traced after others is still found: a threshold lower than a kept outline's + /// is traced later and must not hide either outline from the lookup. + #[test] + fn outlines_traced_later_are_found_by_image_and_threshold() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let data = png(|x, _| (16..48).contains(&x)); + let image = s + .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": 100, "y": 100, "width": 128})) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("object.textWrap", &json!({"ids": [image], "content": true, "mode": "contour", "contour": "alphaChannel", "threshold": 200})) + .unwrap(); + s.execute("object.textWrap", &json!({"ids": [image], "mode": "contour", "contour": "alphaChannel"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.alpha_outlines.len(), 2, "one outline for each threshold"); + let Some(g) = d.item(designcraft_doc::ItemId(image)).and_then(|it| it.graphic()) else { panic!("a graphic") }; + for threshold in [designcraft_doc::DEFAULT_ALPHA_THRESHOLD, 200] { + let o = d.alpha_outline(g.asset, threshold); + assert!(o.is_some_and(|o| o.threshold == threshold), "the outline at {threshold} is found"); + } + assert!(d.alpha_outline(g.asset, 100).is_none(), "no outline at a threshold nothing uses"); + } + /// A wrap with the default threshold saves as it did before thresholds were stored; another /// threshold is saved. #[test] diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index 055f7e5d6..963cb4fd7 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -1339,10 +1339,22 @@ fn a_previewed_image_gets_its_alpha_channel_outline() { } /// The overset count data merge reports is composed with the merged images' Alpha Channel -/// outlines: a caption over the image's transparent part is set, not counted as overset. +/// outlines: a caption over the image's transparent part is set, not counted as overset. With a +/// bounding box wrap the same caption is overset, so the count depends on the outline. #[test] fn a_merge_counts_overset_text_with_the_merged_images_outlines() { - let dir = scratch("alpha-merge"); + let (r, outlines) = merge_with_wrap("alpha-merge", json!({"mode": "contour", "contour": "alphaChannel", "offset": 0})); + assert_eq!(r["oversetStories"], 0, "the caption sits beside the image's visible pixels: {r}"); + assert_eq!(outlines, 1, "the merged document has the image's outline"); + let (r, _) = merge_with_wrap("alpha-merge-box", json!({"mode": "boundingBox", "offset": 0})); + assert_eq!(r["oversetStories"], 1, "the image's frame covers the caption: {r}"); +} + +/// Merges one record whose image is visible only in its left quarter into a graphic placeholder +/// with the text wrap `wrap`, beside a caption over the image's transparent part. Returns the +/// merge's answer and the number of nonempty Alpha Channel outlines in the merged document. +fn merge_with_wrap(name: &str, wrap: Value) -> (Value, usize) { + let dir = scratch(name); // Visible only in the left quarter. let mut pixels = vec![0u8; 64 * 64 * 4]; for y in 0..64 { @@ -1358,11 +1370,15 @@ fn a_merge_counts_overset_text_with_the_merged_images_outlines() { let frame = exec(&mut s, "frame.create", json!({"rect": [100.0, 100.0, 300.0, 300.0], "content": "graphic"})); exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "role": "image", "item": frame["id"]})); exec(&mut s, "data.options", json!({"fitting": "fitContentToFrame"})); - exec(&mut s, "object.textWrap", json!({"ids": [frame["id"]], "mode": "contour", "contour": "alphaChannel", "offset": 0})); + let mut params = wrap; + params["ids"] = json!([frame["id"]]); + exec(&mut s, "object.textWrap", params); text_frame(&mut s, [220.0, 180.0, 290.0, 220.0], "Hi", None); let r = exec(&mut s, "data.merge", json!({})); - assert_eq!(r["oversetStories"], 0, "the caption sits beside the image's visible pixels: {r}"); + let doc = &s.documents()[s.active_index().unwrap()].doc; + let outlines = doc.alpha_outlines.iter().filter(|o| o.width > 0 && !o.outer.subpaths.is_empty()).count(); let _ = std::fs::remove_dir_all(&dir); + (r, outlines) } /// The cell texts of the first table in the active document's first story that has one. From 58cf0ba28afa3f6c8df55ed148bd6f5fee706d17 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 09:08:51 -0800 Subject: [PATCH 1030/1349] Place: WebP EXIF stops at the declared RIFF end The RIFF size counts the bytes after its own field, so the container ends at offset 8 plus the size, not 12. An EXIF chunk that ran up to four bytes past the declared container was read when trailing bytes followed it. A new test covers an exact size with and without trailing bytes, a size declared four bytes short, and a file cut inside the EXIF chunk. --- crates/images/src/resolution.rs | 3 ++- crates/images/src/tests.rs | 34 +++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/images/src/resolution.rs b/crates/images/src/resolution.rs index ea0a55eaa..3b04d8e73 100644 --- a/crates/images/src/resolution.rs +++ b/crates/images/src/resolution.rs @@ -203,8 +203,9 @@ fn png_resolution(bytes: &[u8]) -> Option<(f64, f64)> { /// A WebP EXIF chunk carries a TIFF header: reuse the TIFF resolution tags. fn webp_resolution(bytes: &[u8]) -> Option<(f64, f64)> { + // The RIFF size counts the bytes after the size field itself (offset 8). let riff = u32::from_le_bytes(bytes.get(4..8)?.try_into().ok()?) as usize; - let end = 12usize.checked_add(riff)?.min(bytes.len()); + let end = 8usize.checked_add(riff)?.min(bytes.len()); let mut pos = 12; loop { let kind = bytes.get(pos..pos + 4)?; diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index 1803b310a..d7d46e4a4 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -676,6 +676,40 @@ fn webp_exif_after_many_frames_is_read() { assert_eq!(raster_resolution(&webp), Some((300.0, 300.0))); } +/// The RIFF size counts the bytes after its own field (offset 8): an EXIF chunk that runs past +/// the declared container is not read, even when trailing bytes follow the container. +#[test] +fn webp_exif_past_the_declared_riff_end_is_not_read() { + let mut body = b"WEBP".to_vec(); + body.extend_from_slice(b"VP8X"); + body.extend_from_slice(&10u32.to_le_bytes()); + body.extend_from_slice(&[0; 10]); + let exif = tiff_bytes((300, 1), (300, 1), Some(2)); + body.extend_from_slice(b"EXIF"); + body.extend_from_slice(&(exif.len() as u32).to_le_bytes()); + body.extend_from_slice(&exif); + if exif.len() % 2 == 1 { + body.push(0); + } + let riff = |size: usize, trailing: usize| { + let mut webp = b"RIFF".to_vec(); + webp.extend_from_slice(&(size as u32).to_le_bytes()); + webp.extend_from_slice(&body); + webp.extend_from_slice(&vec![0xAA; trailing]); + webp + }; + // The exact size, with or without trailing data, reads the chunk. + assert_eq!(raster_resolution(&riff(body.len(), 0)), Some((300.0, 300.0))); + assert_eq!(raster_resolution(&riff(body.len(), 4)), Some((300.0, 300.0))); + // A size declared 4 bytes short ends the container inside the EXIF chunk. + assert_eq!(raster_resolution(&riff(body.len() - 4, 4)), None); + assert_eq!(raster_resolution(&riff(body.len() - 4, 0)), None); + // A file cut inside the EXIF chunk is not read either. + let mut cut = riff(body.len(), 0); + cut.truncate(cut.len() - 6); + assert_eq!(raster_resolution(&cut), None); +} + /// A real encoder-written BMP with the header pixels-per-meter patched (compression and image /// size stay zero, as the encoder writes them). fn bmp_with_ppm(ppm: i32) -> Vec { From 970e98fcc53c09552d2907a451df4eb6b192885c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 09:12:05 -0800 Subject: [PATCH 1031/1349] Compose: say where reuse resumes after an edit that moves lines An edit that moves lines into other frames composes on until a paragraph starts in the same frame and place as before, or to the story's end, as an_edit_that_moves_lines_composes_up_to_the_next_frame_the_text_starts_in shows. The ROADMAP line no longer cites an issue about selection lag. --- ROADMAP.md | 2 +- docs/architecture.md | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 87daec8b7..8bc497cbf 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -387,7 +387,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log -- **2026-11-12** · An edit of a long threaded story composes the paragraphs it can change and copies the other lines from the composition before the edit; every typed character composed the whole story. In a 240-paragraph story a typed character composes 3 paragraphs (240 before). An edit that moves lines into other frames is composed to the story's end, and stories with footnotes, tables, anchored objects, balanced columns or keep options that move lines are composed whole (#2298). No readiness percentage change. +- **2026-11-12** · An edit of a long threaded story composes the paragraphs it can change and copies the other lines from the composition before the edit; every typed character composed the whole story. In a 240-paragraph story a typed character composes 3 paragraphs (240 before). An edit that moves lines into other frames composes on until a paragraph starts in the same frame and place as before, or to the story's end, and stories with footnotes, tables, anchored objects, balanced columns or keep options that move lines are composed whole. No readiness percentage change. - **2026-11-04** · Striped strokes retain out-and-back cubic segments whose second control point is away from the coincident endpoints and first control point. A geometry regression checks the offset extent and both stripe bands. No readiness percentage change. - **2026-11-04** · Esperanto is a text language (Character › Language, `type.char {language: "Esperanto"}`, IDML `$ID/Esperanto`): tag `eo`, English-style quotes; not hyphenated yet (#1201). No readiness percentage change. diff --git a/docs/architecture.md b/docs/architecture.md index 4fede8ca4..29e9757ad 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -74,7 +74,8 @@ revision; stories compose in parallel (rayon) on native targets. After an edit o or formatting, composing starts at the paragraph before the first changed one and stops at the first unchanged paragraph it reaches in the state it had before the edit; the lines above and below are copied from the composition before the edit (`crates/compose/src/reuse.rs`). An edit -that moves lines into other frames is composed to the story's end. A story is composed whole +that moves lines into other frames composes on until a paragraph starts in the same frame and +place as before, or to the story's end. A story is composed whole when it has footnotes, endnotes, tables, anchored objects, named lists, tracked deletions, balanced columns, vertical justification other than Top, column rules, type on a path, spanning or split paragraphs, or paragraph borders or shading, and when its layout goes back over a From 2c0121aebb098ccaab6473c8d8eddcc84f81dd5d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 09:14:42 -0800 Subject: [PATCH 1032/1349] Text: Text Frame Options from the Type tool stay with their document The dialog stores the frames it took from the caret or selection with the document state they came from. OK and Preview are refused when another document became active after the dialog opened, or when Revert replaced the document, since the stored frame ids can name a different frame there. --- crates/ui-egui/src/dialogs.rs | 19 +++++++++-- crates/ui-egui/src/dialogs/tests.rs | 53 +++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index f2689c927..b6141a75f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1102,6 +1102,9 @@ fn seed_text_frame_options(app: &DesignApp, d: &mut Dialog) { // text into another frame does not change which frames the options apply to. if let Some(ids) = typing_frame_ids(app) { d.fields.insert("_targets".into(), ids); + // The document state those frames are in: another document, or the document after + // Revert, can reuse their ids. + d.fields.insert("_targetsDoc".into(), json!(app.session.active().map(|doc| doc.identity_epoch))); } d.fields.insert("_shown".into(), shown); } @@ -1605,14 +1608,24 @@ fn text_frame_params(app: &DesignApp, d: &Dialog) -> Result, json!(d.m("paragraphSpacingLimit").filter(|v| *v >= 0.0).ok_or_else(|| bad("the paragraph spacing limit is not a measure"))?), ); } - // Typing in a frame: the options apply to the frame that showed the caret, or to every frame - // that held part of the selected text, when the dialog opened. - if let Some(ids) = d.fields.get("_targets").cloned().or_else(|| typing_frame_ids(app)) { + if let Some(ids) = text_frame_targets(app, d).map_err(bad)? { p.insert("ids".into(), ids); } Ok(p) } +/// Typing in a frame: the frame that showed the caret, or every frame that held part of the +/// selected text, when the dialog opened. Those ids are refused once another document is active, +/// or once Revert has replaced the document. +fn text_frame_targets(app: &DesignApp, d: &Dialog) -> Result, &'static str> { + let Some(ids) = d.fields.get("_targets").cloned() else { return Ok(typing_frame_ids(app)) }; + let active = app.session.active().map(|doc| doc.identity_epoch); + if d.fields.get("_targetsDoc").and_then(Value::as_u64) != active { + return Err("the document the dialog opened on is no longer the active one"); + } + Ok(Some(ids)) +} + /// File › Document Setup, filled from the document. /// The active document's ruler unit (picas without a document). fn doc_unit(app: &DesignApp) -> Unit { diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 272165b08..1d2bcd4a1 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1389,6 +1389,59 @@ fn text_frame_options_set_columns_baseline_and_wrap_as_indesign_does() { assert_eq!((opts(&app).columns_kind, opts(&app).column_width), (designcraft_doc::ColumnsKind::FixedNumber, 120.0)); } +/// The frames Text Frame Options took while typing belong to the document it opened on: when +/// another document becomes active before OK, OK changes nothing there. +#[test] +fn text_frame_options_from_the_type_tool_stay_with_their_document() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let make = |app: &mut crate::DesignApp| { + app.run("file.new", json!({})).unwrap(); + let r = app.run("frame.create", json!({"rect": [36, 36, 300, 300], "content": "text", "text": "Hello"})).unwrap(); + let (id, story) = (r["id"].as_u64().unwrap(), r["story"].as_u64().unwrap()); + app.run("text.select", json!({"story": story, "anchor": 2})).unwrap(); + id + }; + let a = make(&mut app); + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(&app, &mut d); + assert_eq!(d.fields.get("_targets"), Some(&json!([a]))); + d.fields.insert("columns".into(), json!(3)); + // A second document, with a caret in a frame that has the same id, becomes active. + let b = make(&mut app); + assert_eq!(a, b); + app.ui.dialog = Some(d); + let err = confirm(&mut app).unwrap_err().to_string(); + assert!(err.contains("no longer the active one"), "{err}"); + let columns = app.session.active().unwrap().doc.item(designcraft_doc::ItemId(b)).and_then(|i| i.text_frame().map(|t| t.options.columns)); + assert_eq!(columns, Some(1), "the other document's frame is unchanged"); +} + +/// Revert replaces the document while Text Frame Options taken while typing stay open: OK is +/// refused, since the saved frame ids can name another frame in the reverted document. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn text_frame_options_from_the_type_tool_are_refused_after_revert() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let dir = tempfile::tempdir().unwrap(); + app.run("file.saveAs", json!({"path": dir.path().join("revert.designcraft")})).unwrap(); + let a = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": "Unsaved"})).unwrap(); + app.run("text.select", json!({"story": a["story"], "anchor": 1})).unwrap(); + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(&app, &mut d); + d.fields.insert("columns".into(), json!(3)); + app.run("file.revert", json!({})).unwrap(); + let b = app.run("frame.create", json!({"rect": [36, 200, 300, 300], "content": "text", "text": "After"})).unwrap(); + assert_eq!(a["id"], b["id"], "the reverted document gives a new frame the same id"); + app.ui.dialog = Some(d); + let err = confirm(&mut app).unwrap_err().to_string(); + assert!(err.contains("no longer the active one"), "{err}"); + assert!(app.ui.dialog.is_some(), "the dialog stays open"); + let b = designcraft_doc::ItemId(b["id"].as_u64().unwrap()); + let columns = app.session.active().unwrap().doc.item(b).and_then(|i| i.text_frame().map(|t| t.options.columns)); + assert_eq!(columns, Some(1), "the new frame is unchanged"); +} + #[test] fn baseline_grid_increment_error_explains_the_positive_measure_rule() { let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); From 8d39765e936f388bc7fa8675ca4fe598acab5088 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 09:15:31 -0800 Subject: [PATCH 1033/1349] Layers: use the anchored copies object copying now makes Copying a frame now gives the objects anchored in its story copy ids of their own and copies of the stories of anchored text frames. Duplicate Layer renumbered them a second time, so live captions kept pointing at the originals and shared stories were copied again. It now records the ids of those copies instead. Copying a frame also renumbers objects anchored in endnotes inside table cells and footnotes, which kept their original ids before. --- crates/engine/src/cmd/layout/layers.rs | 113 ++++++++++++------------- crates/engine/src/cmd/object.rs | 19 +++-- 2 files changed, 63 insertions(+), 69 deletions(-) diff --git a/crates/engine/src/cmd/layout/layers.rs b/crates/engine/src/cmd/layout/layers.rs index b2a2ec8ac..f93a3c09c 100644 --- a/crates/engine/src/cmd/layout/layers.rs +++ b/crates/engine/src/cmd/layout/layers.rs @@ -1,7 +1,7 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; -use designcraft_doc::{Content, Guide, Hyperlink, HyperlinkSource, Item, ItemId, SpreadRef, Story, StoryId}; +use designcraft_doc::{Guide, Hyperlink, HyperlinkSource, Item, ItemId, SpreadRef, Story, StoryId}; use super::{LAYER_COLORS, Layer, LayerId, Result, Session, Value, bad, json, ok}; @@ -91,15 +91,12 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { copies.push((r, copy)); } } - // A story copy holds the same anchored objects as the original: they get ids of their own, and the stories of - // anchored text frames get copies in turn. The story copies are taken in story order. - let mut pending: Vec = stories.values().copied().collect(); - pending.sort_unstable(); - pending.reverse(); - while let Some(new) = pending.pop() { - let Some(mut st) = d.story(new).cloned() else { continue }; - renumber_anchored(d, &mut st, new_id, &mut stories, &mut ids, &mut pending); - d.stories.insert(new, Arc::new(st)); + // The story copies hold copies of the original's anchored objects with ids of their own (and copies of the + // stories of anchored text frames): record each copy's id against the original's. + for (old, new) in &stories { + if let (Some(orig), Some(copy)) = (src.story(*old), d.story(*new)) { + map_anchored(orig, copy, &mut ids); + } } // Every copy, anchored objects included, has its id before overrides are pointed at the copied parent items and // live captions at the copied objects. @@ -242,27 +239,21 @@ fn too_deep(it: &Item, d: &designcraft_doc::Document, seen: &mut std::collection false } -/// Give the items anchored in `st`, and in the stories of its table cells and notes, new ids from `d` (recorded in `ids`) -/// and layer `to`. An anchored text frame's story gets one copy, recorded in `stories`, that every copied frame of the -/// story shares; a new copy goes on `pending`, and its frame list is filled in afterwards. [`too_deep`] bounds the nesting. -fn renumber_anchored( - d: &mut designcraft_doc::Document, - st: &mut Story, - to: LayerId, - stories: &mut HashMap, - ids: &mut HashMap, - pending: &mut Vec, -) { - for o in &mut st.objects { - renumber_anchored_item(d, &mut Arc::make_mut(o).item, to, stories, ids, pending); +/// Run [`map_ids`] on the items anchored in story `orig` and in its copy `copy`, and in the stories of their table cells +/// and notes. [`too_deep`] bounds the nesting. +fn map_anchored(orig: &Story, copy: &Story, ids: &mut HashMap) { + for (o, c) in orig.objects.iter().zip(©.objects) { + map_ids(&o.item, &c.item, ids); } - for t in st.tables.values_mut() { - for c in &mut Arc::make_mut(t).cells { - renumber_anchored(d, &mut c.text, to, stories, ids, pending); + for (k, t) in &orig.tables { + if let Some(ct) = copy.tables.get(k) { + for (o, c) in t.cells.iter().zip(&ct.cells) { + map_anchored(&o.text, &c.text, ids); + } } } - for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { - renumber_anchored(d, &mut Arc::make_mut(n).text, to, stories, ids, pending); + for (o, c) in orig.notes.iter().chain(&orig.endnotes).zip(copy.notes.iter().chain(©.endnotes)) { + map_anchored(&o.text, &c.text, ids); } } @@ -343,39 +334,6 @@ fn remap_xrefs(st: &mut Story, map: &HashMap) { } } -/// [`renumber_anchored`] for one anchored item and its descendants. -fn renumber_anchored_item( - d: &mut designcraft_doc::Document, - it: &mut Item, - to: LayerId, - stories: &mut HashMap, - ids: &mut HashMap, - pending: &mut Vec, -) { - let id = ItemId(d.alloc()); - ids.insert(it.id, id); - it.id = id; - it.layer = to; - if let Content::Text(tf) = &mut it.content { - tf.story = match stories.get(&tf.story) { - Some(n) => *n, - None => { - let n = StoryId(d.alloc()); - let mut copy = d.story(tf.story).cloned().unwrap_or_else(|| Story::new(n)); - copy.id = n; - copy.frames.clear(); - d.stories.insert(n, Arc::new(copy)); - stories.insert(tf.story, n); - pending.push(n); - n - } - }; - } - for c in it.children_mut().into_iter().flatten() { - renumber_anchored_item(d, Arc::make_mut(c), to, stories, ids, pending); - } -} - /// Put `it` and its descendants on layer `to`, and point overrides at the copied parent items and live captions at the /// copied objects. A copy whose parent item was not copied is detached from it, so the original override stays the only /// one of that item. @@ -908,6 +866,39 @@ mod layer_tests { assert_eq!(redone, after); } + #[test] + fn duplicate_layer_gives_objects_anchored_in_endnotes_of_cells_their_own_ids() { + use designcraft_doc::AnchoredObject; + use std::sync::Arc; + + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let a = s.execute("frame.create", &json!({"rect": [450, 450, 474, 490]})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.caption", &json!({"ids": [a], "text": "{name}", "live": true})).unwrap(); + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Rows"})).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + // The caption's source moves into an endnote of a table cell and keeps its id. + let it = d.item(designcraft_doc::ItemId(a)).cloned().unwrap(); + Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id.0 != a); + let mut table = designcraft_doc::Table::new(d.alloc(), 1, 1, 0, 0, 40.0); + let cell = &mut table.cells[0].text; + cell.insert_endnote(cell.len(), "Endnote", Default::default()).unwrap(); + Arc::make_mut(&mut cell.endnotes[0]).text.insert_object(0, AnchoredObject::new(it, Default::default())); + d.story_mut(sid).unwrap().insert_table(0, table); + d.check().unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + d.check().unwrap(); + let anchored: Vec<_> = d.anchored_items().into_iter().map(|(_, i)| (i.id, i.layer.0)).collect(); + assert_eq!(anchored.len(), 2); + let copied = anchored.iter().find(|i| i.1 == copy).unwrap().0; + assert_ne!(copied.0, a, "the copy has an id of its own"); + let caption = on_layer(d, copy).iter().find_map(|i| i.live_caption.clone()).unwrap(); + assert_eq!(caption.source, copied, "the caption's copy follows the anchored object's copy"); + } + #[test] fn duplicate_layer_gives_copied_cell_anchors_ids_no_other_anchor_has() { use std::sync::Arc; diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 634c90a61..a6526e93b 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -1161,16 +1161,19 @@ fn renumber_in(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut } } -/// Fresh ids for the objects anchored in story copy `st`, its table cells, footnotes and endnotes (#1522). +/// Fresh ids for the objects anchored in story copy `st`, its table cells, footnotes and endnotes, at every depth +/// (#1522). fn renumber_anchored(dst: &mut Document, src: &Document, st: &mut Story, stories: &mut HashMap) { - let mut fresh = |t: &mut Story| { - for o in &mut t.objects { - renumber_in(dst, src, &mut Arc::make_mut(o).item, stories, false); + for o in &mut st.objects { + renumber_in(dst, src, &mut Arc::make_mut(o).item, stories, false); + } + for t in st.tables.values_mut() { + for c in &mut Arc::make_mut(t).cells { + renumber_anchored(dst, src, &mut c.text, stories); } - }; - st.for_each_text_mut(&mut fresh); - for n in &mut st.endnotes { - Arc::make_mut(n).text.for_each_text_mut(&mut fresh); + } + for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + renumber_anchored(dst, src, &mut Arc::make_mut(n).text, stories); } } From f7df4052d68bbd23a9ec6d957aba5a1f0d0aaab5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 09:23:07 -0800 Subject: [PATCH 1034/1349] Layers: count Duplicate Layer's nesting limit across anchored stories Copying an object recurses from its groups into the stories of anchored text frames and on into theirs. The limit on how deeply a layer's objects may nest now counts that depth in all, from the object on the spread, instead of starting again at each story. --- crates/engine/src/cmd/layout/layers.rs | 67 +++++++++++++++++++++----- 1 file changed, 54 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/layout/layers.rs b/crates/engine/src/cmd/layout/layers.rs index f93a3c09c..cd6e72ee2 100644 --- a/crates/engine/src/cmd/layout/layers.rs +++ b/crates/engine/src/cmd/layout/layers.rs @@ -68,7 +68,7 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { let id = LayerId(p.get("id").and_then(Value::as_u64).ok_or_else(|| bad(ID, "missing id"))?); let r = s.edit(|d, _| { let i = d.layers.iter().position(|l| l.id == id).ok_or_else(|| bad(ID, "no such layer"))?; - let mut seen = std::collections::HashSet::new(); + let mut seen = HashMap::new(); if d.spreads.iter().chain(&d.parents).flat_map(|sp| sp.items.iter()).any(|it| it.layer == id && too_deep(it, d, &mut seen)) { return Err(bad(ID, "the layer's objects are nested too deeply to copy")); } @@ -205,20 +205,22 @@ fn map_ids(orig: &Item, copy: &Item, ids: &mut HashMap) { } } -/// A layer whose groups, anchored objects, table cells and notes nest deeper than this within one story or object is -/// not duplicated. +/// A layer whose groups, anchored objects, table cells and notes nest deeper than this, counted from an object on a +/// spread through the stories its anchored text frames show, is not duplicated. const MAX_COPY_DEPTH: usize = 64; -/// Whether `it`, or a story its text frames reach directly or through anchored text frames, nests groups, anchored -/// objects, table cells and notes deeper than [`MAX_COPY_DEPTH`]. Stories in `seen` were checked already and are skipped. -fn too_deep(it: &Item, d: &designcraft_doc::Document, seen: &mut std::collections::HashSet) -> bool { - fn item(it: &Item, depth: usize, next: &mut Vec) -> bool { +/// Whether `it`, with the stories its text frames reach directly or through anchored text frames, nests groups, +/// anchored objects, table cells and notes deeper than [`MAX_COPY_DEPTH`] in all: a story counts from the depth of the +/// frame that shows it, as copying it recurses on from there. `seen` holds the deepest level each story was checked at; +/// a story reached again no deeper is skipped. +fn too_deep(it: &Item, d: &designcraft_doc::Document, seen: &mut HashMap) -> bool { + fn item(it: &Item, depth: usize, next: &mut Vec<(StoryId, usize)>) -> bool { if let Some(t) = it.text_frame() { - next.push(t.story); + next.push((t.story, depth)); } depth > MAX_COPY_DEPTH || it.children().iter().any(|c| item(c, depth + 1, next)) } - fn story(st: &Story, depth: usize, next: &mut Vec) -> bool { + fn story(st: &Story, depth: usize, next: &mut Vec<(StoryId, usize)>) -> bool { depth > MAX_COPY_DEPTH || st.objects.iter().any(|o| item(&o.item, depth + 1, next)) || st.tables.values().flat_map(|t| &t.cells).any(|c| story(&c.text, depth + 1, next)) @@ -228,10 +230,13 @@ fn too_deep(it: &Item, d: &designcraft_doc::Document, seen: &mut std::collection if item(it, 0, &mut next) { return true; } - while let Some(sid) = next.pop() { - if seen.insert(sid) - && let Some(st) = d.story(sid) - && story(st, 0, &mut next) + while let Some((sid, depth)) = next.pop() { + if seen.get(&sid).is_some_and(|&checked| checked >= depth) { + continue; + } + seen.insert(sid, depth); + if let Some(st) = d.story(sid) + && story(st, depth, &mut next) { return true; } @@ -1088,6 +1093,42 @@ mod layer_tests { assert_eq!(s.doc().unwrap().doc.layers, before, "nothing changes"); } + /// Two stories, each anchoring groups nested 40 deep, the innermost group of the first holding a text frame that + /// shows the second: within the limit in each story, past it in all. + #[test] + fn duplicate_layer_refuses_nesting_too_deep_across_stories() { + use designcraft_doc::{AnchoredObject, Content, Item, ItemId}; + use std::sync::Arc; + + fn nest(d: &mut designcraft_doc::Document, mut it: Item, levels: usize) -> Item { + for _ in 0..levels { + let mut group = it.clone(); + group.id = ItemId(d.alloc()); + group.content = Content::Group { items: vec![Arc::new(it)] }; + it = group; + } + it + } + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Top"})).unwrap()["id"].as_u64().unwrap(); + let g = s.execute("frame.create", &json!({"rect": [0, 0, 60, 30], "content": "text", "text": "Inner"})).unwrap()["id"].as_u64().unwrap(); + let h = s.execute("frame.create", &json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap(); + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let top = d.item(ItemId(f)).unwrap().text_frame().unwrap().story; + let (inner_frame, leaf) = (d.item(ItemId(g)).cloned().unwrap(), d.item(ItemId(h)).cloned().unwrap()); + let inner = inner_frame.text_frame().unwrap().story; + Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id.0 != g && i.id.0 != h); + let deep_leaf = nest(d, leaf, 40); + d.story_mut(inner).unwrap().insert_object(0, AnchoredObject::new(deep_leaf, Default::default())); + let deep_frame = nest(d, inner_frame, 40); + d.story_mut(top).unwrap().insert_object(0, AnchoredObject::new(deep_frame, Default::default())); + let before = s.doc().unwrap().doc.layers.clone(); + assert!(s.execute("layer.duplicate", &json!({"id": base})).is_err()); + assert_eq!(s.doc().unwrap().doc.layers, before, "nothing changes"); + } + #[test] fn duplicate_layer_detaches_overrides_of_parent_items_on_other_layers() { let mut s = crate::Session::new(); From a8656662e9ec091ee1e4ac4c7d85f10ebffab19b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 09:29:14 -0800 Subject: [PATCH 1035/1349] Compose: vertical justification looks up each wrap's anchored object once The object anchored at each story byte is indexed once per column, and each wrap's object is found once, not once for every line. --- crates/compose/src/lib.rs | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 9c38b29a5..4891b41a1 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -5691,14 +5691,20 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u }; let in_col = |k: u32| spanned || k == c; let justify = f.opts.vertical_justification == VerticalJustification::Justify; + // The object whose mark is at each story byte, placed on one of these lines (the first one + // listed). + let mut by_anchor = HashMap::new(); + for o in ft.objects.iter().filter(|o| ft.lines.get(o.line).is_some_and(|l| in_col(l.column))) { + if let Some(&a) = anchors.get(o.index) { + by_anchor.entry(a).or_insert(o); + } + } // An own-story anchored object whose anchor is on one of these lines and whose position // follows its line moves with the text: the index in `ft.lines` of its anchor's line, and how // much lower that line was when the wrap was taken (an earlier pass placed the object after // moving the lines). let moves_with_text = |e: &Exclusion| -> Option<(usize, f64)> { - let a = e.after?; - // The object whose mark is the anchor, placed on one of these lines. - let o = ft.objects.iter().find(|o| anchors.get(o.index) == Some(&a) && ft.lines.get(o.line).is_some_and(|l| in_col(l.column)))?; + let o = *by_anchor.get(&e.after?)?; let follows = match &o.object.position { designcraft_doc::AnchorPosition::Inline { .. } | designcraft_doc::AnchorPosition::AboveLine { .. } => true, // Kept within the column, it can stop at the column's edge instead of following. @@ -5709,6 +5715,8 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u let now = ft.lines.get(o.line).map_or(0.0, |l| l.baseline); follows.then(|| (o.line, e.anchor_baseline.map_or(0.0, |b| b - now))) }; + // Each wrap's object is looked up once, not for every line. + let moving: Vec> = f.exclusions.iter().map(moves_with_text).collect(); // Justify keeps the first row (its segments and a table on them) in place, so wraps under it // set no limit. let first = ft.lines.iter().find(|l| in_col(l.column)).map(|l| l.baseline); @@ -5734,8 +5742,7 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u let col = ft.columns.get(k as usize).copied().unwrap_or(f.area); let col = Rect { x0: col.x0.min(x0), x1: col.x1.max(x1), ..col }; let meets = |(a, b): (f64, f64)| a < x1 - EPS && b > x0 + EPS; - for e in f.exclusions.iter().filter(|e| e.wraps_line(start)) { - let anchor = moves_with_text(e); + for (e, &anchor) in f.exclusions.iter().zip(&moving).filter(|(e, _)| e.wraps_line(start)) { if anchor.is_some() && !justify { continue; } From b0f282f607e5cae22116cb85adb0c63bc155a282 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 09:40:38 -0800 Subject: [PATCH 1036/1349] Object styles: the dialog changes only the document it opened for New Object Style and Object Style Options record the document they open on, with the epoch that File > Revert changes. OK is refused, and the dialog stays open with the reason, when another document is active, the document was closed, or it was reverted. Apply Style to Selection applies the new style to the objects selected when the dialog opened that still exist, not to a selection made while it was open. --- crates/ui-egui/src/object_style_dialog.rs | 121 +++++++++++++++++++++- 1 file changed, 118 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/object_style_dialog.rs b/crates/ui-egui/src/object_style_dialog.rs index bdac19645..4200732a9 100644 --- a/crates/ui-egui/src/object_style_dialog.rs +++ b/crates/ui-egui/src/object_style_dialog.rs @@ -42,10 +42,26 @@ fn text_fields(app: &DesignApp, fields: &mut Value, paragraph: Option<&str>, nex } } +/// The active document as the dialog records it: its uid and the epoch that File › Revert +/// changes. +fn document_key(app: &DesignApp) -> Value { + app.session.active().map_or(Value::Null, |st| json!([st.uid, st.identity_epoch])) +} + +/// The document the dialog was opened on is still the active one and was not reverted since, so +/// OK never gives its settings to another document's style of the same name. +fn same_document(app: &DesignApp, d: &Dialog) -> Result<(), String> { + let key = document_key(app); + if !key.is_null() && d.fields.get("doc") == Some(&key) { Ok(()) } else { Err(format!("the active document changed after {} opened", title(d))) } +} + /// The dialog for a new style from the selected object (its fill, stroke, corners and effects, /// as InDesign's New Object Style), named "Object Style n". pub fn open_new(app: &mut DesignApp) { + let doc = document_key(app); let Some(st) = app.session.active() else { return }; + // Apply Style to Selection applies the style to the objects selected now. + let targets: Vec = st.selection.items.iter().map(|i| i.0).collect(); let it = st.selection.items.first().and_then(|i| st.doc.item(*i)).cloned(); let taken = |n: &str| st.doc.styles.object_style(n).is_some(); let name = (1..).map(|i| format!("Object Style {i}")).find(|n| !taken(n)).unwrap_or_default(); @@ -54,6 +70,8 @@ pub fn open_new(app: &mut DesignApp) { let frame = it.as_ref().and_then(|i| i.text_frame()).map(|t| t.options.clone()); let mut fields = json!({ "new": true, + "doc": doc, + "targets": targets, "name": name, "basedOn": designcraft_doc::NO_OBJECT_STYLE, "fill": it.as_ref().map(|i| i.fill.clone()).unwrap_or_default(), @@ -81,6 +99,7 @@ pub fn open_edit(app: &mut DesignApp, name: &str) -> Result<(), String> { } let mut fields = json!({ "new": false, + "doc": document_key(app), "orig": name, "name": name, "basedOn": os.based_on.as_deref().unwrap_or(designcraft_doc::NO_OBJECT_STYLE), @@ -171,6 +190,7 @@ fn general_json(o: &designcraft_doc::TextFrameOptions) -> Value { /// OK: the new style (applied to the selection when asked), or the edited one. pub fn confirm(app: &mut DesignApp, d: &Dialog) -> Result { + same_document(app, d)?; let name = d.s("name").trim().to_string(); if name.is_empty() { return Err(crate::i18n::tr(&app.ui.language, "Enter a style name.").to_string()); @@ -183,10 +203,21 @@ pub fn confirm(app: &mut DesignApp, d: &Dialog) -> Result { let r = app.run("style.object.create", Value::Object(p)).map_err(|e| e.to_string())?; let made = r["name"].as_str().unwrap_or(&name).to_string(); // The style exists now, so OK again mustn't make a second one: a refused apply (locked - // objects) goes to the status line and the dialog closes. + // objects) goes to the status line and the dialog closes. The style goes to the objects + // selected when the dialog opened that still exist, not to a selection made since. + let targets: Vec = app.session.active().map_or_else(Vec::new, |st| { + d.fields + .get("targets") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_u64) + .filter(|id| st.doc.item(designcraft_doc::ItemId(*id)).is_some()) + .collect() + }); if d.b("apply") - && app.session.active().is_some_and(|st| !st.selection.items.is_empty()) - && let Err(e) = app.run("style.object.apply", json!({"name": made})) + && !targets.is_empty() + && let Err(e) = app.run("style.object.apply", json!({"name": made, "ids": targets})) { app.status(e.to_string()); } @@ -771,4 +802,88 @@ mod tests { assert!(e.contains("already named"), "{e}"); assert!(app.ui.dialog.as_ref().is_some_and(|d| d.s("status") == e)); } + + /// Object Style Options and New Object Style act only on the document they opened for. With + /// another document active, after their document closed, or after it was reverted, OK keeps + /// the dialog open with the reason and changes no style. + #[test] + fn the_dialog_acts_only_on_the_document_it_opened_for() { + let name = designcraft_doc::BASIC_GRAPHICS_FRAME; + let weights = |app: &DesignApp| -> Vec { + app.session + .documents() + .iter() + .map(|st| st.doc.styles.object_style(name).and_then(|s| s.stroke.as_ref()).map_or(-1.0, |s| s.weight)) + .collect() + }; + let edit = |app: &mut DesignApp| { + open_edit(app, name).unwrap(); + if let Some(d) = app.ui.dialog.as_mut() { + set(d, &["stroke", "weight"], json!(9.0)); + } + }; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"title": "A"})).unwrap(); + app.run("file.new", json!({"title": "B"})).unwrap(); + app.session.set_active(0); + let before = weights(&app); + assert_eq!(before.len(), 2); + + // Options opened on A, OK with B active: B has a style of the same name. + edit(&mut app); + app.session.set_active(1); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("active document changed"), "{e}"); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.s("status") == e), "the dialog stays open with the reason"); + assert_eq!(weights(&app), before, "neither document's style changed"); + + // New Object Style opened on A makes nothing in B, and OK works once A is active again. + app.ui.dialog = None; + app.session.set_active(0); + open_new(&mut app); + app.session.set_active(1); + assert!(crate::dialogs::confirm(&mut app).is_err()); + assert!(app.session.documents().iter().all(|st| st.doc.styles.object_style("Object Style 1").is_none())); + app.session.set_active(0); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.session.documents()[0].doc.styles.object_style("Object Style 1").is_some()); + assert!(app.session.documents()[1].doc.styles.object_style("Object Style 1").is_none()); + + // Options opened on A, A closed: B is active and keeps its style. + edit(&mut app); + app.session.execute("file.close", &json!({"index": 0})).unwrap(); + assert!(crate::dialogs::confirm(&mut app).is_err()); + assert_eq!(weights(&app), vec![before[1]]); + app.ui.dialog = None; + + // Options opened on B, B reverted: the reverted document keeps its style. + #[cfg(not(target_arch = "wasm32"))] + { + let dir = tempfile::tempdir().unwrap(); + app.run("file.saveAs", json!({"path": dir.path().join("revert.designcraft")})).unwrap(); + app.run("frame.create", json!({"rect": [72, 72, 144, 144], "content": "graphic"})).unwrap(); + edit(&mut app); + app.run("file.revert", json!({})).unwrap(); + assert!(crate::dialogs::confirm(&mut app).is_err()); + assert_eq!(weights(&app), vec![before[1]]); + } + } + + /// Apply Style to Selection applies the new style to the objects selected when the dialog + /// opened, not to a selection made while it was open. + #[test] + fn apply_style_to_selection_uses_the_selection_the_dialog_opened_with() { + let (mut app, a) = app_with_frame(); + let b = app.run("frame.create", json!({"rect": [200, 72, 300, 172], "content": "graphic"})).unwrap()["id"].as_u64().unwrap(); + app.run("selection.set", json!({"ids": [a]})).unwrap(); + open_new(&mut app); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("name".into(), json!("Picked")); + } + app.run("selection.set", json!({"ids": [b]})).unwrap(); + crate::dialogs::confirm(&mut app).unwrap(); + let style = |id: u64| app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().object_style.clone(); + assert_eq!(style(a), "Picked"); + assert_ne!(style(b), "Picked"); + } } From 737fcfec043afabaa32a6bc41e1c0f1cfda08f57 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 09:53:54 -0800 Subject: [PATCH 1037/1349] IDML: an item without corners keeps none over its object style Object styles now export their corners, and an import gives an item without corner attributes the corners of its style chain and of [None]. An item with no corners whose style, a style it is based on, or [None] sets corners now writes None for each corner, so it keeps no corners after export and import. The lookup runs once per style. --- crates/idml/src/export.rs | 3 +++ crates/idml/src/export/item.rs | 36 +++++++++++++++++++++++-- crates/idml/src/tests/object_styles.rs | 37 ++++++++++++++++++++++++++ 3 files changed, 74 insertions(+), 2 deletions(-) diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs index 717bb5d6c..0c85e8f8a 100644 --- a/crates/idml/src/export.rs +++ b/crates/idml/src/export.rs @@ -106,6 +106,8 @@ struct Ex<'a> { /// Index topic path → first serialized sort key; See / See also cross-references. index_topics: BTreeMap, String>, index_xrefs: Vec<(Vec, &'static str, String)>, + /// Object style name → whether its chain or `[None]` sets corners, found once per style. + style_corners: HashMap, } impl<'a> Ex<'a> { @@ -121,6 +123,7 @@ impl<'a> Ex<'a> { link_text_sources: Vec::new(), index_topics: BTreeMap::new(), index_xrefs: Vec::new(), + style_corners: HashMap::new(), }; ex.assign_swatch_ids(); for s in d.stories.values() { diff --git a/crates/idml/src/export/item.rs b/crates/idml/src/export/item.rs index 469053c2f..3c240deca 100644 --- a/crates/idml/src/export/item.rs +++ b/crates/idml/src/export/item.rs @@ -87,8 +87,10 @@ impl<'a> Ex<'a> { el.set("GradientStrokeAngle", num(a)); } self.stroke_attrs(&mut el, &it.stroke); - // Corner options: map path-order corners to the named corners by geometry. - if !it.corners.is_none() { + // Corner options: map path-order corners to the named corners by geometry. An item without + // corners whose object style chain sets some writes None, so an import does not give it + // the style's corners. + if !it.corners.is_none() || self.style_sets_corners(os) { let names_by_index = corner_names(&it.path); for (i, c) in it.corners.corners.iter().enumerate() { let n = names_by_index[i]; @@ -153,6 +155,36 @@ impl<'a> Ex<'a> { el } + /// Whether object style `name`, a style it is based on, or `[None]` (which an import reads + /// after every item's style chain) sets corners other than None. A built-in style the + /// document lacks counts as its default. + fn style_sets_corners(&mut self, name: &str) -> bool { + if let Some(&known) = self.style_corners.get(name) { + return known; + } + let defaults = designcraft_doc::Styles::default(); + let style = |n: &str| self.d.styles.object_style(n).or_else(|| defaults.object_style(n)); + let rounds = |os: &designcraft_doc::ObjectStyle| os.corners.is_some_and(|c| !c.is_none()); + let mut seen: Vec<&str> = Vec::new(); + let mut cur = Some(name); + let mut found = false; + while let Some(n) = cur.take() { + if seen.contains(&n) { + break; + } + let Some(os) = style(n) else { break }; + if rounds(os) { + found = true; + break; + } + seen.push(n); + cur = os.based_on.as_deref(); + } + let found = found || style(designcraft_doc::NO_OBJECT_STYLE).is_some_and(rounds); + self.style_corners.insert(name.to_string(), found); + found + } + fn append_transparency(&self, el: &mut El, it: &Item, os: &str) { // Transparency. // An item whose style sets effects writes the effects it has turned off too, so that on diff --git a/crates/idml/src/tests/object_styles.rs b/crates/idml/src/tests/object_styles.rs index 4ff0fa6bf..6226d4a74 100644 --- a/crates/idml/src/tests/object_styles.rs +++ b/crates/idml/src/tests/object_styles.rs @@ -232,6 +232,43 @@ fn exported_frames_keep_their_own_values_over_their_object_style() { assert_eq!(got.options, want); } +/// Items without corners keep none after export and import, though their object style, the style +/// it is based on, or `[None]` (read after every style chain) sets rounded corners. +#[test] +fn exported_frames_keep_no_corners_over_their_object_style() { + let mut d = small_doc(); + let lid = d.default_layer(); + let id = designcraft_doc::ItemId(d.alloc()); + let rect = designcraft_doc::Item::new(id, lid, Shape::Rectangle, shapes::rectangle(Rect::new(40.0, 420.0, 200.0, 500.0))); + d.insert_item(SpreadRef::Doc(0), rect, None).unwrap(); + let rounded = Some(designcraft_geom::corners::CornerOptions { + corners: [designcraft_geom::corners::Corner { shape: CornerShape::Rounded, size: 12.0 }; 4], + }); + let styles = std::sync::Arc::make_mut(&mut d.styles); + styles.object.push(designcraft_doc::ObjectStyle { name: "Round".into(), corners: rounded, ..Default::default() }); + styles.object.push(designcraft_doc::ObjectStyle { name: "Child".into(), based_on: Some("Round".into()), ..Default::default() }); + match styles.object.iter_mut().find(|o| o.name == designcraft_doc::NO_OBJECT_STYLE) { + Some(none) => none.corners = rounded, + None => { + styles.object.push(designcraft_doc::ObjectStyle { name: designcraft_doc::NO_OBJECT_STYLE.into(), corners: rounded, ..Default::default() }) + } + } + styles.object.push(designcraft_doc::ObjectStyle { name: "Plain".into(), ..Default::default() }); + let names = ["Round", "Child", designcraft_doc::NO_OBJECT_STYLE, "Plain"]; + let ids: Vec<_> = d.spreads.iter().flat_map(|s| s.items.iter().map(|i| i.id)).take(4).collect(); + assert_eq!(ids.len(), 4); + for (id, style) in ids.iter().zip(names) { + let it = d.item_mut(*id).unwrap(); + it.object_style = style.into(); + assert!(it.corners.is_none()); + } + let back = import_idml(&export_idml(&d)).unwrap(); + for style in names { + let it = back.spreads.iter().flat_map(|s| s.items.iter()).find(|i| i.object_style == style).unwrap(); + assert!(it.corners.is_none(), "{style}: {:?}", it.corners); + } +} + #[test] fn text_wrap_side_and_contour_come_from_the_style_for_frames_and_placed_graphics() { let styles = r#" From f0e63b333dd0ff85f6c498d5fa1c31e127cb223e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 10:01:16 -0800 Subject: [PATCH 1038/1349] IDML: a style without a category flag takes it from its based-on style An object style that gives neither EnableStrokeAndCornerOptions nor corners of its own takes the category from the style it is based on, and one without EnableTextFrameGeneralOptions does the same for its text frame options. A style based on [None] still sets neither, and [None] keeps the corners it sets itself. --- crates/idml/src/import/styles.rs | 40 +++++++++++++++++--------- crates/idml/src/tests/object_styles.rs | 37 ++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 13 deletions(-) diff --git a/crates/idml/src/import/styles.rs b/crates/idml/src/import/styles.rs index e2e11e979..023ab2d40 100644 --- a/crates/idml/src/import/styles.rs +++ b/crates/idml/src/import/styles.rs @@ -199,8 +199,9 @@ impl<'r> Importer<'r> { .flatten(); let levels = based_on_levels(e, &objects_by_self); // Text Frame General Options: each attribute from the nearest style whose - // `TextFramePreference` sets it, among the styles that don't turn the category off. - let text_frame = if e.get("EnableTextFrameGeneralOptions") == Some("true") { + // `TextFramePreference` sets it, among the styles that don't turn the category off. A + // style without the category flag takes it from the style it is based on. + let text_frame = if category_on(&levels, "EnableTextFrameGeneralOptions", |_| false) { let prefs: Vec<&El> = levels .iter() .filter(|l| l.get("EnableTextFrameGeneralOptions") != Some("false")) @@ -211,7 +212,7 @@ impl<'r> Importer<'r> { None }; let effects = self.style_effects(e); - let corners = style_corners(e, &levels); + let corners = style_corners(&levels); let apply_next_style = paragraph_style.is_some() && e.get("ApplyNextParagraphStyle") == Some("true"); let s = ObjectStyle { name: name.clone(), based_on, fill, stroke, paragraph_style, apply_next_style, text_frame, effects, corners }; match self.styles.object.iter_mut().find(|o| o.name == name) { @@ -412,21 +413,34 @@ impl<'r> Importer<'r> { } } -/// Object style `e`'s corner options (Stroke & Corner Options), by name, when it sets them. A style -/// that sets some corners, or turns the category on, takes the others from the styles in `levels` -/// (`e` and the styles it is based on) that don't turn the category off. -fn style_corners(e: &El, levels: &[&El]) -> Option { - match e.get("EnableStrokeAndCornerOptions") { - Some("false") => return None, - Some("true") => {} - _ => { - corners(e, "")?; - } +/// The corner options (Stroke & Corner Options) of the object style that starts `levels` (the +/// style, then the styles it is based on), by name, when it sets them. A style that sets some +/// corners, or turns the category on (itself or through the style it is based on), takes the +/// others from the styles in `levels` that don't turn the category off. +fn style_corners(levels: &[&El]) -> Option { + if !category_on(levels, "EnableStrokeAndCornerOptions", |l| corners(l, "").is_some()) { + return None; } let on: Vec<&El> = levels.iter().copied().filter(|l| l.get("EnableStrokeAndCornerOptions") != Some("false")).collect(); corners_in(&on, "").map(|c| CornerOptions { corners: c }) } +/// Whether the style chain `levels` (a style, then the styles it is based on) turns the category +/// whose flag is `flag` on. The nearest style that gives the flag decides; a style without it +/// turns the category on when `own` finds settings of its own. A `[None]` after the first style +/// ends the chain, as a `BasedOn` of `[None]` names no style. +fn category_on(levels: &[&El], flag: &str, own: impl Fn(&El) -> bool) -> bool { + let none = |l: &&El| l.get("Self") == Some("ObjectStyle/$ID/[None]"); + for l in levels.iter().take(1).chain(levels.iter().skip(1).take_while(|l| !none(l))) { + match l.get(flag) { + Some(v) => return v == "true", + None if own(l) => return true, + None => {} + } + } + false +} + /// Object style `e`, then the styles it is based on, nearest first (cycle-safe, at most 16). A /// `BasedOn` may name a style by its `Self` id or by its bare name. fn based_on_levels<'e>(e: &'e El, objects_by_self: &HashMap<&str, &'e El>) -> Vec<&'e El> { diff --git a/crates/idml/src/tests/object_styles.rs b/crates/idml/src/tests/object_styles.rs index 6226d4a74..52cfd3e20 100644 --- a/crates/idml/src/tests/object_styles.rs +++ b/crates/idml/src/tests/object_styles.rs @@ -363,6 +363,43 @@ fn a_style_turning_corners_on_inherits_all_four() { assert_eq!((c.map(|c| c.shape), c.map(|c| c.size)), ([CornerShape::Rounded; 4], [17.0; 4])); } +/// A style with no Stroke & Corner Options or Text Frame General Options flag and no settings of +/// its own takes each category from the style it is based on: on, off, or (for a style based on +/// `[None]`) not set. +#[test] +fn a_style_without_category_flags_takes_them_from_its_based_on_style() { + let styles = r#" + $ID/[None] + + + + ObjectStyle/Round + + + + ObjectStyle/Round + + + ObjectStyle/Framed + + + ObjectStyle/Off + + + $ID/[None] + "#; + let d = fixture(&format!("{ROUND}{styles}"), &[]); + let style = |n: &str| d.styles.object_style(n).cloned().unwrap(); + let c = style("RoundKid").corners.expect("RoundKid inherits Round's corners").corners; + assert_eq!((c.map(|c| c.shape), c.map(|c| c.size)), ([CornerShape::Rounded; 4], [17.0; 4])); + assert_eq!(style("FramedKid").text_frame.map(|t| t.columns), Some(3), "FramedKid inherits Framed's text frame options"); + for n in ["OffKid", "Bare"] { + assert!(style(n).corners.is_none() && style(n).text_frame.is_none(), "{n}: {:?}", style(n)); + } + assert!(style(designcraft_doc::NO_OBJECT_STYLE).corners.is_some(), "[None] keeps the corners it sets itself"); +} + /// An object style giving its corners only with the legacy all-corners `CornerOption` and /// `CornerRadius` keeps them, so applying it to another frame rounds it. #[test] From d3a073470cef09eb58856ca442b83a79cf87db10 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 10:18:07 -0800 Subject: [PATCH 1039/1349] Images: decode JPEG screen proxies at a reduced size A placed JPEG drawn at a fraction of its pixel size was decoded at full size first and then halved down to the level the screen needs. For a 24 MP photo that is a 96 MB decode per image, and with several such images on a page the decoded pixels outgrow the image cache. A YCbCr or grayscale JPEG whose wanted level is a half, a quarter or an eighth of its size (or smaller) is now decoded at that size straight from its compressed blocks with jpeg-decoder's scaled IDCT, cut to the size the halving path gives the same level, and halved from there for smaller levels. The embedded ICC profile is applied as in a full decode. CMYK and YCCK JPEGs, other formats and the full size still decode in full. --- Cargo.lock | 7 ++ ROADMAP.md | 1 + crates/images/Cargo.toml | 2 + crates/images/src/colour/tests.rs | 22 ++++++ crates/images/src/jpeg.rs | 38 +++++++++ crates/images/src/lib.rs | 18 +++++ crates/images/src/tests.rs | 50 ++++++++++++ crates/render/src/decode.rs | 12 ++- crates/render/src/images.rs | 125 ++++++++++++++++++++++++++++++ 9 files changed, 274 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 9760f61ff..4c4887099 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1504,6 +1504,7 @@ dependencies = [ "designcraft-fonts", "flate2", "image", + "jpeg-decoder", "log", "quick-xml 0.41.0", "resvg", @@ -3305,6 +3306,12 @@ dependencies = [ "libc", ] +[[package]] +name = "jpeg-decoder" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00810f1d8b74be64b13dbf3db89ac67740615d6c891f0e7b6179326533011a07" + [[package]] name = "js-sys" version = "0.3.106" diff --git a/ROADMAP.md b/ROADMAP.md index 402c81438..559fed4e1 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -388,6 +388,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log +- **2026-11-12** · A placed JPEG drawn at a half, a quarter or an eighth of its pixel size or less is decoded at that size straight from its compressed blocks, so the canvas, page thumbnails and loaded-graphic thumbnails no longer decode and keep the full-size picture for it. CMYK JPEGs and the full size still decode in full. No readiness percentage change. - **2026-11-12** · The status bar's preflight count and the Preflight panel take their issues from a check on a background worker, which checks the newest state of the document and shows the issues last found meanwhile. Moving or resizing a frame and typing no longer wait for a check of the whole document on every drag step and keystroke. No readiness percentage change. - **2026-11-04** · Striped strokes retain out-and-back cubic segments whose second control point is away from the coincident endpoints and first control point. A geometry regression checks the offset extent and both stripe bands. No readiness percentage change. - **2026-11-04** · Esperanto is a text language (Character › Language, `type.char {language: "Esperanto"}`, IDML `$ID/Esperanto`): tag `eo`, English-style quotes; not hyphenated yet (#1201). No readiness percentage change. diff --git a/crates/images/Cargo.toml b/crates/images/Cargo.toml index 685c7d947..658047784 100644 --- a/crates/images/Cargo.toml +++ b/crates/images/Cargo.toml @@ -21,6 +21,8 @@ log = { workspace = true } craft-cms = { workspace = true } zune-core = { version = "0.5", default-features = false } zune-jpeg = "0.5" +# Reduced-size JPEG decoding (1/2, 1/4, 1/8 through the DCT) for screen proxies. +jpeg-decoder = { version = "0.3", default-features = false } [dev-dependencies] designcraft-fonts = { workspace = true, features = ["testing"] } diff --git a/crates/images/src/colour/tests.rs b/crates/images/src/colour/tests.rs index ca1607965..28bd99c99 100644 --- a/crates/images/src/colour/tests.rs +++ b/crates/images/src/colour/tests.rs @@ -241,3 +241,25 @@ fn unusable_profiles_leave_the_pixels_alone() { let png = png_with_icc(1, 1, &px, Some(vec![0xAB; 300])); assert_eq!(decode_rgba(&png).unwrap().as_raw(), &px); } + +#[test] +fn reduced_jpegs_get_the_colour_handling_of_full_decodes() { + // An Adobe RGB JPEG: the reduced decode applies the profile as the full decode does. + let img = image::RgbImage::from_pixel(64, 48, image::Rgb([64, 192, 64])); + let mut jpeg = Vec::new(); + let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 95); + enc.set_icc_profile(adobe_rgb_icc()).unwrap(); + enc.write_image(img.as_raw(), 64, 48, image::ExtendedColorType::Rgb8).unwrap(); + let full = decode_rgba(&jpeg).unwrap().get_pixel(3, 3).0; + let reduced = crate::decode_rgba_reduced(&jpeg, 3).unwrap(); + assert_eq!(reduced.dimensions(), (8, 6)); + let p = reduced.get_pixel(1, 1).0; + for c in 0..4 { + assert!(p[c].abs_diff(full[c]) <= 2, "{p:?} vs {full:?}"); + } + let want = adobe_to_srgb([64, 192, 64]); + assert!((f32::from(p[0]) - want[0]).abs() <= 3.0, "{p:?} vs {want:?}"); + // CMYK and YCCK JPEGs stay with the full decode, which converts their inks. + assert!(crate::decode_rgba_reduced(&solid_jpeg([0, 255, 255, 255], Some(0)), 1).is_none()); + assert!(crate::decode_rgba_reduced(&solid_jpeg([76, 85, 255, 255], Some(2)), 1).is_none()); +} diff --git a/crates/images/src/jpeg.rs b/crates/images/src/jpeg.rs index 8b44d0c9a..fea0a1e64 100644 --- a/crates/images/src/jpeg.rs +++ b/crates/images/src/jpeg.rs @@ -62,6 +62,44 @@ pub(crate) fn decode_cmyk(bytes: &[u8]) -> Option<(CmykRaster, Option>)> Some((raster, icc)) } +/// The largest reduction [`decode_reduced`] reads straight from a JPEG's 8×8 blocks: 1/8. +pub(crate) const MAX_SHRINK: u8 = 3; + +/// A YCbCr, RGB or grayscale JPEG decoded at 1/2^`shrink` of its size, each side rounded up, for +/// `shrink` 1 to [`MAX_SHRINK`]: straight RGBA and whether the image has colour. `None` for CMYK, +/// 12-bit and lossless JPEGs, other formats and anything that doesn't decode. +pub(crate) fn decode_reduced(bytes: &[u8], shrink: u8) -> Option<(image::RgbaImage, bool)> { + use jpeg_decoder::PixelFormat; + if !bytes.starts_with(&[0xFF, 0xD8]) || shrink == 0 || shrink > MAX_SHRINK { + return None; + } + let mut d = jpeg_decoder::Decoder::new(bytes); + d.set_max_decoding_buffer_size(MAX_BYTES); + d.read_info().ok()?; + let info = d.info()?; + let colour = match info.pixel_format { + PixelFormat::RGB24 => true, + PixelFormat::L8 => false, + PixelFormat::L16 | PixelFormat::CMYK32 => return None, + }; + let reduced = |n: u16| u16::try_from(u32::from(n).div_ceil(1 << shrink)).ok(); + let (w, h) = d.scale(reduced(info.width)?, reduced(info.height)?).ok()?; + let px = d.decode().ok()?; + let pixels = usize::from(w).checked_mul(usize::from(h))?; + let rgba: Vec = if colour { + if px.len() != pixels.checked_mul(3)? { + return None; + } + px.as_chunks::<3>().0.iter().flat_map(|p| [p[0], p[1], p[2], 255]).collect() + } else { + if px.len() != pixels { + return None; + } + px.iter().flat_map(|&v| [v, v, v, 255]).collect() + }; + Some((image::RgbaImage::from_raw(u32::from(w), u32::from(h), rgba)?, colour)) +} + /// Whether an APP14 "Adobe" segment comes before the image data. fn adobe_marker(bytes: &[u8]) -> bool { let mut i = 2; diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 081af6c2b..530ca8097 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -442,6 +442,24 @@ pub fn decode_rgba(bytes: &[u8]) -> Option { to_display_rgba(px, Some(&icc), &DisplayColour::active()) } +/// The largest `shrink` [`decode_rgba_reduced`] takes: 3, an eighth of each side. +pub const MAX_REDUCED_SHRINK: u8 = jpeg::MAX_SHRINK; + +/// [`decode_rgba`] of a JPEG at 1/2^`shrink` of its size (`shrink` 1 to [`MAX_REDUCED_SHRINK`], each +/// side rounded up), read from its compressed blocks without a full-size decode. The embedded ICC +/// profile is applied as [`decode_rgba`] applies it. `None` where only a full decode applies: other +/// formats, CMYK, 12-bit and lossless JPEGs, and files [`decode_rgba`] refuses as too large. +pub fn decode_rgba_reduced(bytes: &[u8], shrink: u8) -> Option { + use colour::{DisplayColour, Pixels, to_display_rgba}; + if too_large_to_decode(bytes) { + return None; + } + let (rgba, has_colour) = jpeg::decode_reduced(bytes, shrink)?; + let Some(icc) = embedded_icc(bytes) else { return Some(rgba) }; + let px = if has_colour { Pixels::Rgb(rgba) } else { Pixels::Gray(rgba) }; + to_display_rgba(px, Some(&icc), &DisplayColour::active()) +} + /// False when `bytes` is a WebP whose `ICCP` chunk declares more bytes than the file holds or than /// [`colour::MAX_ICC_BYTES`]. The decoder sizes its buffer from the declared length before it reads /// anything, so such a file must not reach `icc_profile()`; its pixels decode without it. diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index cd577f09a..ae5435a62 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -561,3 +561,53 @@ fn a_webp_icc_chunk_that_declares_more_than_it_holds_is_refused_before_decoding( assert!(webp_icc_is_sane(b"\x89PNG not a webp")); assert!(webp_icc_is_sane(&webp_with(&[(b"VP8L", 6, &[0; 6])]))); } + +/// A JPEG of a smooth gradient, `w` × `h`. +fn gradient_jpeg(w: u32, h: u32, gray: bool) -> Vec { + let rgb = image::RgbImage::from_fn(w, h, |x, y| image::Rgb([(x * 255 / w) as u8, (y * 255 / h) as u8, 128])); + let img = if gray { image::DynamicImage::ImageRgb8(rgb).into_luma8().into() } else { image::DynamicImage::ImageRgb8(rgb) }; + let mut out = Vec::new(); + img.write_with_encoder(image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 90)).unwrap(); + out +} + +#[test] +fn reduced_jpegs_decode_at_a_half_quarter_or_eighth_rounded_up() { + let jpeg = gradient_jpeg(1001, 77, false); + let full = decode_rgba(&jpeg).unwrap(); + for (shrink, size) in [(1, (501, 39)), (2, (251, 20)), (3, (126, 10))] { + let img = decode_rgba_reduced(&jpeg, shrink).unwrap(); + assert_eq!(img.dimensions(), size, "shrink {shrink}"); + // The same picture as the full decode sampled at the block centres, give or take rounding. + let step = 1u32 << shrink; + let (mut total, mut n) = (0u64, 0u64); + for y in 0..size.1 - 1 { + for x in 0..size.0 - 1 { + let (p, q) = (img.get_pixel(x, y).0, full.get_pixel(x * step + step / 2, y * step + step / 2).0); + total += (0..3).map(|c| u64::from(p[c].abs_diff(q[c]))).sum::(); + n += 3; + assert_eq!(p[3], 255); + } + } + assert!(total / n <= 3, "shrink {shrink}: mean difference {}", total / n); + } + // Only 1/2, 1/4 and 1/8 are read from the blocks. + assert!(decode_rgba_reduced(&jpeg, 0).is_none()); + assert!(decode_rgba_reduced(&jpeg, 4).is_none()); +} + +#[test] +fn reduced_decoding_is_for_jpegs_and_survives_damaged_ones() { + let gray = decode_rgba_reduced(&gradient_jpeg(64, 64, true), 2).unwrap(); + assert_eq!(gray.dimensions(), (16, 16)); + assert!(gray.pixels().all(|p| p[0] == p[1] && p[1] == p[2] && p[3] == 255)); + let png = png_from_rgba(16, 16, vec![255; 16 * 16 * 4]).unwrap(); + assert!(decode_rgba_reduced(&png, 1).is_none()); + assert!(decode_rgba_reduced(&[0xFF, 0xD8], 1).is_none()); + let jpeg = gradient_jpeg(200, 150, false); + for n in (0..jpeg.len()).step_by(37) { + if let Some(img) = decode_rgba_reduced(&jpeg[..n], 1) { + assert_eq!(img.dimensions(), (100, 75)); + } + } +} diff --git a/crates/render/src/decode.rs b/crates/render/src/decode.rs index 135dbf108..8c703701e 100644 --- a/crates/render/src/decode.rs +++ b/crates/render/src/decode.rs @@ -19,7 +19,17 @@ pub fn decode_pixmap_page(bytes: &[u8], page: u32) -> Option { let data = px.as_chunks::<4>().0.iter().map(|p| vello_cpu::color::PremulRgba8 { r: p[0], g: p[1], b: p[2], a: p[3] }).collect(); return Some(Pixmap::from_parts(data, w.min(u16::MAX as u32) as u16, h.min(u16::MAX as u32) as u16)); } - let img = designcraft_images::decode_rgba(bytes)?; + premultiplied(&designcraft_images::decode_rgba(bytes)?) +} + +/// [`decode_pixmap`] of a JPEG at 1/2^`shrink` of its size, `shrink` 1 to +/// [`designcraft_images::MAX_REDUCED_SHRINK`], without a full-size decode. `None` where only a +/// full decode applies (other formats, CMYK JPEGs). +pub(crate) fn decode_pixmap_reduced(bytes: &[u8], shrink: u8) -> Option { + premultiplied(&designcraft_images::decode_rgba_reduced(bytes, shrink)?) +} + +fn premultiplied(img: &image::RgbaImage) -> Option { let (w, h) = img.dimensions(); if w == 0 || h == 0 || w > u16::MAX as u32 || h > u16::MAX as u32 { return None; diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 37606097d..69691135e 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -10,6 +10,7 @@ use std::sync::{Arc, Mutex}; use vello_cpu::Pixmap; +use crate::decode::decode_pixmap_reduced; use crate::{decode_pixmap_page, halve}; /// Decoded pixels kept (bytes). @@ -130,6 +131,11 @@ pub fn decoded(bytes: &Arc>, page: u32) -> Option> { /// The mip level of `bytes` closest above `on_screen` device pixels per point for a graphic /// `width_pt` points wide. pub fn mip(bytes: &Arc>, page: u32, width_pt: f64, on_screen: f64) -> Option> { + if lookup((Arc::as_ptr(bytes) as usize, page, 0)).is_none() + && let Some(pm) = reduced(bytes, page, width_pt, on_screen) + { + return Some(pm); + } let full = decoded(bytes, page)?; let ppt = full.width() as f64 / width_pt.max(1e-6); let id = Arc::as_ptr(bytes) as usize; @@ -149,6 +155,71 @@ pub fn mip(bytes: &Arc>, page: u32, width_pt: f64, on_screen: f64) -> Op Some(pm) } +/// [`mip`]'s level for a JPEG, decoded at 1/2, 1/4 or 1/8 of its size straight from its blocks +/// and halved from there, so a screen-sized level needs no full-size decode. `None` when the +/// full size is drawn, for other formats and for JPEGs only a full decode reads (CMYK). +fn reduced(bytes: &Arc>, page: u32, width_pt: f64, on_screen: f64) -> Option> { + if page != 0 || !bytes.starts_with(&[0xFF, 0xD8]) { + return None; + } + let id = Arc::as_ptr(bytes) as usize; + if with(|c| c.bad.contains_key(&(id, page))) { + return None; + } + // The level `mip` picks from a full decode, with each level's size as `halve` gives it. + let (mut w, mut h) = crate::image_size(bytes)?; + let ppt = w as f64 / width_pt.max(1e-6); + let mut sizes = vec![(w, h)]; + while ppt / (1u64 << sizes.len()) as f64 >= on_screen * 1.2 && w > 64 && h > 64 && sizes.len() <= 8 { + (w, h) = ((w / 2).max(1), (h / 2).max(1)); + sizes.push((w, h)); + } + let level = u8::try_from(sizes.len() - 1).ok()?; + if level == 0 { + return None; + } + if let Some(pm) = lookup((id, page, level)) { + return Some(pm); + } + let shrink = level.min(designcraft_images::MAX_REDUCED_SHRINK); + let mut pm = match lookup((id, page, shrink)) { + Some(p) => p, + None => { + // Cut to `halve`'s size (it rounds down, the decoder up), as the level a full + // decode makes. + let (sw, sh) = sizes[usize::from(shrink)]; + let p = Arc::new(crop(decode_pixmap_reduced(bytes, shrink)?, sw, sh)?); + store(bytes, page, shrink, p.clone()); + p + } + }; + for l in shrink + 1..=level { + pm = match lookup((id, page, l)) { + Some(p) => p, + None => { + let half = Arc::new(halve(&pm)); + store(bytes, page, l, half.clone()); + half + } + }; + } + Some(pm) +} + +/// The top-left `w` × `h` of `pm`; `None` when `pm` is smaller. +fn crop(pm: Pixmap, w: u32, h: u32) -> Option { + let (pw, ph) = (u32::from(pm.width()), u32::from(pm.height())); + if (pw, ph) == (w, h) { + return Some(pm); + } + if w > pw || h > ph || w == 0 || h == 0 { + return None; + } + let (pw, w, h) = (pw as usize, w as usize, h as usize); + let data: Vec<_> = pm.data().chunks_exact(pw).take(h).flat_map(|row| &row[..w]).copied().collect(); + Some(Pixmap::from_parts(data, u16::try_from(w).ok()?, u16::try_from(h).ok()?)) +} + /// Drop every decoded image. pub fn clear() { with(|c| { @@ -176,4 +247,58 @@ mod tests { let last = &buffers[MAX_BAD + 9]; assert!(c.bad.contains_key(&(Arc::as_ptr(last) as usize, 0))); } + + fn jpeg(w: u32, h: u32) -> Arc> { + let img = image::RgbImage::from_fn(w, h, |x, y| image::Rgb([(x * 255 / w) as u8, (y * 255 / h) as u8, 128])); + let mut out = Vec::new(); + img.write_with_encoder(image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 90)).unwrap(); + Arc::new(out) + } + + #[test] + fn screen_levels_of_a_jpeg_need_no_full_size_decode() { + let bytes = jpeg(1024, 768); + let id = Arc::as_ptr(&bytes) as usize; + // 1 px per point drawn at 0.1: level 3, an eighth, read straight from the blocks. + let pm = mip(&bytes, 0, 1024.0, 0.1).unwrap(); + assert_eq!((pm.width(), pm.height()), (128, 96)); + assert!(lookup((id, 0, 0)).is_none(), "no full-size decode is kept"); + // Close to the full decode halved three times. + let mut want = decode_pixmap_page(&bytes, 0).unwrap(); + for _ in 0..3 { + want = halve(&want); + } + let diff: u64 = pm.data().iter().zip(want.data()).map(|(p, q)| u64::from(p.r.abs_diff(q.r)) + u64::from(p.g.abs_diff(q.g))).sum(); + assert!(diff / (2 * 128 * 96) <= 3, "mean difference {}", diff / (2 * 128 * 96)); + // Smaller levels are halved from that eighth, down to 64 px as before. + let small = mip(&bytes, 0, 1024.0, 0.02).unwrap(); + assert_eq!((small.width(), small.height()), (64, 48)); + assert!(lookup((id, 0, 0)).is_none(), "no full-size decode is kept"); + // The full size is still a full decode. + let full = mip(&bytes, 0, 1024.0, 1.0).unwrap(); + assert_eq!((full.width(), full.height()), (1024, 768)); + } + + #[test] + fn reduced_levels_of_odd_sized_jpegs_have_the_halved_size() { + let bytes = jpeg(1001, 771); + let mut want = decode_pixmap_page(&bytes, 0).unwrap(); + for _ in 0..3 { + want = halve(&want); + } + let pm = mip(&bytes, 0, 1001.0, 0.1).unwrap(); + assert!(lookup((Arc::as_ptr(&bytes) as usize, 0, 0)).is_none()); + assert_eq!((pm.width(), pm.height()), (want.width(), want.height())); + assert_eq!((pm.width(), pm.height()), (125, 96)); + } + + #[test] + fn a_jpeg_that_does_not_decode_is_remembered_as_failed() { + let mut broken = jpeg(256, 256).to_vec(); + broken.truncate(40); + let bytes = Arc::new(broken); + assert!(mip(&bytes, 0, 256.0, 0.1).is_none()); + assert!(with(|c| c.bad.contains_key(&(Arc::as_ptr(&bytes) as usize, 0)))); + assert!(mip(&bytes, 0, 256.0, 0.1).is_none()); + } } From 4e363e1bfacc4a2c3b36f4b7f5c56afcef94833c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 10:29:50 -0800 Subject: [PATCH 1040/1349] Render: placed images are premultiplied in their decoded buffer Decoding a placed raster built a second full-size pixel vector from the RGBA image and premultiplied every pixel into it. The pixels are now premultiplied in place, opaque pixels are skipped, and the buffer becomes the pixmap's pixels without a copy (bytemuck's cast_vec, with a copy when the capacity is not a whole number of pixels). The rendered SVG path reuses its buffer the same way. For a 6000 x 4000 opaque image the step takes 7 ms instead of 120 ms, with identical pixels. --- Cargo.lock | 1 + Cargo.toml | 2 ++ ROADMAP.md | 1 + crates/render/Cargo.toml | 1 + crates/render/src/decode.rs | 38 ++++++++++++++++++++++++++----------- crates/render/src/tests.rs | 30 +++++++++++++++++++++++++++++ 6 files changed, 62 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9760f61ff..09e504a80 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1574,6 +1574,7 @@ dependencies = [ name = "designcraft-render" version = "0.20.1" dependencies = [ + "bytemuck", "craft-pdf", "designcraft-color", "designcraft-compose", diff --git a/Cargo.toml b/Cargo.toml index dcf2c7235..d90986f91 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -64,6 +64,8 @@ skrifa = "0.47" harfrust = "0.13" vello_cpu = "0.2" vello_common = { version = "0.2", default-features = false } +# Decoded image buffers become pixmap pixels without a copy; the version vello_common uses. +bytemuck = { version = "1.25", features = ["extern_crate_alloc"] } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "tiff", "bmp"] } # CMYK TIFF samples for PDF export (`image` decodes them to RGB); the version `image` uses. tiff = "0.11" diff --git a/ROADMAP.md b/ROADMAP.md index 402c81438..f7f8aff00 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -388,6 +388,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log +- **2026-11-12** · A decoded placed image becomes a screen pixmap in its own buffer, premultiplied in place, and opaque pixels are left as they are: 120 ms becomes 7 ms for a 24-megapixel opaque photo, with the same pixels. No readiness percentage change. - **2026-11-12** · The status bar's preflight count and the Preflight panel take their issues from a check on a background worker, which checks the newest state of the document and shows the issues last found meanwhile. Moving or resizing a frame and typing no longer wait for a check of the whole document on every drag step and keystroke. No readiness percentage change. - **2026-11-04** · Striped strokes retain out-and-back cubic segments whose second control point is away from the coincident endpoints and first control point. A geometry regression checks the offset extent and both stripe bands. No readiness percentage change. - **2026-11-04** · Esperanto is a text language (Character › Language, `type.char {language: "Esperanto"}`, IDML `$ID/Esperanto`): tag `eo`, English-style quotes; not hyphenated yet (#1201). No readiness percentage change. diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 8cd446af1..ac5d8a0f1 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -16,6 +16,7 @@ designcraft-fonts = { workspace = true } designcraft-compose = { workspace = true } vello_cpu = { workspace = true } vello_common = { workspace = true } +bytemuck = { workspace = true } image = { workspace = true } craft-pdf = { workspace = true, features = ["raster"] } designcraft-images = { workspace = true } diff --git a/crates/render/src/decode.rs b/crates/render/src/decode.rs index 135dbf108..d720362c7 100644 --- a/crates/render/src/decode.rs +++ b/crates/render/src/decode.rs @@ -16,23 +16,39 @@ pub fn decode_pixmap_page(bytes: &[u8], page: u32) -> Option { } if designcraft_images::is_svg(bytes) { let (px, w, h) = designcraft_images::render_svg(bytes, 3000)?; - let data = px.as_chunks::<4>().0.iter().map(|p| vello_cpu::color::PremulRgba8 { r: p[0], g: p[1], b: p[2], a: p[3] }).collect(); - return Some(Pixmap::from_parts(data, w.min(u16::MAX as u32) as u16, h.min(u16::MAX as u32) as u16)); + return Some(Pixmap::from_parts(premul_pixels(px), w.min(u16::MAX as u32) as u16, h.min(u16::MAX as u32) as u16)); } let img = designcraft_images::decode_rgba(bytes)?; let (w, h) = img.dimensions(); if w == 0 || h == 0 || w > u16::MAX as u32 || h > u16::MAX as u32 { return None; } - let data: Vec = img - .pixels() - .map(|p| { - let a = p[3] as u16; - let m = |c: u8| ((c as u16 * a + 127) / 255) as u8; - vello_cpu::color::PremulRgba8 { r: m(p[0]), g: m(p[1]), b: m(p[2]), a: p[3] } - }) - .collect(); - Some(Pixmap::from_parts(data, w as u16, h as u16)) + let mut px = img.into_raw(); + px.truncate(w as usize * h as usize * 4); + Some(Pixmap::from_parts(premultiply(px), w as u16, h as u16)) +} + +/// Premultiply straight-alpha RGBA bytes in place and return them as pixmap pixels. Opaque pixels +/// are left as they are. +pub(crate) fn premultiply(mut px: Vec) -> Vec { + for p in px.as_chunks_mut::<4>().0 { + let a = p[3]; + if a != 255 { + let m = |c: u8| ((c as u16 * a as u16 + 127) / 255) as u8; + p[0] = m(p[0]); + p[1] = m(p[1]); + p[2] = m(p[2]); + } + } + premul_pixels(px) +} + +/// Premultiplied RGBA bytes as pixmap pixels, in the same allocation when its capacity is a whole +/// number of pixels and in a copy otherwise. +fn premul_pixels(px: Vec) -> Vec { + bytemuck::allocation::try_cast_vec(px).unwrap_or_else(|(_, px)| { + px.as_chunks::<4>().0.iter().map(|p| vello_cpu::color::PremulRgba8 { r: p[0], g: p[1], b: p[2], a: p[3] }).collect() + }) } /// Box-filter downsample by 2. diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 9e3d74e8b..8309667b2 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -30,6 +30,36 @@ fn eps_source_decodes_like_its_preview() { assert!(image_size(corrupt).is_none()); } +#[test] +fn decoded_images_are_premultiplied_for_every_alpha() { + // Column x holds colour value x, row y holds alpha y. + let img = image::RgbaImage::from_fn(256, 256, |x, y| image::Rgba([x as u8, 255 - x as u8, (x / 2) as u8, y as u8])); + let mut png = Vec::new(); + image::DynamicImage::ImageRgba8(img.clone()).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let pm = decode_pixmap(&png).unwrap(); + assert_eq!((pm.width(), pm.height()), (256, 256)); + for (p, q) in img.pixels().zip(pm.data()) { + let m = |c: u8| ((c as u16 * p[3] as u16 + 127) / 255) as u8; + assert_eq!([q.r, q.g, q.b, q.a], [m(p[0]), m(p[1]), m(p[2]), p[3]], "{p:?}"); + } +} + +#[test] +fn premultiplied_pixels_reuse_the_decoded_buffer() { + use vello_cpu::color::PremulRgba8; + let expected = + [PremulRgba8 { r: 10, g: 20, b: 30, a: 255 }, PremulRgba8 { r: 100, g: 50, b: 25, a: 128 }, PremulRgba8 { r: 0, g: 0, b: 0, a: 0 }]; + let px = vec![10, 20, 30, 255, 200, 100, 50, 128, 1, 2, 3, 0]; + let ptr = px.as_ptr() as usize; + let out = decode::premultiply(px); + assert_eq!(out.as_ptr() as usize, ptr); + assert_eq!(out, expected); + // A capacity that is not a whole number of pixels is copied. + let mut px = Vec::with_capacity(13); + px.extend([10, 20, 30, 255, 200, 100, 50, 128, 1, 2, 3, 0]); + assert_eq!(decode::premultiply(px), expected); +} + #[test] fn footnote_vector_objects_are_painted() { use designcraft_doc::{AnchorPosition, AnchoredObject, ItemId, Shape, SpreadRef}; From 855d017d5b56b61bdf5a46c974a280f0eace7398 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 10:34:02 -0800 Subject: [PATCH 1041/1349] Images: limit reduced JPEG decodes by the full image size A reduced decode now applies the full decode's size limits before it reads any image data: - A file whose size pixel_size cannot read is refused, so the 256 Mpx check always has a size to compare. The JPEG decoder's own reading of the frame size is checked against the same limit. - A progressive JPEG keeps the coefficients of the full-size image until its last scan, whatever the output size. When those take more than 512 MiB (each component counted at full size, each side rounded up to 32 pixels), the reduced decode is refused and the full decode, with its own limits, applies. --- crates/images/src/jpeg.rs | 21 ++++++++++++-- crates/images/src/lib.rs | 12 ++++++-- crates/images/src/tests.rs | 58 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 87 insertions(+), 4 deletions(-) diff --git a/crates/images/src/jpeg.rs b/crates/images/src/jpeg.rs index fea0a1e64..6188a53fc 100644 --- a/crates/images/src/jpeg.rs +++ b/crates/images/src/jpeg.rs @@ -67,21 +67,38 @@ pub(crate) const MAX_SHRINK: u8 = 3; /// A YCbCr, RGB or grayscale JPEG decoded at 1/2^`shrink` of its size, each side rounded up, for /// `shrink` 1 to [`MAX_SHRINK`]: straight RGBA and whether the image has colour. `None` for CMYK, -/// 12-bit and lossless JPEGs, other formats and anything that doesn't decode. +/// 12-bit and lossless JPEGs, other formats and anything that doesn't decode. `None` as well for a +/// JPEG whose full size is over the full decode's limit, and for a progressive JPEG whose +/// full-size coefficients take more than [`MAX_BYTES`]; the full decode applies its own limits to +/// those. pub(crate) fn decode_reduced(bytes: &[u8], shrink: u8) -> Option<(image::RgbaImage, bool)> { - use jpeg_decoder::PixelFormat; + use jpeg_decoder::{CodingProcess, PixelFormat}; if !bytes.starts_with(&[0xFF, 0xD8]) || shrink == 0 || shrink > MAX_SHRINK { return None; } let mut d = jpeg_decoder::Decoder::new(bytes); + // This limits the output only, which is the reduced size. d.set_max_decoding_buffer_size(MAX_BYTES); d.read_info().ok()?; let info = d.info()?; + if crate::over_rgba_budget(u32::from(info.width), u32::from(info.height)) { + return None; + } let colour = match info.pixel_format { PixelFormat::RGB24 => true, PixelFormat::L8 => false, PixelFormat::L16 | PixelFormat::CMYK32 => return None, }; + if info.coding_process == CodingProcess::DctProgressive { + // A progressive JPEG holds every coefficient of the full-size image (two bytes each) until + // its last scan, whatever the output size. Each component is counted at the full size and + // each side is rounded up to the largest MCU (32 pixels): an upper bound. + let side = |n: u16| u64::from(n).next_multiple_of(32); + let components: u64 = if colour { 3 } else { 1 }; + if side(info.width) * side(info.height) * components * 2 > MAX_BYTES as u64 { + return None; + } + } let reduced = |n: u16| u16::try_from(u32::from(n).div_ceil(1 << shrink)).ok(); let (w, h) = d.scale(reduced(info.width)?, reduced(info.height)?).ok()?; let px = d.decode().ok()?; diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 530ca8097..5754e8788 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -407,7 +407,12 @@ const MAX_RGBA_BYTES: u64 = 1 << 30; /// Whether a raster's header gives it more pixels than [`decode_rgba`] decodes. pub fn too_large_to_decode(bytes: &[u8]) -> bool { // `image` limits only its own output, which can be a quarter of the RGBA copy or less. - pixel_size(bytes).is_some_and(|(w, h)| u64::from(w).saturating_mul(u64::from(h)).saturating_mul(4) > MAX_RGBA_BYTES) + pixel_size(bytes).is_some_and(|(w, h)| over_rgba_budget(w, h)) +} + +/// Whether a `w` × `h` raster takes more than [`MAX_RGBA_BYTES`] as RGBA. +fn over_rgba_budget(w: u32, h: u32) -> bool { + u64::from(w).saturating_mul(u64::from(h)).saturating_mul(4) > MAX_RGBA_BYTES } /// Straight (non-premultiplied) RGBA8 of a raster in display sRGB: an embedded ICC profile is @@ -448,9 +453,12 @@ pub const MAX_REDUCED_SHRINK: u8 = jpeg::MAX_SHRINK; /// [`decode_rgba`] of a JPEG at 1/2^`shrink` of its size (`shrink` 1 to [`MAX_REDUCED_SHRINK`], each /// side rounded up), read from its compressed blocks without a full-size decode. The embedded ICC /// profile is applied as [`decode_rgba`] applies it. `None` where only a full decode applies: other -/// formats, CMYK, 12-bit and lossless JPEGs, and files [`decode_rgba`] refuses as too large. +/// formats, CMYK, 12-bit and lossless JPEGs, files whose size [`pixel_size`] cannot read, and files +/// [`decode_rgba`] refuses as too large. pub fn decode_rgba_reduced(bytes: &[u8], shrink: u8) -> Option { use colour::{DisplayColour, Pixels, to_display_rgba}; + // The size check must have a size to check: a header only the JPEG decoder reads is refused. + pixel_size(bytes)?; if too_large_to_decode(bytes) { return None; } diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index ae5435a62..184e3c9c9 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -611,3 +611,61 @@ fn reduced_decoding_is_for_jpegs_and_survives_damaged_ones() { } } } + +#[test] +fn reduced_decoding_refuses_a_jpeg_whose_size_the_size_check_cannot_read() { + let jpeg = gradient_jpeg(64, 48, false); + assert_eq!(decode_rgba_reduced(&jpeg, 1).unwrap().dimensions(), (32, 24)); + // A stray byte after the start marker: the JPEG decoder skips it, but `pixel_size` doesn't + // recognize the file, so `too_large_to_decode` has no size to check. + let mut stray = jpeg.clone(); + stray.insert(2, 0); + assert_eq!(pixel_size(&stray), None); + assert!(decode_rgba_reduced(&stray, 1).is_none()); + assert!(decode_rgba(&stray).is_none()); +} + +/// A progressive JPEG with only its DC scan, `w` × `h` with `components` 1×1-sampled components: +/// every coefficient is zero (a flat mid-gray image). +fn progressive_jpeg(w: u16, h: u16, components: u8) -> Vec { + let mut out = vec![0xFF, 0xD8]; + // One quantization table of ones. + out.extend([0xFF, 0xDB, 0, 67, 0]); + out.extend([1; 64]); + // Start of frame, progressive DCT. + out.extend([0xFF, 0xC2, 0, 8 + 3 * components, 8]); + out.extend(h.to_be_bytes()); + out.extend(w.to_be_bytes()); + out.push(components); + for id in 1..=components { + out.extend([id, 0x11, 0]); + } + // A DC table with one code, "0", for a difference of 0. + out.extend([0xFF, 0xC4, 0, 20, 0x00, 1]); + out.extend([0; 15]); + out.push(0); + // The DC scan of every component (Ss, Se, Ah/Al all 0), then zero bits. + out.extend([0xFF, 0xDA, 0, 6 + 2 * components, components]); + for id in 1..=components { + out.extend([id, 0x00]); + } + out.extend([0, 0, 0]); + out.extend([0; 16]); + out.extend([0xFF, 0xD9]); + out +} + +#[test] +fn reduced_decoding_refuses_progressive_jpegs_whose_full_size_coefficients_are_over_the_limit() { + let small = decode_rgba_reduced(&progressive_jpeg(64, 48, 3), 3).unwrap(); + assert_eq!(small.dimensions(), (8, 6)); + // 10,240 × 8,800 is within the RGBA limit, but its three components' coefficients take + // 10,240 × 8,800 × 3 × 2 bytes, over 512 MiB, whatever the output size. + let large = progressive_jpeg(10_240, 8_800, 3); + assert_eq!(pixel_size(&large), Some((10_240, 8_800))); + assert!(!too_large_to_decode(&large)); + assert!(decode_rgba_reduced(&large, 3).is_none()); + // One component of the same size stays under the limit. + let gray = decode_rgba_reduced(&progressive_jpeg(10_240, 8_800, 1), 3).unwrap(); + assert_eq!(gray.dimensions(), (1_280, 1_100)); +} From b5fad8e858447d8251ce90962cc8c0840547d4a7 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 12 Nov 2026 19:45:08 +0100 Subject: [PATCH 1042/1349] Use mutable subpath iteration for current Clippy --- crates/engine/src/cmd/paths.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/paths.rs b/crates/engine/src/cmd/paths.rs index 946da4215..6a2dca01c 100644 --- a/crates/engine/src/cmd/paths.rs +++ b/crates/engine/src/cmd/paths.rs @@ -92,8 +92,8 @@ fn orient_holes_within(path: &mut PathData, command: &str, max_tests: usize) -> let boxes: Vec<_> = beziers.iter().map(BezPath::bounding_box).collect(); let n = path.subpaths.len(); let mut tests = 0usize; - for i in 0..n { - let Some(p) = path.subpaths[i].anchors.first().map(|a| a.p) else { continue }; + for (i, sp) in path.subpaths.iter_mut().enumerate() { + let Some(p) = sp.anchors.first().map(|a| a.p) else { continue }; let mut depth = 0; for j in (0..n).filter(|&j| j != i && boxes[j].inflate(1e-6, 1e-6).contains(p)) { tests += 1; @@ -102,7 +102,6 @@ fn orient_holes_within(path: &mut PathData, command: &str, max_tests: usize) -> } depth += usize::from(designcraft_geom::hit::fill_contains(&beziers[j], designcraft_geom::FillRule::NonZero, p)); } - let sp = &mut path.subpaths[i]; let cw = sp.area() > 0.0; if cw == (depth % 2 == 1) { sp.reverse(); From fe631061dba453dfd5ad500da01d8fd55c087364 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 12 Nov 2026 19:49:14 +0100 Subject: [PATCH 1043/1349] Use mutable row iteration in render fixture --- crates/render/src/tests.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 9e3d74e8b..3287ab836 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -529,9 +529,9 @@ fn degenerate_dash_patterns_draw_solid_and_fill_types_close_table_corners() { let (fid, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 336.0, 400.0), lid, "", ParaFormat::default()).unwrap(); d.item_mut(fid).unwrap().stroke = designcraft_doc::Stroke { weight: 2.0, kind: fine.clone(), ..Default::default() }; let mut t = designcraft_doc::Table::new(1, 2, 2, 0, 0, 200.0); - for r in 0..2 { - t.rows[r].height = 60.0; - t.rows[r].mode = designcraft_doc::RowHeightMode::Exactly; + for row in t.rows.iter_mut().take(2) { + row.height = 60.0; + row.mode = designcraft_doc::RowHeightMode::Exactly; } let stroke = |kind| designcraft_doc::CellStroke { weight: 8.0, kind, gap_color: "C=100 M=0 Y=0 K=0".into(), ..Default::default() }; for cell in &mut t.cells { From 75d1119def2c22979c4113cbbc99cb3cd02f8a99 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 10:59:49 -0800 Subject: [PATCH 1044/1349] Text: Text Frame Options previews go from their document, and Undo refuses stored frames A preview remembers the document it is shown in. When OK is refused or Cancel is chosen after another document became active, that document goes back as it was instead of keeping the previewed options. The frames taken from the caret or selected text are also refused once the document has changed after the dialog opened. Undo puts back the document's id counter, so a frame made after Undo can take a stored id. --- crates/ui-egui/src/dialogs.rs | 116 +++++++++++++++++++++++++++++----- 1 file changed, 101 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 927ed1968..ab53948f9 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -589,6 +589,68 @@ mod color_theme_tests { assert_eq!((inset(&app, a), inset(&app, b)), (24.0, 0.0)); } + /// A preview shown in one document goes when OK is refused, or Cancel is chosen, after another + /// document became active. + #[test] + fn text_frame_options_preview_goes_from_its_document_after_another_becomes_active() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let make = |app: &mut crate::DesignApp| { + app.run("file.new", json!({})).unwrap(); + let r = app.run("frame.create", json!({"rect": [36, 36, 300, 300], "content": "text", "text": "Hello"})).unwrap(); + app.run("text.select", json!({"story": r["story"], "anchor": 2})).unwrap(); + designcraft_doc::ItemId(r["id"].as_u64().unwrap()) + }; + let a = make(&mut app); + let first = |app: &DesignApp| { + let st = &app.session.documents()[0]; + (st.doc.item(a).unwrap().text_frame().unwrap().options.columns, st.interaction.is_some()) + }; + let preview = |app: &mut DesignApp| { + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(app, &mut d); + d.fields.insert("columns".into(), json!("3")); + d.fields.insert("preview".into(), json!(true)); + text_frame_preview(app, &mut d); + assert_eq!(first(app), (3, true), "previewed in the first document"); + d + }; + let d = preview(&mut app); + make(&mut app); + app.ui.dialog = Some(d); + let err = confirm(&mut app).unwrap_err().to_string(); + assert!(err.contains("no longer the active one"), "{err}"); + assert_eq!(first(&app), (1, false), "OK refused: the first document is as it was"); + app.ui.dialog = None; + app.session.set_active(0); + let d = preview(&mut app); + app.session.set_active(1); + app.ui.dialog = Some(d); + cancel(&mut app); + assert_eq!(first(&app), (1, false), "Cancel: the first document is as it was"); + } + + /// Undo puts back the document's id counter, so a frame made after Undo can take the id of a + /// frame the dialog stored; OK is refused instead of changing the new frame. + #[test] + fn text_frame_options_from_the_type_tool_are_refused_after_undo_reuses_the_frame_id() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let a = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": "First"})).unwrap(); + app.run("text.select", json!({"story": a["story"], "anchor": 1})).unwrap(); + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(&app, &mut d); + d.fields.insert("columns".into(), json!("3")); + app.run("edit.undo", json!({})).unwrap(); + let b = app.run("frame.create", json!({"rect": [36, 200, 300, 300], "content": "text", "text": "Second"})).unwrap(); + assert_eq!(a["id"], b["id"], "the new frame takes the undone frame's id"); + app.run("text.select", json!({"story": b["story"], "anchor": 1})).unwrap(); + app.ui.dialog = Some(d); + let err = confirm(&mut app).unwrap_err().to_string(); + assert!(err.contains("changed after the dialog opened"), "{err}"); + let b = designcraft_doc::ItemId(b["id"].as_u64().unwrap()); + assert_eq!(app.session.doc().unwrap().doc.item(b).unwrap().text_frame().unwrap().options.columns, 1, "the new frame is unchanged"); + } + #[test] fn toc_right_indent_separator_survives_the_dialog_and_update() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); @@ -1152,10 +1214,17 @@ fn seed_text_frame_options(app: &DesignApp, d: &mut Dialog) { // The document state those frames are in: another document, or the document after // Revert, can reuse their ids. d.fields.insert("_targetsDoc".into(), json!(app.session.active().map(|doc| doc.identity_epoch))); + // Undo puts back the document's id counter, so a frame made after it can take a stored id. + d.fields.insert("_targetsRevision".into(), json!(app.session.active().map(base_revision))); } d.fields.insert("_shown".into(), shown); } +/// The document's revision without a preview on top: the one the open gesture began at. +fn base_revision(st: &designcraft_engine::DocState) -> u64 { + st.interaction.as_ref().map_or(st.revision, |it| it.revision) +} + /// With the Type tool and no frame selected: the frame that shows the caret, or every frame that /// holds part of the selected text. fn typing_frame_ids(app: &DesignApp) -> Option { @@ -1280,8 +1349,7 @@ fn text_frame_preview(app: &mut DesignApp, d: &mut Dialog) { let shown = d.fields.get(PREVIEWED).cloned(); if !d.b("preview") { if shown.is_some() { - app.session.cancel_interaction(); - d.fields.remove(PREVIEWED); + end_text_frame_preview(app, d); d.fields.remove("status"); } return; @@ -1291,8 +1359,7 @@ fn text_frame_preview(app: &mut DesignApp, d: &mut Dialog) { Err(e) => { // Values OK would refuse don't stay on the page: it goes back to how it was. if shown.is_some() { - app.session.cancel_interaction(); - d.fields.remove(PREVIEWED); + end_text_frame_preview(app, d); } d.fields.insert("status".into(), json!(e)); return; @@ -1304,16 +1371,16 @@ fn text_frame_preview(app: &mut DesignApp, d: &mut Dialog) { // Nothing edited (yet, or any more): the page as it was. if params.as_object().is_some_and(|m| m.keys().all(|k| k == "ids")) { if shown.is_some() { - app.session.cancel_interaction(); - d.fields.remove(PREVIEWED); + end_text_frame_preview(app, d); } return; } - if shown.is_none() - && let Err(e) = app.session.begin_interaction("Text Frame Options") - { - d.fields.insert("status".into(), json!(e.to_string())); - return; + if shown.is_none() { + if let Err(e) = app.session.begin_interaction("Text Frame Options") { + d.fields.insert("status".into(), json!(e.to_string())); + return; + } + d.fields.insert(PREVIEW_DOC.into(), json!(app.session.active().map(|doc| doc.uid))); } match app.session.preview("object.textFrameOptions", params.clone()) { Ok(()) => d.fields.remove("status"), @@ -1322,6 +1389,15 @@ fn text_frame_preview(app: &mut DesignApp, d: &mut Dialog) { d.fields.insert(PREVIEWED.into(), params); } +/// The preview goes from the document it was shown in, also when another document is active now. +fn end_text_frame_preview(app: &mut DesignApp, d: &mut Dialog) { + d.fields.remove(PREVIEWED); + match d.fields.remove(PREVIEW_DOC).as_ref().and_then(Value::as_u64) { + Some(uid) => app.session.cancel_interaction_of(uid), + None => app.session.cancel_interaction(), + } +} + /// Text Frame Options › General, as InDesign's: Columns (kind, number and width, gutter and /// maximum, Balance Columns), Inset Spacing (top and bottom, the link, left and right; one Inset /// for a non-rectangular frame), Vertical Justification (align, paragraph spacing limit) and @@ -1568,8 +1644,8 @@ fn text_frame_baseline_grid(d: &Dialog, bad: &dyn Fn(&str) -> String) -> Result< fn confirm_text_frame_options(app: &mut DesignApp, d: &mut Dialog) -> Result { seed_text_frame_options(app, d); // The preview goes; the options are set once, as one undo step. - if d.fields.remove(PREVIEWED).is_some() { - app.session.cancel_interaction(); + if d.fields.contains_key(PREVIEWED) { + end_text_frame_preview(app, d); } let p = text_frame_params(app, d)?; if p.keys().all(|k| k == "ids") { @@ -1679,13 +1755,17 @@ fn text_frame_params(app: &DesignApp, d: &Dialog) -> Result, /// Typing in a frame: the frame that showed the caret, or every frame that held part of the /// selected text, when the dialog opened. Those ids are refused once another document is active, -/// or once Revert has replaced the document. +/// once Revert has replaced the document, or once the document has changed (Undo can give a new +/// frame a stored id). fn text_frame_targets(app: &DesignApp, d: &Dialog) -> Result, &'static str> { let Some(ids) = d.fields.get("_targets").cloned() else { return Ok(typing_frame_ids(app)) }; let active = app.session.active().map(|doc| doc.identity_epoch); if d.fields.get("_targetsDoc").and_then(Value::as_u64) != active { return Err("the document the dialog opened on is no longer the active one"); } + if d.fields.get("_targetsRevision").and_then(Value::as_u64) != app.session.active().map(base_revision) { + return Err("the document changed after the dialog opened"); + } Ok(Some(ids)) } @@ -4258,7 +4338,11 @@ pub fn cancel(app: &mut DesignApp) { } crate::new_document::end_preview(app); if d.as_ref().is_some_and(|d| d.fields.contains_key(PREVIEWED)) { - app.session.cancel_interaction(); + // Text Frame Options names the document its preview is in. + match d.as_ref().and_then(|d| d.fields.get(PREVIEW_DOC)).and_then(Value::as_u64) { + Some(uid) => app.session.cancel_interaction_of(uid), + None => app.session.cancel_interaction(), + } } app.cancel_pdf_import(); if let Some(d) = d @@ -8978,6 +9062,8 @@ fn toc_dialog(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { } /// The params a previewing dialog shows on the page (its interaction is open while it is set). const PREVIEWED: &str = "_previewed"; +/// The uid of the document a Text Frame Options preview is shown in. +const PREVIEW_DOC: &str = "_previewDoc"; /// Edit › Step and Repeat, as in InDesign: Repeat (Count, or Rows and Columns with Create as a /// grid), Offset (Vertical, Horizontal, in the document's ruler units) and Preview, which shows From 2aa93ea807aa7b0da2c95c342d6270ee4981c4e0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 11:10:13 -0800 Subject: [PATCH 1045/1349] Text: Text Frame Options from the Type tool show the inset of the frames they change The one Inset field of a non-rectangular frame and the inset link now follow the frames the dialog changes: the frame that shows the caret, or every frame holding selected text. Before, a caret with no stored frame showed four sides for an oval frame, and the link checked every frame of the story. --- crates/ui-egui/src/dialogs.rs | 47 ++++++++++++++++++----------- crates/ui-egui/src/dialogs/tests.rs | 6 ++-- 2 files changed, 33 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index ab53948f9..7b5ff93ca 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -589,6 +589,30 @@ mod color_theme_tests { assert_eq!((inset(&app, a), inset(&app, b)), (24.0, 0.0)); } + /// With the caret in the oval second frame of a thread whose first frame has uneven insets, the + /// dialog shows the one Inset of the oval and keeps the link on: both follow the frame it changes. + #[test] + fn text_frame_options_from_the_type_tool_show_the_inset_of_the_caret_frame() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let text = (0..40).map(|i| format!("Line {i} of the threaded story.")).collect::>().join(" "); + let a = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": text})).unwrap(); + let b = + app.run("frame.create", json!({"rect": [36, 200, 300, 700], "shape": "ellipse", "content": "text", "text": "", "caret": false})).unwrap(); + let (a, b, sid) = + (designcraft_doc::ItemId(a["id"].as_u64().unwrap()), designcraft_doc::ItemId(b["id"].as_u64().unwrap()), a["story"].as_u64().unwrap()); + app.run("text.thread", json!({"from": a.0, "to": b.0})).unwrap(); + app.run("object.textFrameOptions", json!({"ids": [a.0], "inset": [1, 2, 3, 4]})).unwrap(); + let cs = designcraft_compose::compose_story(&app.session.doc().unwrap().doc, designcraft_doc::StoryId(sid), &Default::default()); + let caret = cs.frame(b).unwrap().range.start + 2; + app.run("text.select", json!({"story": sid, "anchor": caret})).unwrap(); + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(&app, &mut d); + assert_eq!(d.fields.get("_targets"), Some(&json!([b.0]))); + assert!(d.b("_shaped"), "the oval shows one Inset"); + assert!(d.b("insetLinked"), "the first frame's uneven sides do not turn the link off"); + } + /// A preview shown in one document goes when OK is refused, or Cancel is chosen, after another /// document became active. #[test] @@ -1105,25 +1129,17 @@ fn selected_frame_options(app: &DesignApp) -> Option bool { let Some(st) = app.session.active() else { return true; }; - let mut ids = st.selection.items.clone(); - if ids.is_empty() - && let Some(t) = st.selection.text - { - ids = match t.frame { - Some(f) => vec![f], - None => st.doc.story(t.story).map(|s| s.frames.clone()).unwrap_or_default(), - }; - } + let ids = designcraft_engine::cmd::text_frame_options_frames(&app.session); ids.iter().filter_map(|id| st.doc.item(*id)?.text_frame()).all(|t| t.options.inset.iter().all(|v| (v - t.options.inset[0]).abs() < 1e-9)) } -/// Whether every selected text frame (the selected items, or the frame of the caret) has an -/// outline that is not its own axis-aligned rectangle: an oval, a polygon, rounded or other corner +/// Whether every text frame the dialog changes (the selected items, else the frame that shows the +/// caret or every frame holding selected text) has an outline that is not its own axis-aligned rectangle: an oval, a polygon, rounded or other corner /// options. Its text keeps one inset from the outline, as compose sets it; type on a path doesn't. /// A selection that mixes them with rectangular frames shows the four sides, so each frame keeps /// the sides left as shown. @@ -1137,11 +1153,8 @@ fn selected_frame_is_shaped(app: &DesignApp) -> bool { let bp = if item.corners.is_none() { item.path.to_bezpath() } else { designcraft_geom::corners::apply(&item.path, &item.corners) }; Some(designcraft_compose::FrameOutline::new(&bp, 0.0).is_some()) }; - if st.selection.items.is_empty() { - let Some(fid) = st.selection.text.and_then(|t| t.frame) else { return false }; - return shaped(fid).unwrap_or(false); - } - st.selection.items.iter().all(|&fid| shaped(fid).unwrap_or(false)) + let ids = designcraft_engine::cmd::text_frame_options_frames(&app.session); + !ids.is_empty() && ids.iter().all(|&fid| shaped(fid).unwrap_or(false)) } /// Object › Text Frame Options shows the selected frame's options. `_shown` keeps what it showed, diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 9f66fb4f8..0bad3ce0e 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1831,15 +1831,15 @@ fn text_frame_options_link_the_insets_only_when_every_selected_frame_has_even_si assert!(!seeded(&app).b("insetLinked")); app.run("text.select", json!({"story": other_even_story, "anchor": 0, "focus": 0})).unwrap(); assert!(seeded(&app).b("insetLinked")); - // A story threaded on into the uneven frame: a caret placed in the first frame changes only - // that frame, and a caret with no frame changes every frame of the story. + // A story threaded on into the uneven frame: a caret placed in the first frame, or a caret + // with no stored frame drawn in the first frame, changes only that frame. let (first, story) = frame(&mut app, [300, 300, 500, 500], json!(6)); let (last, _) = frame(&mut app, [300, 520, 500, 700], json!([1, 2, 3, 4])); app.run("text.thread", json!({"from": first.0, "to": last.0})).unwrap(); app.run("text.placeCaret", json!({"frame": first.0, "point": [310, 310]})).unwrap(); assert!(seeded(&app).b("insetLinked")); app.run("text.select", json!({"story": story, "anchor": 0, "focus": 0})).unwrap(); - assert!(!seeded(&app).b("insetLinked")); + assert!(seeded(&app).b("insetLinked")); } #[test] From b9894b47c5131ab47c996e507fe2083f62525acf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 11:14:54 -0800 Subject: [PATCH 1046/1349] Images: decode the images in view together before drawing A render decoded each placed image that was not cached yet while drawing it, one after another, so page thumbnails, image exports and the first canvas frame of a page with several large photos took the sum of their decodes. Before drawing, the renderer now lists the images in view (with the same culling as drawing: hidden items and layers, nonprinting items, items out of view, PDF layer choices) and decodes the uncached ones on up to eight threads, with the mip levels they are drawn at. It leaves the work to the render when fewer than two images need decoding, on the web, and in Fast display. The images it decodes stay within what the cache keeps, sized by their pixels (PDF pages and SVGs at the size they are rasterized at), and decodes in flight together stay within half the cache budget. --- ROADMAP.md | 1 + crates/render/src/decode.rs | 34 ++++- crates/render/src/draw.rs | 151 +++++++++++++++------- crates/render/src/driver.rs | 33 +++-- crates/render/src/images.rs | 248 +++++++++++++++++++++++++++++++++++- crates/render/src/stroke.rs | 45 ++++--- crates/render/src/tests.rs | 86 +++++++++++++ 7 files changed, 517 insertions(+), 81 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 1ed2064a0..00836637e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -388,6 +388,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log +- **2026-11-12** · A render decodes the placed images in view that are not cached yet on several threads before it draws, instead of one after another while drawing. Page thumbnails, image exports and the first canvas frame of a page with six 24 MP photos take about 1.2 s instead of 2.8 s. No readiness percentage change. - **2026-11-12** · An edit of a long threaded story composes the paragraphs it can change and copies the other lines from the composition before the edit; every typed character composed the whole story. In a 240-paragraph story a typed character composes 3 paragraphs (240 before). An edit that moves lines into other frames composes on until a paragraph starts in the same frame and place as before, or to the story's end, and stories with footnotes, tables, anchored objects, balanced columns or keep options that move lines are composed whole. No readiness percentage change. - **2026-11-12** · Type shortcuts: Justify All Lines ⇧⌘F, Insert White Space › Em Space ⇧⌘M and En Space ⇧⌘N (shown in the menu, enabled at an insertion point), Paragraph Rules… ⌥⌘J (shown in the Paragraph panel menu). On the Mac a menu-bar insert (Em/En Space, Current Page Number) no longer types into the document while a text field has focus, a dialog or Quick Apply is open, or an input method is composing. An alignment the paragraphs already have records no undo step (#1138). No readiness percentage change. - **2026-11-12** · The status bar's preflight count and the Preflight panel take their issues from a check on a background worker, which checks the newest state of the document and shows the issues last found meanwhile. Moving or resizing a frame and typing no longer wait for a check of the whole document on every drag step and keystroke. No readiness percentage change. diff --git a/crates/render/src/decode.rs b/crates/render/src/decode.rs index 135dbf108..5668a205f 100644 --- a/crates/render/src/decode.rs +++ b/crates/render/src/decode.rs @@ -6,16 +6,46 @@ pub fn decode_pixmap(bytes: &[u8]) -> Option { decode_pixmap_page(bytes, 0) } +/// Longer side (pixels) PDF pages and SVGs are drawn at by [`decode_pixmap_page`]. +const VECTOR_SIDE: u32 = 3000; + +/// About how many bytes [`decode_pixmap_page`] of `bytes` takes, with its smaller levels (a third +/// more): PDF pages and SVGs at [`VECTOR_SIDE`] pixels on the longer side, an EPS without a +/// preview at up to 8 pixels per point and 4000 pixels on the longer side (as its PostScript is +/// drawn), other images and previews at their pixel size. 0 when the size can't be read. +pub(crate) fn decoded_bytes(bytes: &[u8], page: u32) -> usize { + let drawn = |(w, h): (f64, f64), side: f64, most: f64| { + let k = (side / w.max(h).max(1e-3)).min(most); + ((w * k).round().max(1.0), (h * k).round().max(1.0)) + }; + let size = if designcraft_images::is_eps(bytes) { + image_size(bytes).zip(designcraft_images::eps_size(bytes)).map(|((pw, ph), (w, h))| { + // Without a preview, the pixel size is the 2 pixels per point placeholder's. + let placeholder = ((w * 2.0).round().clamp(2.0, 4000.0), (h * 2.0).round().clamp(2.0, 4000.0)); + let px = (pw as f64, ph as f64); + if px == placeholder { drawn((w, h), 4000.0, 8.0) } else { px } + }) + } else if is_pdf(bytes) { + // As render_pdf_page scales: at most 8 times the page size. + pdf_page_size(bytes, page as usize).map(|s| drawn(s, VECTOR_SIDE as f64, 8.0)) + } else if designcraft_images::is_svg(bytes) { + designcraft_images::natural_size(bytes).map(|s| drawn(s, VECTOR_SIDE as f64, f64::INFINITY)) + } else { + image_size(bytes).map(|(w, h)| (w as f64, h as f64)) + }; + size.map_or(0, |(w, h)| (w * h * 16.0 / 3.0) as usize) +} + /// [`decode_pixmap`] for page `page` of a PDF (other formats have one page). pub fn decode_pixmap_page(bytes: &[u8], page: u32) -> Option { // Documents retain the EPS source; only display its TIFF preview or placeholder. let proxy = if designcraft_images::is_eps(bytes) { Some(designcraft_images::eps_proxy(bytes)?.0) } else { None }; let bytes = proxy.as_deref().unwrap_or(bytes); if is_pdf(bytes) { - return render_pdf_page(bytes, page as usize, 3000); + return render_pdf_page(bytes, page as usize, VECTOR_SIDE); } if designcraft_images::is_svg(bytes) { - let (px, w, h) = designcraft_images::render_svg(bytes, 3000)?; + let (px, w, h) = designcraft_images::render_svg(bytes, VECTOR_SIDE)?; let data = px.as_chunks::<4>().0.iter().map(|p| vello_cpu::color::PremulRgba8 { r: p[0], g: p[1], b: p[2], a: p[3] }).collect(); return Some(Pixmap::from_parts(data, w.min(u16::MAX as u32) as u16, h.min(u16::MAX as u32) as u16)); } diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 625338eb0..add9daa87 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -1,8 +1,9 @@ use super::color::{HIDDEN_LAYERS, blend_mode, color_of, overprints, rect_overlaps, screen_color, set_fill_paint, spread_blends}; -use super::types::{DisplayQuality, Frame}; +use super::stroke::image_want; +use super::types::{DisplayQuality, Frame, RenderOptions}; use super::{ - Affine, Arc, BezPath, BlendMode, Compose, ComposedStory, Content, DcBlend, Item, Mix, RenderContext, Renderer, Shape, ShownOn, SpreadRef, - StoryId, Vec2, blendspace, corners, fx, grid, kurbo, peniko, + Affine, Arc, BezPath, BlendMode, Compose, ComposedStory, Content, DcBlend, Document, Item, Mix, RenderContext, Renderer, Shape, ShownOn, + SpreadRef, StoryId, Vec2, blendspace, corners, fx, grid, images, kurbo, peniko, }; /// An item's fill under its content; an overprinting fill multiplies into what is beneath. @@ -25,6 +26,104 @@ fn draw_body_fill(ctx: &mut RenderContext, f: &Frame, it: &Item, bp: &BezPath, x } } +/// Each item spread `sr` draws at the top level, in drawing order (layers back to front; within +/// each layer parent items first), with its transform to the spread and where it shows. +fn each_top_item(doc: &Document, sr: SpreadRef, opts: &RenderOptions, mut visit: impl FnMut(&Item, Affine, ShownOn)) { + let Some(sp) = doc.spread(sr) else { return }; + for layer in doc.layers.iter().rev() { + if !layer.visible || opts.printing_only && !layer.printable { + continue; + } + // Document pages show their parent and its bases; a parent spread shows its bases. + let first = match sr { + SpreadRef::Doc(si) => Some(doc.first_page_of_spread(si)), + SpreadRef::Parent(_) => None, + }; + // Base items compose for where they show: the document page, or this parent spread. + let shown_on = |pi: usize| match (sr, first) { + (SpreadRef::Parent(p), _) => ShownOn::Parent(p), + (_, Some(a)) => ShownOn::Page(a + pi), + (_, None) => ShownOn::Own, + }; + for (pi, page) in sp.pages.iter().enumerate() { + if !page.show_parent_items { + continue; + } + let chain = doc.shown_parent_pages(sr, pi); + // This page's overrides and those of every parent page behind it (#1469). + let overridden = doc.overridden_parent_items(sr, pi); + for (ppi, ppage) in chain { + let Some(parent) = doc.parents.get(ppi) else { continue }; + let Some(ppg) = parent.pages.get(ppage) else { continue }; + let dx = page.x - ppg.x; + for it in &parent.items { + if it.layer != layer.id || overridden.contains(&it.id) { + continue; + } + // Parent items belong to the parent page they sit on. + if parent.page_at_x(it.bounds().center().x) != Some(ppage) && parent.pages.len() > 1 { + continue; + } + visit(it, Affine::translate((dx, 0.0)), shown_on(pi)); + } + } + } + for it in &sp.items { + if it.layer == layer.id { + visit(it, Affine::IDENTITY, ShownOn::Own); + } + } + } +} + +/// The placed images drawing spread `sr` in frame `f` takes from the image cache (see +/// [`images::warm`]), with the culling [`Renderer::draw_item`] applies. Images inside text (inline +/// and anchored objects) are left to the render. +pub(crate) fn wanted_images(f: &Frame, sr: SpreadRef, out: &mut Vec) { + // Fast display draws grey boxes for images. + if f.opts.quality == DisplayQuality::Fast { + return; + } + each_top_item(f.doc, sr, f.opts, |it, parent, _| wanted_in(f, it, parent, 0, out)); +} + +fn wanted_in(f: &Frame, it: &Item, parent: Affine, depth: usize, out: &mut Vec) { + // As deep as draw_item draws. + if depth >= 64 || it.hidden || f.opts.hidden.contains(&it.id) || f.opts.printing_only && it.nonprinting { + return; + } + let xf = parent * it.xf; + if !it.children().is_empty() && !it.has_nested_items() { + for c in it.shown_children() { + wanted_in(f, c, xf, depth + 1, out); + } + return; + } + let vb = xf.transform_rect_bbox(it.inner_bounds()).inflate(it.stroke.extent() + 2.0, it.stroke.extent() + 2.0); + let fx_outset = if it.effects.any() && f.opts.quality != DisplayQuality::Fast { fx::outset(it) } else { 0.0 }; + if !rect_overlaps(vb.inflate(fx_outset, fx_outset), f.visible) { + return; + } + match &it.content { + Content::Graphic(g) => { + let g = &if it.media.is_some() { it.drawn_graphic(&f.doc.assets).unwrap_or_else(|| g.clone()) } else { g.clone() }; + let Some(asset) = f.doc.assets.get(&g.asset) else { return }; + let hidden = it.has_pdf_layer_override().then(|| it.pdf_hidden_layers.clone()); + let previous = HIDDEN_LAYERS.with(|h| h.replace(hidden)); + if let Some((want, ..)) = image_want(f, asset, g, xf) { + out.push(want); + } + HIDDEN_LAYERS.with(|h| h.replace(previous)); + } + Content::Group { items } if it.has_nested_items() => { + for c in items { + wanted_in(f, c, xf, depth + 1, out); + } + } + _ => {} + } +} + impl Renderer { pub(crate) fn draw_spread(&mut self, ctx: &mut RenderContext, f: &Frame, sr: SpreadRef) { let doc = f.doc; @@ -70,51 +169,7 @@ impl Renderer { if isolate { ctx.push_layer(None, None, None, None, None); } - // Layers back to front; within each layer parent items first. - for layer in doc.layers.iter().rev() { - if !layer.visible || f.opts.printing_only && !layer.printable { - continue; - } - // Document pages show their parent and its bases; a parent spread shows its bases. - let first = match sr { - SpreadRef::Doc(si) => Some(doc.first_page_of_spread(si)), - SpreadRef::Parent(_) => None, - }; - // Base items compose for where they show: the document page, or this parent spread. - let shown_on = |pi: usize| match (sr, first) { - (SpreadRef::Parent(p), _) => ShownOn::Parent(p), - (_, Some(a)) => ShownOn::Page(a + pi), - (_, None) => ShownOn::Own, - }; - for (pi, page) in sp.pages.iter().enumerate() { - if !page.show_parent_items { - continue; - } - let chain = doc.shown_parent_pages(sr, pi); - // This page's overrides and those of every parent page behind it (#1469). - let overridden = doc.overridden_parent_items(sr, pi); - for (ppi, ppage) in chain { - let Some(parent) = doc.parents.get(ppi) else { continue }; - let Some(ppg) = parent.pages.get(ppage) else { continue }; - let dx = page.x - ppg.x; - for it in &parent.items { - if it.layer != layer.id || overridden.contains(&it.id) { - continue; - } - // Parent items belong to the parent page they sit on. - if parent.page_at_x(it.bounds().center().x) != Some(ppage) && parent.pages.len() > 1 { - continue; - } - self.draw_item(ctx, f, it, Affine::translate((dx, 0.0)), shown_on(pi)); - } - } - } - for it in &sp.items { - if it.layer == layer.id { - self.draw_item(ctx, f, it, Affine::IDENTITY, ShownOn::Own); - } - } - } + each_top_item(doc, sr, f.opts, |it, parent, page| self.draw_item(ctx, f, it, parent, page)); if isolate { ctx.pop_layer(); } diff --git a/crates/render/src/driver.rs b/crates/render/src/driver.rs index c837e3686..e217def45 100644 --- a/crates/render/src/driver.rs +++ b/crates/render/src/driver.rs @@ -1,8 +1,10 @@ use super::color::{PLATE, RICH_BLACK, blend_space_view, rect_overlaps}; use super::decode::now; +use super::draw::wanted_images; use super::types::{Frame, FrameStats, MAX_PAGE_PIXELS, MAX_SIDE, Placed, RenderOptions, Rendered, default_threads}; use super::{ - Affine, Cache, Document, HashMap, PageSide, Rect, RenderContext, Renderer, Resources, SpreadRef, Vec2, blendspace, kurbo, peniko, text, vello_cpu, + Affine, Cache, Document, HashMap, PageSide, Rect, RenderContext, Renderer, Resources, SpreadRef, Vec2, blendspace, images, kurbo, peniko, text, + vello_cpu, }; impl Renderer { @@ -100,17 +102,26 @@ impl Renderer { } let px = 1.0 / view.determinant().abs().sqrt().max(1e-12); let canvas_visible = view.inverse().transform_rect_bbox(Rect::new(0.0, 0.0, w as f64, h as f64)); - for pl in spreads { - let Some(sp) = doc.spread(pl.spread) else { continue }; - let sview = view * pl.xf; - let visible = pl.xf.inverse().transform_rect_bbox(canvas_visible); - let bounds = sp.bounds(); - // Cull spreads far outside the viewport (pasteboard items may extend; allow a margin). - if !rect_overlaps(bounds.inflate(2000.0, 2000.0), visible) { - continue; + let frames: Vec<(Frame, SpreadRef)> = spreads + .iter() + .filter_map(|pl| { + let sp = doc.spread(pl.spread)?; + let visible = pl.xf.inverse().transform_rect_bbox(canvas_visible); + // Cull spreads far outside the viewport (pasteboard items may extend; allow a margin). + rect_overlaps(sp.bounds().inflate(2000.0, 2000.0), visible) + .then_some((Frame { doc, cache, view: view * pl.xf, visible, px, opts, mt }, pl.spread)) + }) + .collect(); + // Decode the images in view that aren't cached yet together, before drawing them. + if images::can_warm() { + let mut wanted = Vec::new(); + for (f, sr) in &frames { + wanted_images(f, *sr, &mut wanted); } - let f = Frame { doc, cache, view: sview, visible, px, opts, mt }; - self.draw_spread(&mut ctx, &f, pl.spread); + images::warm(wanted); + } + for (f, sr) in &frames { + self.draw_spread(&mut ctx, f, *sr); } ctx.flush(); // Render straight into the returned buffer (no extra copy of the frame). diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 37606097d..ee0d917ba 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -6,10 +6,12 @@ //! are evicted beyond a memory budget; at most `MAX_BAD` failed assets are remembered. use std::collections::HashMap; -use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex}; use vello_cpu::Pixmap; +use crate::decode::decoded_bytes; use crate::{decode_pixmap_page, halve}; /// Decoded pixels kept (bytes). @@ -114,7 +116,10 @@ pub fn decoded(bytes: &Arc>, page: u32) -> Option> { return None; } // Decode outside the lock: other threads keep drawing cached images meanwhile. - match decode_pixmap_page(bytes, page) { + let pm = decode_pixmap_page(bytes, page); + #[cfg(test)] + DECODED_ON.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push((id, std::thread::current().id())); + match pm { Some(pm) => { let pm = Arc::new(pm); store(bytes, page, 0, pm.clone()); @@ -149,6 +154,160 @@ pub fn mip(bytes: &Arc>, page: u32, width_pt: f64, on_screen: f64) -> Op Some(pm) } +/// The decodes [`decoded`] ran: the address of the encoded bytes and the thread. +#[cfg(test)] +pub(crate) static DECODED_ON: Mutex> = Mutex::new(Vec::new()); + +/// A placed image a render draws, as [`mip`] takes it: the encoded bytes, the PDF page, the +/// width (points) and the device pixels per point. +pub(crate) struct Want { + pub bytes: Arc>, + pub page: u32, + pub width_pt: f64, + pub on_screen: f64, +} + +/// Threads [`warm`] decodes on (1 on the web, which has none). +fn workers() -> usize { + #[cfg(target_arch = "wasm32")] + { + 1 + } + #[cfg(not(target_arch = "wasm32"))] + { + std::thread::available_parallelism().map_or(2, std::num::NonZero::get).clamp(2, 8) + } +} + +/// Whether [`warm`] can decode on several threads here. +pub(crate) fn can_warm() -> bool { + workers() >= 2 +} + +/// Whether a decode of about `size` bytes may start while decodes of `in_flight` bytes run: when +/// none run, or when together they take at most half the budget. +fn admits(in_flight: usize, size: usize) -> bool { + in_flight == 0 || in_flight.saturating_add(size) <= BUDGET / 2 +} + +/// Bytes decoding at once and the most there were, with the signal that some finished. +type Gate = (Mutex<(usize, usize)>, Condvar); + +/// Takes a finished decode's bytes off its [`Gate`] when dropped. +struct Release<'a>(&'a Gate, usize); + +impl Drop for Release<'_> { + fn drop(&mut self) { + let mut g = self.0.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + g.0 = g.0.saturating_sub(self.1); + drop(g); + self.0.1.notify_all(); + } +} + +/// Decode the images in `wants` that are not cached yet on several threads at once, with the +/// mip levels they are drawn at, so the render that draws them next finds them cached instead +/// of decoding them one after another. Does nothing when fewer than two images need decoding. +/// The images in view that are cached count against the cache budget first; a new image that +/// would take the total past what the cache keeps (by its pixel size) is left to the render. +/// Decodes wait while those in flight together would take more than half the budget. Returns +/// the most bytes (estimated) that were decoding at once. +pub(crate) fn warm(wants: Vec) -> usize { + let workers = workers(); + if workers < 2 { + return 0; + } + // What is drawn of each asset and page, in drawing order. + let mut assets: Vec<((usize, u32), Vec)> = Vec::new(); + let mut index: HashMap<(usize, u32), usize> = HashMap::new(); + for w in wants { + let key = (Arc::as_ptr(&w.bytes) as usize, w.page); + match index.get(&key).and_then(|&i| assets.get_mut(i)) { + Some(a) => a.1.push(w), + None => { + index.insert(key, assets.len()); + assets.push((key, vec![w])); + } + } + } + // The bytes each asset in view holds in the cache, when it is cached or failed, and the bytes + // of everything else cached. Its levels become the most recently used, so the stores below + // evict other images first. + let (held, others) = with(|c| { + c.clock += 1; + let clock = c.clock; + let mut held: HashMap<(usize, u32), usize> = HashMap::new(); + for (k, e) in c.map.iter_mut() { + if index.contains_key(&(k.0, k.1)) { + e.stamp = clock; + *held.entry((k.0, k.1)).or_default() += size_of(&e.pm); + } + } + let in_view = held.values().sum::(); + // Smaller levels alone don't make an asset cached. + held.retain(|k, _| c.map.contains_key(&(k.0, k.1, 0))); + for k in index.keys() { + if c.bad.contains_key(k) { + held.entry(*k).or_default(); + } + } + (held, c.bytes.saturating_sub(in_view)) + }); + // One image to decode gains nothing from threads (and is not worth sizing). + if assets.iter().filter(|(key, _)| !held.contains_key(key)).count() < 2 { + return 0; + } + let mut pixels = held.values().fold(0usize, |n, b| n.saturating_add(*b)); + let mut jobs: Vec<(usize, Vec)> = Vec::new(); + for (key, wanted) in assets { + if held.contains_key(&key) { + continue; + } + let size = wanted.first().map_or(0, |w| decoded_bytes(&w.bytes, w.page)); + // A store past the budget evicts down to three quarters of it: the images in view must + // fit in that, unless they and the rest fit in the budget. + let total = pixels.saturating_add(size); + if total > BUDGET * 3 / 4 && others.saturating_add(total) > BUDGET { + continue; + } + pixels = total; + jobs.push((size, wanted)); + } + if jobs.len() < 2 { + return 0; + } + // While it converts the pixels, a decode holds buffers of about its size besides the cache: + // a decode waits while those in flight would take it past half the budget (one always runs). + let gate: Gate = (Mutex::new((0, 0)), Condvar::new()); + let lock = || gate.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let next = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..workers.min(jobs.len()) { + let work = || { + while let Some((size, job)) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { + let mut g = lock(); + while !admits(g.0, *size) { + g = gate.1.wait(g).unwrap_or_else(std::sync::PoisonError::into_inner); + } + g.0 += size; + g.1 = g.1.max(g.0); + drop(g); + // Released even if the decode panics, so no other decode waits forever. + let _release = Release(&gate, *size); + for w in job { + let _ = mip(&w.bytes, w.page, w.width_pt, w.on_screen); + } + } + }; + // A thread that can't start leaves its share to the others, or to the render. + if std::thread::Builder::new().name("image decode".into()).spawn_scoped(s, work).is_err() { + break; + } + } + }); + gate.0.into_inner().unwrap_or_else(std::sync::PoisonError::into_inner).1 +} + /// Drop every decoded image. pub fn clear() { with(|c| { @@ -176,4 +335,89 @@ mod tests { let last = &buffers[MAX_BAD + 9]; assert!(c.bad.contains_key(&(Arc::as_ptr(last) as usize, 0))); } + + fn png(side: u32, value: u8) -> Arc> { + let mut out = Vec::new(); + let img = image::RgbaImage::from_pixel(side, side, image::Rgba([value, 0, 0, 255])); + img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + Arc::new(out) + } + + fn want(bytes: &Arc>) -> Want { + Want { bytes: bytes.clone(), page: 0, width_pt: 100.0, on_screen: 1.0 } + } + + /// A PSD header claiming `side` pixels square (its pixels don't decode). + fn psd(side: u32) -> Arc> { + let mut psd = b"8BPS".to_vec(); + psd.resize(26, 0); + psd[14..18].copy_from_slice(&side.to_be_bytes()); + psd[18..22].copy_from_slice(&side.to_be_bytes()); + Arc::new(psd) + } + + /// Where the decode log ends now. Taken after the test's images are made: while they live, + /// no other buffer has their address, so later entries with it are theirs. + fn mark() -> usize { + DECODED_ON.lock().unwrap().len() + } + + /// The threads that decoded `bytes` after `since`. + fn decoders(bytes: &Arc>, since: usize) -> Vec { + let id = Arc::as_ptr(bytes) as usize; + DECODED_ON.lock().unwrap().iter().skip(since).filter(|(a, _)| *a == id).map(|(_, t)| *t).collect() + } + + #[test] + fn warm_decodes_several_images_off_the_calling_thread() { + let images: Vec<_> = (0..3u8).map(|i| png(8, 40 + i)).collect(); + let since = mark(); + // The same image drawn at two sizes is one decode. + let mut wants: Vec = images.iter().map(want).collect(); + wants.push(Want { on_screen: 0.1, ..want(&images[0]) }); + warm(wants); + let me = std::thread::current().id(); + for img in &images { + let on = decoders(img, since); + assert_eq!(on.len(), 1, "decoded once"); + assert_ne!(on[0], me, "decoded on a worker"); + } + } + + #[test] + fn warm_leaves_one_image_or_an_over_budget_one_to_the_render() { + // A header claiming 100,000 pixels square is far past the budget. + let (one, huge, a, b, c) = (png(8, 7), psd(100_000), png(8, 9), png(8, 11), png(8, 13)); + let since = mark(); + warm(vec![want(&one)]); + assert!(decoders(&one, since).is_empty(), "one image: no threads"); + // The huge one, first or not, is left to the render; the small images beside it are + // decoded ahead. + warm(vec![want(&huge), want(&a), want(&b)]); + assert!(decoders(&huge, since).is_empty(), "over budget: not decoded ahead"); + assert_eq!((decoders(&a, since).len(), decoders(&b, since).len()), (1, 1)); + // With the huge one and a single small image, nothing is left to do together. + warm(vec![want(&c), want(&huge)]); + assert!(decoders(&c, since).is_empty() && decoders(&huge, since).is_empty()); + } + + #[test] + fn warm_decodes_large_images_one_at_a_time() { + // Two 7,000 pixel square images fit the budget together, but decoding both at once would + // take more than half of it; the small image still decodes beside them. + let (d, e, small) = (psd(7000), psd(7000), png(8, 15)); + let since = mark(); + let large = decoded_bytes(&d, 0); + assert!(large > BUDGET / 4 && 2 * large <= BUDGET * 3 / 4); + assert!(admits(0, large) && !admits(large, large) && admits(large, decoded_bytes(&small, 0))); + assert!(admits(0, usize::MAX), "an image over half the budget still decodes alone"); + let peak = warm(vec![want(&d), want(&e), want(&small)]); + assert!(peak <= BUDGET / 2, "{peak} bytes decoding at once"); + assert!(peak >= large, "the large images were decoded ahead"); + let me = std::thread::current().id(); + for img in [&d, &e, &small] { + let on = decoders(img, since); + assert!(on.len() == 1 && on[0] != me); + } + } } diff --git a/crates/render/src/stroke.rs b/crates/render/src/stroke.rs index a63dd44a3..a10df2da2 100644 --- a/crates/render/src/stroke.rs +++ b/crates/render/src/stroke.rs @@ -6,6 +6,30 @@ use super::{ pdf_layers, peniko, vello_cpu, }; +/// The pixels drawing placed graphic `g` takes from the image cache, the page rectangle they +/// cover in graphic space and that page's height (points). `None` for video and sound, Fast +/// display and a PDF whose hidden layers can't be applied (none of these draw image pixels). +pub(crate) fn image_want(f: &Frame, asset: &designcraft_doc::Asset, g: &designcraft_doc::Graphic, xf: Affine) -> Option<(images::Want, Rect, f64)> { + if designcraft_doc::media_kind(&asset.mime).is_some() || f.opts.quality == DisplayQuality::Fast { + return None; + } + // Pick a mip level close to the on-screen size (Typical: a 72 ppi proxy). + let on_screen = (f.view * xf * g.xf).determinant().abs().sqrt(); + let on_screen = if f.opts.quality == DisplayQuality::Typical { on_screen.min(1.0) } else { on_screen }; + let hidden = HIDDEN_LAYERS.with(|h| h.borrow().clone()); + let data = match hidden.as_deref().filter(|_| is_pdf(&asset.data)) { + // An explicit choice (including all-on) that cannot be rewritten fails closed: + // stale persisted/relinked choices must not reveal hidden source content. + Some(hidden) => pdf_layers::layered(&asset.data, hidden)?, + None => asset.data.clone(), + }; + // A placed PDF cropped to a box: the whole page, placed so that the box spans graphic space. + let [l, t, r, b] = shown_box(asset).unwrap_or([0.0, 0.0, 1.0, 1.0]); + let (page_w, page_h) = (g.size.0 / (r - l), g.size.1 / (b - t)); + let page = Rect::new(-l * page_w, -t * page_h, (1.0 - l) * page_w, (1.0 - t) * page_h); + Some((images::Want { bytes: data, page: asset.page, width_pt: page_w, on_screen }, page, page_h)) +} + /// `stroke` as round dots `weight` wide, one every `2 × weight`. Kurbo's stroker drops /// zero-length dashes, so each dot is a dash a hair long, centred where the zero-length dash /// would be (so the path's ends get dots too). @@ -170,24 +194,9 @@ impl Renderer { ctx.fill_rect(&Rect::new(0.0, 0.0, g.size.0, g.size.1)); return; } - // Pick a mip level close to the on-screen size (Typical: a 72 ppi proxy). - let on_screen = (f.view * xf * g.xf).determinant().abs().sqrt(); - let on_screen = if f.opts.quality == DisplayQuality::Typical { on_screen.min(1.0) } else { on_screen }; - let hidden = HIDDEN_LAYERS.with(|h| h.borrow().clone()); - let data = match hidden.as_deref().filter(|_| is_pdf(&asset.data)) { - // An explicit choice (including all-on) that cannot be rewritten fails closed: - // stale persisted/relinked choices must not reveal hidden source content. - Some(hidden) => { - let Some(variant) = pdf_layers::layered(&asset.data, hidden) else { return }; - variant - } - None => asset.data.clone(), - }; - // A placed PDF cropped to a box: the whole page, placed so that the box spans graphic space. - let [l, t, r, b] = shown_box(asset).unwrap_or([0.0, 0.0, 1.0, 1.0]); - let (page_w, page_h) = (g.size.0 / (r - l), g.size.1 / (b - t)); - let page = Rect::new(-l * page_w, -t * page_h, (1.0 - l) * page_w, (1.0 - t) * page_h); - let Some(pm) = images::mip(&data, asset.page, page_w, on_screen) else { return }; + let Some((want, page, page_h)) = image_want(f, asset, g, xf) else { return }; + let page_w = want.width_pt; + let Some(pm) = images::mip(&want.bytes, want.page, page_w, want.on_screen) else { return }; // A coloured image is already in the plate's inks (its colours come from `color_of`). let pm = match (colorize::colorized(f.doc, &g.fill, &asset.data, &pm), PLATE.with(std::cell::Cell::get)) { (Some(coloured), _) => coloured, diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 3287ab836..5d4f6a048 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -773,3 +773,89 @@ fn dotted_strokes_draw_every_dot() { let dots = outline.elements().iter().filter(|e| matches!(e, kurbo::PathEl::MoveTo(_))).count(); assert_eq!(dots, 13); } + +/// The size the image cache budgets for a decode is the size the decode has: a PDF page by the +/// pixels it is rasterized at, not by its size in points. +#[test] +fn decode_size_estimates_match_the_decodes() { + let mut png = Vec::new(); + image::RgbaImage::from_pixel(30, 20, image::Rgba([1, 2, 3, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let pdf = one_page_pdf("0 0 1 rg 0 0 100 100 re f"); + for bytes in [&png, &pdf] { + let pm = decode_pixmap_page(bytes, 0).unwrap(); + assert_eq!(decode::decoded_bytes(bytes, 0), pm.width() as usize * pm.height() as usize * 16 / 3); + } + assert_eq!(decode::decoded_bytes(b"not an image", 0), 0); + // An EPS drawn from its PostScript is budgeted at no less than it takes. + let eps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 50\n%%EndComments\n0 0 1 setrgbcolor 0 0 100 50 rectfill\n%%EOF\n"; + let pm = decode_pixmap_page(eps, 0).unwrap(); + let drawn = pm.width() as usize * pm.height() as usize * 16 / 3; + assert!(drawn > 200 * 100 * 16 / 3, "drawn above 2 pixels per point: {}×{}", pm.width(), pm.height()); + assert!(decode::decoded_bytes(eps, 0) >= drawn); +} + +#[test] +fn images_in_view_are_decoded_together_before_drawing() { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + // Place a 4×4 PNG of one red value in `r`; returns its encoded bytes. + let place = |d: &mut Document, r: Rect, red: u8, hidden: bool| { + let mut png = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([red, 0, 0, 255])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let data = Arc::new(png); + let aid = designcraft_doc::AssetId(d.alloc()); + let asset = designcraft_doc::Asset { + id: aid, + name: "red.png".into(), + mime: "image/png".into(), + data: data.clone(), + pixels: Some((4, 4)), + ..Default::default() + }; + d.assets.insert(aid, Arc::new(asset)); + let mut it = Item::new(designcraft_doc::ItemId(d.alloc()), lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(r)); + it.hidden = hidden; + it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic { + layer_options: None, + asset: aid, + size: (r.width(), r.height()), + xf: Affine::translate((r.x0, r.y0)), + clip: None, + auto_fit: Default::default(), + fit_align: 4, + crop: [0.0; 4], + wrap: Default::default(), + fill: Default::default(), + }); + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + data + }; + let shown: Vec<_> = + (0..3).map(|i| place(&mut d, Rect::new(20.0 + 90.0 * i as f64, 20.0, 100.0 + 90.0 * i as f64, 100.0), 200 + i as u8, false)).collect(); + let hidden = place(&mut d, Rect::new(20.0, 150.0, 100.0, 230.0), 10, true); + let outside = place(&mut d, Rect::new(400.0, 600.0, 500.0, 700.0), 20, false); + // Decodes logged from here on with these buffers' addresses are theirs (they live on). + let since = images::DECODED_ON.lock().unwrap().len(); + let cache = Cache::new(); + let mut r = Renderer::new(); + r.threads = 0; + let placed = [Placed { spread: SpreadRef::Doc(0), xf: Affine::IDENTITY }]; + let img = r.render(&d, &cache, &placed, (300, 300), Affine::IDENTITY, &RenderOptions { background: Some([255; 4]), ..Default::default() }); + for i in 0..3u8 { + assert_eq!(img.pixel(60 + 90 * u32::from(i), 60)[..3], [200 + i, 0, 0], "image {i} drawn"); + } + let me = std::thread::current().id(); + let decoded_on = |data: &Arc>| -> Vec { + let id = Arc::as_ptr(data) as usize; + images::DECODED_ON.lock().unwrap().iter().skip(since).filter(|(a, _)| *a == id).map(|(_, t)| *t).collect() + }; + for (i, data) in shown.iter().enumerate() { + let on = decoded_on(data); + assert_eq!(on.len(), 1, "image {i} decoded once"); + assert_ne!(on[0], me, "image {i} decoded ahead, off the render thread"); + } + assert!(decoded_on(&hidden).is_empty(), "a hidden image is not decoded"); + assert!(decoded_on(&outside).is_empty(), "an image out of view is not decoded"); +} From 213f3b75a309b0ad45e087f975800011ee5b494f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 15:43:43 -0500 Subject: [PATCH 1047/1349] Report recovery writes owned by another session --- crates/engine/src/recovery.rs | 37 ++++++++++++++++++++--------- crates/engine/src/recovery/tests.rs | 26 ++++++++++++++++++++ 2 files changed, 52 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index d045b2415..16b1e0ee2 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -886,8 +886,14 @@ pub(crate) fn start_tracked(s: &mut Session, dir: &Path) -> Result { // A write still running for this document already holds a snapshot of it; the next // timer tick catches up with the edits made since. match worker::submit(entry) { - Some(true) => queued += 1, - Some(false) => {} + Some(worker::Submit::Queued) => queued += 1, + Some(worker::Submit::AlreadyQueued) => {} + Some(worker::Submit::Conflict) => { + return Err(crate::EngineError::Other(format!( + "recovery data for document {} is already being written by another session", + document.uid + ))); + } None => { // No thread: write this one here rather than lose the recovery data. let written = write_snapshot(&Snapshot::of(&access, dir, document), || false); @@ -1326,24 +1332,33 @@ mod worker { }) } - /// Queue a document's write. `None`: no writer thread (the caller writes it itself); - /// `Some(false)`: one for this document is still queued or running. - pub(super) fn submit(entry: Snapshot) -> Option { + pub(super) enum Submit { + Queued, + AlreadyQueued, + Conflict, + } + + /// Queue a document's write. `None`: no writer thread (the caller writes it itself). + pub(super) fn submit(entry: Snapshot) -> Option { let w = writer()?; let mut running = w.running.lock().ok()?; let key = (entry.key.clone(), entry.uid); - // A session is writing this document now: this write waits for a later turn. - if w.writing_now.lock().is_ok_and(|now| now.contains_key(&key)) { - return Some(false); + // Another session's save or recovery write owns this destination. Check ownership while + // holding the same reservation locks used to queue or publish writes. + if let Some(owner) = w.writing_now.lock().ok().and_then(|now| now.get(&key).copied()) { + return Some(if owner == entry.owner { Submit::AlreadyQueued } else { Submit::Conflict }); } if let Some(q) = running.get_mut(&key) { // The write in flight was cancelled (the document was saved since), so it holds // nothing to recover: this one follows it, in place of any that was waiting. if w.cancelled.lock().is_ok_and(|cancelled| cancelled.contains(&key)) { + if q.next.as_ref().is_some_and(|next| next.owner != entry.owner) { + return Some(Submit::Conflict); + } q.next = Some(entry); - return Some(true); + return Some(Submit::Queued); } - return Some(false); + return Some(if q.owner == entry.owner { Submit::AlreadyQueued } else { Submit::Conflict }); } running.insert(key.clone(), Queued { owner: entry.owner, dir: entry.dir.clone(), next: None }); // A write is wanted again: whatever cancelled the last one does not apply to this one. @@ -1354,7 +1369,7 @@ mod worker { running.remove(&key); return None; } - Some(true) + Some(Submit::Queued) } } diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index f66d28879..8d28dc8a9 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -705,6 +705,32 @@ fn a_clean_document_leaves_another_sessions_write_queued_behind_its_own() { discard(dir.path(), uid); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_background_recovery_write_reports_another_sessions_held_write() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut first = dirty_session(); + first.recovery_dir = Some(dir.path().to_path_buf()); + let uid = first.docs[0].uid; + let mut second = dirty_session(); + second.recovery_dir = Some(dir.path().to_path_buf()); + second.docs[0].uid = uid; + second.execute("frame.create", &json!({"rect": [20, 20, 60, 60]})).unwrap(); + + let held = testing::hold_next_write(dir.path()); + first.execute("file.recovery.save", &json!({"background": true})).unwrap(); + held.wait_until_held(); + + let err = second.execute("file.recovery.save", &json!({"background": true})).unwrap_err(); + assert!(err.to_string().contains("another session"), "{err}"); + + held.release(); + assert_eq!(finished_writes(&mut first), 1); + assert!(files(dir.path(), uid).0.exists(), "the first session's recovery file remains intact"); + discard(dir.path(), uid); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn a_clean_document_in_another_session_leaves_this_sessions_write_alone() { From b30d39fdec19ade8a1aabcf47237f8c995e3869a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 12:48:41 -0800 Subject: [PATCH 1048/1349] Layers: Duplicate Layer maps copies by the original's anchors and tables object::renumber now gives a story copy's anchors and tables new ids. Duplicate Layer keys each copied anchor by the original anchor's id, so copied cross-references point at the copied paragraph, and pairs copied tables with the originals in order, so objects anchored in table cells keep their live captions. A copy that renumber reports incomplete is refused with the nested-too-deeply error. --- crates/engine/src/cmd/layout/layers.rs | 53 +++++++++++++++++++++----- 1 file changed, 44 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/layout/layers.rs b/crates/engine/src/cmd/layout/layers.rs index cd6e72ee2..6601e11e0 100644 --- a/crates/engine/src/cmd/layout/layers.rs +++ b/crates/engine/src/cmd/layout/layers.rs @@ -86,7 +86,9 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { let Some(sp) = src.spread(r) else { continue }; for it in sp.items.iter().filter(|it| it.layer == id) { let mut copy = Item::clone(it); - super::super::object::renumber(d, &src, &mut copy, &mut stories); + if !super::super::object::renumber(d, &src, &mut copy, &mut stories) { + return Err(bad(ID, "the layer's objects are nested too deeply to copy")); + } map_ids(it, ©, &mut ids); copies.push((r, copy)); } @@ -113,8 +115,10 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { // and those of the other copies point at, and tables with ids of their own, the tables in its cells and notes // included, allocated in story order. let mut anchors = HashMap::new(); + // The copies' own anchors are given ids below, so only the other stories' anchors count as taken. + let copied: HashSet = stories.values().copied().collect(); let mut used = HashSet::new(); - for st in d.stories.values() { + for st in d.stories.values().filter(|st| !copied.contains(&st.id)) { anchor_ids(st, &mut used); } let mut order: Vec<(StoryId, StoryId)> = stories.iter().map(|(old, new)| (*old, *new)).collect(); @@ -125,7 +129,10 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { st.link = Some((stories.get(&parent).copied().unwrap_or(parent), revision)); } st.frames = src.story(*old).map(|o| o.frames.iter().filter_map(|f| ids.get(f).copied()).collect()).unwrap_or_default(); - for (k, a) in (1..).zip(st.anchors.iter_mut()) { + // The copy's anchors may already have new ids: each is keyed by the id of the original's anchor, which the + // copied cross-references still point at. + let originals: Vec = src.story(*old).map(|o| o.anchors.iter().map(|a| a.id).collect()).unwrap_or_default(); + for ((k, a), orig_id) in (1..).zip(st.anchors.iter_mut()).zip(originals) { // `story id << 24 | n`, as anchors are made, or a new id when another anchor has that one or the story id // does not fit. let made = new.0.checked_mul(1 << 24).and_then(|base| base.checked_add(k)).filter(|id| !used.contains(id)); @@ -138,7 +145,7 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { } }, }; - anchors.insert(a.id, id); + anchors.insert(orig_id, id); used.insert(id); Arc::make_mut(a).id = id; } @@ -250,11 +257,10 @@ fn map_anchored(orig: &Story, copy: &Story, ids: &mut HashMap) { for (o, c) in orig.objects.iter().zip(©.objects) { map_ids(&o.item, &c.item, ids); } - for (k, t) in &orig.tables { - if let Some(ct) = copy.tables.get(k) { - for (o, c) in t.cells.iter().zip(&ct.cells) { - map_anchored(&o.text, &c.text, ids); - } + // Copied tables have new ids, given in the order of the old ones, so the two maps list them in the same order. + for (t, ct) in orig.tables.values().zip(copy.tables.values()) { + for (o, c) in t.cells.iter().zip(&ct.cells) { + map_anchored(&o.text, &c.text, ids); } } for (o, c) in orig.notes.iter().chain(&orig.endnotes).zip(copy.notes.iter().chain(©.endnotes)) { @@ -1129,6 +1135,35 @@ mod layer_tests { assert_eq!(s.doc().unwrap().doc.layers, before, "nothing changes"); } + /// An empty group inside 64 others: within the layer's depth check, which counts the objects below a group, but + /// past the limit of the copy, which counts the group itself. + #[test] + fn duplicate_layer_refuses_an_empty_group_at_the_copy_limit() { + use designcraft_doc::{Content, ItemId}; + use std::sync::Arc; + + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let f = s.execute("frame.create", &json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap(); + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let mut it = d.item(ItemId(f)).cloned().unwrap(); + it.content = Content::Group { items: Vec::new() }; + for _ in 0..super::MAX_COPY_DEPTH { + let mut group = it.clone(); + group.id = ItemId(d.alloc()); + group.content = Content::Group { items: vec![Arc::new(it)] }; + it = group; + } + let items = &mut Arc::make_mut(&mut d.spreads[0]).items; + items.retain(|i| i.id.0 != f); + items.push(Arc::new(it)); + let before = s.doc().unwrap().doc.clone(); + let e = s.execute("layer.duplicate", &json!({"id": base})).unwrap_err().to_string(); + assert!(e.contains("too deeply to copy"), "{e}"); + assert_eq!(s.doc().unwrap().doc, before, "nothing changes"); + } + #[test] fn duplicate_layer_detaches_overrides_of_parent_items_on_other_layers() { let mut s = crate::Session::new(); From 6d8f26a6beff4c0c5e63e5acf5b5678baefdd69d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 12:48:49 -0800 Subject: [PATCH 1049/1349] Render: cull a scaled object by its scaled stroke and glow Culling grew an object's box by its unscaled stroke and effect outset, so a view or repaint patch that showed only the outer part of a scaled object's stroke or hardened glow skipped the object. Culling now scales both by the object's largest scale factor, as drawing does. The CMYK ink-pass area grows each object, and each nested child, by its stroke and effect outset under its full transform. --- crates/render/src/blendspace.rs | 45 +++++++++++++++++++++++++++++++-- crates/render/src/draw.rs | 7 +++-- crates/render/src/fx.rs | 44 ++++++++++++++++++++++++++++++++ 3 files changed, 92 insertions(+), 4 deletions(-) diff --git a/crates/render/src/blendspace.rs b/crates/render/src/blendspace.rs index 6096b3419..5dd8232a5 100644 --- a/crates/render/src/blendspace.rs +++ b/crates/render/src/blendspace.rs @@ -371,10 +371,18 @@ impl Renderer { } } // What an object can paint on the spread: its bounds with its (and its children's) - // strokes and effects. + // strokes and effects, which are drawn through each one's transform and grow with it. + fn outset(it: &Item, outer: Affine, o: &mut f64) { + let xf = outer * it.xf; + let scale = crate::fx::max_scale(xf).unwrap_or(1.0); + *o = o.max(crate::fx::outset_scaled(it, scale) + it.stroke.extent() * scale); + for c in it.children() { + outset(c, xf, o); + } + } let reach = |it: &Item| { let mut o: f64 = 0.0; - it.walk(&mut |c| o = o.max(crate::fx::outset(c) + c.stroke.extent())); + outset(it, Affine::IDENTITY, &mut o); it.bounds().inflate(o + 2.0, o + 2.0) }; let items: Vec<(Rect, bool)> = sp.items.iter().filter(|it| visible(it)).map(|it| (reach(it), transparent(it))).collect(); @@ -601,6 +609,39 @@ mod tests { assert_eq!(draw(&doc, &mut renderer).pixels, rgb.pixels); } + /// A hardened outer glow is stroked through the object's transform, and through its group's, + /// so the ink-pass area grows by the scaled growth: the square at 30..60 glows out to -30. + #[test] + fn cmyk_area_holds_a_scaled_objects_glow() { + for nested in [false, true] { + let mut doc = document(); + let mut item = Item::new( + ItemId(doc.alloc()), + doc.default_layer(), + Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(10.0, 10.0, 20.0, 20.0)), + ); + item.fill = Fill::swatch("C=100 M=0 Y=0 K=0"); + let g = &mut item.effects.outer_glow; + (g.on, g.color, g.opacity, g.size, g.spread) = (true, designcraft_color::swatch::BLACK.into(), 1.0, 20.0, 100.0); + if nested { + let mut group = Item::new(ItemId(doc.alloc()), doc.default_layer(), Shape::Group, Default::default()); + group.xf = Affine::scale(3.0); + group.content = Content::Group { items: vec![Arc::new(item)] }; + doc.insert_item(SpreadRef::Doc(0), group, None).unwrap(); + } else { + item.xf = Affine::scale(3.0); + doc.insert_item(SpreadRef::Doc(0), item, None).unwrap(); + } + let cache = Cache::new(); + let opts = RenderOptions::default(); + let f = + Frame { doc: &doc, cache: &cache, view: Affine::IDENTITY, visible: Rect::new(-1e4, -1e4, 1e4, 1e4), px: 1.0, opts: &opts, mt: false }; + let area = Renderer::new().transparent_area(&f, SpreadRef::Doc(0)).unwrap(); + assert!(area.x0 <= -30.0, "nested {nested}: the area {area:?} holds the glow out to -30"); + } + } + #[test] fn cmyk_pass_count_is_constant_and_unchanged_views_are_cached() { let mut doc = document(); diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 625338eb0..dbaa1d1b3 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -179,7 +179,10 @@ impl Renderer { return; } let xf = parent * it.xf; - let vb = xf.transform_rect_bbox(it.inner_bounds()).inflate(it.stroke.extent() + 2.0, it.stroke.extent() + 2.0); + // The stroke and the effects' growth are drawn through `xf`, which stretches them. + let scale = fx::max_scale(xf).unwrap_or(1.0); + let stroke = it.stroke.extent() * scale; + let vb = xf.transform_rect_bbox(it.inner_bounds()).inflate(stroke + 2.0, stroke + 2.0); // A frame with items pasted into it draws like any other object (draw_body: fill, the items // clipped to the frame, stroke), so its effects apply to all of it. if !it.children().is_empty() && !it.has_nested_items() { @@ -193,7 +196,7 @@ impl Renderer { _ => 0.0, }; let effects = it.effects.any() && f.opts.quality != DisplayQuality::Fast; - let fx_outset = if effects { fx::outset(it) } else { 0.0 }; + let fx_outset = if effects { fx::outset_scaled(it, scale) } else { 0.0 }; if !rect_overlaps(vb.inflate(margin + fx_outset, margin + fx_outset), f.visible) { return; } diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index 0fc1ba048..89f193d06 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -1576,4 +1576,48 @@ mod tests { assert!(lum < 200, "{threads} threads: the glow 50 pt left of the scaled square is drawn, luminance {lum}"); } } + + /// Culling measures a scaled item's stroke and hardened glow as they are drawn, through its + /// transform, so a view (or a repaint patch) that shows only that part still draws it. + #[test] + fn a_scaled_items_hard_glow_and_stroke_are_not_culled() { + use designcraft_doc::build::NewDocument; + use designcraft_doc::{Document, SpreadRef}; + let square = |glow: bool| { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let mut it = Item::new( + designcraft_doc::ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(50.0, 50.0, 90.0, 90.0)), + ); + it.xf = Affine::scale(3.0); + it.fill = designcraft_doc::Fill::swatch(designcraft_color::swatch::BLACK); + if glow { + let g = &mut it.effects.outer_glow; + (g.on, g.color, g.opacity, g.size, g.spread) = (true, designcraft_color::swatch::BLACK.into(), 1.0, 20.0, 100.0); + } else { + (it.stroke.swatch, it.stroke.weight) = (designcraft_color::swatch::BLACK.into(), 20.0); + } + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + d + }; + let cache = crate::Cache::new(); + let opts = crate::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + // The square covers 150..270 on the spread. Its glow grows 60 pt (to 90), past the + // unscaled 33 pt reach; its 20 pt stroke is 60 pt wide (to 120), past the unscaled 22 pt. + for (glow, x) in [(true, 95.0), (false, 123.0)] { + let d = square(glow); + for threads in [0, 2] { + let mut r = Renderer::new(); + r.threads = threads; + let place = [crate::Placed { spread: SpreadRef::Doc(0), xf: Affine::IDENTITY }]; + let image = r.render(&d, &cache, &place, (4, 20), Affine::translate((-x, -200.0)), &opts); + let p = image.pixel(1, 10); + let lum = u32::from(p[0]) + u32::from(p[1]) + u32::from(p[2]); + assert!(lum < 200, "glow {glow}, {threads} threads: the view at x {x} shows the scaled square's edge, luminance {lum}"); + } + } + } } From 55963c491872cec854735278c7d80b60da2bc6cc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 12:57:16 -0800 Subject: [PATCH 1050/1349] Images: pick a reduced JPEG's scale by its long side The JPEG decoder takes the smallest scale that meets either requested side. A short side rounds up to the same size at several scales, so a 100 x 2 JPEG asked for at a half decoded at an eighth (13 x 1). The long side alone now picks the scale, and a decode whose size differs from the requested reduction is refused, which falls back to the full decode. --- crates/images/src/jpeg.rs | 9 ++++++++- crates/images/src/tests.rs | 13 +++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/crates/images/src/jpeg.rs b/crates/images/src/jpeg.rs index 6188a53fc..a4a2a0971 100644 --- a/crates/images/src/jpeg.rs +++ b/crates/images/src/jpeg.rs @@ -100,7 +100,14 @@ pub(crate) fn decode_reduced(bytes: &[u8], shrink: u8) -> Option<(image::RgbaIma } } let reduced = |n: u16| u16::try_from(u32::from(n).div_ceil(1 << shrink)).ok(); - let (w, h) = d.scale(reduced(info.width)?, reduced(info.height)?).ok()?; + let expected = (reduced(info.width)?, reduced(info.height)?); + // The decoder takes the smallest scale that meets either requested side, and a short side + // rounds up to the same size at several scales, so only the long side is requested. + let request = if info.width >= info.height { (expected.0, u16::MAX) } else { (u16::MAX, expected.1) }; + let (w, h) = d.scale(request.0, request.1).ok()?; + if (w, h) != expected { + return None; + } let px = d.decode().ok()?; let pixels = usize::from(w).checked_mul(usize::from(h))?; let rgba: Vec = if colour { diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index 184e3c9c9..3edfa89b9 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -596,6 +596,19 @@ fn reduced_jpegs_decode_at_a_half_quarter_or_eighth_rounded_up() { assert!(decode_rgba_reduced(&jpeg, 4).is_none()); } +#[test] +fn a_thin_reduced_jpeg_keeps_its_long_side_at_the_requested_reduction() { + // The short side rounds up to 1 at every reduction, so it cannot pick the scale. + for (w, h) in [(100, 2), (2, 100)] { + let jpeg = gradient_jpeg(w, h, false); + for (shrink, long) in [(1, 50), (2, 25), (3, 13)] { + let img = decode_rgba_reduced(&jpeg, shrink).unwrap(); + let size = if w > h { (long, 1) } else { (1, long) }; + assert_eq!(img.dimensions(), size, "{w} × {h}, shrink {shrink}"); + } + } +} + #[test] fn reduced_decoding_is_for_jpegs_and_survives_damaged_ones() { let gray = decode_rgba_reduced(&gradient_jpeg(64, 64, true), 2).unwrap(); From 07d264fd238013bae6ac85e2f976f96a294a884f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 12:57:17 -0800 Subject: [PATCH 1051/1349] Copy: bound the anchored-object walk through cells and notes Copying a story gives the objects anchored in its table cells and notes fresh ids down to 64 levels, as the table copy does. A copy whose stories below that level hold anchored objects, tables or notes is refused with the nested-too-deeply error instead of recursing without limit. --- crates/engine/src/cmd/object.rs | 70 +++++++++++++++++++++++++++++++-- 1 file changed, 66 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 8b0e1cd51..b7a6d780b 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -1281,21 +1281,41 @@ fn retarget_xrefs(copy: &mut Story, orig: &Story, map: &HashMap, depth } } -/// Fresh ids for the objects anchored in story copy `st`, its table cells, footnotes and endnotes, at every depth -/// (#1522), each `depth` levels deep. False when one of them nests groups deeper than [`MAX_COPY_DEPTH`]. +/// Fresh ids for the objects anchored in story copy `st`, its table cells, footnotes and endnotes down to +/// [`MAX_COPY_DEPTH`] levels (#1522), each `depth` levels deep. False when one of them nests groups deeper than +/// [`MAX_COPY_DEPTH`], or when the stories below that level hold anchored objects, tables or notes. #[must_use = "false means the copy is incomplete and must not be inserted"] fn renumber_anchored(dst: &mut Document, src: &Document, st: &mut Story, stories: &mut HashMap, depth: usize) -> bool { + renumber_anchored_in(dst, src, st, stories, depth, 0) +} + +/// [`renumber_anchored`] for a story `level` table cells and notes below the story copy. +#[must_use = "false means the copy is incomplete and must not be inserted"] +fn renumber_anchored_in( + dst: &mut Document, + src: &Document, + st: &mut Story, + stories: &mut HashMap, + depth: usize, + level: usize, +) -> bool { let mut complete = true; for o in &mut st.objects { complete &= renumber_in(dst, src, &mut Arc::make_mut(o).item, stories, depth, false); } + if level >= MAX_COPY_DEPTH { + let leaf = |s: &Story| s.objects.is_empty() && s.tables.is_empty() && s.notes.is_empty() && s.endnotes.is_empty(); + return complete + && st.tables.values().all(|t| t.cells.iter().all(|c| leaf(&c.text))) + && st.notes.iter().chain(&st.endnotes).all(|n| leaf(&n.text)); + } for t in st.tables.values_mut() { for c in &mut Arc::make_mut(t).cells { - complete &= renumber_anchored(dst, src, &mut c.text, stories, depth); + complete &= renumber_anchored_in(dst, src, &mut c.text, stories, depth, level + 1); } } for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { - complete &= renumber_anchored(dst, src, &mut Arc::make_mut(n).text, stories, depth); + complete &= renumber_anchored_in(dst, src, &mut Arc::make_mut(n).text, stories, depth, level + 1); } complete } @@ -5744,6 +5764,48 @@ mod copy_ids_tests { assert_eq!(s.doc().unwrap().doc, before, "nothing is pasted"); } + #[test] + fn objects_anchored_in_cells_nested_too_deeply_are_not_copied() { + use std::sync::Arc; + + // The first cell of the story's table holds `n` tables, each in the first cell of the one before, and the cell + // of the innermost one holds an anchored object. + fn nested(n: usize) -> crate::Session { + let mut s = crate::Session::new(); + let (f, sid) = marked_frame(&mut s); + let leaf = s.execute("frame.create", &json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap(); + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let item = d.item(designcraft_doc::ItemId(leaf)).cloned().unwrap(); + Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id.0 != leaf); + let mut chain: Option = None; + for _ in 0..n { + let mut t = designcraft_doc::Table::new(d.alloc(), 1, 1, 0, 0, 40.0); + match chain.take() { + Some(inner) => { + t.cells[0].text.insert_table(0, inner); + } + None => { + t.cells[0].text.insert_object(0, designcraft_doc::AnchoredObject::new(item.clone(), Default::default())); + } + } + chain = Some(t); + } + let st = d.story_mut(sid).unwrap(); + let text = &mut Arc::make_mut(st.tables.values_mut().next().unwrap()).cells[0].text; + text.insert_table(text.len(), chain.unwrap()); + s.execute("selection.set", &json!({"ids": [f]})).unwrap(); + s + } + let mut s = nested(super::MAX_COPY_DEPTH - 1); + s.execute("edit.duplicate", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.anchored_items().len(), 2, "the anchored object is copied"); + let mut s = nested(super::MAX_COPY_DEPTH); + let before = s.doc().unwrap().doc.clone(); + let e = s.execute("edit.duplicate", &json!({})).unwrap_err().to_string(); + assert!(e.contains("too deeply to copy"), "{e}"); + assert_eq!(s.doc().unwrap().doc, before, "nothing is copied"); + } + #[test] fn pasted_cross_references_follow_the_pasted_anchors_of_other_stories() { let mut s = crate::Session::new(); From fc5221060c38df2573f4f6a5c150c9bf9f9a5d1f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 15:59:29 -0500 Subject: [PATCH 1052/1349] Fix vertical justification test arguments --- crates/compose/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index d2f92f2ee..41a734f4c 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -2660,7 +2660,7 @@ fn vertical_justification_counts_table_fragment_bottoms() { let mut spec = frame_specs(&d, sid).remove(0); spec.opts.vertical_justification = mode; - vertical_justify(&mut ft, &spec, false, &d.footnote_options, &[]); + vertical_justify(&mut ft, &spec, false, &d.footnote_options, &[], &[]); let moved = ft.lines[anchor].baseline - baseline; let limit = ft.notes[0].rect.y0 - d.footnote_options.space_before; From 946e3ea4c19e18693c4fb144ef7b3a5ed02496c0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 12:50:29 -0800 Subject: [PATCH 1053/1349] Compose: grid-aligned vertical justification takes only grid steps that fit a shaped frame In a frame that narrows and widens again, Bottom, Center and Justify now try lower grid steps until the lines fit the outline, and leave the lines in place when none does, instead of taking the next lower step unchecked. A grid whose step is too small to count across the column is now treated as no grid when a line is placed, so the line keeps a finite baseline. Tests cover a waist-shaped frame on a 40 pt grid, a tiny-step grid that starts away from the line, and Justify with a wrapped paragraph under All Lines and First Line Only. --- crates/compose/src/lib.rs | 20 ++++++++--- crates/compose/src/tests.rs | 70 +++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 4 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index b83f479fe..9a11229c4 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -1858,8 +1858,14 @@ fn position_line(input: PositionLineInput<'_, '_>) -> LinePosition { if cur.last_baseline.is_some() { baseline += cur.last_reference - reference; } - let grid = f.grid.filter(|&(_, inc)| { - inc > 0.0 && inc.is_finite() && (pp.grid_align == GridAlign::AllLines || (pp.grid_align == GridAlign::FirstLineOnly && line_no == 0)) + // A step so small that the column holds more steps than an f64 can count is no grid: the + // line is placed as it is without one. + let countable = |g_start: f64, inc: f64| [baseline, col.y0, col.y1].iter().all(|y| ((y - g_start) / inc).is_finite()); + let grid = f.grid.filter(|&(g_start, inc)| { + inc > 0.0 + && inc.is_finite() + && countable(g_start, inc) + && (pp.grid_align == GridAlign::AllLines || (pp.grid_align == GridAlign::FirstLineOnly && line_no == 0)) }); if let Some((g_start, inc)) = grid { let n = pp.grid_gyoudori.min(grid::MAX_GYOUDORI); @@ -6152,8 +6158,14 @@ fn vertical_justify( let most = (space / inc + 1e-9).floor().min((room / unit + 1e-9).floor()).max(0.0); // Bottom and Justify take the lowest grid line, Center the one nearest the middle. let mut steps = if center { (space / 2.0 / inc).round().min(most) } else { most }; - if steps > 0.0 && !fits(&shifts(steps * unit)) { - steps -= 1.0; + // A shaped frame can narrow and widen again, so a lower step may not fit either: take + // the nearest step that fits, and leave the lines in place when none of the next + // `MAX_GRID_TRIES` does. + const MAX_GRID_TRIES: usize = 512; + let mut tries = 0; + while steps > 0.0 && !fits(&shifts(steps * unit)) { + tries += 1; + steps = if tries < MAX_GRID_TRIES { steps - 1.0 } else { 0.0 }; } // With no step taken the lines stay put, even when Center's doubled step overflows. shifts(if steps > 0.0 { steps * unit } else { 0.0 }) diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 41a734f4c..ab8f56837 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -2799,6 +2799,25 @@ fn vertical_justification_keeps_grid_aligned_lines_on_the_grid() { let (_, first_only, _) = compose_with(Bottom, GridAlign::FirstLineOnly); assert!(first_only.iter().all(|&b| on_grid(b, grid)), "Bottom, first lines only: {first_only:?}"); + // Justify with a paragraph that wraps: with all lines aligned the last line lands on the grid; + // with first lines only it is not a first line, so it goes down to the bottom inset. + let wrapped = "The first line of this paragraph sits on the baseline grid, and the lines after it keep the leading they have."; + let justify_wrapped = |align: GridAlign| { + let (lines, _) = grid_doc(wrapped, ParaAttrs { grid_align: Some(align), ..Default::default() }, |d, sid| { + let spec = frame_specs(d, sid).remove(0); + d.item_mut(spec.id).unwrap().text_frame_mut().unwrap().options.vertical_justification = Justify; + }); + lines.iter().map(|l| l.baseline).collect::>() + }; + let all = justify_wrapped(GridAlign::AllLines); + assert!(all.len() >= 2, "the paragraph wraps: {all:?}"); + let last = all[all.len() - 1]; + assert!(on_grid(last, grid) && last <= area.y1 + 1e-6 && last > area.y1 - inc, "Justify, all lines: last baseline {last}"); + let first_lines = justify_wrapped(GridAlign::FirstLineOnly); + assert!(first_lines.len() >= 2, "the paragraph wraps: {first_lines:?}"); + let last = first_lines[first_lines.len() - 1]; + assert!((last - area.y1).abs() < 1e-6 && !on_grid(last, grid), "Justify, first lines only: last baseline {last}, inset at {}", area.y1); + // Without grid alignment the last baseline goes down to the bottom inset. let (_, free, _) = compose_with(Bottom, GridAlign::None); assert!((free[2] - area.y1).abs() < 1e-6, "Bottom without the grid: {free:?}"); @@ -2839,6 +2858,57 @@ fn vertical_justification_with_an_extreme_grid_increment_stays_finite() { // A step far larger than the room: the line does not move. let (_, b) = compose_with(Center, 1e308); assert!((b - natural).abs() < 1e-6, "Center with a huge increment: baseline {b}, natural {natural}"); + + // A grid that starts away from the line, with a step too small to count the distance: the line + // is placed as it is without a grid. + for mode in [Top, Bottom, Center, Justify] { + let mut area = Rect::ZERO; + let (lines, _) = grid_doc("One", ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }, |d, sid| { + let spec = frame_specs(d, sid).remove(0); + area = spec.area; + let opts = &mut d.item_mut(spec.id).unwrap().text_frame_mut().unwrap().options; + opts.baseline_grid = Some(designcraft_doc::FrameBaselineGrid::new(start - 5.0, 1e-310)); + opts.vertical_justification = mode; + }); + let b = lines[0].baseline; + assert!(b.is_finite() && b >= natural - 1e-6 && b <= area.y1 + 1e-6, "{mode:?}, grid away from the line: baseline {b}, text area {area:?}"); + if mode == Top { + assert!((b - natural).abs() < 1e-6, "Top, grid away from the line: baseline {b}, natural {natural}"); + } + } +} + +/// In a shaped frame that narrows and widens again, Bottom with Align to Baseline Grid takes the +/// lowest grid step at which the line's slot fits the outline, even when the grid steps next to +/// the lowest room all fall in the narrow part. +#[test] +fn vertical_justification_on_the_grid_skips_steps_that_leave_a_shaped_frame() { + use designcraft_doc::GridAlign; + use designcraft_doc::VerticalJustification::Bottom; + use designcraft_geom::{Anchor, PathData, Point, SubPath}; + // Full width down to 100 pt, a waist at 150 pt, full width again from 200 to 230 pt, then a + // point at 300 pt. + let pts = [(0.0, 0.0), (300.0, 0.0), (300.0, 100.0), (200.0, 150.0), (300.0, 200.0), (300.0, 230.0), (150.0, 300.0)]; + let pts: Vec<(f64, f64)> = pts.iter().copied().chain([(0.0, 230.0), (0.0, 200.0), (100.0, 150.0), (0.0, 100.0)]).collect(); + let para = ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }; + let (mut d, sid, fid) = doc_with("Typography", Rect::new(0.0, 0.0, 300.0, 300.0), para); + let it = d.item_mut(fid).unwrap(); + it.path = PathData::single(SubPath { anchors: pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), closed: true }); + let o = &mut it.text_frame_mut().unwrap().options; + o.inset = [0.0; 4]; + o.baseline_grid = Some(designcraft_doc::FrameBaselineGrid::new(0.0, 40.0)); + let grid = frame_specs(&d, sid)[0].grid.unwrap(); + let top = all_lines(&compose_story(&d, sid, &ComposeOptions::default()))[0].baseline; + assert!(on_grid(top, grid), "Top: baseline {top} on the grid {grid:?}"); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = Bottom; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let l = all_lines(&cs)[0]; + let (b, band_top) = (l.baseline, l.baseline - l.ascent); + assert!(on_grid(b, grid), "Bottom: baseline {b} on the grid {grid:?}"); + let upper = b <= 100.0 + 1e-6; + let lower = band_top >= 200.0 - 1e-6 && b <= 230.0 + 1e-6; + assert!(upper || lower, "Bottom: the line's band {band_top}..{b} reaches into the narrow part"); + assert!(b > top, "Bottom moves the line down a grid step that fits: {b}, Top at {top}"); } /// A corner radius leaves a Cap Height first line where it sits in a rectangular frame, with Top From fb77a73d93bcd7cdabd1ac78f306b8e9ae21f257 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 13:04:14 -0800 Subject: [PATCH 1054/1349] Compose: Center on the grid takes the fitting step nearest the middle in a shaped frame When the grid step nearest the centered place puts the lines outside a frame that narrows and widens again, Center now tries the steps on both sides of it, nearest first, instead of only the steps above it. --- crates/compose/src/lib.rs | 27 +++++++++++++------ crates/compose/src/tests.rs | 52 +++++++++++++++++++++++-------------- 2 files changed, 51 insertions(+), 28 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 9a11229c4..9c423cec0 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -6157,15 +6157,26 @@ fn vertical_justify( // The last baseline stays above the bottom of the text, and the rows above it fit. let most = (space / inc + 1e-9).floor().min((room / unit + 1e-9).floor()).max(0.0); // Bottom and Justify take the lowest grid line, Center the one nearest the middle. - let mut steps = if center { (space / 2.0 / inc).round().min(most) } else { most }; - // A shaped frame can narrow and widen again, so a lower step may not fit either: take - // the nearest step that fits, and leave the lines in place when none of the next - // `MAX_GRID_TRIES` does. + let target = if center { (space / 2.0 / inc).round().min(most) } else { most }; + // A shaped frame can narrow and widen again, so the target step may not fit: take + // the fitting step nearest it, up to `most` (the lower one on a tie, and no step + // when that is as near), and leave the lines in place when none within + // `MAX_GRID_TRIES` steps of it fits. const MAX_GRID_TRIES: usize = 512; - let mut tries = 0; - while steps > 0.0 && !fits(&shifts(steps * unit)) { - tries += 1; - steps = if tries < MAX_GRID_TRIES { steps - 1.0 } else { 0.0 }; + let mut steps = 0.0; + for d in 0..MAX_GRID_TRIES { + let (below, above) = (target - d as f64, target + d as f64); + if below <= 0.0 { + break; + } + if fits(&shifts(below * unit)) { + steps = below; + break; + } + if d > 0 && above <= most && fits(&shifts(above * unit)) { + steps = above; + break; + } } // With no step taken the lines stay put, even when Center's doubled step overflows. shifts(if steps > 0.0 { steps * unit } else { 0.0 }) diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index ab8f56837..59777d657 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -2878,37 +2878,49 @@ fn vertical_justification_with_an_extreme_grid_increment_stays_finite() { } } -/// In a shaped frame that narrows and widens again, Bottom with Align to Baseline Grid takes the -/// lowest grid step at which the line's slot fits the outline, even when the grid steps next to -/// the lowest room all fall in the narrow part. +/// In a shaped frame that narrows and widens again, Align to Baseline Grid takes the grid step +/// nearest the place Bottom or Center would choose at which the line's slot fits the outline: +/// Bottom goes up past steps in the narrow part, and Center goes down a step when the step nearest +/// the middle is in the narrow part and the next one fits. #[test] fn vertical_justification_on_the_grid_skips_steps_that_leave_a_shaped_frame() { use designcraft_doc::GridAlign; - use designcraft_doc::VerticalJustification::Bottom; + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Top}; use designcraft_geom::{Anchor, PathData, Point, SubPath}; // Full width down to 100 pt, a waist at 150 pt, full width again from 200 to 230 pt, then a // point at 300 pt. let pts = [(0.0, 0.0), (300.0, 0.0), (300.0, 100.0), (200.0, 150.0), (300.0, 200.0), (300.0, 230.0), (150.0, 300.0)]; let pts: Vec<(f64, f64)> = pts.iter().copied().chain([(0.0, 230.0), (0.0, 200.0), (100.0, 150.0), (0.0, 100.0)]).collect(); - let para = ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }; - let (mut d, sid, fid) = doc_with("Typography", Rect::new(0.0, 0.0, 300.0, 300.0), para); - let it = d.item_mut(fid).unwrap(); - it.path = PathData::single(SubPath { anchors: pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), closed: true }); - let o = &mut it.text_frame_mut().unwrap().options; - o.inset = [0.0; 4]; - o.baseline_grid = Some(designcraft_doc::FrameBaselineGrid::new(0.0, 40.0)); - let grid = frame_specs(&d, sid)[0].grid.unwrap(); - let top = all_lines(&compose_story(&d, sid, &ComposeOptions::default()))[0].baseline; + let compose_with = |mode: VerticalJustification, inc: f64| { + let para = ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }; + let (mut d, sid, fid) = doc_with("Typography", Rect::new(0.0, 0.0, 300.0, 300.0), para); + let it = d.item_mut(fid).unwrap(); + it.path = PathData::single(SubPath { anchors: pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), closed: true }); + let o = &mut it.text_frame_mut().unwrap().options; + o.inset = [0.0; 4]; + o.baseline_grid = Some(designcraft_doc::FrameBaselineGrid::new(0.0, inc)); + o.vertical_justification = mode; + let grid = frame_specs(&d, sid)[0].grid.unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let l = all_lines(&cs)[0]; + (grid, l.baseline, l.baseline - l.ascent) + }; + let lower = |b: f64, band_top: f64| band_top >= 200.0 - 1e-6 && b <= 230.0 + 1e-6; + + // A 40 pt grid: the lowest room ends between 160 and 200 pt, and the steps above it down to + // 120 pt put the line in the waist. + let (grid, top, _) = compose_with(Top, 40.0); assert!(on_grid(top, grid), "Top: baseline {top} on the grid {grid:?}"); - d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = Bottom; - let cs = compose_story(&d, sid, &ComposeOptions::default()); - let l = all_lines(&cs)[0]; - let (b, band_top) = (l.baseline, l.baseline - l.ascent); + let (_, b, band_top) = compose_with(Bottom, 40.0); assert!(on_grid(b, grid), "Bottom: baseline {b} on the grid {grid:?}"); - let upper = b <= 100.0 + 1e-6; - let lower = band_top >= 200.0 - 1e-6 && b <= 230.0 + 1e-6; - assert!(upper || lower, "Bottom: the line's band {band_top}..{b} reaches into the narrow part"); + assert!(b <= 100.0 + 1e-6 || lower(b, band_top), "Bottom: the line's band {band_top}..{b} reaches into the narrow part"); assert!(b > top, "Bottom moves the line down a grid step that fits: {b}, Top at {top}"); + + // A 45 pt grid: the step nearest the middle puts the baseline at 180 pt, in the waist; the + // step below it fits in the lower full-width part. + let (grid, b, band_top) = compose_with(Center, 45.0); + assert!(on_grid(b, grid), "Center: baseline {b} on the grid {grid:?}"); + assert!(lower(b, band_top), "Center: the line's band {band_top}..{b} is not in the lower full-width part"); } /// A corner radius leaves a Cap Height first line where it sits in a rectangular frame, with Top From 5931b17bb6e78c2fd8e47e7569a6366ee35a2663 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 16:22:26 -0500 Subject: [PATCH 1055/1349] Translate duplicate layer in remaining locales --- crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/hu.rs | 1 + crates/ui-egui/src/i18n/sv.rs | 1 + 3 files changed, 3 insertions(+) diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 685591a96..91ad54dd1 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -212,6 +212,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("New Hyperlink", "Nouvel hyperlien"), ("New Hyperlink Destination", "Nouvelle destination d'hyperlien"), ("New Layer", "Nouveau calque"), + ("Duplicate Layer \"{name}\"", "Dupliquer le calque « {name} »"), ("New Page Reference", "Nouvelle référence de page"), ("New Parent", "Nouveau gabarit"), ("Export Layouts and Versions…", "Exporter les mises en page et versions…"), diff --git a/crates/ui-egui/src/i18n/hu.rs b/crates/ui-egui/src/i18n/hu.rs index fd9057213..f0e1e28c0 100644 --- a/crates/ui-egui/src/i18n/hu.rs +++ b/crates/ui-egui/src/i18n/hu.rs @@ -865,6 +865,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Last Page", "Utolsó oldal"), ("Last Spread", "Utolsó oldalpár"), ("Layer Options…", "Réteg beállításai…"), + ("Duplicate Layer \"{name}\"", "„{name}” réteg duplikálása"), ("Layers", "Rétegek"), ("Layout", "Elrendezés"), ("Layout/Index", "Elrendezés/Tárgymutató"), diff --git a/crates/ui-egui/src/i18n/sv.rs b/crates/ui-egui/src/i18n/sv.rs index bc826031d..f835146cc 100644 --- a/crates/ui-egui/src/i18n/sv.rs +++ b/crates/ui-egui/src/i18n/sv.rs @@ -2177,6 +2177,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Color Group Options…", "Alternativ för färggrupp…"), ("Layer Options", "Lageralternativ"), ("Layer Options for \"{name}\"…", "Lageralternativ för \"{name}\"…"), + ("Duplicate Layer \"{name}\"", "Duplicera lagret ”{name}”"), ("Swatch Name:", "Färgrutenamn:"), ("Name with Color Value", "Namn med färgvärde"), ("Color Type:", "Färgtyp:"), From 9847f972da194e4c7ab05ad0ec42e6577e9a17dc Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 16:27:52 -0500 Subject: [PATCH 1056/1349] Update recovery test for explicit write conflict --- crates/engine/src/recovery/tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index 8d28dc8a9..ab967f4ff 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -394,8 +394,8 @@ fn no_other_sessions_write_of_the_uid_is_queued_during_a_write_now() { other.recovery_dir = Some(dir.path().to_path_buf()); other.docs[0].uid = uid; let now = worker::write_now(dir.path(), uid, writing.recovery_owner.0).expect("nothing else is in flight"); - let queued = other.execute("file.recovery.save", &json!({"background": true})).unwrap(); - assert_eq!(queued["queued"], 0, "another session's write was queued during the write now: {queued}"); + let err = other.execute("file.recovery.save", &json!({"background": true})).unwrap_err(); + assert!(err.to_string().contains("another session"), "{err}"); assert!(worker::write_now(dir.path(), uid, other.recovery_owner.0).is_none(), "a second write now of the uid started"); drop(now); let queued = other.execute("file.recovery.save", &json!({"background": true})).unwrap(); From 2b6fb6fa061d9b954f87a07bc14d83d0c324917b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 11:56:44 -0800 Subject: [PATCH 1057/1349] Images: count a decode's buffers at their peak before decoding in parallel The gate that limits parallel decodes counted each image at its cached size (4 bytes a pixel and a third more for the smaller levels). A decode holds more than that while it converts the pixels: an 8-bit image keeps its RGBA copy beside the decoded or the premultiplied pixels, 8 bytes a pixel. Two 5,500 pixel square images passed the gate together and could hold more than half the cache budget at once. - decode_sizes returns the cached size and the peak size from one size read. The peak counts the samples as stored beside their converted copy (designcraft_images::decode_bytes_per_pixel): 8 bytes a pixel for 8-bit color, 10 for 16-bit RGB, 12 for 16-bit CMYK TIFFs and 16-bit RGBA, 10 for 8-bit CMYKA TIFFs, 15 for 16-bit CMYKA TIFFs, 9 for PSDs. An EPS counts as its TIFF preview. PDF pages, SVGs and EPS files without a preview count 8. - warm budgets the cache with the cached size and gates decodes with the peak size. - Every warm call in the process shares one gate, so the canvas worker, thumbnails and exports together stay within half the budget while they decode. warm returns the most its own call had decoding. - An EPS without a preview is sized at the larger of its drawn PostScript and its placeholder. The placeholder is clamped to 4000 pixels on each side, so a 10,000 by 4,000 point EPS that is not drawn takes 4000 by 4000 pixels, not the 4000 by 1600 counted before. --- crates/images/src/eps.rs | 2 +- crates/images/src/lib.rs | 33 +++++++++ crates/images/src/tests.rs | 26 ++++++++ crates/render/src/decode.rs | 32 +++++++-- crates/render/src/images.rs | 129 ++++++++++++++++++++++++++++-------- crates/render/src/tests.rs | 8 +++ 6 files changed, 197 insertions(+), 33 deletions(-) diff --git a/crates/images/src/eps.rs b/crates/images/src/eps.rs index bd2498f1a..1f209ccf0 100644 --- a/crates/images/src/eps.rs +++ b/crates/images/src/eps.rs @@ -98,7 +98,7 @@ pub fn eps_size(bytes: &[u8]) -> Option<(f64, f64)> { ((0.001..=20_000.0).contains(&w) && (0.001..=20_000.0).contains(&h)).then_some((w, h)) } -fn preview(bytes: &[u8]) -> Option<(&[u8], (u32, u32))> { +pub(crate) fn preview(bytes: &[u8]) -> Option<(&[u8], (u32, u32))> { let (_, tiff) = sections(bytes); let tiff = tiff?; let (w, h) = crate::pixel_size(tiff)?; diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 081af6c2b..820f9a8b4 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -442,6 +442,39 @@ pub fn decode_rgba(bytes: &[u8]) -> Option { to_display_rgba(px, Some(&icc), &DisplayColour::active()) } +/// About how many bytes a pixel [`decode_rgba`] of `bytes` holds at once, with a premultiplied +/// copy of its result: the samples as stored beside the copy they are converted to, and at least +/// 8 (the RGBA result and its premultiplied copy). 16-bit CMYK TIFF samples are narrowed into an +/// 8-bit copy and CMYK alpha is split off into one, so a 16-bit CMYKA TIFF counts 15. An EPS +/// counts as its TIFF preview, or 8 for its placeholder or drawn PostScript. +pub fn decode_bytes_per_pixel(bytes: &[u8]) -> usize { + if is_eps(bytes) { + return eps::preview(bytes).map_or(8, |(tiff, _)| if is_eps(tiff) { 8 } else { decode_bytes_per_pixel(tiff) }); + } + if is_psd(bytes) { + // RGBA-sized channels, an alpha plane, and the RGBA copy of CMYK inks. + return 9; + } + if let Some(mut d) = tiff_decoder(bytes) { + let cmyk = match d.colortype() { + Ok(tiff::ColorType::CMYK(bits)) => Some((4, bits)), + Ok(tiff::ColorType::CMYKA(bits)) => Some((5, bits)), + _ => None, + }; + if let Some((samples, bits)) = cmyk { + let stored = samples * usize::from(bits).div_ceil(8); + let copy = if bits > 8 || samples == 5 { samples } else { 0 }; + return (stored + copy).max(samples + 4).max(8); + } + } + let sample = image::ImageReader::new(std::io::Cursor::new(bytes)) + .with_guessed_format() + .ok() + .and_then(|r| r.into_decoder().ok()) + .map_or(4, |d| usize::from(image::ImageDecoder::color_type(&d).bytes_per_pixel())); + (sample + 4).max(8) +} + /// False when `bytes` is a WebP whose `ICCP` chunk declares more bytes than the file holds or than /// [`colour::MAX_ICC_BYTES`]. The decoder sizes its buffer from the declared length before it reads /// anything, so such a file must not reach `icc_profile()`; its pixels decode without it. diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index cd577f09a..0d8e65ab2 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -372,6 +372,32 @@ fn cmyk_tiff_keeps_inks() { assert_eq!(decode_cmyk_tiff(&b[..b.len() / 2]), None, "truncated"); } +/// A decode holds the samples as stored beside the copy they are converted to. +#[test] +fn decode_bytes_per_pixel_counts_the_stored_samples_and_their_copy() { + use tiff::encoder::colortype::{CMYK8, CMYK16, CMYKA8, RGB16}; + assert_eq!(decode_bytes_per_pixel(&tiff_of::(1, 1, &[0; 4], false)), 8); + assert_eq!(decode_bytes_per_pixel(&tiff_of::(1, 1, &[0; 5], true)), 10); + assert_eq!(decode_bytes_per_pixel(&tiff_of::(1, 1, &[0; 4], false)), 12); + assert_eq!(decode_bytes_per_pixel(&tiff_of::(1, 1, &[0; 3], false)), 10); + let mut psd = b"8BPS".to_vec(); + psd.resize(26, 0); + assert_eq!(decode_bytes_per_pixel(&psd), 9); + assert_eq!(decode_bytes_per_pixel(b"not an image"), 8); + // An EPS counts as its TIFF preview, or 8 without one. + let ps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 10 10\nnewpath\n%%EOF\n"; + assert_eq!(decode_bytes_per_pixel(ps), 8); + let preview = tiff_of::(1, 1, &[0; 4], false); + let mut dos = vec![0xC5, 0xD0, 0xD3, 0xC6]; + for v in [30, ps.len(), 0, 0, 30 + ps.len(), preview.len()] { + dos.extend((v as u32).to_le_bytes()); + } + dos.extend([0xFF, 0xFF]); + dos.extend_from_slice(ps); + dos.extend_from_slice(&preview); + assert_eq!(decode_bytes_per_pixel(&dos), 12); +} + /// Indexed colour (PhotometricInterpretation 3), which the `tiff` encoder has no type for. struct Palette; impl tiff::encoder::colortype::ColorType for Palette { diff --git a/crates/render/src/decode.rs b/crates/render/src/decode.rs index 5668a205f..dfaed5c55 100644 --- a/crates/render/src/decode.rs +++ b/crates/render/src/decode.rs @@ -12,18 +12,39 @@ const VECTOR_SIDE: u32 = 3000; /// About how many bytes [`decode_pixmap_page`] of `bytes` takes, with its smaller levels (a third /// more): PDF pages and SVGs at [`VECTOR_SIDE`] pixels on the longer side, an EPS without a /// preview at up to 8 pixels per point and 4000 pixels on the longer side (as its PostScript is -/// drawn), other images and previews at their pixel size. 0 when the size can't be read. +/// drawn) or at its placeholder's size when that is larger, other images and previews at their +/// pixel size. 0 when the size can't be read. +#[cfg(test)] pub(crate) fn decoded_bytes(bytes: &[u8], page: u32) -> usize { + decode_sizes(bytes, page).0 +} + +/// [`decoded_bytes`] of `bytes`, and about how many bytes [`decode_pixmap_page`] of it holds at +/// once while it runs: a raster as decoded and its RGBA copy, or that copy and the premultiplied +/// pixels, whichever is more ([`designcraft_images::decode_bytes_per_pixel`]: 8 bytes a pixel +/// for 8-bit color, 12 for 16-bit RGBA, an EPS as its TIFF preview). PDF pages, SVGs and EPS +/// files without a preview count 8 bytes a pixel. Both are 0 when the size can't be read. +pub(crate) fn decode_sizes(bytes: &[u8], page: u32) -> (usize, usize) { + let Some((w, h)) = drawn_size(bytes, page) else { return (0, 0) }; + let raster = !is_pdf(bytes) && !designcraft_images::is_svg(bytes); + let per_pixel = if raster { designcraft_images::decode_bytes_per_pixel(bytes) } else { 8 } as f64; + ((w * h * 16.0 / 3.0) as usize, (w * h * per_pixel) as usize) +} + +/// The pixel size [`decode_pixmap_page`] of `bytes` draws at, as [`decoded_bytes`] describes it. +fn drawn_size(bytes: &[u8], page: u32) -> Option<(f64, f64)> { let drawn = |(w, h): (f64, f64), side: f64, most: f64| { let k = (side / w.max(h).max(1e-3)).min(most); ((w * k).round().max(1.0), (h * k).round().max(1.0)) }; - let size = if designcraft_images::is_eps(bytes) { + if designcraft_images::is_eps(bytes) { image_size(bytes).zip(designcraft_images::eps_size(bytes)).map(|((pw, ph), (w, h))| { - // Without a preview, the pixel size is the 2 pixels per point placeholder's. + // Without a preview, the pixel size is the 2 pixels per point placeholder's. The + // PostScript may be drawn instead, at another size: count the larger of the two. let placeholder = ((w * 2.0).round().clamp(2.0, 4000.0), (h * 2.0).round().clamp(2.0, 4000.0)); let px = (pw as f64, ph as f64); - if px == placeholder { drawn((w, h), 4000.0, 8.0) } else { px } + let rendered = drawn((w, h), 4000.0, 8.0); + if px == placeholder && rendered.0 * rendered.1 > px.0 * px.1 { rendered } else { px } }) } else if is_pdf(bytes) { // As render_pdf_page scales: at most 8 times the page size. @@ -32,8 +53,7 @@ pub(crate) fn decoded_bytes(bytes: &[u8], page: u32) -> usize { designcraft_images::natural_size(bytes).map(|s| drawn(s, VECTOR_SIDE as f64, f64::INFINITY)) } else { image_size(bytes).map(|(w, h)| (w as f64, h as f64)) - }; - size.map_or(0, |(w, h)| (w * h * 16.0 / 3.0) as usize) + } } /// [`decode_pixmap`] for page `page` of a PDF (other formats have one page). diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index ee0d917ba..dca7bcead 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -11,7 +11,7 @@ use std::sync::{Arc, Condvar, Mutex}; use vello_cpu::Pixmap; -use crate::decode::decoded_bytes; +use crate::decode::decode_sizes; use crate::{decode_pixmap_page, halve}; /// Decoded pixels kept (bytes). @@ -190,18 +190,20 @@ fn admits(in_flight: usize, size: usize) -> bool { in_flight == 0 || in_flight.saturating_add(size) <= BUDGET / 2 } -/// Bytes decoding at once and the most there were, with the signal that some finished. -type Gate = (Mutex<(usize, usize)>, Condvar); +/// Bytes [`warm`] is decoding at once in every render in the process (canvas worker, thumbnails, +/// exports), with the signal that some finished. +static GATE: (Mutex, Condvar) = (Mutex::new(0), Condvar::new()); -/// Takes a finished decode's bytes off its [`Gate`] when dropped. -struct Release<'a>(&'a Gate, usize); +/// Takes a finished decode's bytes off [`GATE`] and off its own call's count when dropped. +struct Release<'a>(&'a AtomicUsize, usize); impl Drop for Release<'_> { fn drop(&mut self) { - let mut g = self.0.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - g.0 = g.0.saturating_sub(self.1); + self.0.fetch_sub(self.1, Ordering::Relaxed); + let mut g = GATE.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + *g = g.saturating_sub(self.1); drop(g); - self.0.1.notify_all(); + GATE.1.notify_all(); } } @@ -210,8 +212,8 @@ impl Drop for Release<'_> { /// of decoding them one after another. Does nothing when fewer than two images need decoding. /// The images in view that are cached count against the cache budget first; a new image that /// would take the total past what the cache keeps (by its pixel size) is left to the render. -/// Decodes wait while those in flight together would take more than half the budget. Returns -/// the most bytes (estimated) that were decoding at once. +/// Decodes wait while those in flight in every render together would take more than half the +/// budget. Returns the most bytes (estimated) this call had decoding at once. pub(crate) fn warm(wants: Vec) -> usize { let workers = workers(); if workers < 2 { @@ -263,7 +265,7 @@ pub(crate) fn warm(wants: Vec) -> usize { if held.contains_key(&key) { continue; } - let size = wanted.first().map_or(0, |w| decoded_bytes(&w.bytes, w.page)); + let (size, decoding) = wanted.first().map_or((0, 0), |w| decode_sizes(&w.bytes, w.page)); // A store past the budget evicts down to three quarters of it: the images in view must // fit in that, unless they and the rest fit in the budget. let total = pixels.saturating_add(size); @@ -271,29 +273,34 @@ pub(crate) fn warm(wants: Vec) -> usize { continue; } pixels = total; - jobs.push((size, wanted)); + jobs.push((decoding, wanted)); } if jobs.len() < 2 { return 0; } - // While it converts the pixels, a decode holds buffers of about its size besides the cache: - // a decode waits while those in flight would take it past half the budget (one always runs). - let gate: Gate = (Mutex::new((0, 0)), Condvar::new()); - let lock = || gate.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + // While it converts the pixels, a decode holds the buffers `decode_sizes` counts: a + // decode waits while those in flight in any render would take it past half the budget (one + // always runs). + let lock = || GATE.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let next = AtomicUsize::new(0); + // This call's bytes decoding, and the most there were. + let (mine, peak) = (AtomicUsize::new(0), AtomicUsize::new(0)); std::thread::scope(|s| { for _ in 0..workers.min(jobs.len()) { let work = || { while let Some((size, job)) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { let mut g = lock(); - while !admits(g.0, *size) { - g = gate.1.wait(g).unwrap_or_else(std::sync::PoisonError::into_inner); + while !admits(*g, *size) { + #[cfg(test)] + waited(job); + g = GATE.1.wait(g).unwrap_or_else(std::sync::PoisonError::into_inner); } - g.0 += size; - g.1 = g.1.max(g.0); + *g = g.saturating_add(*size); + let now = mine.fetch_add(*size, Ordering::Relaxed).saturating_add(*size); + peak.fetch_max(now, Ordering::Relaxed); drop(g); // Released even if the decode panics, so no other decode waits forever. - let _release = Release(&gate, *size); + let _release = Release(&mine, *size); for w in job { let _ = mip(&w.bytes, w.page, w.width_pt, w.on_screen); } @@ -305,7 +312,19 @@ pub(crate) fn warm(wants: Vec) -> usize { } } }); - gate.0.into_inner().unwrap_or_else(std::sync::PoisonError::into_inner).1 + peak.into_inner() +} + +/// The images whose decode waited at [`GATE`] (the address of the encoded bytes), with the +/// signal that one did. +#[cfg(test)] +static WAITED: (Mutex>, Condvar) = (Mutex::new(Vec::new()), Condvar::new()); + +#[cfg(test)] +fn waited(job: &[Want]) { + let id = job.first().map_or(0, |w| Arc::as_ptr(&w.bytes) as usize); + WAITED.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(id); + WAITED.1.notify_all(); } /// Drop every decoded image. @@ -320,6 +339,11 @@ pub fn clear() { #[cfg(test)] mod tests { use super::*; + use crate::decode::decoded_bytes; + + fn decode_peak_bytes(bytes: &[u8], page: u32) -> usize { + decode_sizes(bytes, page).1 + } #[test] fn failed_assets_are_capped_and_oldest_is_dropped() { @@ -403,21 +427,74 @@ mod tests { #[test] fn warm_decodes_large_images_one_at_a_time() { - // Two 7,000 pixel square images fit the budget together, but decoding both at once would + // Two 6,500 pixel square images fit the budget together, but decoding both at once would // take more than half of it; the small image still decodes beside them. - let (d, e, small) = (psd(7000), psd(7000), png(8, 15)); + let (d, e, small) = (psd(6500), psd(6500), png(8, 15)); let since = mark(); let large = decoded_bytes(&d, 0); assert!(large > BUDGET / 4 && 2 * large <= BUDGET * 3 / 4); - assert!(admits(0, large) && !admits(large, large) && admits(large, decoded_bytes(&small, 0))); + let decoding = decode_peak_bytes(&d, 0); + assert!(admits(0, decoding) && !admits(decoding, decoding) && admits(decoding, decode_peak_bytes(&small, 0))); assert!(admits(0, usize::MAX), "an image over half the budget still decodes alone"); let peak = warm(vec![want(&d), want(&e), want(&small)]); assert!(peak <= BUDGET / 2, "{peak} bytes decoding at once"); - assert!(peak >= large, "the large images were decoded ahead"); + assert!(peak >= decoding, "the large images were decoded ahead"); let me = std::thread::current().id(); for img in [&d, &e, &small] { let on = decoders(img, since); assert!(on.len() == 1 && on[0] != me); } } + + #[test] + fn warm_counts_a_decode_at_its_peak() { + // A decode holds the RGBA copy beside the decoded or the premultiplied pixels: two 5,500 + // pixel square images would take less than half the budget cached, but more than half of + // it while both decode, so they decode one at a time. + let (f, g) = (psd(5500), psd(5500)); + let decoding = decode_peak_bytes(&f, 0); + assert_eq!(decoding, 5500 * 5500 * 9, "9 bytes a pixel for a PSD"); + assert!(2 * decoded_bytes(&f, 0) <= BUDGET / 2 && !admits(decoding, decode_peak_bytes(&g, 0))); + assert_eq!(warm(vec![want(&f), want(&g)]), decoding, "one decode at a time"); + // 16-bit RGBA decodes at 8 bytes a pixel before its RGBA copy. + let mut deep = Vec::new(); + let img = image::ImageBuffer::, Vec>::from_pixel(4, 4, image::Rgba([9, 0, 0, 65535])); + img.write_to(&mut std::io::Cursor::new(&mut deep), image::ImageFormat::Png).unwrap(); + assert_eq!(decode_peak_bytes(&deep, 0), 16 * 12); + assert_eq!(decode_peak_bytes(&png(8, 1), 0), 64 * 8); + } + + #[test] + fn warm_waits_for_decodes_in_other_renders() { + // Another render's decodes take half the budget: this render's decodes wait for them. + let (a, b) = (png(8, 17), png(8, 19)); + let ids = [Arc::as_ptr(&a) as usize, Arc::as_ptr(&b) as usize]; + let (since, decoded_since) = (WAITED.0.lock().unwrap().len(), mark()); + let other = BUDGET / 2; + *GATE.0.lock().unwrap() += other; + let done = std::sync::atomic::AtomicBool::new(false); + let (waited, peak) = std::thread::scope(|s| { + let render = s.spawn(|| { + let peak = warm(vec![want(&a), want(&b)]); + let w = WAITED.0.lock().unwrap(); + done.store(true, Ordering::SeqCst); + drop(w); + WAITED.1.notify_all(); + peak + }); + let seen = |w: &Vec| w.iter().skip(since).any(|id| ids.contains(id)); + let mut w = WAITED.0.lock().unwrap(); + while !seen(&w) && !done.load(Ordering::SeqCst) { + w = WAITED.1.wait(w).unwrap(); + } + let waited = seen(&w); + drop(w); + *GATE.0.lock().unwrap() -= other; + GATE.1.notify_all(); + (waited, render.join().unwrap()) + }); + assert!(waited, "decoded beside the other render's decodes"); + assert_eq!((decoders(&a, decoded_since).len(), decoders(&b, decoded_since).len()), (1, 1)); + assert!(peak > 0 && peak <= BUDGET / 2, "{peak} bytes decoding at once"); + } } diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 5d4f6a048..82e8fc77f 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -792,6 +792,14 @@ fn decode_size_estimates_match_the_decodes() { let drawn = pm.width() as usize * pm.height() as usize * 16 / 3; assert!(drawn > 200 * 100 * 16 / 3, "drawn above 2 pixels per point: {}×{}", pm.width(), pm.height()); assert!(decode::decoded_bytes(eps, 0) >= drawn); + // A wide EPS whose PostScript isn't drawn keeps its placeholder, clamped to 4000 pixels on + // each side: it is budgeted at no less than that. + let eps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 10000 4000\n%%EndComments\n0 0 moveto 10 10 lineto stroke\n%%EOF\n"; + let pm = decode_pixmap_page(eps, 0).unwrap(); + assert_eq!((pm.width(), pm.height()), (4000, 4000)); + let px = pm.width() as usize * pm.height() as usize; + assert!(decode::decoded_bytes(eps, 0) >= px * 16 / 3); + assert!(decode::decode_sizes(eps, 0).1 >= px * 8); } #[test] From 6bb9907de5df77d3532dfbfeb639084bf75f7aef Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 16:54:46 -0500 Subject: [PATCH 1058/1349] Use shared French duplicate layer translation --- crates/ui-egui/src/i18n/fr.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index bbe23824f..8a7c537ce 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -212,7 +212,6 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("New Hyperlink", "Nouvel hyperlien"), ("New Hyperlink Destination", "Nouvelle destination d'hyperlien"), ("New Layer", "Nouveau calque"), - ("Duplicate Layer \"{name}\"", "Dupliquer le calque « {name} »"), ("New Page Reference", "Nouvelle référence de page"), ("New Parent", "Nouveau gabarit"), ("Export Layouts and Versions…", "Exporter les mises en page et versions…"), From 2794a60bf079b15f7285101f3fcce423d0876af4 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 17:21:20 -0500 Subject: [PATCH 1059/1349] Account for image decode buffers in warm gate --- crates/render/src/images.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index f9f82ac31..8ae0691c7 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -250,9 +250,9 @@ pub(crate) fn warm(wants: Vec) -> usize { *held.entry((k.0, k.1)).or_default() += size_of(&e.pm); } } - let in_view = held.values().sum::(); // Smaller levels alone don't make an asset cached. held.retain(|k, _| c.map.contains_key(&(k.0, k.1, 0))); + let in_view = held.values().sum::(); for k in index.keys() { if c.bad.contains_key(k) { held.entry(*k).or_default(); @@ -278,7 +278,9 @@ pub(crate) fn warm(wants: Vec) -> usize { continue; } pixels = total; - jobs.push((decoding, wanted)); + // The estimate covers the decoded image and its converted pixels; leave headroom for + // temporary buffers inside individual format decoders. + jobs.push((decoding.saturating_mul(3) / 2, wanted)); } if jobs.len() < 2 { return 0; From 9595f3d62e62963df4e3118b24c3b0df8a523601 Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Thu, 12 Nov 2026 14:23:50 -0800 Subject: [PATCH 1060/1349] Anchored text frames: test nested hosts in groups, footnotes and table cells (#2722) Adds three tests for a text frame anchored inside another anchored text frame: the outer frame as a member of an anchored group with a rotation and a scale, the inner frame in a footnote of the outer frame, and the inner frame in a table cell of the outer frame. Each checks the inner frame's spread, transform and page. --- crates/compose/src/tests.rs | 120 ++++++++++++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 59777d657..3c182f871 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -9622,6 +9622,126 @@ fn a_frame_anchored_in_an_anchored_frame_is_placed_through_both_hosts() { assert_eq!(Cache::new().get(&d, isid, None).frames.len(), 1); } +/// An unplaced `w` × `h` text frame showing a new story of `text`, ready to anchor. +fn anchored_text_frame(d: &mut Document, text: &str, w: f64, h: f64) -> (designcraft_doc::Item, StoryId) { + let lid = d.default_layer(); + let (fid, fsid) = (ItemId(d.alloc()), StoryId(d.alloc())); + let mut story = Story::with_text(fsid, text, ParaFormat::default()); + story.frames.push(fid); + d.stories.insert(fsid, Arc::new(story)); + let mut it = + designcraft_doc::Item::new(fid, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, w, h))); + it.content = Content::Text(designcraft_doc::TextFrame { story: fsid, options: Default::default() }); + (it, fsid) +} + +/// A one-page document whose body frame holds `outer` anchored before its second line. Returns +/// the body frame and the body story's composition. +fn body_holding(d: &mut Document, outer: designcraft_doc::Item) -> (ItemId, ComposedStory) { + let lid = d.default_layer(); + let body = "One.\nTwo.\nThree."; + let (bf, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 400.0, 400.0), lid, body, ParaFormat::default()).unwrap(); + d.story_mut(sid).unwrap().insert_object(body.find("Two").unwrap(), designcraft_doc::AnchoredObject::new(outer, Default::default())); + (bf, compose_story(d, sid, &ComposeOptions::default())) +} + +/// `isid`'s one frame, `inner`, is placed on page 1 with parent space `want`, and the cache +/// composes it there. +fn assert_placed_on_page_one(d: &Document, isid: StoryId, inner: ItemId, want: Affine) { + let placed = placed::placements(d, isid, &mut |h| Arc::new(compose_story(d, h, &ComposeOptions::default()))); + assert_eq!(placed.len(), 1, "{placed:?}"); + let (id, p) = placed[0]; + assert_eq!((id, p.spread), (inner, SpreadRef::Doc(0))); + let (got, want) = (p.xf.as_coeffs(), want.as_coeffs()); + assert!(got.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{got:?} != {want:?}"); + assert_eq!(frame_specs_placed(d, isid, &placed)[0].page, Some(0)); + assert_eq!(Cache::new().get(d, isid, None).frames.len(), 1); +} + +/// A text frame anchored in an anchored text frame that is a member of an anchored group with a +/// rotation and a scale is placed through the group's transform and the member's own. +#[test] +fn a_frame_anchored_in_a_grouped_anchored_frame_is_placed_through_the_group() { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let (mut outer, osid) = anchored_text_frame(&mut d, "Outer text", 200.0, 100.0); + let (inner, isid) = anchored_text_frame(&mut d, "Inner", 80.0, 30.0); + let (outer_id, inner_id) = (outer.id, inner.id); + outer.xf = Affine::translate((12.0, 7.0)); + d.story_mut(osid).unwrap().insert_object("Outer ".len(), designcraft_doc::AnchoredObject::new(inner, Default::default())); + let mut g = + designcraft_doc::Item::new(ItemId(d.alloc()), d.default_layer(), designcraft_doc::Shape::Group, designcraft_geom::PathData::default()); + g.content = Content::Group { items: vec![Arc::new(outer)] }; + g.xf = Affine::rotate(0.25) * Affine::scale(1.25); + let (gid, gxf) = (g.id, g.xf); + let (bf, host) = body_holding(&mut d, g); + + let o1 = &host.frame(bf).unwrap().objects[0]; + // The composed group keeps its rotation and scale; its offset puts its box at the object's origin. + let gxf_placed = o1.object.item.xf; + assert_eq!((o1.object.item.id, gxf_placed.as_coeffs()[..4].to_vec()), (gid, gxf.as_coeffs()[..4].to_vec())); + let mid = compose_story(&d, osid, &ComposeOptions::default()); + let o2 = &mid.frame(outer_id).unwrap().objects[0]; + let want = d.text_xf(d.item(bf).unwrap()) + * Affine::translate(o1.origin.to_vec2()) + * gxf_placed + * d.text_xf(d.anchored_item(outer_id).unwrap()) + * Affine::translate(o2.origin.to_vec2()); + assert_placed_on_page_one(&d, isid, inner_id, want); +} + +/// A text frame anchored in a footnote of an anchored text frame is placed through the footnote's +/// spot in that frame as well as both hosts. +#[test] +fn a_frame_anchored_in_a_footnote_of_an_anchored_frame_is_placed_through_the_footnote() { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let (outer, osid) = anchored_text_frame(&mut d, "Outer text", 200.0, 120.0); + let (inner, isid) = anchored_text_frame(&mut d, "Inner", 80.0, 30.0); + let (outer_id, inner_id) = (outer.id, inner.id); + let st = d.story_mut(osid).unwrap(); + st.insert_note("Outer".len(), "Note text", ParaFormat::default()); + Arc::make_mut(&mut st.notes[0]).text.insert_object("Note ".len(), designcraft_doc::AnchoredObject::new(inner, Default::default())); + let (bf, host) = body_holding(&mut d, outer); + + let o1 = &host.frame(bf).unwrap().objects[0]; + let mid = compose_story(&d, osid, &ComposeOptions::default()); + let note = &mid.frame(outer_id).unwrap().notes[0]; + let o2 = ¬e.text.frames[0].objects[0]; + let want = d.text_xf(d.item(bf).unwrap()) + * Affine::translate(o1.origin.to_vec2()) + * d.text_xf(d.anchored_item(outer_id).unwrap()) + * Affine::translate(note.origin.to_vec2()) + * Affine::translate(o2.origin.to_vec2()); + assert_placed_on_page_one(&d, isid, inner_id, want); +} + +/// A text frame anchored in a table cell of an anchored text frame is placed through the cell's +/// spot in that frame as well as both hosts. +#[test] +fn a_frame_anchored_in_a_table_cell_of_an_anchored_frame_is_placed_through_the_cell() { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let (outer, osid) = anchored_text_frame(&mut d, "Outer text", 200.0, 150.0); + let (inner, isid) = anchored_text_frame(&mut d, "Inner", 80.0, 30.0); + let (outer_id, inner_id) = (outer.id, inner.id); + let mut table = designcraft_doc::Table::new(77, 1, 1, 0, 0, 180.0); + table.cells[0].text.insert(0, "Cell "); + table.cells[0].text.insert_object("Cell ".len(), designcraft_doc::AnchoredObject::new(inner, Default::default())); + let st = d.story_mut(osid).unwrap(); + let end = st.len(); + st.insert_table(end, table); + let (bf, host) = body_holding(&mut d, outer); + + let o1 = &host.frame(bf).unwrap().objects[0]; + let mid = compose_story(&d, osid, &ComposeOptions::default()); + let cell = &mid.frame(outer_id).unwrap().tables[0].cells[0]; + let o2 = &cell.text.frames[0].objects[0]; + let want = d.text_xf(d.item(bf).unwrap()) + * Affine::translate(o1.origin.to_vec2()) + * d.text_xf(d.anchored_item(outer_id).unwrap()) + * Affine::translate(cell.origin.to_vec2()) + * Affine::translate(o2.origin.to_vec2()); + assert_placed_on_page_one(&d, isid, inner_id, want); +} + /// A marginal note (an anchored text frame, Only Align First Line to Grid, 9/10) hangs 15 pt /// above its anchor's baseline on a right-hand page. It composes against the document grid where /// it is placed: its first line moves down onto the grid line, the second follows 10 pt below, From c803ea80b10429204dba64baede4be5c2846a0aa Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Thu, 12 Nov 2026 14:24:34 -0800 Subject: [PATCH 1061/1349] Compose: vertical justification in a shaped frame tests lines to their baselines (#2708) Center, Bottom and Justify tested every moved line except the last against the frame's outline down to its descent, so an outline that narrows under an earlier line held the text higher by that line's descent. Each moved line is now tested from its top down to its baseline, and its descenders may cross the outline, as the last line's already did. Above footnotes and in vertical frames the descenders still stay inside. --- ROADMAP.md | 1 + crates/compose/src/lib.rs | 12 +++++++----- crates/compose/src/tests.rs | 33 ++++++++++++++++++++++++++++++--- 3 files changed, 38 insertions(+), 8 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index afecef5d3..9e83d73ae 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -395,6 +395,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log - **2026-11-12** · An edit of a long threaded story composes the paragraphs it can change and copies the other lines from the composition before the edit; every typed character composed the whole story. In a 240-paragraph story a typed character composes 3 paragraphs (240 before). An edit that moves lines into other frames composes on until a paragraph starts in the same frame and place as before, or to the story's end, and stories with footnotes, tables, anchored objects, balanced columns or keep options that move lines are composed whole. No readiness percentage change. +- **2026-11-12** · Center, Bottom and Justify vertical justification in a shaped frame test each moved line against the outline down to its baseline. The descenders of earlier lines may cross the outline, as the last line's do, so an outline that narrows under an earlier line no longer holds the text higher by that line's descent. No readiness percentage change. - **2026-11-12** · Type shortcuts: Justify All Lines ⇧⌘F, Insert White Space › Em Space ⇧⌘M and En Space ⇧⌘N (shown in the menu, enabled at an insertion point), Paragraph Rules… ⌥⌘J (shown in the Paragraph panel menu). On the Mac a menu-bar insert (Em/En Space, Current Page Number) no longer types into the document while a text field has focus, a dialog or Quick Apply is open, or an input method is composing. An alignment the paragraphs already have records no undo step (#1138). No readiness percentage change. - **2026-11-12** · A placed JPEG drawn at a half, a quarter or an eighth of its pixel size or less is decoded at that size straight from its compressed blocks, so the canvas, page thumbnails and loaded-graphic thumbnails no longer decode and keep the full-size picture for it. CMYK JPEGs and the full size still decode in full. No readiness percentage change. - **2026-11-12** · A decoded placed image becomes a screen pixmap in its own buffer, premultiplied in place, and opaque pixels are left as they are: 120 ms becomes 7 ms for a 24-megapixel opaque photo, with the same pixels. No readiness percentage change. diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 9c423cec0..e2665720e 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -6066,12 +6066,14 @@ fn vertical_justify( }; // Only the last row's descenders hang below the bottom of the text: an earlier line whose // ink reaches below the last baseline (tight leading) isn't moved past the text area. - // In a shaped frame each moved line's slot stays inside the outline over its new band, as - // when the line was fitted: a frame that narrows towards the bottom holds the text higher. - let in_outline = |l: &Line, last: bool, dy: f64| match &f.outline { + // In a shaped frame each moved line's slot stays inside the outline from its top down to + // its baseline: a frame that narrows towards the bottom holds the text higher. Every moved + // line's descenders may cross the outline, as the last line's do below the bottom of the + // text; above footnotes, and in vertical frames, they stay inside. + let in_outline = |l: &Line, dy: f64| match &f.outline { Some(o) => { let b = l.baseline + dy; - let desc = if last && !inside { 0.0 } else { l.descent.max(0.0) }; + let desc = if inside { l.descent.max(0.0) } else { 0.0 }; let tol = 1e-6; o.intervals(l.x0, l.x1, (b - l.ascent).max(f.area.y0).min(b), b + desc).iter().any(|&(a, z)| a <= l.x0 + tol && z >= l.x1 - tol) } @@ -6095,7 +6097,7 @@ fn vertical_justify( let fits = |shift: &[f64]| { idx.iter().zip(&rows).rev().all(|(&i, &k)| { let l = &ft.lines[i]; - shift[k] <= 0.0 || ((k == n || l.baseline + l.descent + shift[k] <= limit + 1e-9) && in_outline(l, k == n, shift[k])) + shift[k] <= 0.0 || ((k == n || l.baseline + l.descent + shift[k] <= limit + 1e-9) && in_outline(l, shift[k])) }) && clear(shift) }; // In a rectangular frame fit decreases monotonically as the shift grows. A shaped diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 3c182f871..38dad232c 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -3019,13 +3019,13 @@ fn vertical_justification_keeps_lines_inside_a_shaped_frame() { assert!(lines.len() >= 2, "{mode:?}: {lines:?}"); (spec.area, lines) }; - // Narrowing downward: |x - 150| <= (300 - y) / 2 over each slot's band, the last line's - // descenders left out. + // Narrowing downward: |x - 150| <= (300 - y) / 2 over each slot's band, from the line's top to + // its baseline. let down = [Point::new(0.0, 0.0), Point::new(300.0, 0.0), Point::new(150.0, 300.0)]; for mode in [Center, Bottom, Justify] { let (area, lines) = compose_with(down, mode); for (k, l) in lines.iter().enumerate() { - let bottom = if k + 1 == lines.len() { l.baseline } else { l.baseline + l.descent }; + let bottom = l.baseline; let top = (l.baseline - l.ascent).max(area.y0); for (x, y) in [(l.x0, top), (l.x1, top), (l.x0, bottom), (l.x1, bottom)] { assert!((x - 150.0).abs() <= (300.0 - y) / 2.0 + 1e-3, "{mode:?}: line {k} corner ({x}, {y}) outside the triangle: {lines:?}"); @@ -3055,6 +3055,33 @@ fn vertical_justification_keeps_lines_inside_a_shaped_frame() { assert!((last.baseline - 260.0).abs() < 1e-3, "Bottom: last baseline at {}", last.baseline); } +/// In a shaped frame, Center and Bottom move every line until its slot reaches the outline at its +/// baseline: an earlier line's descenders may cross the outline, as the last line's do. A frame +/// full width down to 20 pt and half width below it holds the first line's baseline at 20 pt. +#[test] +fn vertical_justification_lets_earlier_descenders_cross_a_shaped_frame() { + use designcraft_doc::VerticalJustification::{Bottom, Center}; + use designcraft_geom::{Anchor, PathData, Point, SubPath}; + let pts = [(0.0, 0.0), (300.0, 0.0), (300.0, 20.0), (150.0, 20.0), (150.0, 300.0), (0.0, 300.0)]; + for mode in [Center, Bottom] { + let (mut d, sid, fid) = doc_with("Typography\ngypsy", Rect::new(0.0, 0.0, 300.0, 300.0), ParaAttrs::default()); + let it = d.item_mut(fid).unwrap(); + it.path = PathData::single(SubPath { anchors: pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), closed: true }); + let o = &mut it.text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.inset = [0.0; 4]; + assert!(frame_specs(&d, sid)[0].outline.is_some()); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + assert_eq!(lines.len(), 2, "{mode:?}: {lines:?}"); + let (first, last) = (lines[0], lines[1]); + assert!((first.x1 - 300.0).abs() < 1e-6 && (last.x1 - 150.0).abs() < 1e-6, "{mode:?}: slots {lines:?}"); + assert!(first.descent > 1.0, "{mode:?}: {first:?}"); + assert!((first.baseline - 20.0).abs() < 1e-3, "{mode:?}: first baseline at {}, step at 20", first.baseline); + assert!(last.baseline <= 300.0 + 1e-6, "{mode:?}: last baseline at {}", last.baseline); + } +} + /// In a shaped frame with a text wrap under the text, Center, Bottom and Justify keep the lines /// inside the outline and out of the wrap together: in a triangle that widens downward, Bottom and /// Justify put the last baseline on the wrap's top and Center moves half as far; in one that From 6923c220ad3920415efe0e12bd3c59e9295e7b95 Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Thu, 12 Nov 2026 14:24:40 -0800 Subject: [PATCH 1062/1349] Text wrap: Bottom and Center move a line down between a contour's arms (#2719) A line set in the open middle of a U-shaped contour now goes down to the contour's base. The clearance check tests the occupied parts of the contour in the line's band, as line setting does, instead of its outer extent across both arms. --- crates/compose/src/lib.rs | 7 ++++--- crates/compose/src/tests.rs | 38 +++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index e2665720e..a367e7ade 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -6309,9 +6309,10 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u { // A contour beside or under this line whose box reaches the line's slot (the // contour stays inside its box). Moved down by `d`, the line's band sweeps from its - // top to its baseline plus `d`; the contour's extent there only grows with `d`, so - // the furthest clear move is found by bisection to 0.01 pt. - let hits = |d: f64| contour.band_extent(top + dy, bottom + d + dy).and_then(|x| sided(e, col, x)).is_some_and(meets); + // top to its baseline plus `d`; the parts of the contour there only grow with `d`, + // so the furthest clear move is found by bisection to 0.01 pt. As when the line is + // set, the gaps between parts of the contour stay open. + let hits = |d: f64| contour.band_spans(top + dy, bottom + d + dy).into_iter().any(|x| sided(e, col, x).is_some_and(meets)); let (mut lo, mut hi) = ((r.y0 - bottom).max(0.0), (r.y1 - top).min(f.area.y1 - bottom).min(cap)); if lo < hi && hits(hi) { if hits(lo) { diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 38dad232c..ccc71578d 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -723,6 +723,44 @@ fn vertical_justification_stops_where_a_contour_under_the_text_meets_it() { assert!(b > 122.0, "Bottom stopped the line at {b}, short of where the contour meets the column at 122.5"); } +/// A line set in the open middle of a U-shaped contour goes down between its arms: Bottom stops +/// it on the contour's base, not where the line starts because the arms span its slot. +#[test] +fn vertical_justification_moves_a_line_down_between_the_arms_of_a_contour() { + use designcraft_doc::VerticalJustification::{Bottom, Top}; + // Arms 0..15 and 45..60 from y = 0, joined by a base from y = 170 down to y = 190. + let pts = [ + Point::new(0.0, 0.0), + Point::new(15.0, 0.0), + Point::new(15.0, 170.0), + Point::new(45.0, 170.0), + Point::new(45.0, 0.0), + Point::new(60.0, 0.0), + Point::new(60.0, 190.0), + Point::new(0.0, 190.0), + ]; + let run = |vj| { + let (mut d, sid, fid) = doc_with("42", Rect::new(0.0, 0.0, 60.0, 200.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = vj; + let lid = d.default_layer(); + let path = designcraft_geom::path::PathData::single(designcraft_geom::path::SubPath::polyline(&pts, true)); + let mut it = designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Polygon, path); + it.wrap.mode = WrapMode::Contour; + it.wrap.side = WrapSide::BothSides; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + let l = all_lines(&cs)[0]; + (l.baseline, l.x0, l.x1) + }; + let (top, x0, x1) = run(Top); + assert!(x0 >= 15.0 - 1e-6 && x1 <= 45.0 + 1e-6, "Top sets the line between the arms: {x0}..{x1}"); + let (b, x0, x1) = run(Bottom); + assert!(x0 >= 15.0 - 1e-6 && x1 <= 45.0 + 1e-6, "Bottom keeps the line between the arms: {x0}..{x1}"); + assert!(b <= 170.0 + 1e-6, "Bottom moved the baseline to {b}, into the contour's base at 170"); + assert!(b > 169.9, "Bottom stopped the line at {b} (Top at {top}), short of the contour's base at 170"); +} + /// An object anchored in the text and positioned from its anchor moves down with the lines, so /// Center places lines above it as it places them without its wrap. #[test] From 66b8c8ba3e1b66faf8b48b69647e2e982761a437 Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Thu, 12 Nov 2026 14:25:39 -0800 Subject: [PATCH 1063/1349] Object styles: checks and fixes for corners, strokes and the style dialog (#2721) - Corner options use path order for a path with more than one subpath, so a second rectangle no longer takes the first one's corner order. - IDML export writes EnableStrokeAndCornerOptions="false" for a style without corners, so it does not take corners from its based-on style on import. - style.object.create and style.object.edit refuse a stroke gap tint outside 0 to 1 and a stroke type field that its kind does not take, as object.stroke does. An edit that changes nothing returns restyled: 0. - New Object Style and Object Style Options read a bare number in the document's ruler unit, keep a Text Frame General measurement that was not edited at its exact value, and New Object Style refuses a name another style has. - Clear Overrides in the Object Styles panel is enabled when any selected object differs from its style. --- crates/engine/src/cmd/object.rs | 30 +++--- crates/engine/src/cmd/style.rs | 4 +- crates/engine/src/cmd/style/object.rs | 17 +++- crates/engine/src/tests.rs | 19 +++- crates/geom/src/corners.rs | 10 +- crates/idml/src/export/styles.rs | 2 +- crates/idml/src/tests/object_styles.rs | 14 +++ crates/ui-egui/src/object_style_dialog.rs | 114 +++++++++++++++++++--- crates/ui-egui/src/panels/styles.rs | 58 +++++++++-- 9 files changed, 222 insertions(+), 46 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 03e93a35b..c269e4f1d 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -26,6 +26,22 @@ pub(crate) fn known_swatch(doc: &designcraft_doc::Document, name: &str, cmd: &st Err(bad(cmd, format!("{key}: no swatch named `{name}`{hint}; create one with `swatch.create` and use its returned name"))) } +/// The fields of a stroke `type` object must be `kind` and the one its kind takes (`pattern` for +/// dashed, `bands` for stripes, `name` for style). `kind` is the type's own, else `base_kind`. +pub(crate) fn check_stroke_type_fields(v: &Value, base_kind: Option<&str>, cmd: &str) -> Result<()> { + let Some(fields) = v.as_object() else { return Ok(()) }; + let field = match v.get("kind").and_then(Value::as_str).or(base_kind) { + Some("dashed") => Some("pattern"), + Some("stripes") => Some("bands"), + Some("style") => Some("name"), + _ => None, + }; + match fields.keys().find(|key| *key != "kind" && Some(key.as_str()) != field) { + Some(key) => Err(bad(cmd, format!("type: unknown field `{key}`"))), + None => Ok(()), + } +} + pub fn specs() -> Vec { vec![ cmd!( @@ -265,19 +281,7 @@ pub fn specs() -> Vec { let kind: Option = p .get("type") .map(|v| { - if let Some(fields) = v.as_object() { - let field = match v.get("kind").and_then(Value::as_str) { - Some("dashed") => Some("pattern"), - Some("stripes") => Some("bands"), - Some("style") => Some("name"), - _ => None, - }; - for key in fields.keys() { - if key != "kind" && Some(key.as_str()) != field { - return Err(bad("object.stroke", format!("type: unknown field `{key}`"))); - } - } - } + check_stroke_type_fields(v, None, "object.stroke")?; serde_json::from_value(v.clone()).map_err(|e| bad("object.stroke", format!("type: {e}"))) }) .transpose()?; diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 7e55e0529..0b592786c 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -182,7 +182,7 @@ pub fn specs() -> Vec { "New Object Style…", [], None, - "{name, fromSelection?: true (fill, stroke, corners, effects and text frame options of the first selected item), fill?: swatch | {swatch?, tint?}, stroke?: {swatch?, weight?, tint?, type?, …} (swatches must exist; unknown fill and stroke keys are refused), corners?: {shape?, size?} | {corners: [{shape, size}] ×4}, paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns? (1–40), columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right] | one number for all four, verticalJustification?: top|center|bottom|justify, vjParagraphSpacingLimit?, ignoreWrap?} | null (Text Frame General Options, named as `document.inspect` names text frame options; lengths 0–15552 pt; other keys are refused; a frame keeps its baseline, auto-size and column rule settings; null: the style sets none), effects?: {dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?}, dropShadow?: {on?, color?, opacity? (0–1), angle?, globalLight?, distance?, size?, spread?}, feather?: width, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} → {name} (made unique)", + "{name, fromSelection?: true (fill, stroke, corners, effects and text frame options of the first selected item), fill?: swatch | {swatch?, tint?}, stroke?: {swatch?, weight?, tint?, type?, …} (swatches must exist; tint and gapTint 0–1; unknown fill, stroke and stroke type keys are refused), corners?: {shape?, size?} | {corners: [{shape, size}] ×4}, paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns? (1–40), columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right] | one number for all four, verticalJustification?: top|center|bottom|justify, vjParagraphSpacingLimit?, ignoreWrap?} | null (Text Frame General Options, named as `document.inspect` names text frame options; lengths 0–15552 pt; other keys are refused; a frame keeps its baseline, auto-size and column rule settings; null: the style sets none), effects?: {dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?}, dropShadow?: {on?, color?, opacity? (0–1), angle?, globalLight?, distance?, size?, spread?}, feather?: width, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} → {name} (made unique)", has_doc, create_object ), @@ -191,7 +191,7 @@ pub fn specs() -> Vec { "Object Style Options…", [], None, - "{name, rename?: new name (every use follows), fill?: swatch | {swatch?, tint?} | null, stroke?: {swatch?, weight?, tint?, type?, …} | null (swatches must exist; unknown fill and stroke keys are refused), corners?: {shape?: none|rounded|inverseRounded|inset|bevel|fancy, size?} | {corners: [{shape, size}] ×4} | null (null: the style no longer sets it; items keep theirs), paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns? (1–40), columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right] | one number for all four, verticalJustification?: top|center|bottom|justify, vjParagraphSpacingLimit?, ignoreWrap?} | null (Text Frame General Options, named as `document.inspect` names text frame options; lengths 0–15552 pt; other keys are refused; a frame keeps its baseline, auto-size and column rule settings; null: the style sets none), effects?: {…} | null (the style no longer sets effects), dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} — effect objects merge field by field into the style's effects (fields as in `document.inspect` item effects); values that aren't finite numbers are refused, the others clamped (opacities 0–1, sizes and distances ≥ 0); items using the style whose effects (fill, stroke, corners) match the style's (an item's defaults, when the style set none) take the new ones, items with their own keep them; the text of frames still in the old paragraph styles takes the new ones → {name, updated, restyled}", + "{name, rename?: new name (every use follows), fill?: swatch | {swatch?, tint?} | null, stroke?: {swatch?, weight?, tint?, type?, …} | null (swatches must exist; tint and gapTint 0–1; unknown fill, stroke and stroke type keys are refused), corners?: {shape?: none|rounded|inverseRounded|inset|bevel|fancy, size?} | {corners: [{shape, size}] ×4} | null (null: the style no longer sets it; items keep theirs), paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns? (1–40), columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right] | one number for all four, verticalJustification?: top|center|bottom|justify, vjParagraphSpacingLimit?, ignoreWrap?} | null (Text Frame General Options, named as `document.inspect` names text frame options; lengths 0–15552 pt; other keys are refused; a frame keeps its baseline, auto-size and column rule settings; null: the style sets none), effects?: {…} | null (the style no longer sets effects), dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} — effect objects merge field by field into the style's effects (fields as in `document.inspect` item effects); values that aren't finite numbers are refused, the others clamped (opacities 0–1, sizes and distances ≥ 0); items using the style whose effects (fill, stroke, corners) match the style's (an item's defaults, when the style set none) take the new ones, items with their own keep them; the text of frames still in the old paragraph styles takes the new ones → {name, updated, restyled}", has_doc, edit_object ), diff --git a/crates/engine/src/cmd/style/object.rs b/crates/engine/src/cmd/style/object.rs index a8572a3fa..630eaf117 100644 --- a/crates/engine/src/cmd/style/object.rs +++ b/crates/engine/src/cmd/style/object.rs @@ -243,11 +243,17 @@ fn bool_param(cmd: &str, p: &Value, key: &str) -> Result> { } } -/// `p.stroke` merged over `base` (as [`group_param`]), refused when the weight isn't a number ≥ 0 -/// or the tint isn't 0–1. +/// `p.stroke` merged over `base` (as [`group_param`]), refused when the weight isn't a number ≥ 0, +/// the tint or gap tint isn't 0–1, or the type has a field its kind doesn't take. fn stroke_param(cmd: &str, p: &Value, base: Option<&designcraft_doc::Stroke>) -> Result>> { let optional = ["gapOverprint", "gradientAngle", "gradientVector"]; - let st = group_param(cmd, p, "stroke", base.unwrap_or(&designcraft_doc::Stroke::default()), &optional)?; + let base = base.cloned().unwrap_or_default(); + // A type without `kind` keeps the style's kind, so it takes that kind's fields. + if let Some(t) = p.get("stroke").and_then(|s| s.get("type")) { + let base_kind = serde_json::to_value(&base.kind).ok().and_then(|k| k.get("kind").and_then(Value::as_str).map(str::to_string)); + crate::cmd::object::check_stroke_type_fields(t, base_kind.as_deref(), cmd)?; + } + let st = group_param(cmd, p, "stroke", &base, &optional)?; if let Some(Some(st)) = &st { if !(st.weight.is_finite() && st.weight >= 0.0) { return Err(bad(cmd, "stroke weight must be a number ≥ 0")); @@ -255,6 +261,9 @@ fn stroke_param(cmd: &str, p: &Value, base: Option<&designcraft_doc::Stroke>) -> if !(0.0..=1.0).contains(&st.tint) { return Err(bad(cmd, "stroke tint must be 0..1")); } + if !(0.0..=1.0).contains(&st.gap_tint) { + return Err(bad(cmd, "stroke gap tint must be 0..1")); + } } Ok(st) } @@ -382,7 +391,7 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { new.name = r.clone(); } if new == old { - return Ok(json!({"name": name, "updated": 0})); + return Ok(json!({"name": name, "updated": 0, "restyled": 0})); } s.edit(|d, _| { let Some(os) = d.styles_mut().object.iter_mut().find(|o| o.name == name) else { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index afbd25e73..10b42ee68 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -752,8 +752,9 @@ fn object_style_effects_follow_the_style_until_overridden() { assert_eq!(s.doc().unwrap().revision, rev); } -/// `style.object.create` and `edit` refuse an unknown swatch, a misspelled setting, a word or null -/// for a switch, a rename that isn't a name and a corner size outside 0–10000 pt. +/// `style.object.create` and `edit` refuse an unknown swatch, a misspelled setting (a stroke type's +/// included), a word or null for a switch, a rename that isn't a name, a corner size outside +/// 0–10000 pt and a stroke gap tint outside 0–1. #[test] fn object_style_parameters_are_checked() { let mut s = session(); @@ -768,6 +769,11 @@ fn object_style_parameters_are_checked() { json!({"corners": {"size": -1}}), json!({"corners": {"size": 10_001}}), json!({"applyNextStyle": null}), + json!({"stroke": {"gapTint": -1}}), + json!({"stroke": {"gapTint": 1.5}}), + json!({"stroke": {"type": {"kind": "dashed", "pattern": [2, 2], "patern": [4, 4]}}}), + json!({"stroke": {"type": {"kind": "solid", "pattern": [2, 2]}}}), + json!({"stroke": {"type": {"bands": [[0, 0.5]]}}}), ] { let mut p = bad.clone(); p["name"] = json!("Framed"); @@ -787,6 +793,15 @@ fn object_style_parameters_are_checked() { assert!(!names.iter().any(|n| n == "Other" || n == "Odd"), "{names:?}"); } +/// An edit that leaves the style as it is answers with the same fields as one that changes it. +#[test] +fn an_object_style_edit_that_changes_nothing_reports_no_restyled_frames() { + let mut s = session(); + s.execute("style.object.create", &json!({"name": "Framed", "fromSelection": false})).unwrap(); + let r = s.execute("style.object.edit", &json!({"name": "Framed"})).unwrap(); + assert_eq!((r["name"].as_str(), r["updated"].as_u64(), r["restyled"].as_u64()), (Some("Framed"), Some(0), Some(0)), "{r}"); +} + /// The course's "Rounded Corner Image, White Stroke" style: made from a frame with rounded corners /// and a paper stroke, applied to another frame, then edited (a thicker stroke, bigger corners): /// the frames that follow the style change, one with its own stroke keeps it; a rename follows. diff --git a/crates/geom/src/corners.rs b/crates/geom/src/corners.rs index 9c1bfbb00..10db62fd4 100644 --- a/crates/geom/src/corners.rs +++ b/crates/geom/src/corners.rs @@ -60,7 +60,7 @@ pub struct CornerOptions { /// anchors at four different corners keeps a rectangle's order. pub fn named_slots(path: &PathData) -> [usize; 4] { let rect_order = [0, 1, 2, 3]; - let Some(sp) = path.subpaths.first() else { return rect_order }; + let [sp] = path.subpaths.as_slice() else { return rect_order }; let Some(b) = path.bounds() else { return rect_order }; if sp.anchors.len() != 4 { return rect_order; @@ -317,6 +317,14 @@ mod tests { assert_eq!(named.named_to_path(&rectangle(Rect::new(0.0, 0.0, 10.0, 10.0))), named); let tri = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(5.0, 9.0)], true)); assert_eq!(named.named_to_path(&tri), named); + // A path of two rectangles keeps the order: one subpath's order can't name the other's + // anchors. + let two = PathData::new(vec![ + SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(0.0, 100.0), Point::new(100.0, 100.0), Point::new(100.0, 0.0)], true), + SubPath::polyline(&[Point::new(40.0, 40.0), Point::new(60.0, 40.0), Point::new(60.0, 60.0), Point::new(40.0, 60.0)], true), + ]); + assert_eq!(named_slots(&two), [0, 1, 2, 3]); + assert_eq!(named.named_to_path(&two), named); } #[test] diff --git a/crates/idml/src/export/styles.rs b/crates/idml/src/export/styles.rs index d131dc19d..b5dc46cff 100644 --- a/crates/idml/src/export/styles.rs +++ b/crates/idml/src/export/styles.rs @@ -121,8 +121,8 @@ impl<'a> Ex<'a> { el.set("EnableStroke", bool_s(os.stroke.is_some())); el.set("EnableParagraphStyle", bool_s(os.paragraph_style.is_some())); el.set("EnableTextFrameGeneralOptions", bool_s(os.text_frame.is_some())); + el.set("EnableStrokeAndCornerOptions", bool_s(os.corners.is_some())); if let Some(c) = &os.corners { - el.set("EnableStrokeAndCornerOptions", "true"); for (n, c) in ["TopLeft", "TopRight", "BottomRight", "BottomLeft"].iter().zip(c.corners) { el.set(&format!("{n}CornerOption"), names::corner_out(c.shape)); el.set(&format!("{n}CornerRadius"), num(c.size)); diff --git a/crates/idml/src/tests/object_styles.rs b/crates/idml/src/tests/object_styles.rs index 52cfd3e20..719936f40 100644 --- a/crates/idml/src/tests/object_styles.rs +++ b/crates/idml/src/tests/object_styles.rs @@ -177,6 +177,20 @@ fn object_style_apply_next_style_round_trips() { } } +/// A style that sets no corners keeps none after export and import, though the style it is based +/// on sets rounded corners. +#[test] +fn a_style_without_corners_keeps_none_over_its_based_on_style() { + let mut d = small_doc(); + let rounded = Some(designcraft_geom::corners::CornerOptions::uniform(CornerShape::Rounded, 12.0)); + let styles = std::sync::Arc::make_mut(&mut d.styles); + styles.object.push(designcraft_doc::ObjectStyle { name: "Round".into(), corners: rounded, ..Default::default() }); + styles.object.push(designcraft_doc::ObjectStyle { name: "Square".into(), based_on: Some("Round".into()), ..Default::default() }); + let back = import_idml(&export_idml(&d)).unwrap(); + assert_eq!(back.styles.object_style("Round").and_then(|s| s.corners), rounded); + assert_eq!(back.styles.object_style("Square").and_then(|s| s.corners), None); +} + /// A style's Text Frame General Options take each setting its own `TextFramePreference` leaves out /// from the style it is based on (named by its id or bare name, and only when that style doesn't /// turn the category off), and export and import keep the merged options. diff --git a/crates/ui-egui/src/object_style_dialog.rs b/crates/ui-egui/src/object_style_dialog.rs index 4200732a9..a89ef46d9 100644 --- a/crates/ui-egui/src/object_style_dialog.rs +++ b/crates/ui-egui/src/object_style_dialog.rs @@ -28,20 +28,31 @@ const ATTRIBUTES: [(&str, &str); 6] = [ /// The fields of the Paragraph Styles and Text Frame General Options pages: the style's paragraph /// style (`""`: none), Apply Next Style, and text frame options `tf` as the Text Frame Options -/// dialog shows them (`tfBase` keeps the options the page doesn't show). +/// dialog shows them (`tfBase` keeps the options as they are, `tfShown` the fields as first shown). fn text_fields(app: &DesignApp, fields: &mut Value, paragraph: Option<&str>, next: bool, tf: &designcraft_doc::TextFrameOptions) { - let units = app.session.active().map_or(designcraft_geom::Unit::Picas, |s| s.doc.settings.horizontal_units); fields["paragraphStyle"] = json!(paragraph.unwrap_or("")); fields["applyNext"] = json!(next); fields["tfBase"] = serde_json::to_value(tf).unwrap_or_default(); fields["insetLinked"] = json!(tf.inset.iter().all(|v| (v - tf.inset[0]).abs() < 1e-9)); - if let (Value::Object(f), Value::Object(shown)) = - (fields, crate::dialogs::text_frame_fields(tf, units, None, &crate::dialogs::document_grid(app))) - { + let shown = crate::dialogs::text_frame_fields(tf, doc_units(app), None, &crate::dialogs::document_grid(app)); + fields["tfShown"] = shown.clone(); + if let (Value::Object(f), Value::Object(shown)) = (fields, shown) { f.extend(shown); } } +/// The active document's ruler unit, which a bare number in a measurement field is in. +fn doc_units(app: &DesignApp) -> designcraft_geom::Unit { + app.session.active().map_or(designcraft_geom::Unit::Picas, |s| s.doc.settings.horizontal_units) +} + +/// The dialog with `fields`, reading bare numbers in the document's ruler unit. +fn dialog(app: &DesignApp, fields: Value) -> Dialog { + let mut d = Dialog::new(ID, fields); + d.unit = doc_units(app); + d +} + /// The active document as the dialog records it: its uid and the epoch that File › Revert /// changes. fn document_key(app: &DesignApp) -> Value { @@ -85,7 +96,7 @@ pub fn open_new(app: &mut DesignApp) { "apply": from, }); text_fields(app, &mut fields, None, false, &frame.unwrap_or_default()); - app.ui.dialog = Some(Dialog::new(ID, fields)); + app.ui.dialog = Some(dialog(app, fields)); } /// Object Style Options for style `name`; refused for a style the document doesn't have and for @@ -116,7 +127,7 @@ pub fn open_edit(app: &mut DesignApp, name: &str) -> Result<(), String> { "apply": false, }); text_fields(app, &mut fields, os.paragraph_style.as_deref(), os.apply_next_style, &os.text_frame.clone().unwrap_or_default()); - app.ui.dialog = Some(Dialog::new(ID, fields)); + app.ui.dialog = Some(dialog(app, fields)); Ok(()) } @@ -157,23 +168,31 @@ fn frame_options(d: &Dialog) -> Result } let mut o: designcraft_doc::TextFrameOptions = d.fields.get("tfBase").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); let bad = |what: &str| format!("Text Frame General Options: {what}"); - let measure = |key: &str| d.m(key).filter(|v| v.is_finite() && (0.0..=15552.0).contains(v)); + // A field still as first shown keeps the option's value, which the field shows rounded. + let shown = d.fields.get("tfShown").cloned().unwrap_or(Value::Null); + let measure = |key: &str, was: f64| { + if d.fields.get(key).is_some_and(|v| *v == shown[key]) { + return Some(was); + } + d.m(key).filter(|v| v.is_finite() && (0.0..=15552.0).contains(v)) + }; o.columns = d .n("columns") .filter(|n| (1.0..=40.0).contains(n) && n.fract() == 0.0) .ok_or_else(|| bad("the number of columns is a whole number from 1 to 40"))? as u32; - o.gutter = measure("gutter").ok_or_else(|| bad("the gutter is not a measure"))?; + o.gutter = measure("gutter", o.gutter).ok_or_else(|| bad("the gutter is not a measure"))?; o.columns_kind = serde_json::from_value(json!(d.s("columnsKind"))).unwrap_or(o.columns_kind); if o.columns_kind == designcraft_doc::ColumnsKind::FixedWidth { - o.column_width = measure("columnWidth").ok_or_else(|| bad("the column width is not a measure"))?; + o.column_width = measure("columnWidth", o.column_width).ok_or_else(|| bad("the column width is not a measure"))?; } o.balance_columns = d.b("balanceColumns"); for (side, key) in o.inset.iter_mut().zip(["insetTop", "insetLeft", "insetBottom", "insetRight"]) { - *side = measure(key).ok_or_else(|| bad("an inset is not a measure"))?; + *side = measure(key, *side).ok_or_else(|| bad("an inset is not a measure"))?; } o.vertical_justification = serde_json::from_value(json!(d.s("verticalJustification"))).unwrap_or(o.vertical_justification); if o.vertical_justification == designcraft_doc::VerticalJustification::Justify { - o.vj_paragraph_spacing_limit = measure("paragraphSpacingLimit").ok_or_else(|| bad("the paragraph spacing limit is not a measure"))?; + o.vj_paragraph_spacing_limit = + measure("paragraphSpacingLimit", o.vj_paragraph_spacing_limit).ok_or_else(|| bad("the paragraph spacing limit is not a measure"))?; } o.ignore_wrap = d.b("ignoreWrap"); Ok(Some(o)) @@ -198,6 +217,10 @@ pub fn confirm(app: &mut DesignApp, d: &Dialog) -> Result { let mut p = attrs(d); p.insert("textFrame".into(), frame_options(d)?.map_or(Value::Null, |o| general_json(&o))); if d.b("new") { + // A name another style has is refused, as Object Style Options refuses it. + if app.session.active().is_some_and(|st| st.doc.styles.object_style(&name).is_some()) { + return Err(format!("an object style is already named `{name}`")); + } p.insert("name".into(), json!(name)); p.insert("fromSelection".into(), json!(false)); let r = app.run("style.object.create", Value::Object(p)).map_err(|e| e.to_string())?; @@ -775,8 +798,8 @@ mod tests { assert!(app.ui.dialog.as_ref().is_some_and(|d| d.b("new"))); } - /// A refused OK (an empty name, a name another style has) keeps the dialog and its edits, - /// with the reason shown. + /// A refused OK (an empty name, a name another style has, in Object Style Options and in New + /// Object Style) keeps the dialog and its edits, with the reason shown. #[test] fn a_refused_ok_keeps_the_dialog_open_with_the_reason() { let (mut app, _) = app_with_frame(); @@ -801,6 +824,69 @@ mod tests { let e = crate::dialogs::confirm(&mut app).unwrap_err(); assert!(e.contains("already named"), "{e}"); assert!(app.ui.dialog.as_ref().is_some_and(|d| d.s("status") == e)); + // New Object Style with a name another style has makes no style under another name. + app.ui.dialog = None; + let count = |app: &DesignApp| app.session.active().unwrap().doc.styles.object.len(); + let before = count(&app); + open_new(&mut app); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("name".into(), json!("Taken")); + } + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("already named"), "{e}"); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.s("status") == e)); + assert_eq!(count(&app), before, "no style was made"); + } + + fn app_with_text_frame(units: &str) -> DesignApp { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("document.preferences", json!({"horizontalUnits": units, "verticalUnits": units})).unwrap(); + let r = app.run("frame.create", json!({"rect": [36, 36, 336, 336], "content": "text", "caret": false})).unwrap(); + app.run("selection.set", json!({"ids": [r["id"]]})).unwrap(); + app + } + + /// In a document measured in millimeters, a bare number in a Text Frame General Options field + /// is millimeters, in New Object Style and in Object Style Options. + #[test] + fn bare_numbers_are_in_the_documents_ruler_unit() { + let mut app = app_with_text_frame("millimeters"); + let mm = 72.0 / 25.4; + let frame = |app: &DesignApp| app.session.active().unwrap().doc.styles.object_style("Metric").and_then(|s| s.text_frame.clone()).unwrap(); + open_new(&mut app); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("name".into(), json!("Metric")); + for k in ["insetTop", "insetLeft", "insetBottom", "insetRight"] { + d.fields.insert(k.into(), json!("6")); + } + } + crate::dialogs::confirm(&mut app).unwrap(); + assert!(frame(&app).inset.iter().all(|v| (v - 6.0 * mm).abs() < 1e-6), "{:?}", frame(&app).inset); + open_edit(&mut app, "Metric").unwrap(); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("columns".into(), json!("2")); + d.fields.insert("gutter".into(), json!("5")); + } + crate::dialogs::confirm(&mut app).unwrap(); + assert!((frame(&app).gutter - 5.0 * mm).abs() < 1e-6, "{}", frame(&app).gutter); + } + + /// Object Style Options keeps a General measurement the user did not edit exactly as the style + /// has it, though the field shows it rounded. + #[test] + fn general_measurements_left_alone_keep_their_value() { + let mut app = app_with_text_frame("points"); + let tf = json!({"gutter": 2.123456, "inset": [1.23456, 2.34567, 3.45678, 4.56789]}); + app.run("style.object.create", json!({"name": "Precise", "fromSelection": false, "textFrame": tf})).unwrap(); + open_edit(&mut app, "Precise").unwrap(); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("name".into(), json!("Precise Too")); + d.fields.insert("insetTop".into(), json!("7 pt")); + } + crate::dialogs::confirm(&mut app).unwrap(); + let o = app.session.active().unwrap().doc.styles.object_style("Precise Too").and_then(|s| s.text_frame.clone()).unwrap(); + assert_eq!((o.gutter, o.inset), (2.123456, [7.0, 2.34567, 3.45678, 4.56789])); } /// Object Style Options and New Object Style act only on the document they opened for. With diff --git a/crates/ui-egui/src/panels/styles.rs b/crates/ui-egui/src/panels/styles.rs index fac694ace..3b2d19e1e 100644 --- a/crates/ui-egui/src/panels/styles.rs +++ b/crates/ui-egui/src/panels/styles.rs @@ -110,15 +110,21 @@ pub fn character(app: &mut DesignApp, ui: &mut egui::Ui) { fn object_style_of_selection(app: &DesignApp) -> Option<(String, bool)> { let st = app.session.active()?; let it = st.selection.items.first().and_then(|i| st.doc.item(*i))?; + Some((it.object_style.clone(), overrides_its_style(&st.doc, it))) +} + +/// Whether `it` differs from its object style: its own attributes, or a text frame's paragraphs +/// in other styles than the object style gives them. +fn overrides_its_style(doc: &designcraft_doc::Document, it: &designcraft_doc::Item) -> bool { + let Some(os) = doc.styles.object_style(&it.object_style) else { return false }; let mut styled = it.clone(); - let mut over = false; - if let Some(os) = st.doc.styles.object_style(&it.object_style) { - os.apply_to(&mut styled); - if let Some(tf) = it.text_frame() { - over = st.doc.story(tf.story).is_some_and(|s| !os.story_follows(&st.doc.styles, s)); - } - } - Some((it.object_style.clone(), over || styled != *it)) + os.apply_to(&mut styled); + styled != *it || it.text_frame().is_some_and(|tf| doc.story(tf.story).is_some_and(|s| !os.story_follows(&doc.styles, s))) +} + +/// Whether any selected object differs from its object style (Clear Overrides clears them all). +fn selection_overrides_styles(app: &DesignApp) -> bool { + app.session.active().is_some_and(|st| st.selection.items.iter().filter_map(|i| st.doc.item(*i)).any(|it| overrides_its_style(&st.doc, it))) } /// Window › Styles › Object Styles, as InDesign's: the selected object's style on top (`+` when @@ -188,7 +194,7 @@ pub fn object(app: &mut DesignApp, ui: &mut egui::Ui) { crate::object_style_dialog::open_new(app); } } - let over = current.as_ref().is_some_and(|c| c.1); + let over = selection_overrides_styles(app); if ui.add_enabled_ui(over, |ui| icons::button(ui, "style-clear", 20.0, false, crate::i18n::tr(&lang, "Clear Overrides"))).inner.clicked() && over { @@ -409,6 +415,40 @@ mod tests { assert!(styles.contains(&"Object Style 1".to_string()), "{styles:?}"); } + /// Clear Overrides is on when any selected frame differs from its style, not only the first; + /// the label on top describes the first. + #[test] + fn clear_overrides_is_on_when_a_later_selected_frame_is_overridden() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let frame = |app: &mut DesignApp, x: f64| { + app.run("frame.create", json!({"rect": [x, 36, x + 100.0, 136], "content": "graphic"})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (frame(&mut app, 36.0), frame(&mut app, 200.0)); + app.run("style.object.create", json!({"name": "Framed", "fromSelection": false, "stroke": {"swatch": "[Paper]", "weight": 3}})).unwrap(); + app.run("style.object.apply", json!({"name": "Framed", "ids": [a, b]})).unwrap(); + app.run("object.stroke", json!({"weight": 1, "ids": [b]})).unwrap(); + app.run("selection.set", json!({"ids": [a, b]})).unwrap(); + let mut h = Harness::builder().with_size(vec2(320.0, 260.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let id = egui::Id::unique("test_fonts"); + if ui.data(|d| d.get_temp::(id)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(id, true)); + return; + } + object(app, ui); + }, + app, + ); + h.run_steps(4); + assert_eq!(h.get_all_by_label("Framed").count(), 2, "the first frame follows its style"); + h.get_by_label("Clear Overrides").click(); + h.run_steps(3); + let weight = |h: &Harness| h.state().session.active().unwrap().doc.item(designcraft_doc::ItemId(b)).unwrap().stroke.weight; + assert_eq!(weight(&h), 3.0); + } + #[test] fn paragraph_color_override_is_marked_and_cleared_from_the_row_menu() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); From 5fb75aaefcf71d57e328c581b8602c08c97ed7ec Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Thu, 12 Nov 2026 14:27:08 -0800 Subject: [PATCH 1064/1349] Properties: Text Frame section shows inset spacing and vertical justification (#2661) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Properties: Text Frame section shows inset spacing and vertical justification Properties › Text Frame now shows the frame's inset spacing under the columns: Top and Bottom, a link that makes all four the same, then Left and Right. A non-rectangular frame shows one Inset, the distance its text keeps from the outline. Four buttons set Vertical Justification to Top, Center, Bottom or Justify. Type on a path shows neither. The section also shows with the Type tool in a frame. There it changes the frame that shows the insertion point, or every frame that holds part of the selected text, as Object › Text Frame Options does. * Properties: one Inset for a non-rectangular frame keeps the other sides The single Inset sets only the top inset, the one kept from the outline. A rectangular frame that holds part of the same selected text keeps its own sides. * Properties: the one Inset field and the composer share the frame outline test FrameOutline::of_item builds an item's outline with its corner options applied. The composer uses it to keep the top inset from the outline, and the Properties panel uses it to decide whether a frame shows one Inset, so the two give the same answer for every frame. * Text Frame Options: frames taken while typing stay with their document OK is refused when another document became active after the dialog opened, so the saved frame ids do not change frames in that document. * Properties: the inset link starts linked again after Revert The link's state is kept per document state instead of per document, so a frame with equal insets in the reverted document starts linked. * Text Frame Options: frames taken while typing are refused after Revert Revert keeps the document's id but replaces its state, so a new frame can reuse a saved frame id. The dialog now ties the frames to the document state, and OK is refused after Revert as it is in another document. * Properties: the one Inset of a non-rectangular frame sets all four sides The composer bounds a shaped frame's text by its rectangle less all four insets as well as by the outline, so a single Inset that changed only the top left hidden sides in place: lowering a uniform 96 pt inset to 0 kept text overset. When every frame the field changes is shaped, it now sets all four sides. With a rectangular frame among them, only the top inset changes and each frame keeps its other sides. * Fix text frame dialog merge resolution * Keep text frame preview targets fixed * Fix target field key inference * Tests: Text Frame Options show four sides for text through an oval and a rectangle With the Type tool and text selected through an oval and a threaded rectangle, with the oval as the caret's stored frame, the dialog shows the four inset sides, a changed Top leaves the rectangle's other sides as they were, and the link stays off while the rectangle's sides are uneven. * Properties: the inset link starts off when another frame has uneven sides With selected text that runs through several frames, the link of Text Frame > Inset Spacing started linked when the frame the section shows had four equal insets, and a changed Top then set all four sides of every frame. The link now starts linked only when every frame the field changes has four equal insets. Its state is kept for that set of frames, so a link turned on for one frame does not carry over to selected text that also runs through a frame with uneven sides. --------- Co-authored-by: Dylan M. Taylor --- ROADMAP.md | 2 + crates/compose/src/lib.rs | 5 +- crates/compose/src/outline.rs | 7 + crates/engine/src/cmd/object.rs | 1 - crates/ui-egui/src/dialogs.rs | 6 + crates/ui-egui/src/dialogs/tests.rs | 55 +++- crates/ui-egui/src/icons.rs | 27 ++ crates/ui-egui/src/panels/properties.rs | 9 +- crates/ui-egui/src/panels/properties/tests.rs | 269 +++++++++++++++++- crates/ui-egui/src/panels/properties/text.rs | 132 ++++++++- docs/target-app-parity.md | 1 + 11 files changed, 496 insertions(+), 18 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 9e83d73ae..ee0f4e022 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -394,12 +394,14 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log +- **2026-11-12** · Properties › Text Frame shows the frame's inset spacing (Top, Bottom, Left and Right with a link that makes all four the same; one Inset for a non-rectangular frame) and four Vertical Justification buttons (Top, Center, Bottom, Justify), and the section also shows with the Type tool in a frame, where it changes the frame that shows the insertion point. No readiness percentage change. - **2026-11-12** · An edit of a long threaded story composes the paragraphs it can change and copies the other lines from the composition before the edit; every typed character composed the whole story. In a 240-paragraph story a typed character composes 3 paragraphs (240 before). An edit that moves lines into other frames composes on until a paragraph starts in the same frame and place as before, or to the story's end, and stories with footnotes, tables, anchored objects, balanced columns or keep options that move lines are composed whole. No readiness percentage change. - **2026-11-12** · Center, Bottom and Justify vertical justification in a shaped frame test each moved line against the outline down to its baseline. The descenders of earlier lines may cross the outline, as the last line's do, so an outline that narrows under an earlier line no longer holds the text higher by that line's descent. No readiness percentage change. - **2026-11-12** · Type shortcuts: Justify All Lines ⇧⌘F, Insert White Space › Em Space ⇧⌘M and En Space ⇧⌘N (shown in the menu, enabled at an insertion point), Paragraph Rules… ⌥⌘J (shown in the Paragraph panel menu). On the Mac a menu-bar insert (Em/En Space, Current Page Number) no longer types into the document while a text field has focus, a dialog or Quick Apply is open, or an input method is composing. An alignment the paragraphs already have records no undo step (#1138). No readiness percentage change. - **2026-11-12** · A placed JPEG drawn at a half, a quarter or an eighth of its pixel size or less is decoded at that size straight from its compressed blocks, so the canvas, page thumbnails and loaded-graphic thumbnails no longer decode and keep the full-size picture for it. CMYK JPEGs and the full size still decode in full. No readiness percentage change. - **2026-11-12** · A decoded placed image becomes a screen pixmap in its own buffer, premultiplied in place, and opaque pixels are left as they are: 120 ms becomes 7 ms for a 24-megapixel opaque photo, with the same pixels. No readiness percentage change. - **2026-11-12** · The status bar's preflight count and the Preflight panel take their issues from a check on a background worker, which checks the newest state of the document and shows the issues last found meanwhile. Moving or resizing a frame and typing no longer wait for a check of the whole document on every drag step and keystroke. No readiness percentage change. + - **2026-11-12** · Object › Text Frame Options… (Cmd+B) opens with the Type tool in a frame, so inset spacing and vertical justification can be changed while typing; it changes the frame that shows the insertion point, or every frame that holds part of the selected text (#2396). No readiness percentage change. - **2026-11-04** · Striped strokes retain out-and-back cubic segments whose second control point is away from the coincident endpoints and first control point. A geometry regression checks the offset extent and both stripe bands. No readiness percentage change. - **2026-11-04** · Esperanto is a text language (Character › Language, `type.char {language: "Esperanto"}`, IDML `$ID/Esperanto`): tag `eo`, English-style quotes; not hyphenated yet (#1201). No readiness percentage change. diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index a367e7ade..333959626 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -1205,10 +1205,7 @@ pub(crate) fn frame_specs_placed(doc: &Document, sid: StoryId, placed: &[(ItemId // area (all four insets) still bounds the lines. let outline = match &tf.options.path { Some(_) => None, - None => { - let bp = if item.corners.is_none() { item.path.to_bezpath() } else { designcraft_geom::corners::apply(&item.path, &item.corners) }; - FrameOutline::new(&bp, tf.options.inset[0]) - } + None => FrameOutline::of_item(item, tf.options.inset[0]), }; // Vertical type: composed in the turned box; wraps and page rects turned with it. let vertical = doc.frame_vertical(item); diff --git a/crates/compose/src/outline.rs b/crates/compose/src/outline.rs index bfc709710..dd1f59c0e 100644 --- a/crates/compose/src/outline.rs +++ b/crates/compose/src/outline.rs @@ -59,6 +59,13 @@ impl FrameOutline { Some(FrameOutline { edges, inset }) } + /// The outline of `item`'s path with its corner options applied, or None when that is the + /// item's own rectangle. The composer and the Properties panel's one Inset field both use it. + pub fn of_item(item: &designcraft_doc::Item, inset: f64) -> Option { + let bp = if item.corners.is_none() { item.path.to_bezpath() } else { designcraft_geom::corners::apply(&item.path, &item.corners) }; + FrameOutline::new(&bp, inset) + } + /// The outline mapped by `xf` (into a vertical frame's turned box). pub fn transformed(&self, xf: Affine) -> FrameOutline { FrameOutline { edges: self.edges.iter().map(|&(a, b)| (xf * a, xf * b)).collect(), inset: self.inset } diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index c269e4f1d..c41564047 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -2732,7 +2732,6 @@ fn content_type(s: &mut Session, p: &Value) -> Result { /// The most columns a text frame takes. const MAX_FRAME_COLUMNS: u64 = 40; - /// The frames `object.textFrameOptions` changes when the call names none: the selected objects, /// or with the Type tool the frame that shows the caret or every frame holding part of the /// selected text. diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a5babb120..409943f75 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1173,6 +1173,12 @@ fn seed_text_frame_options(app: &DesignApp, d: &mut Dialog) { m.insert("inset".into(), json!(format_measure(o.inset[0], units))); } d.fields.insert("_shaped".into(), json!(shaped)); + if let Some(targets) = typing_frame_ids(app) { + d.fields.entry("_targets").or_insert(targets); + if let Some(epoch) = app.session.active().map(|doc| doc.identity_epoch) { + d.fields.entry("_targetsDoc").or_insert(json!(epoch)); + } + } if let Value::Object(m) = &shown { for (k, v) in m { d.fields.entry(k.clone()).or_insert_with(|| v.clone()); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 0bad3ce0e..ca057856d 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1690,6 +1690,47 @@ fn text_frame_options_show_four_sides_for_a_mixed_selection() { assert!(d.b("_shaped")); } +/// With the Type tool, text selected through an oval and a threaded rectangle shows the four +/// sides even when the caret's frame is the oval, and a changed side leaves the rectangle's other +/// sides as they were. +#[test] +fn text_frame_options_show_four_sides_for_text_through_an_oval_and_a_rectangle() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let text = (0..40).map(|i| format!("Line {i} of the threaded story.")).collect::>().join(" "); + let oval = app.run("frame.create", json!({"rect": [36, 36, 236, 136], "shape": "ellipse", "content": "text", "text": text})).unwrap(); + let sid = oval["story"].as_u64().unwrap(); + let oval = designcraft_doc::ItemId(oval["id"].as_u64().unwrap()); + let rect = app.run("frame.create", json!({"rect": [36, 200, 336, 700], "content": "text", "text": "", "caret": false})).unwrap(); + let rect = designcraft_doc::ItemId(rect["id"].as_u64().unwrap()); + app.run("text.thread", json!({"from": oval.0, "to": rect.0})).unwrap(); + app.run("object.textFrameOptions", json!({"ids": [oval.0, rect.0], "inset": [6, 2, 3, 4]})).unwrap(); + let opts = |app: &DesignApp, id| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.clone(); + let select_through_both = |app: &mut DesignApp| { + app.run("text.select", json!({"story": sid, "anchor": 0, "focus": text.len()})).unwrap(); + // The caret's stored frame is the oval. + if let Some(t) = app.session.active_mut().unwrap().selection.text.as_mut() { + t.frame = Some(oval); + } + assert_eq!(designcraft_engine::cmd::text_frame_options_frames(&app.session), vec![oval, rect], "the selected text runs through both frames"); + }; + select_through_both(&mut app); + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(&app, &mut d); + assert!(!d.b("_shaped") && !d.fields.contains_key("inset"), "text through a rectangle shows the four sides"); + d.fields.insert("insetTop".into(), json!("1p0")); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + assert_eq!(opts(&app, rect).inset, [12.0, 2.0, 3.0, 4.0]); + assert_eq!(opts(&app, oval).inset, [12.0, 2.0, 3.0, 4.0]); + // An even oval does not link the sides while the rectangle's sides are uneven. + app.run("object.textFrameOptions", json!({"ids": [oval.0], "inset": [5, 5, 5, 5]})).unwrap(); + select_through_both(&mut app); + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(&app, &mut d); + assert!(!d.b("insetLinked"), "a frame with uneven sides among the targets leaves the link off"); +} + /// The dialog dims Top, Left, Bottom, Right and the link for a non-rectangular frame and adds an /// Inset field; for a rectangle it shows no Inset field and the sides stay editable. #[test] @@ -4350,12 +4391,20 @@ fn retype_beside(h: &mut egui_kittest::Harness<'static, crate::test_window::Wind h.run_steps(3); } +/// The dialog's "Make all settings the same" links, in reading order: the Properties panel's +/// own links (its Text Frame insets, with a caret in a frame) are to the right of its Quick +/// Actions heading's left edge and are left out. +fn dialog_links(h: &egui_kittest::Harness<'static, crate::test_window::Window>) -> Vec { + use egui_kittest::kittest::Queryable; + let panel_left = h.query_by_label("Quick Actions").map_or(f32::INFINITY, |n| n.rect().left()); + h.get_all_by_label("Make all settings the same").map(|n| n.rect()).filter(|r| r.center().x < panel_left).collect() +} + /// The course's chapter 40: Paragraph Border's four weights are linked as InDesign's, so a /// side typed in sets all four; with the link off ("Make all settings the same") a side is set /// alone, as the lesson gives the border only a thick left side. The corners link the same way. #[test] fn paragraph_border_sides_and_corners_link_as_indesigns() { - use egui_kittest::kittest::Queryable; let (app, _) = ruled_paragraph(); let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); h.state_mut().app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "border", "p.borderOn": true}))); @@ -4370,7 +4419,7 @@ fn paragraph_border_sides_and_corners_link_as_indesigns() { // The link of the weights (0), corners (1) or offsets (2), where it is now: the dialog // scrolls as fields take focus. let link = |h: &egui_kittest::Harness<'static, crate::test_window::Window>, n: usize| { - let links: Vec = h.get_all_by_label("Make all settings the same").map(|n| n.rect()).collect(); + let links = dialog_links(h); assert_eq!(links.len(), 3, "weights, corners and offsets each have a link"); links[n].center() }; @@ -4427,7 +4476,7 @@ fn paragraph_shading_page_is_laid_out_as_indesigns() { assert_eq!(field(&h, "shadingOverprint"), json!(true)); // The corners' link (0) and the offsets' (1). let link = |h: &egui_kittest::Harness<'static, crate::test_window::Window>, n: usize| { - let links: Vec = h.get_all_by_label("Make all settings the same").map(|n| n.rect()).collect(); + let links = dialog_links(h); assert_eq!(links.len(), 2, "corners and offsets each have a link"); links[n].center() }; diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index c8eeee911..e15c90ec9 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -997,6 +997,19 @@ fn paint_text(pen: &mut Pen, name: &str) -> bool { pen.line(&[(12.0, 3.5), (12.0, 16.5)]); pen.line(&[(9.0, 10.0), (11.0, 10.0)]); } + "vjust-top" | "vjust-center" | "vjust-bottom" | "vjust-justify" => { + // A frame with three lines of text at its top, middle or bottom, or spread over it. + pen.rect(2.5, 2.5, 17.5, 17.5); + let ys = match name { + "vjust-top" => [5.5, 8.0, 10.5], + "vjust-center" => [7.5, 10.0, 12.5], + "vjust-bottom" => [9.5, 12.0, 14.5], + _ => [5.5, 10.0, 14.5], + }; + for y in ys { + pen.line(&[(5.0, y), (15.0, y)]); + } + } "small-caps" => { // Two original T shapes share a baseline; no phonetic small-cap glyph is required. pen.line(&[(3.0, 5.0), (10.0, 5.0)]); @@ -1383,6 +1396,20 @@ mod tests { } } + /// Each Vertical Justification button in Properties › Text Frame has its own glyph. + #[test] + fn vertical_justification_glyphs_are_distinct() { + let names = ["vjust-top", "vjust-center", "vjust-bottom", "vjust-justify"]; + let unknown = drawing("no-such-icon"); + let glyphs: Vec = names.iter().map(|n| drawing(n)).collect(); + for (k, g) in glyphs.iter().enumerate() { + assert_ne!(*g, unknown, "{} falls back to the placeholder", names[k]); + for (j, other) in glyphs.iter().enumerate().skip(k + 1) { + assert_ne!(g, other, "{} and {} draw alike", names[k], names[j]); + } + } + } + #[test] fn distribute_icons_are_distinct_from_align_and_each_other() { // `objalign-*` ship upstream and back the Properties Align row; only the diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 9b949f547..b6dabfe65 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -38,7 +38,8 @@ pub use object_panels::{align_panel, attributes_panel, effects_panel, pathfinder use object_panels::{anchor_point_sections, pathfinder_row}; pub(crate) use text::{LANGUAGES, kerning_control, language_menu}; use text::{ - bullets_section, character_section, paragraph_section, quick_actions_text, text_appearance_section, text_frame_section, text_style_section, + bullets_section, character_section, paragraph_section, quick_actions_text, text_appearance_section, text_frame_section, text_frame_target, + text_style_section, }; pub use typography::{DIGIT_OPTIONS, character_panel, digit_label, paragraph_panel, show_typography_panel}; #[cfg(test)] @@ -137,6 +138,12 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { section(ui, crate::i18n::tr(&app.ui.language, "Bullets and Numbering"), true); bullets_section(app, ui); divider(ui); + // The frame that shows the caret, as with the frame selected. + if text_frame_target(app).is_some() { + section(ui, crate::i18n::tr(&app.ui.language, "Text Frame"), true); + text_frame_section(app, ui); + divider(ui); + } section(ui, crate::i18n::tr(&app.ui.language, "Quick Actions"), true); quick_actions_text(app, ui); return; diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 59e0cbd1e..1792e3b3a 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -798,7 +798,9 @@ fn bullets_options_open_the_bullets_and_numbering_dialog() { let f = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "4 eggs"})).unwrap(); app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 6})).unwrap(); let mut h = panel(app); - h.get_by_label("Options").click(); + // Bullets and Numbering's Options, above Text Frame's. + let bullets = h.get_all_by_label("Options").min_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap(); + bullets.click(); h.run_steps(3); let d = h.state().ui.dialog.clone().expect("a dialog"); assert_eq!((d.id.as_str(), d.s("section").as_str()), ("paragraphLocal", "bullets")); @@ -1278,6 +1280,269 @@ fn transform_flips_and_rotates_from_properties() { assert!(h.query_by(|n| n.role() == egui::accesskit::Role::TextInput && n.value().as_deref() == Some("90°")).is_some()); } +/// The vertical extent of Properties › Text Frame: from its heading (the last "Text Frame" label; +/// the selection band above may say "Text Frame" too) to the Quick Actions heading. +fn text_frame_band(h: &Harness<'_, DesignApp>) -> (f32, f32) { + let top = h.get_all_by_label("Text Frame").map(|n| n.rect().bottom()).fold(f32::MIN, f32::max); + (top, h.get_by_label("Quick Actions").rect().top()) +} + +/// The text fields of Properties › Text Frame, in reading order. +fn text_frame_fields(h: &Harness<'_, DesignApp>) -> Vec { + let (top, bottom) = text_frame_band(h); + let mut v: Vec = + h.get_all_by_role(egui::accesskit::Role::TextInput).map(|n| n.rect()).filter(|r| r.center().y > top && r.center().y < bottom).collect(); + v.sort_by(|a, b| (a.top(), a.left()).partial_cmp(&(b.top(), b.left())).unwrap()); + v +} + +/// Clicks the control labeled `label` inside Properties › Text Frame. +fn click_in_text_frame(h: &mut Harness<'_, DesignApp>, label: &str) { + let (top, bottom) = text_frame_band(h); + h.get_all_by_label(label).find(|n| n.rect().center().y > top && n.rect().center().y < bottom).unwrap().click(); + h.run_steps(3); +} + +fn type_in_field(h: &mut Harness<'_, DesignApp>, at: egui::Rect, text: &str) { + h.hover_at(at.center()); + h.drag_at(at.center()); + h.drop_at(at.center()); + h.run_steps(2); + h.event(egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }); + h.event(egui::Event::Text(text.into())); + h.key_press(egui::Key::Enter); + h.run_steps(3); +} + +fn frame_options(app: &DesignApp, id: u64) -> designcraft_doc::TextFrameOptions { + app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().text_frame().unwrap().options.clone() +} + +/// Properties › Text Frame shows the frame's inset spacing under the columns, linked while the +/// four insets are the same, and the four vertical justification buttons. Each change is one +/// undo step; the button that is already on adds none. +#[test] +fn properties_text_frame_sets_inset_spacing_and_vertical_justification() { + use designcraft_doc::VerticalJustification; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [72, 72, 300, 300], "content": "text", "text": "Hello"})).unwrap()["id"].as_u64().unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + let mut h = panel(app); + // Columns and gutter, then Top and Left, then Bottom and Right. + let f = text_frame_fields(&h); + assert_eq!(f.len(), 6, "columns, gutter and four insets: {f:?}"); + let steps = undo_steps(h.state()); + // Linked: the top inset sets all four. + type_in_field(&mut h, f[2], "12pt"); + assert_eq!(frame_options(h.state(), id).inset, [12.0; 4]); + assert_eq!(undo_steps(h.state()), steps + 1); + // Unlinked: the bottom one alone. + click_in_text_frame(&mut h, "Make all settings the same"); + let f = text_frame_fields(&h); + type_in_field(&mut h, f[4], "6pt"); + assert_eq!(frame_options(h.state(), id).inset, [12.0, 12.0, 6.0, 12.0], "[top, left, bottom, right]"); + // Vertical justification. + assert_eq!(frame_options(h.state(), id).vertical_justification, VerticalJustification::Top); + for (label, vj) in + [("Bottom", VerticalJustification::Bottom), ("Center", VerticalJustification::Center), ("Justify", VerticalJustification::Justify)] + { + click_in_text_frame(&mut h, label); + assert_eq!(frame_options(h.state(), id).vertical_justification, vj, "{label}"); + } + let steps = undo_steps(h.state()); + click_in_text_frame(&mut h, "Justify"); + assert_eq!(undo_steps(h.state()), steps, "the button already on adds no undo step"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(frame_options(h.state(), id).vertical_justification, VerticalJustification::Center); +} + +/// Insets unlinked before Revert start linked again in the reverted document, whose frame has the +/// same id and four equal insets. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn properties_text_frame_inset_link_starts_linked_after_revert() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [72, 72, 300, 300], "content": "text", "text": "Hello"})).unwrap()["id"].as_u64().unwrap(); + let dir = tempfile::tempdir().unwrap(); + app.run("file.saveAs", json!({"path": dir.path().join("revert.designcraft")})).unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + let mut h = panel(app); + click_in_text_frame(&mut h, "Make all settings the same"); + h.state_mut().run("frame.create", json!({"rect": [320, 72, 400, 150], "content": "text", "text": "unsaved"})).unwrap(); + h.state_mut().run("file.revert", json!({})).unwrap(); + h.state_mut().run("selection.set", json!({"ids": [id]})).unwrap(); + h.run_steps(3); + let f = text_frame_fields(&h); + type_in_field(&mut h, f[4], "6pt"); + assert_eq!(frame_options(h.state(), id).inset, [6.0; 4], "linked: the bottom inset sets all four"); +} + +/// With the Type tool in the second frame of a thread, Properties shows the Text Frame section, +/// and its insets and vertical justification change that frame and not the first. +#[test] +fn properties_text_frame_shows_while_typing_and_changes_the_caret_frame() { + use designcraft_doc::VerticalJustification; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let text = (0..40).map(|i| format!("Line {i} of the threaded story.")).collect::>().join(" "); + let a = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": text})).unwrap(); + let b = app.run("frame.create", json!({"rect": [36, 200, 300, 700], "content": "text", "text": "", "caret": false})).unwrap(); + let (a, b, sid) = (a["id"].as_u64().unwrap(), b["id"].as_u64().unwrap(), a["story"].as_u64().unwrap()); + app.run("text.thread", json!({"from": a, "to": b})).unwrap(); + // The end of the story is in the second frame. + app.run("text.select", json!({"story": sid, "anchor": text.len()})).unwrap(); + let mut h = panel(app); + let f = text_frame_fields(&h); + assert_eq!(f.len(), 6, "columns, gutter and four insets while typing: {f:?}"); + type_in_field(&mut h, f[2], "9pt"); + click_in_text_frame(&mut h, "Bottom"); + let (oa, ob) = (frame_options(h.state(), a), frame_options(h.state(), b)); + assert_eq!((oa.inset, ob.inset), ([0.0; 4], [9.0; 4])); + assert_eq!((oa.vertical_justification, ob.vertical_justification), (VerticalJustification::Top, VerticalJustification::Bottom)); + assert!(h.state().session.active().unwrap().selection.text.is_some(), "the caret stays in the text"); +} + +/// A non-rectangular text frame shows one Inset, which sets the distance its text keeps from +/// the outline. The composer also bounds its text by all four insets, so the field sets all four. +#[test] +fn properties_text_frame_shows_one_inset_for_an_oval() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [72, 72, 300, 300], "shape": "ellipse", "content": "text", "text": "Hello"})).unwrap()["id"] + .as_u64() + .unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + let mut h = panel(app); + let f = text_frame_fields(&h); + assert_eq!(f.len(), 3, "columns, gutter and one inset: {f:?}"); + h.state_mut().run("object.textFrameOptions", json!({"ids": [id], "inset": [1, 2, 3, 4]})).unwrap(); + h.run_steps(2); + type_in_field(&mut h, f[2], "8pt"); + assert_eq!(frame_options(h.state(), id).inset, [8.0; 4]); +} + +/// Lowering an oval's uniform inset with the one Inset field lowers every side, so no hidden +/// side keeps the old inset and the text area that goes with it. +#[test] +fn properties_text_frame_one_inset_lowers_a_uniform_inset_on_every_side() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [72, 72, 300, 300], "shape": "ellipse", "content": "text", "text": "Hello"})).unwrap()["id"] + .as_u64() + .unwrap(); + app.run("object.textFrameOptions", json!({"ids": [id], "inset": 96})).unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + let mut h = panel(app); + let f = text_frame_fields(&h); + assert_eq!(f.len(), 3, "columns, gutter and one inset: {f:?}"); + type_in_field(&mut h, f[2], "0pt"); + assert_eq!(frame_options(h.state(), id).inset, [0.0; 4]); +} + +/// With selected text that runs from an oval into a rectangular frame, the one Inset field +/// changes the top inset of both, and each frame keeps its other sides. +#[test] +fn properties_text_frame_one_inset_keeps_the_sides_of_a_rectangle_in_the_selection() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let text = (0..40).map(|i| format!("Line {i} of the threaded story.")).collect::>().join(" "); + let a = app.run("frame.create", json!({"rect": [72, 72, 300, 300], "shape": "ellipse", "content": "text", "text": text})).unwrap(); + let b = app.run("frame.create", json!({"rect": [72, 400, 300, 760], "content": "text", "text": "", "caret": false})).unwrap(); + let (oval, rect, sid) = (a["id"].as_u64().unwrap(), b["id"].as_u64().unwrap(), a["story"].as_u64().unwrap()); + app.run("text.thread", json!({"from": oval, "to": rect})).unwrap(); + app.run("object.textFrameOptions", json!({"ids": [oval, rect], "inset": [1, 2, 3, 4]})).unwrap(); + app.run("text.select", json!({"story": sid, "anchor": 0, "focus": text.len()})).unwrap(); + assert_eq!( + designcraft_engine::cmd::text_frame_options_frames(&app.session), + [designcraft_doc::ItemId(oval), designcraft_doc::ItemId(rect)], + "the selected text runs through both frames" + ); + let mut h = panel(app); + let f = text_frame_fields(&h); + assert_eq!(f.len(), 3, "columns, gutter and one inset for the first frame, an oval: {f:?}"); + type_in_field(&mut h, f[2], "8pt"); + assert_eq!(frame_options(h.state(), oval).inset, [8.0, 2.0, 3.0, 4.0]); + assert_eq!(frame_options(h.state(), rect).inset, [8.0, 2.0, 3.0, 4.0]); +} + +/// With selected text that runs through two rectangular frames, the inset link starts off when +/// one of them has uneven sides, even while the frame the section shows has four equal insets, so +/// a changed Top leaves the other sides of each frame as they were. +#[test] +fn properties_text_frame_inset_link_starts_off_when_another_frame_has_uneven_sides() { + for even_first in [true, false] { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let text = (0..40).map(|i| format!("Line {i} of the threaded story.")).collect::>().join(" "); + let a = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": text})).unwrap(); + let b = app.run("frame.create", json!({"rect": [36, 200, 300, 700], "content": "text", "text": "", "caret": false})).unwrap(); + let (a, b, sid) = (a["id"].as_u64().unwrap(), b["id"].as_u64().unwrap(), a["story"].as_u64().unwrap()); + app.run("text.thread", json!({"from": a, "to": b})).unwrap(); + let (even, uneven) = if even_first { (a, b) } else { (b, a) }; + app.run("object.textFrameOptions", json!({"ids": [even], "inset": 5})).unwrap(); + app.run("object.textFrameOptions", json!({"ids": [uneven], "inset": [1, 2, 3, 4]})).unwrap(); + app.run("text.select", json!({"story": sid, "anchor": 0, "focus": text.len()})).unwrap(); + assert_eq!( + designcraft_engine::cmd::text_frame_options_frames(&app.session), + [designcraft_doc::ItemId(a), designcraft_doc::ItemId(b)], + "the selected text runs through both frames" + ); + let mut h = panel(app); + let f = text_frame_fields(&h); + assert_eq!(f.len(), 6, "columns, gutter and four insets: {f:?}"); + type_in_field(&mut h, f[2], "8pt"); + assert_eq!(frame_options(h.state(), even).inset, [8.0, 5.0, 5.0, 5.0], "even frame first: {even_first}"); + assert_eq!(frame_options(h.state(), uneven).inset, [8.0, 2.0, 3.0, 4.0], "even frame first: {even_first}"); + } +} + +/// A link turned on for one frame does not carry over to selected text that runs from that frame +/// into a frame with uneven sides: the link starts off there, and a changed Top leaves the other +/// sides as they were. +#[test] +fn properties_text_frame_inset_link_of_one_frame_does_not_carry_to_a_text_selection() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let text = (0..40).map(|i| format!("Line {i} of the threaded story.")).collect::>().join(" "); + let a = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": text})).unwrap(); + let b = app.run("frame.create", json!({"rect": [36, 200, 300, 700], "content": "text", "text": "", "caret": false})).unwrap(); + let (a, b, sid) = (a["id"].as_u64().unwrap(), b["id"].as_u64().unwrap(), a["story"].as_u64().unwrap()); + app.run("text.thread", json!({"from": a, "to": b})).unwrap(); + app.run("object.textFrameOptions", json!({"ids": [a], "inset": 5})).unwrap(); + app.run("object.textFrameOptions", json!({"ids": [b], "inset": [1, 2, 3, 4]})).unwrap(); + app.run("selection.set", json!({"ids": [a]})).unwrap(); + let mut h = panel(app); + // Off, then on again: the link of the first frame alone is now turned on by hand. + click_in_text_frame(&mut h, "Make all settings the same"); + click_in_text_frame(&mut h, "Make all settings the same"); + // The caret at the start of the story is in the first frame; the selection runs into the second. + h.state_mut().run("text.select", json!({"story": sid, "anchor": text.len(), "focus": 0})).unwrap(); + h.run_steps(3); + let f = text_frame_fields(&h); + assert_eq!(f.len(), 6, "columns, gutter and four insets: {f:?}"); + type_in_field(&mut h, f[2], "8pt"); + assert_eq!(frame_options(h.state(), a).inset, [8.0, 5.0, 5.0, 5.0]); + assert_eq!(frame_options(h.state(), b).inset, [8.0, 2.0, 3.0, 4.0]); +} + +/// Type on a path sets one line along the path: Properties › Text Frame shows no insets and no +/// vertical justification buttons for it. +#[test] +fn properties_text_frame_shows_no_insets_for_type_on_a_path() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "shape": "ellipse"})).unwrap()["id"].as_u64().unwrap(); + app.run("type.onPath", json!({"id": id, "text": "Around"})).unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + assert!(frame_options(&app, id).path.is_some()); + let h = panel(app); + assert_eq!(text_frame_fields(&h).len(), 2, "columns and gutter only"); + let (top, bottom) = text_frame_band(&h); + assert!(h.query_all_by_label("Justify").all(|n| n.rect().center().y < top || n.rect().center().y > bottom)); +} + /// With the Type tool, the Text Frame section shows the frame Text Frame Options change: the frame /// the caret is drawn in, not the caret's stored frame. #[test] @@ -1294,6 +1559,6 @@ fn text_frame_section_shows_the_frame_that_shows_the_caret() { // The end of the story is drawn in the second frame; the caret's stored frame is the first. app.session.doc_mut().unwrap().selection = Selection::text(TextSel { story: StoryId(sid), anchor: text.len(), focus: text.len(), frame: Some(ItemId(a)), cell: None }); - let shown = super::text::text_frame_target(&app).map(|(id, o)| (id, o.columns)); + let shown = super::text::text_frame_target(&app).map(|(id, o, _)| (id, o.columns)); assert_eq!(shown, Some((ItemId(b), 3))); } diff --git a/crates/ui-egui/src/panels/properties/text.rs b/crates/ui-egui/src/panels/properties/text.rs index f444d6ba2..94e3b4ef8 100644 --- a/crates/ui-egui/src/panels/properties/text.rs +++ b/crates/ui-egui/src/panels/properties/text.rs @@ -517,20 +517,31 @@ pub(super) fn quick_actions_text(app: &mut DesignApp, ui: &mut Ui) { } /// The text frame the Text Frame section shows, as Text Frame Options shows it: the first selected -/// frame, the frame that shows the caret, or the first frame holding selected text. Its id and its -/// options. -pub(super) fn text_frame_target(app: &DesignApp) -> Option<(designcraft_doc::ItemId, designcraft_doc::TextFrameOptions)> { +/// frame, the frame that shows the caret, or the first frame holding selected text. Its id, its +/// options, and whether its outline is not its own rectangle (an oval, a polygon or corner +/// options), where the text keeps one inset from the outline. Type on a path is not shaped. +pub(super) fn text_frame_target(app: &DesignApp) -> Option<(designcraft_doc::ItemId, designcraft_doc::TextFrameOptions, bool)> { let st = app.session.active()?; let fid = designcraft_engine::cmd::text_frame_options_frames(&app.session).first().copied()?; - Some((fid, st.doc.item(fid)?.text_frame()?.options.clone())) + let item = st.doc.item(fid)?; + let opts = item.text_frame()?.options.clone(); + Some((fid, opts, is_shaped(item))) } -/// Text Frame section: columns, gutter, [Options]. With the Type tool it changes the frame that -/// shows the caret, or every frame that holds part of the selected text. +/// Whether a text frame's outline is not its own rectangle, where its text keeps one inset from +/// the outline. Type on a path is not shaped. +fn is_shaped(item: &designcraft_doc::Item) -> bool { + item.text_frame().is_some_and(|tf| tf.options.path.is_none()) && designcraft_compose::FrameOutline::of_item(item, 0.0).is_some() +} + +/// Text Frame section: columns, gutter, [Options]; Inset Spacing (Top and Bottom, the link that +/// makes all four the same, Left and Right; one Inset for a non-rectangular frame); the four +/// Vertical Justification buttons (neither for type on a path). With the Type tool it changes the +/// frame that shows the caret, or every frame that holds part of the selected text. pub(super) fn text_frame_section(app: &mut DesignApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let u = units(app); - let Some((_, opts)) = text_frame_target(app) else { return }; + let Some((fid, opts, shaped)) = text_frame_target(app) else { return }; let b = block(ui, FIELD_H); icons::paint(ui.painter(), sub(b, 0.0, 1.0, 19.0, 19.0), "text-columns", t.icon); if let Some(v) = place(ui, sub(b, 22.0, 0.0, 54.0, FIELD_H), |ui| { @@ -548,6 +559,113 @@ pub(super) fn text_frame_section(app: &mut DesignApp, ui: &mut Ui) { if place(ui, sub(b, 164.0, 0.5, ow, 20.0), |ui| outline_button(ui, crate::i18n::tr(&app.ui.language, "Options"), ow)).clicked() { app.ui.dialog = Some(crate::dialogs::Dialog::new("textFrameOptions", json!({}))); } + // Type on a path sets one line along the path: insets and vertical justification do not apply. + if opts.path.is_some() { + return; + } + text_frame_insets(app, ui, fid, &opts, shaped); + ui.add_space(4.0); + let cur = opts.vertical_justification; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + for (vj, icon, tip) in [ + (designcraft_doc::VerticalJustification::Top, "vjust-top", "Top"), + (designcraft_doc::VerticalJustification::Center, "vjust-center", "Center"), + (designcraft_doc::VerticalJustification::Bottom, "vjust-bottom", "Bottom"), + (designcraft_doc::VerticalJustification::Justify, "vjust-justify", "Justify"), + ] { + if icon_toggle(ui, icon, cur == vj, crate::i18n::tr(&app.ui.language, tip)).clicked() { + let _ = app.run("object.textFrameOptions", json!({"verticalJustification": vj})); + } + } + }); +} + +/// Inset Spacing under the columns: Top and Bottom, the link that makes all four the same, then +/// Left and Right, as the wrap offsets are laid out. A non-rectangular frame shows one Inset, the +/// distance its text keeps from the outline. +fn text_frame_insets(app: &mut DesignApp, ui: &mut Ui, fid: designcraft_doc::ItemId, opts: &designcraft_doc::TextFrameOptions, shaped: bool) { + let t = Tokens::get(ui.ctx()); + let lang = app.ui.language.clone(); + let tr = |s: &str| crate::i18n::tr(&lang, s).to_string(); + let u = units(app); + let inset = opts.inset; + ui.add_space(4.0); + if shaped { + let b = block(ui, FIELD_H); + let ir = sub(b, 0.0, 2.0, 17.0, 17.0); + icons::paint(ui.painter(), ir, "margin-top", t.icon); + ui.interact(ir, ui.scope_id().with("prop_tf_inset"), Sense::hover()).on_hover_ui(|ui| { + crate::rtl::label(ui, tr("Inset")); + }); + if let Some(v) = place(ui, sub(b, 20.0, 0.0, 76.0, FIELD_H), |ui| { + NumField::measure("tfInset", Some(inset[0]), u).width(76.0).spinner().range(0.0, 15552.0).show(ui) + }) { + // The composer also bounds the text by the frame's rectangle less all four insets, so + // when every frame it changes is shaped the one Inset sets all four. With a + // rectangular frame among them (part of the same selected text), only the top inset + // changes and each frame keeps its other sides. + let all_shaped = app.session.active().is_some_and(|st| { + designcraft_engine::cmd::text_frame_options_frames(&app.session) + .iter() + .filter_map(|id| st.doc.item(*id)) + .filter(|it| it.text_frame().is_some_and(|tf| tf.options.path.is_none())) + .all(is_shaped) + }); + let inset = if all_shaped { json!(v) } else { json!([v, null, null, null]) }; + let _ = app.run("object.textFrameOptions", json!({"inset": inset})); + } + return; + } + let b = block(ui, 2.0 * FIELD_H + 5.0); + // The link's state belongs to the frames the field changes in this document state: other + // frames, or frames with the same ids in another document or after Revert, start linked when + // every one of them has four equal insets, so a frame with uneven sides keeps them when one + // side changes. + let doc_epoch = app.session.active().map_or(0, |st| st.identity_epoch); + let targets = designcraft_engine::cmd::text_frame_options_frames(&app.session); + let target_ids: Vec = targets.iter().map(|id| id.0).collect(); + let link_id = egui::Id::unique(("prop_tf_inset_linked", doc_epoch, fid.0, target_ids)); + let even = |i: &[f64; 4]| i.iter().all(|v| (v - i[0]).abs() < 1e-9); + let same = even(&inset) + && app.session.active().is_none_or(|st| targets.iter().filter_map(|id| st.doc.item(*id)?.text_frame()).all(|tf| even(&tf.options.inset))); + let linked = ui.data(|d| d.get_temp::(link_id)).unwrap_or(same); + let mut set = None; + // Insets are [top, left, bottom, right]. + for (k, key, icon, tip, x, y) in [ + (0, "tfInsetTop", "margin-top", "Top", 0.0, 0.0), + (2, "tfInsetBottom", "margin-bottom", "Bottom", 0.0, FIELD_H + 5.0), + (1, "tfInsetLeft", "margin-inside", "Left", 140.0, 0.0), + (3, "tfInsetRight", "margin-outside", "Right", 140.0, FIELD_H + 5.0), + ] { + let ir = sub(b, x, y + 2.0, 17.0, 17.0); + icons::paint(ui.painter(), ir, icon, t.icon); + ui.interact(ir, ui.scope_id().with(("prop_tf_inset", k)), Sense::hover()).on_hover_ui(|ui| { + crate::rtl::label(ui, tr(tip)); + }); + let nv = place(ui, sub(b, x + 20.0, y, 76.0, FIELD_H), |ui| { + NumField::measure(key, Some(inset[k]), u).width(76.0).spinner().range(0.0, 15552.0).show(ui) + }); + if let Some(v) = nv { + // Linked, all four; else this side alone. + let mut o = [None; 4]; + if linked { + o = [Some(v); 4]; + } else { + o[k] = Some(v); + } + set = Some(o); + } + } + if place(ui, sub(b, 106.0, (FIELD_H + 5.0) / 2.0, 22.0, FIELD_H), |ui| { + widgets::icon_toggle_sized(ui, if linked { "link" } else { "link-broken" }, linked, &tr("Make all settings the same"), vec2(22.0, 21.0)) + .clicked() + }) { + ui.data_mut(|d| d.insert_temp(link_id, !linked)); + } + if let Some(o) = set { + let _ = app.run("object.textFrameOptions", json!({"inset": o})); + } } /// Languages offered for text (InDesign-style names). diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 608b587f8..52bd45ddc 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -353,6 +353,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - Auto-size (Text Frame Options › Auto-Size, `object.textFrameOptions {autoSize: off|heightOnly|widthOnly|heightAndWidth|heightAndWidthProportionally, autoSizeReference, useMinimumHeight, minimumHeight, useMinimumWidth, minimumWidth, noLineBreaks}`): the frame fits its text exactly after every edit (typing, pasting, style changes, option changes) in the same undo step (opening a file keeps the frame sizes it gives); it grows and shrinks around the reference point, which stays put in spread space for rotated frames too, never below the minimum height/width and never past 10,000 pt. Width Only and No Line Breaks set each paragraph on one line; Height and Width without No Line Breaks keeps the width; Keep Proportions scales both sides until the text fits. IDML keeps all the options (`AutoSizing…`, `…ForAutoSizing` attributes). Not covered: frames of a thread other than the last, vertical frames, type on a path, and multi-column balancing in Keep Proportions. - Balance Columns (Text Frame Options › Balance Columns, `object.textFrameOptions {balanceColumns}`, IDML `VerticalBalanceColumns`): in the frame the story ends in, the columns after the last explicit column break fill to about the same depth (the last may be shorter by a line per column); keep options hold, spanning and split paragraphs keep their own balancing, vertical justification then applies to each column as usual, and vertical frames balance their bands. A frame the text runs on from, or that is overset, fills normally. - Text Frame Options from the Type tool (Object › Text Frame Options…, Cmd+B, `object.textFrameOptions` without `ids`): with the insertion point in a frame, the options change the frame it is drawn in; with text selected, every frame that holds part of it. Options a frame already has add no undo step. +- Properties › Text Frame (DesignCraft's own layout): columns and gutter; Inset Spacing with Top, Bottom, Left and Right and a link that makes all four the same (one Inset for a non-rectangular frame); four Vertical Justification buttons (Top, Center, Bottom, Justify); neither insets nor vertical justification for type on a path; Options opens Text Frame Options. With the Type tool in a frame the section shows too and changes the frame that shows the insertion point, or every frame that holds part of the selected text (`object.textFrameOptions {inset, verticalJustification}`). - Text Frame Options dialog, laid out as InDesign's (General, Column Rules, Baseline Options, Auto-Size; framed Columns, Inset Spacing and Vertical Justification groups with spinner fields; Fixed Number shows each column's width as the fields change). Preview shows the edits on the page until OK (one undo step) or Cancel. An invalid value (such as a gutter that isn't a measure) takes the preview off the page, so the frame shows as it was, and the dialog's status line gives the reason; OK refuses the value too. Preview stays checked and shows the edits again once the value is valid. Vertical Justification › Paragraph Spacing Limit (`object.textFrameOptions {paragraphSpacingLimit}`, IDML `VerticalThreshold`): with Justify, the extra space goes between paragraphs up to the limit, the rest between lines. - Text Frame Options › Inset Spacing for a non-rectangular frame (an oval, a polygon, a frame with corner options; when every selected text frame is one, a mixed selection keeps the four sides): Top, Left, Bottom, Right and the link are dimmed, and one Inset field sets the distance kept between the text and the frame's outline (`object.textFrameOptions {inset: }`, all four sides). - Place a page of an IDML or DesignCraft document (`file.place {layoutPage}`): its objects, stories, styles and swatches as one group (INDD files are not readable). From 67a5cb273ef40ff3190900bd2e2d2df6241d41e4 Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Thu, 12 Nov 2026 14:27:13 -0800 Subject: [PATCH 1065/1349] Tables: table commands are disabled with the caret in footnote text (#2706) Footnote text is addressed as a cell, so with the insertion point in a footnote the table commands (Insert Row, Delete Column, Merge Cells, Table Options, Select Table, table styles) were enabled and then failed with "no table 18446744073709551615". They are now disabled with "place the insertion point in a table", as the cell commands already were. The caret's footnote offset is no longer looked up in the main story either, where it could land on a table's paragraph. table.get and the other commands that take any selection report the same message instead of the footnote address. A call that names a table still runs. --- ROADMAP.md | 1 + crates/engine/src/cmd/table/target.rs | 5 ++- crates/engine/src/tests/table.rs | 45 +++++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index ee0f4e022..c06cfceaa 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -400,6 +400,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m - **2026-11-12** · Type shortcuts: Justify All Lines ⇧⌘F, Insert White Space › Em Space ⇧⌘M and En Space ⇧⌘N (shown in the menu, enabled at an insertion point), Paragraph Rules… ⌥⌘J (shown in the Paragraph panel menu). On the Mac a menu-bar insert (Em/En Space, Current Page Number) no longer types into the document while a text field has focus, a dialog or Quick Apply is open, or an input method is composing. An alignment the paragraphs already have records no undo step (#1138). No readiness percentage change. - **2026-11-12** · A placed JPEG drawn at a half, a quarter or an eighth of its pixel size or less is decoded at that size straight from its compressed blocks, so the canvas, page thumbnails and loaded-graphic thumbnails no longer decode and keep the full-size picture for it. CMYK JPEGs and the full size still decode in full. No readiness percentage change. - **2026-11-12** · A decoded placed image becomes a screen pixmap in its own buffer, premultiplied in place, and opaque pixels are left as they are: 120 ms becomes 7 ms for a 24-megapixel opaque photo, with the same pixels. No readiness percentage change. +- **2026-11-12** · With the insertion point in footnote text, the table commands (Insert Row, Delete Column, Merge Cells, Table Options, Select Table, table styles) are disabled, as they are outside a table, instead of failing with "no table 18446744073709551615". A call that names a table still runs. No readiness percentage change. - **2026-11-12** · The status bar's preflight count and the Preflight panel take their issues from a check on a background worker, which checks the newest state of the document and shows the issues last found meanwhile. Moving or resizing a frame and typing no longer wait for a check of the whole document on every drag step and keystroke. No readiness percentage change. - **2026-11-12** · Object › Text Frame Options… (Cmd+B) opens with the Type tool in a frame, so inset spacing and vertical justification can be changed while typing; it changes the frame that shows the insertion point, or every frame that holds part of the selected text (#2396). No readiness percentage change. diff --git a/crates/engine/src/cmd/table/target.rs b/crates/engine/src/cmd/table/target.rs index 0240aff23..a939a09dd 100644 --- a/crates/engine/src/cmd/table/target.rs +++ b/crates/engine/src/cmd/table/target.rs @@ -8,10 +8,12 @@ use super::{ pub(super) fn in_table(s: &Session) -> std::result::Result<(), String> { has_doc(s)?; let st = s.active().ok_or("no document open")?; - if st.selection.cells.is_some() || st.selection.text.is_some_and(|t| t.cell.is_some()) { + // Footnote text is addressed as a cell too, but isn't in a table. + if st.selection.cells.is_some() || st.selection.text.is_some_and(|t| t.cell.is_some_and(|c| c.footnote_id().is_none())) { return Ok(()); } if let Some(t) = st.selection.text + && t.cell.is_none() && st.doc.story(t.story).is_some_and(|x| x.table_at(t.focus).is_some()) { return Ok(()); @@ -81,6 +83,7 @@ pub(super) fn target(s: &Session, p: &Value, cmd: &str) -> Result { (c.story, c.table, Some(c.range)) } else if let Some(t) = st.selection.text { match t.cell { + Some(c) if c.footnote_id().is_some() => return Err(bad(cmd, "place the insertion point in a table")), Some(c) => (t.story, c.table, Some(CellRange::cell(c.row, c.col))), None => { let tid = doc.story(t.story).and_then(|x| x.table_at(t.focus)).ok_or_else(|| bad(cmd, "the insertion point is not in a table"))?; diff --git a/crates/engine/src/tests/table.rs b/crates/engine/src/tests/table.rs index 7626005f4..fd5323ffb 100644 --- a/crates/engine/src/tests/table.rs +++ b/crates/engine/src/tests/table.rs @@ -643,6 +643,51 @@ fn a_named_table_edit_keeps_a_footnote_caret() { check(&s); } +/// A caret in footnote text is not in a table: the table commands that need one are disabled +/// there, also when the caret's offset in the footnote falls on a table's paragraph in the main +/// story, and a call that names a table still runs. +#[test] +fn table_commands_are_disabled_in_footnote_text() { + let in_table = ["table.insertRow", "table.deleteColumn", "table.merge", "table.options", "table.selectTable", "style.table.apply"]; + let info = |s: &Session, id: &str| crate::cmd::find_command(id).unwrap().info(s); + for on_table in [false, true] { + let (mut s, sid, _) = session_with_frame(); + let tid = if on_table { + s.execute("story.setText", &json!({"story": sid, "text": "Hello"})).unwrap(); + s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap(); + let tid = s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap(); + let end = s.doc().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().text.len(); + s.execute("text.select", &json!({"story": sid, "anchor": end, "focus": end})).unwrap(); + s.execute("footnote.insert", &json!({})).unwrap(); + tid + } else { + let tid = s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap(); + s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap(); + s.execute("footnote.insert", &json!({"text": "Note"})).unwrap(); + tid + }; + let before = s.doc().unwrap().selection.clone(); + let caret = before.text.unwrap(); + assert!(caret.cell.and_then(|c| c.footnote_id()).is_some(), "the caret is in the footnote"); + let story = s.doc().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap(); + assert_eq!(story.table_at(caret.focus).is_some(), on_table, "focus {}", caret.focus); + for id in in_table { + let i = info(&s, id); + assert!(!i.enabled, "{id} {on_table}"); + assert_eq!(i.disabled_reason.as_deref(), Some("place the insertion point in a table"), "{id} {on_table}"); + assert!(matches!(s.execute(id, &json!({})), Err(crate::EngineError::Disabled(..))), "{id} {on_table}"); + } + // A query that takes any selection and names no table is told where to put the caret. + let error = s.execute("table.get", &json!({})).unwrap_err().to_string(); + assert!(error.contains("place the insertion point in a table"), "{on_table}: {error}"); + assert_eq!(s.doc().unwrap().selection, before); + s.execute("table.insertRow", &json!({"table": tid})).unwrap(); + assert_eq!(s.execute("table.get", &json!({"table": tid})).unwrap()["rows"].as_array().unwrap().len(), 3); + assert_eq!(s.doc().unwrap().selection, before); + check(&s); + } +} + /// With nothing selected, the table commands stay disabled for menus and for calls that name no /// table. #[test] From 0f792e1fe9375183881cc5b64d446d9821757543 Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Thu, 12 Nov 2026 14:32:12 -0800 Subject: [PATCH 1066/1349] Compose: vertical justification moves an object kept within its column with its line (#2720) * Text wrap: an object kept within its column moves with its line Vertical justification treated an object positioned from its anchor and kept within its column as fixed, so its wrap stopped Center, Bottom and Justify where the object started, although the object moves down with its anchor's line until it reaches the column's bottom. A line now moves down at most the room above the object plus the distance the object can move before the column stops it. The story's object-mark positions are now collected once per composition instead of once per frame that holds an anchored object. * Compose: Justify keeps the room under an object held at the column's top An object kept within its column and held at the column's top moves only after its anchor's row has moved down far enough to bring it off the top. Justify took that distance off a later line's room even when the anchor's row moved less, so with the anchor in the first row, which stays in place, the later line stopped that distance short of the object's wrap. A line now moves its room plus how far the anchor's row moves past that distance. --- crates/compose/src/lib.rs | 102 +++++++++++++++++++++++++----------- crates/compose/src/tests.rs | 86 ++++++++++++++++++++++++++++++ 2 files changed, 158 insertions(+), 30 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 333959626..ab2a9ede7 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -3626,6 +3626,8 @@ struct FinishInput<'a> { fn finish_composition(input: FinishInput<'_>) -> ComposedStory { let FinishInput { doc, story, frames, cols, notes, out, boxes, span_paras, split_paras, grid_paras, styles_tab } = input; notes.finish(doc, story, frames, cols, out); + // The story byte of each anchored object's mark, found once for every frame that holds one. + let mut marks: Option> = None; // Ranges, content heights and vertical justification. for (fi, ft) in out.frames.iter_mut().enumerate() { let f = &frames[fi]; @@ -3641,9 +3643,12 @@ fn finish_composition(input: FinishInput<'_>) -> ComposedStory { let before: Vec = ft.tables.iter().map(|t| ft.lines.get(t.line).map_or(0.0, |l| l.baseline)).collect(); let spanned = ft.columns.len() > 1 && ft.lines.iter().any(|l| span_paras.get(l.para) == Some(&true)) || ft.lines.iter().any(|l| split_paras.get(l.para) == Some(&true)); - let anchors: Vec = - if ft.objects.is_empty() { Vec::new() } else { story.text.match_indices(designcraft_doc::OBJECT_MARK).map(|(i, _)| i).collect() }; - vertical_justify(ft, f, spanned, &doc.footnote_options, grid_paras, &anchors); + let anchors: &[usize] = if ft.objects.is_empty() { + &[] + } else { + marks.get_or_insert_with(|| story.text.match_indices(designcraft_doc::OBJECT_MARK).map(|(i, _)| i).collect()) + }; + vertical_justify(ft, f, spanned, &doc.footnote_options, grid_paras, anchors); for (t, b) in ft.tables.iter_mut().zip(before) { let now = ft.lines.get(t.line).map_or(b, |l| l.baseline); t.shift(now - b); @@ -6077,18 +6082,19 @@ fn vertical_justify( None => true, }; // Each row moves no further than a text wrap under it allows. An object that moves with its - // anchor's row (Justify) limits how much further than that row a later row moves. + // anchor's row (Justify) lets a later row move its room plus how far the object moves. let mut row_of = vec![None; ft.lines.len()]; for (&i, &k) in idx.iter().zip(&rows) { row_of[i] = Some(k); } - let follow: Vec<(usize, usize, f64)> = follow + let follow: Vec<(usize, usize, f64, f64)> = follow .iter() - .filter_map(|&(i, a, room)| Some((row_of.get(i).copied().flatten()?, row_of.get(a).copied().flatten()?, room.max(0.0)))) + .filter_map(|&(i, a, room, pin)| Some((row_of.get(i).copied().flatten()?, row_of.get(a).copied().flatten()?, room.max(0.0), pin))) .collect(); + // The object moves only once its anchor's row has moved `pin`. let clear = |shift: &[f64]| { idx.iter().zip(&rows).all(|(&i, &k)| shift[k] <= rooms[i].max(0.0) + 1e-9) - && follow.iter().all(|&(k, m, room)| shift[k] - shift[m] <= room + 1e-9) + && follow.iter().all(|&(k, m, room, pin)| shift[k] <= room + (shift[m] - pin).max(0.0) + 1e-9) }; // The lowest lines are tested first: they are the ones a narrowing outline stops. let fits = |shift: &[f64]| { @@ -6206,13 +6212,16 @@ fn vertical_justify( /// box. Beside or under a contour, the line moves down only as far as its band stays clear of the /// contour on its way down (to 0.01 pt). Only wraps that reach into a line's column (or the /// columns it spans) count, as when the lines are set. An anchored object that moves with the -/// lines being justified (inline, above the line, or positioned from its anchor and not kept -/// within its column) is skipped, except under Justify, where it moves with the row of its -/// anchor's line: its wrap is taken where the object sits before the lines move, and its rooms go -/// in the second list as (line, anchor's line, room), so a line moves down at most that much -/// further than the anchor's row. Justify keeps the first row in place, so its room stays -/// infinite. `anchors` holds the story byte of each anchored object's mark, by object index. -fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[usize]) -> (Vec, Vec<(usize, usize, f64)>) { +/// lines being justified (inline, above the line, or positioned from its anchor) is skipped, +/// except under Justify, where it moves with the row of its anchor's line: its wrap is taken where +/// the object sits before the lines move, and its rooms go in the second list as (line, anchor's +/// line, room, pin), so a line moves down at most the room plus how far the anchor's row moves +/// past `pin`. An object positioned from its anchor and kept within its column moves with its +/// anchor's row until it stops at the column's bottom, so in every mode a line moves down at most +/// the room under it plus the distance the object can move. Held at the column's top, the object +/// moves only after its anchor's row has moved `pin` (0 for the other objects), and until then a +/// line keeps the whole room. Justify keeps the first row in place, so its room stays infinite. `anchors` holds the story byte of each anchored object's mark, by object index. +fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[usize]) -> (Vec, Vec<(usize, usize, f64, f64)>) { const EPS: f64 = 1e-6; // One-sided wraps also block the column on the other side of the object: the x-range wrap // `e` keeps text out of in column `col`, from the object's x-range `a..b` there (None when that @@ -6247,23 +6256,43 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u } } // An own-story anchored object whose anchor is on one of these lines and whose position - // follows its line moves with the text: the index in `ft.lines` of its anchor's line, and how - // much lower that line was when the wrap was taken (an earlier pass placed the object after - // moving the lines). - let moves_with_text = |e: &Exclusion| -> Option<(usize, f64)> { + // follows its line moves with the text: the index in `ft.lines` of its anchor's line, how + // much lower the object was when the wrap was taken (an earlier pass placed the object after + // moving the lines), and, for one kept within its column, how far its line moves before the + // object leaves the column's top and how far the object then moves before it stops at the + // column's bottom (none and infinite for the others). + let moves_with_text = |e: &Exclusion| -> Option<(usize, f64, f64, f64)> { let o = *by_anchor.get(&e.after?)?; - let follows = match &o.object.position { - designcraft_doc::AnchorPosition::Inline { .. } | designcraft_doc::AnchorPosition::AboveLine { .. } => true, - // Kept within the column, it can stop at the column's edge instead of following. - designcraft_doc::AnchorPosition::Custom { y_relative, keep_within_column, .. } => { - *y_relative == designcraft_doc::anchored::AnchorRelative::Anchor && !keep_within_column + let l = ft.lines.get(o.line)?; + let now = l.baseline; + let dy = e.anchor_baseline.map_or(0.0, |b| b - now); + match &o.object.position { + designcraft_doc::AnchorPosition::Inline { .. } | designcraft_doc::AnchorPosition::AboveLine { .. } => { + Some((o.line, dy, 0.0, f64::INFINITY)) } - }; - let now = ft.lines.get(o.line).map_or(0.0, |l| l.baseline); - follows.then(|| (o.line, e.anchor_baseline.map_or(0.0, |b| b - now))) + designcraft_doc::AnchorPosition::Custom { y_relative, keep_within_column, y_offset, object_point, .. } + if *y_relative == designcraft_doc::anchored::AnchorRelative::Anchor => + { + if !keep_within_column { + return Some((o.line, dy, 0.0, f64::INFINITY)); + } + // Placed as the lines' final positions place it: from its anchor's baseline, + // held between the column's top and bottom. + let col = ft.columns.get(l.column as usize).copied().unwrap_or(f.area); + let h = o.size.1; + let ofy = [0.0, 0.5, 1.0][(*object_point / 3).min(2) as usize]; + let (lo, hi) = (col.y0, (col.y1 - h).max(col.y0)); + let place = |b: f64| b + y_offset - h * ofy; + let raw = place(now); + let y = raw.clamp(lo, hi); + let then = e.anchor_baseline.map_or(y, |b| place(b).clamp(lo, hi)); + Some((o.line, then - y, (lo - raw).max(0.0), (hi - y).max(0.0))) + } + designcraft_doc::AnchorPosition::Custom { .. } => None, + } }; // Each wrap's object is looked up once, not for every line. - let moving: Vec> = f.exclusions.iter().map(moves_with_text).collect(); + let moving: Vec> = f.exclusions.iter().map(moves_with_text).collect(); // Justify keeps the first row (its segments and a table on them) in place, so wraps under it // set no limit. let first = ft.lines.iter().find(|l| in_col(l.column)).map(|l| l.baseline); @@ -6290,13 +6319,15 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u let col = Rect { x0: col.x0.min(x0), x1: col.x1.max(x1), ..col }; let meets = |(a, b): (f64, f64)| a < x1 - EPS && b > x0 + EPS; for (e, &anchor) in f.exclusions.iter().zip(&moving).filter(|(e, _)| e.wraps_line(start)) { - if anchor.is_some() && !justify { + // Center and Bottom move every row as far: only an object kept within its column, which + // can stop at the column's edges, holds the lines back. + if anchor.is_some_and(|(_, _, _, slack)| slack == f64::INFINITY) && !justify { continue; } // The wrap where its object sits before the lines move (moved up by `dy`), and how // far it lets this line move down (relative to its anchor's row for an object that // moves with the text). - let dy = anchor.map_or(0.0, |(_, dy)| dy); + let dy = anchor.map_or(0.0, |(_, dy, _, _)| dy); let cap = if anchor.is_some() { f64::INFINITY } else { room }; let mut room_e = f64::INFINITY; let r = Rect { y0: e.rect.y0 - dy, y1: e.rect.y1 - dy, ..e.rect }; @@ -6335,7 +6366,18 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u } } match anchor { - Some((a, _)) if room_e.is_finite() => follow.push((line, a, room_e)), + // An object kept within its column moves once its line has moved `pin` (to leave + // the column's top) and stops after moving `slack` (at the column's bottom). + Some((a, _, pin, slack)) if room_e.is_finite() => { + if room_e >= pin { + if justify { + follow.push((line, a, room_e, pin)); + } + room = room.min(room_e + slack); + } else { + room = room.min(room_e); + } + } Some(_) => {} None => room = room.min(room_e), } diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index ccc71578d..a37729faa 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -890,6 +890,92 @@ fn vertical_justification_stops_at_an_anchored_object_kept_within_its_column() { ); } +/// An object positioned from its anchor and kept within its column moves with its anchor's line +/// until it reaches the column's bottom, so Bottom moves the lines above it down that far, not +/// only as far as where the object starts. +#[test] +fn vertical_justification_moves_an_object_kept_within_its_column_until_it_stops() { + use designcraft_doc::VerticalJustification::{Bottom, Center, Justify}; + for vj in [Bottom, Center, Justify] { + let (mut d, sid, fid) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = vj; + // Hung 40 pt under the first baseline, under the second line, and far above the column's + // bottom. + anchor_box(&mut d, sid, 1, 0.0, 40.0, true, WrapMode::BoundingBox); + if let designcraft_doc::AnchorPosition::Custom { keep_within_column, .. } = + &mut std::sync::Arc::make_mut(&mut d.story_mut(sid).unwrap().objects[0]).position + { + *keep_within_column = true; + } + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + let o = &cs.frames[0].objects[0]; + let (top, bottom) = (o.origin.y, o.origin.y + 60.0); + let l = lines[1]; + assert!(l.baseline <= top + 1e-6, "{vj:?}: the second line at {} meets the object at {top}..{bottom}", l.baseline); + match vj { + // The object stops at the column's bottom and the second line comes down onto it. + Bottom => { + assert!((bottom - 400.0).abs() < 1e-6, "{vj:?}: the object stopped at {top}..{bottom}, above the column's bottom"); + assert!(l.baseline > top - 0.01, "{vj:?}: the second line stopped at {}, above the object at {top}", l.baseline); + } + // Justify keeps the first line, and the object anchored in it, in place; the second + // line comes down onto the object. + Justify => { + assert!((top - lines[0].baseline - 40.0).abs() < 1e-6, "{vj:?}: the object moved to {top}..{bottom}"); + assert!(l.baseline > top - 0.01, "{vj:?}: the second line stopped at {}, above the object at {top}", l.baseline); + } + // Center moves the lines half of the room under them: the object moves with them. + _ => assert!(bottom < 400.0 - 1e-6 && l.baseline > 150.0, "{vj:?}: second line at {}, object at {top}..{bottom}", l.baseline), + } + } +} + +/// An object anchored in the first line, positioned from its anchor and kept within its column, +/// is held at the column's top. Justify keeps the first line in place, so the object stays there, +/// and the second line comes down onto the wider lower part of its contour. +#[test] +fn vertical_justify_keeps_the_room_under_an_object_held_at_the_columns_top() { + use designcraft_doc::anchored::AnchorRelative as R; + let (mut d, sid, fid) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Justify; + // Beside the lines at x 250..300 down to y 100, then x 100..300 down to y 160. + let pts = [ + Point::new(150.0, 0.0), + Point::new(200.0, 0.0), + Point::new(200.0, 160.0), + Point::new(0.0, 160.0), + Point::new(0.0, 100.0), + Point::new(150.0, 100.0), + ]; + let lid = d.default_layer(); + let path = designcraft_geom::path::PathData::single(designcraft_geom::path::SubPath::polyline(&pts, true)); + let mut it = designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Polygon, path); + it.wrap.mode = WrapMode::Contour; + it.wrap.side = WrapSide::BothSides; + // 50 pt above the first baseline, so the column's top holds it. + let position = designcraft_doc::AnchorPosition::Custom { + x_relative: R::TextFrame, + y_relative: R::Anchor, + x_offset: 100.0, + y_offset: -50.0, + object_point: 0, + ref_point: 0, + keep_within_column: true, + spine_relative: false, + }; + d.story_mut(sid).unwrap().insert_object(1, designcraft_doc::AnchoredObject::new(it, position)); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + assert_eq!(lines.len(), 2); + let top = cs.frames[0].objects[0].origin.y; + assert!(lines[0].baseline < 50.0 && top.abs() < 1e-6, "the object is held at the column's top: {top}, {}", lines[0].baseline); + let wide = top + 100.0; + let b = lines[1].baseline; + assert!(b <= wide + 1e-6, "Justify moved the second line to {b}, into the contour's wider part at {wide}"); + assert!(b > wide - 0.01, "Justify stopped the second line at {b}, short of the contour's wider part at {wide}"); +} + /// Justify keeps the first line in place and moves later lines further, so an object anchored in /// the first line and hung under the last one still stops the lines after its anchor. #[test] From 33f0c21510bb765dcfc3fd2a6d87c17af3ddb9d4 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 17:40:51 -0500 Subject: [PATCH 1067/1349] Estimate reduced JPEG cache and decode sizes --- crates/render/src/images.rs | 83 ++++++++++++++++++++++++++++++------- 1 file changed, 68 insertions(+), 15 deletions(-) diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 8ae0691c7..fd937903d 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -172,6 +172,54 @@ pub(crate) struct Want { pub on_screen: f64, } +/// Dimensions of the JPEG mip level selected for a request. `None` means the request uses the +/// full decode or is not an eligible JPEG, so warming must reserve its full decode size. +fn reduced_sizes(bytes: &Arc>, page: u32, width_pt: f64, on_screen: f64) -> Option> { + if page != 0 || !bytes.starts_with(&[0xFF, 0xD8]) { + return None; + } + let (mut w, mut h) = crate::image_size(bytes)?; + let ppt = w as f64 / width_pt.max(1e-6); + let mut sizes = vec![(w, h)]; + while ppt / (1u64 << sizes.len()) as f64 >= on_screen * 1.2 && w > 64 && h > 64 && sizes.len() <= 8 { + (w, h) = ((w / 2).max(1), (h / 2).max(1)); + sizes.push((w, h)); + } + Some(sizes) +} + +/// Cache and peak decode estimates for a group of requests that all use reduced JPEG mips. +fn reduced_estimates(wants: &[Want]) -> Option<(usize, usize)> { + let mut dims = None; + let mut levels = [false; 9]; + let mut peak = 0usize; + for w in wants { + let sizes = reduced_sizes(&w.bytes, w.page, w.width_pt, w.on_screen)?; + let level = sizes.len() - 1; + if level == 0 { + return None; + } + let shrink = level.min(usize::from(designcraft_images::MAX_REDUCED_SHRINK)); + for cached in shrink..=level { + levels[cached] = true; + } + let denom = 1u32 << shrink; + let (w_px, h_px) = sizes[0]; + // The reduced decoder rounds each side up before the mip is cropped to `sizes[shrink]`. + let decode_pixels = w_px.div_ceil(denom) as usize * h_px.div_ceil(denom) as usize; + peak = peak.max(decode_pixels.saturating_mul(8)); + if dims.as_ref().is_none_or(|d: &Vec<(u32, u32)>| d.len() < sizes.len()) { + dims = Some(sizes); + } + } + let dims = dims?; + let cached = levels.iter().enumerate().filter(|(_, keep)| **keep).fold(0usize, |n, (level, _)| { + let (w, h) = dims[level]; + n.saturating_add(w as usize * h as usize * 4) + }); + Some((cached, peak)) +} + /// Threads [`warm`] decodes on (1 on the web, which has none). fn workers() -> usize { #[cfg(target_arch = "wasm32")] @@ -270,7 +318,8 @@ pub(crate) fn warm(wants: Vec) -> usize { if held.contains_key(&key) { continue; } - let (size, decoding) = wanted.first().map_or((0, 0), |w| decode_sizes(&w.bytes, w.page)); + let full = wanted.first().map_or((0, 0), |w| decode_sizes(&w.bytes, w.page)); + let (size, decoding) = reduced_estimates(&wanted).unwrap_or(full); // A store past the budget evicts down to three quarters of it: the images in view must // fit in that, unless they and the rest fit in the budget. let total = pixels.saturating_add(size); @@ -338,21 +387,12 @@ fn waited(job: &[Want]) { /// and halved from there, so a screen-sized level needs no full-size decode. `None` when the /// full size is drawn, for other formats and for JPEGs only a full decode reads (CMYK). fn reduced(bytes: &Arc>, page: u32, width_pt: f64, on_screen: f64) -> Option> { - if page != 0 || !bytes.starts_with(&[0xFF, 0xD8]) { - return None; - } let id = Arc::as_ptr(bytes) as usize; if with(|c| c.bad.contains_key(&(id, page))) { return None; } // The level `mip` picks from a full decode, with each level's size as `halve` gives it. - let (mut w, mut h) = crate::image_size(bytes)?; - let ppt = w as f64 / width_pt.max(1e-6); - let mut sizes = vec![(w, h)]; - while ppt / (1u64 << sizes.len()) as f64 >= on_screen * 1.2 && w > 64 && h > 64 && sizes.len() <= 8 { - (w, h) = ((w / 2).max(1), (h / 2).max(1)); - sizes.push((w, h)); - } + let sizes = reduced_sizes(bytes, page, width_pt, on_screen)?; let level = u8::try_from(sizes.len() - 1).ok()?; if level == 0 { return None; @@ -506,10 +546,11 @@ mod tests { let large = decoded_bytes(&d, 0); assert!(large > BUDGET / 4 && 2 * large <= BUDGET * 3 / 4); let decoding = decode_peak_bytes(&d, 0); - assert!(admits(0, decoding) && !admits(decoding, decoding) && admits(decoding, decode_peak_bytes(&small, 0))); + let reserved = decoding * 3 / 2; + assert!(admits(0, reserved) && !admits(reserved, reserved) && admits(reserved, decode_peak_bytes(&small, 0) * 3 / 2)); assert!(admits(0, usize::MAX), "an image over half the budget still decodes alone"); let peak = warm(vec![want(&d), want(&e), want(&small)]); - assert!(peak <= BUDGET / 2, "{peak} bytes decoding at once"); + assert!(peak <= decoding * 3 / 2, "{peak} bytes decoding at once"); assert!(peak >= decoding, "the large images were decoded ahead"); let me = std::thread::current().id(); for img in [&d, &e, &small] { @@ -526,8 +567,9 @@ mod tests { let (f, g) = (psd(5500), psd(5500)); let decoding = decode_peak_bytes(&f, 0); assert_eq!(decoding, 5500 * 5500 * 9, "9 bytes a pixel for a PSD"); - assert!(2 * decoded_bytes(&f, 0) <= BUDGET / 2 && !admits(decoding, decode_peak_bytes(&g, 0))); - assert_eq!(warm(vec![want(&f), want(&g)]), decoding, "one decode at a time"); + let reserved = decoding * 3 / 2; + assert!(2 * decoded_bytes(&f, 0) <= BUDGET / 2 && !admits(reserved, decode_peak_bytes(&g, 0) * 3 / 2)); + assert_eq!(warm(vec![want(&f), want(&g)]), reserved, "one decode at a time"); // 16-bit RGBA decodes at 8 bytes a pixel before its RGBA copy. let mut deep = Vec::new(); let img = image::ImageBuffer::, Vec>::from_pixel(4, 4, image::Rgba([9, 0, 0, 65535])); @@ -601,6 +643,17 @@ mod tests { assert_eq!((full.width(), full.height()), (1024, 768)); } + #[test] + fn warm_estimates_a_jpegs_reduced_levels() { + let bytes = jpeg(1024, 768); + let want = Want { bytes: bytes.clone(), page: 0, width_pt: 1024.0, on_screen: 0.1 }; + let (cached, peak) = reduced_estimates(&[want]).unwrap(); + assert_eq!(cached, 128 * 96 * 4, "only the selected eighth-size mip is cached"); + assert_eq!(peak, 128 * 96 * 8, "only the selected eighth-size mip is decoded"); + let full = decode_sizes(&bytes, 0); + assert!(cached < full.0 && peak < full.1, "reduced estimates {cached}/{peak}, full {full:?}"); + } + #[test] fn reduced_levels_of_odd_sized_jpegs_have_the_halved_size() { let bytes = jpeg(1001, 771); From 764b06526bc4d4ff5f1ddb27d1478c3beb9729d1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 17:41:55 -0500 Subject: [PATCH 1068/1349] Estimate reduced JPEG warm reservations --- crates/images/src/jpeg.rs | 30 ++++++++++++++++++++++++++++++ crates/images/src/lib.rs | 6 ++++++ crates/render/src/images.rs | 7 ++----- 3 files changed, 38 insertions(+), 5 deletions(-) diff --git a/crates/images/src/jpeg.rs b/crates/images/src/jpeg.rs index a4a2a0971..8e504d72c 100644 --- a/crates/images/src/jpeg.rs +++ b/crates/images/src/jpeg.rs @@ -65,6 +65,36 @@ pub(crate) fn decode_cmyk(bytes: &[u8]) -> Option<(CmykRaster, Option>)> /// The largest reduction [`decode_reduced`] reads straight from a JPEG's 8×8 blocks: 1/8. pub(crate) const MAX_SHRINK: u8 = 3; +/// Output size of a JPEG reduction without decoding pixels. `None` when the reduced decoder +/// cannot handle the JPEG, including its full-size resource limits. +pub(crate) fn reduced_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32)> { + use jpeg_decoder::{CodingProcess, PixelFormat}; + if !bytes.starts_with(&[0xFF, 0xD8]) || shrink == 0 || shrink > MAX_SHRINK { + return None; + } + let mut d = jpeg_decoder::Decoder::new(bytes); + d.set_max_decoding_buffer_size(MAX_BYTES); + d.read_info().ok()?; + let info = d.info()?; + let colour = match info.pixel_format { + PixelFormat::RGB24 => true, + PixelFormat::L8 => false, + PixelFormat::L16 | PixelFormat::CMYK32 => return None, + }; + if crate::over_rgba_budget(u32::from(info.width), u32::from(info.height)) { + return None; + } + if info.coding_process == CodingProcess::DctProgressive { + let side = |n: u16| u64::from(n).next_multiple_of(32); + let components: u64 = if colour { 3 } else { 1 }; + if side(info.width) * side(info.height) * components * 2 > MAX_BYTES as u64 { + return None; + } + } + let reduced = |n: u16| u32::from(n).div_ceil(1 << shrink); + Some((reduced(info.width), reduced(info.height))) +} + /// A YCbCr, RGB or grayscale JPEG decoded at 1/2^`shrink` of its size, each side rounded up, for /// `shrink` 1 to [`MAX_SHRINK`]: straight RGBA and whether the image has colour. `None` for CMYK, /// 12-bit and lossless JPEGs, other formats and anything that doesn't decode. `None` as well for a diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index e925de471..07f91a467 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -510,6 +510,12 @@ pub fn decode_rgba_reduced(bytes: &[u8], shrink: u8) -> Option to_display_rgba(px, Some(&icc), &DisplayColour::active()) } +/// Dimensions of a JPEG decoded at `1/2^shrink`, without decoding its pixels. `None` when the +/// reduced decoder cannot handle the image. +pub fn reduced_jpeg_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32)> { + jpeg::reduced_size(bytes, shrink) +} + /// False when `bytes` is a WebP whose `ICCP` chunk declares more bytes than the file holds or than /// [`colour::MAX_ICC_BYTES`]. The decoder sizes its buffer from the declared length before it reads /// anything, so such a file must not reach `icc_profile()`; its pixels decode without it. diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index fd937903d..4df71f42b 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -200,14 +200,11 @@ fn reduced_estimates(wants: &[Want]) -> Option<(usize, usize)> { return None; } let shrink = level.min(usize::from(designcraft_images::MAX_REDUCED_SHRINK)); + let (decoded_w, decoded_h) = designcraft_images::reduced_jpeg_size(&w.bytes, shrink as u8)?; for cached in shrink..=level { levels[cached] = true; } - let denom = 1u32 << shrink; - let (w_px, h_px) = sizes[0]; - // The reduced decoder rounds each side up before the mip is cropped to `sizes[shrink]`. - let decode_pixels = w_px.div_ceil(denom) as usize * h_px.div_ceil(denom) as usize; - peak = peak.max(decode_pixels.saturating_mul(8)); + peak = peak.max(decoded_w as usize * decoded_h as usize * 8); if dims.as_ref().is_none_or(|d: &Vec<(u32, u32)>| d.len() < sizes.len()) { dims = Some(sizes); } From 437c53251152b651f2352edb0a4f803000bda24d Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Thu, 12 Nov 2026 14:42:10 -0800 Subject: [PATCH 1069/1349] Compose: count endnote, anchored object and cross-reference marks once per story (#2705) * Compose: count endnote, anchored object and cross-reference marks once per story Each paragraph of a story with endnotes, anchored objects or cross-references counted the marks before it from the story start, so composing the story read its text once per paragraph. The marks before each paragraph are now counted in one pass when composition starts. * Compose: test cross-reference mark counts past the first paragraph The mark-count fixture now puts a cross-reference in every paragraph, so the test checks nonzero cross-reference counts and that each paragraph shows its own cross-reference's text. --------- Co-authored-by: Dylan M. Taylor --- ROADMAP.md | 1 + crates/compose/src/lib.rs | 64 ++++++++++++++++++++++++++++++++--- crates/compose/src/tests.rs | 67 +++++++++++++++++++++++++++++++++++++ crates/compose/src/xref.rs | 17 +++++++++- 4 files changed, 144 insertions(+), 5 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index c06cfceaa..961d69281 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -396,6 +396,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m - **2026-11-12** · Properties › Text Frame shows the frame's inset spacing (Top, Bottom, Left and Right with a link that makes all four the same; one Inset for a non-rectangular frame) and four Vertical Justification buttons (Top, Center, Bottom, Justify), and the section also shows with the Type tool in a frame, where it changes the frame that shows the insertion point. No readiness percentage change. - **2026-11-12** · An edit of a long threaded story composes the paragraphs it can change and copies the other lines from the composition before the edit; every typed character composed the whole story. In a 240-paragraph story a typed character composes 3 paragraphs (240 before). An edit that moves lines into other frames composes on until a paragraph starts in the same frame and place as before, or to the story's end, and stories with footnotes, tables, anchored objects, balanced columns or keep options that move lines are composed whole. No readiness percentage change. +- **2026-11-12** · Composing a story with endnotes, anchored objects or cross-references counts their marks in one pass over the story, instead of counting again from the story start for every paragraph. No readiness percentage change. - **2026-11-12** · Center, Bottom and Justify vertical justification in a shaped frame test each moved line against the outline down to its baseline. The descenders of earlier lines may cross the outline, as the last line's do, so an outline that narrows under an earlier line no longer holds the text higher by that line's descent. No readiness percentage change. - **2026-11-12** · Type shortcuts: Justify All Lines ⇧⌘F, Insert White Space › Em Space ⇧⌘M and En Space ⇧⌘N (shown in the menu, enabled at an insertion point), Paragraph Rules… ⌥⌘J (shown in the Paragraph panel menu). On the Mac a menu-bar insert (Em/En Space, Current Page Number) no longer types into the document while a text field has focus, a dialog or Quick Apply is open, or an input method is composing. An alignment the paragraphs already have records no undo step (#1138). No readiness percentage change. - **2026-11-12** · A placed JPEG drawn at a half, a quarter or an eighth of its pixel size or less is decoded at that size straight from its compressed blocks, so the canvas, page thumbnails and loaded-graphic thumbnails no longer decode and keep the full-size picture for it. CMYK JPEGs and the full size still decode in full. No readiness percentage change. diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index ab2a9ede7..81cdad56a 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -1294,10 +1294,63 @@ struct SubstitutionInput<'a> { var_story: bool, var_cache: &'a mut HashMap<(Option, bool), Arc>>, notes: &'a mut Notes, + /// The marks in the story before `range`. + marks: MarkCounts, +} + +/// Endnote references, anchored-object marks and cross-reference marks in a stretch of story text. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct MarkCounts { + endnotes: usize, + objects: usize, + xrefs: usize, +} + +#[cfg(test)] +thread_local! { + /// Bytes of story text [`MarkCounts::of`] has read on this thread. + static MARK_BYTES_SCANNED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +impl MarkCounts { + /// The marks in `text`. + fn of(text: &str) -> Self { + #[cfg(test)] + MARK_BYTES_SCANNED.with(|n| n.set(n.get() + text.len())); + let mut m = Self::default(); + for c in text.chars() { + match c { + designcraft_doc::ENDNOTE_REF => m.endnotes += 1, + designcraft_doc::OBJECT_MARK => m.objects += 1, + designcraft_doc::XREF_MARK => m.xrefs += 1, + _ => {} + } + } + m + } + + /// The marks before each paragraph of `ranges` (the story's paragraphs, in order), read in + /// one pass over the story. Empty when the story holds no endnotes, anchored objects or + /// cross-references. + fn before_paragraphs(story: &Story, ranges: &[Range]) -> Vec { + if story.endnotes.is_empty() && story.objects.is_empty() && story.xrefs.is_empty() { + return Vec::new(); + } + let mut total = Self::default(); + ranges + .iter() + .map(|r| { + let before = total; + let m = story.text.get(r.clone()).map_or_else(Self::default, Self::of); + total = Self { endnotes: total.endnotes + m.endnotes, objects: total.objects + m.objects, xrefs: total.xrefs + m.xrefs }; + before + }) + .collect() + } } fn paragraph_substitution(input: SubstitutionInput<'_>) -> SubstCtx { - let SubstitutionInput { doc, story, range: prange, props: pp, frame: cur_frame, opts, var_story, var_cache, notes } = input; + let SubstitutionInput { doc, story, range: prange, props: pp, frame: cur_frame, opts, var_story, var_cache, notes, marks } = input; let var_values = if var_story { let page = opts.page.or_else(|| cur_frame.and_then(|f| f.page)); // A parent page itself (not composed for one of the pages it applies to). @@ -1319,13 +1372,13 @@ fn paragraph_substitution(input: SubstitutionInput<'_>) -> SubstCtx { }; if !story.endnotes.is_empty() { // Endnote reference numbers continue through the document. - let first = doc.endnote_start(story.id).saturating_add(story.text[..prange.start].matches(designcraft_doc::ENDNOTE_REF).count() as u32); + let first = doc.endnote_start(story.id).saturating_add(u32::try_from(marks.endnotes).unwrap_or(u32::MAX)); for (k, (i, _)) in story.text[prange.clone()].match_indices(designcraft_doc::ENDNOTE_REF).enumerate() { sub.notes.insert(prange.start + i, doc.endnote_options.label(first.saturating_add(k as u32))); } } if !story.objects.is_empty() { - let before = story.text[..prange.start].matches(designcraft_doc::OBJECT_MARK).count(); + let before = marks.objects; for (k, (i, _)) in story.text[prange.clone()].match_indices(designcraft_doc::OBJECT_MARK).enumerate() { let Some(o) = story.objects.get(before + k) else { continue }; let (w, h) = o.size(); @@ -1338,7 +1391,7 @@ fn paragraph_substitution(input: SubstitutionInput<'_>) -> SubstCtx { } } if !story.xrefs.is_empty() { - sub.xrefs = xref::texts_in(doc, story, prange.clone(), opts.xrefs.as_deref()); + sub.xrefs = xref::texts_after(doc, story, prange.clone(), marks.xrefs, opts.xrefs.as_deref()); } if notes.active() { notes.number_refs(doc, prange.clone(), cur_frame.and_then(|f| f.page), &mut sub); @@ -3157,6 +3210,8 @@ fn compose_run( let mut list_counter = ListCounter::default(); // Named lists number independently of layout: one pass up front, for the labels. let named_labels = named_list_labels(doc, story, ¶_ranges, &deleted); + // Endnote, anchored-object and cross-reference marks before each paragraph, for their numbers. + let marks_before = MarkCounts::before_paragraphs(story, ¶_ranges); // Border and shading of each paragraph set, drawn once the lines are in place. let mut boxes: Vec> = vec![None; np]; // Keep options: paragraphs are re-laid from a snapshot when a keep is violated, either forced @@ -3316,6 +3371,7 @@ fn compose_run( var_story, var_cache: &mut var_cache, notes: &mut notes, + marks: marks_before.get(pi).copied().unwrap_or_default(), }); #[cfg(test)] reuse::SHAPED.with(|n| n.set(n.get() + 1)); diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index a37729faa..a0eac4061 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -8689,6 +8689,73 @@ fn spine_relative_anchored_notes_stay_in_the_outside_margin_on_both_pages() { const OBJECT_LEN: usize = designcraft_doc::OBJECT_MARK.len_utf8(); +/// A story of `paras` paragraphs, each with an inline anchored object at its start, an endnote +/// reference after it and a cross-reference that shows `Ref.` for paragraph `k`. +fn story_with_marks(paras: usize) -> (Document, StoryId) { + let text = vec!["Some words, a note and an object."; paras].join("\n"); + let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 400.0, 20_000.0), ParaAttrs::default()); + let starts: Vec = d.story(sid).unwrap().para_ranges().iter().map(|r| r.start).collect(); + let lid = d.default_layer(); + for (k, &s) in starts.iter().enumerate().rev() { + let it = designcraft_doc::Item::new( + ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 6.0, 6.0)), + ); + let story = d.story_mut(sid).unwrap(); + story.insert_xref(s + 19, designcraft_doc::CrossRef { text: Some(format!("Ref{k}.")), ..Default::default() }); + story.insert_endnote(s + 10, "An endnote.", ParaFormat::default()); + story.insert_object(s, designcraft_doc::AnchoredObject::new(it, designcraft_doc::AnchorPosition::Inline { y_offset: 0.0 })); + } + (d, sid) +} + +/// The marks before each paragraph match a count from the story start, for every kind of mark. +#[test] +fn mark_counts_before_each_paragraph_match_a_count_from_the_start() { + let (d, sid) = story_with_marks(5); + let story = d.story(sid).unwrap(); + let ranges = story.para_ranges(); + let counts = MarkCounts::before_paragraphs(story, &ranges); + assert_eq!(counts.len(), ranges.len()); + for (k, (r, m)) in ranges.iter().zip(&counts).enumerate() { + let head = &story.text[..r.start]; + assert_eq!(m.endnotes, head.matches(designcraft_doc::ENDNOTE_REF).count(), "paragraph {k}"); + assert_eq!(m.objects, head.matches(designcraft_doc::OBJECT_MARK).count(), "paragraph {k}"); + assert_eq!(m.xrefs, head.matches(designcraft_doc::XREF_MARK).count(), "paragraph {k}"); + assert_eq!(*m, MarkCounts { endnotes: k, objects: k, xrefs: k }, "paragraph {k}"); + } + // Each paragraph shows its own cross-reference's text, so the composer numbers the + // cross-references from the marks before the paragraph. + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let shown: String = cs.frames[0].lines.iter().flat_map(|l| l.glyphs.iter().filter(|g| g.visible).map(|g| g.rendered_char)).collect(); + let refs: Vec<&str> = shown.match_indices("Ref").map(|(i, _)| &shown[i..i + 5]).collect(); + assert_eq!(refs, ["Ref0.", "Ref1.", "Ref2.", "Ref3.", "Ref4."], "{shown:?}"); + // A story without endnotes, anchored objects or cross-references reads nothing. + let (plain, psid, _) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 300.0), ParaAttrs::default()); + let p = plain.story(psid).unwrap(); + assert!(MarkCounts::before_paragraphs(p, &p.para_ranges()).is_empty()); +} + +/// Composing a story with endnotes, anchored objects and cross-references reads its text for their numbers in one +/// pass, so four times the paragraphs read about four times the bytes, not sixteen times. +#[test] +fn composing_reads_marks_once_per_story() { + let scanned = |paras: usize| { + let (d, sid) = story_with_marks(paras); + MARK_BYTES_SCANNED.with(|n| n.set(0)); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + assert_eq!(cs.frames[0].objects.len(), paras); + (MARK_BYTES_SCANNED.with(std::cell::Cell::get), d.story(sid).unwrap().text.len()) + }; + let (small, small_len) = scanned(40); + let (big, big_len) = scanned(160); + assert!(small > 0); + assert!(big * small_len <= 2 * small * big_len, "40 paragraphs read {small} of {small_len} bytes, 160 read {big} of {big_len}"); +} + #[test] fn anchored_object_wraps_its_own_storys_later_lines() { let text = [LOREM; 4].join(" "); diff --git a/crates/compose/src/xref.rs b/crates/compose/src/xref.rs index 1d72f1ee1..d658eb3d9 100644 --- a/crates/compose/src/xref.rs +++ b/crates/compose/src/xref.rs @@ -68,11 +68,26 @@ pub fn xref_text(doc: &Document, x: &xref::CrossRef, index: Option<&XrefIndex>) /// Generated text of the cross-references in `range` of `story`, by byte of their mark. pub fn texts_in(doc: &Document, story: &Story, range: std::ops::Range, index: Option<&XrefIndex>) -> HashMap { + if story.xrefs.is_empty() { + return HashMap::new(); + } + let before = story.text[..range.start].matches(XREF_MARK).count(); + texts_after(doc, story, range, before, index) +} + +/// [`texts_in`] for a caller that already knows `before`, the number of cross-reference marks in +/// `story` before `range`. +pub(crate) fn texts_after( + doc: &Document, + story: &Story, + range: std::ops::Range, + before: usize, + index: Option<&XrefIndex>, +) -> HashMap { let mut out = HashMap::new(); if story.xrefs.is_empty() { return out; } - let before = story.text[..range.start].matches(XREF_MARK).count(); for (k, (i, _)) in story.text[range.clone()].match_indices(XREF_MARK).enumerate() { if let Some(x) = story.xrefs.get(before + k) { out.insert(range.start + i, xref_text(doc, x, index)); From 067fc9712842f50779f3069aa3ff901f9b3a2acd Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 17:45:02 -0500 Subject: [PATCH 1070/1349] Use iterator for reduced mip accounting --- crates/render/src/images.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 4df71f42b..e2d49873c 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -201,8 +201,8 @@ fn reduced_estimates(wants: &[Want]) -> Option<(usize, usize)> { } let shrink = level.min(usize::from(designcraft_images::MAX_REDUCED_SHRINK)); let (decoded_w, decoded_h) = designcraft_images::reduced_jpeg_size(&w.bytes, shrink as u8)?; - for cached in shrink..=level { - levels[cached] = true; + for cached in levels.iter_mut().take(level + 1).skip(shrink) { + *cached = true; } peak = peak.max(decoded_w as usize * decoded_h as usize * 8); if dims.as_ref().is_none_or(|d: &Vec<(u32, u32)>| d.len() < sizes.len()) { From 1c3285d8a3affaec03949c7fa2b610c4b94dcc34 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 17:55:11 -0500 Subject: [PATCH 1071/1349] Count progressive JPEG buffers in warm budget --- crates/images/src/jpeg.rs | 16 +++++++++++----- crates/images/src/lib.rs | 7 ++++--- crates/render/src/images.rs | 4 ++-- 3 files changed, 17 insertions(+), 10 deletions(-) diff --git a/crates/images/src/jpeg.rs b/crates/images/src/jpeg.rs index 8e504d72c..9db1709cc 100644 --- a/crates/images/src/jpeg.rs +++ b/crates/images/src/jpeg.rs @@ -67,7 +67,7 @@ pub(crate) const MAX_SHRINK: u8 = 3; /// Output size of a JPEG reduction without decoding pixels. `None` when the reduced decoder /// cannot handle the JPEG, including its full-size resource limits. -pub(crate) fn reduced_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32)> { +pub(crate) fn reduced_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32, usize)> { use jpeg_decoder::{CodingProcess, PixelFormat}; if !bytes.starts_with(&[0xFF, 0xD8]) || shrink == 0 || shrink > MAX_SHRINK { return None; @@ -84,15 +84,21 @@ pub(crate) fn reduced_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32)> { if crate::over_rgba_budget(u32::from(info.width), u32::from(info.height)) { return None; } - if info.coding_process == CodingProcess::DctProgressive { + let progressive_bytes = if info.coding_process == CodingProcess::DctProgressive { let side = |n: u16| u64::from(n).next_multiple_of(32); let components: u64 = if colour { 3 } else { 1 }; - if side(info.width) * side(info.height) * components * 2 > MAX_BYTES as u64 { + let bytes = side(info.width) * side(info.height) * components * 2; + if bytes > MAX_BYTES as u64 { return None; } - } + usize::try_from(bytes).ok()? + } else { + 0 + }; let reduced = |n: u16| u32::from(n).div_ceil(1 << shrink); - Some((reduced(info.width), reduced(info.height))) + let (width, height) = (reduced(info.width), reduced(info.height)); + let output_bytes = width as usize * height as usize * 8; + Some((width, height, progressive_bytes.saturating_add(output_bytes))) } /// A YCbCr, RGB or grayscale JPEG decoded at 1/2^`shrink` of its size, each side rounded up, for diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 07f91a467..9afb009fa 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -510,9 +510,10 @@ pub fn decode_rgba_reduced(bytes: &[u8], shrink: u8) -> Option to_display_rgba(px, Some(&icc), &DisplayColour::active()) } -/// Dimensions of a JPEG decoded at `1/2^shrink`, without decoding its pixels. `None` when the -/// reduced decoder cannot handle the image. -pub fn reduced_jpeg_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32)> { +/// Dimensions and estimated peak bytes for a JPEG decoded at `1/2^shrink`, without decoding its +/// pixels. Progressive JPEG coefficient buffers are included. `None` when the reduced decoder +/// cannot handle the image. +pub fn reduced_jpeg_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32, usize)> { jpeg::reduced_size(bytes, shrink) } diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index e2d49873c..8e57ef448 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -200,11 +200,11 @@ fn reduced_estimates(wants: &[Want]) -> Option<(usize, usize)> { return None; } let shrink = level.min(usize::from(designcraft_images::MAX_REDUCED_SHRINK)); - let (decoded_w, decoded_h) = designcraft_images::reduced_jpeg_size(&w.bytes, shrink as u8)?; + let (_, _, decode_peak) = designcraft_images::reduced_jpeg_size(&w.bytes, shrink as u8)?; for cached in levels.iter_mut().take(level + 1).skip(shrink) { *cached = true; } - peak = peak.max(decoded_w as usize * decoded_h as usize * 8); + peak = peak.max(decode_peak); if dims.as_ref().is_none_or(|d: &Vec<(u32, u32)>| d.len() < sizes.len()) { dims = Some(sizes); } From 2eff7e822f799bb740d0bc0447a0c7cdead1c679 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 17:55:36 -0500 Subject: [PATCH 1072/1349] Name reduced JPEG estimate API --- crates/images/src/jpeg.rs | 2 +- crates/images/src/lib.rs | 4 ++-- crates/render/src/images.rs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/images/src/jpeg.rs b/crates/images/src/jpeg.rs index 9db1709cc..b6ef06c09 100644 --- a/crates/images/src/jpeg.rs +++ b/crates/images/src/jpeg.rs @@ -67,7 +67,7 @@ pub(crate) const MAX_SHRINK: u8 = 3; /// Output size of a JPEG reduction without decoding pixels. `None` when the reduced decoder /// cannot handle the JPEG, including its full-size resource limits. -pub(crate) fn reduced_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32, usize)> { +pub(crate) fn reduced_estimate(bytes: &[u8], shrink: u8) -> Option<(u32, u32, usize)> { use jpeg_decoder::{CodingProcess, PixelFormat}; if !bytes.starts_with(&[0xFF, 0xD8]) || shrink == 0 || shrink > MAX_SHRINK { return None; diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 9afb009fa..334a62ed9 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -513,8 +513,8 @@ pub fn decode_rgba_reduced(bytes: &[u8], shrink: u8) -> Option /// Dimensions and estimated peak bytes for a JPEG decoded at `1/2^shrink`, without decoding its /// pixels. Progressive JPEG coefficient buffers are included. `None` when the reduced decoder /// cannot handle the image. -pub fn reduced_jpeg_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32, usize)> { - jpeg::reduced_size(bytes, shrink) +pub fn reduced_jpeg_estimate(bytes: &[u8], shrink: u8) -> Option<(u32, u32, usize)> { + jpeg::reduced_estimate(bytes, shrink) } /// False when `bytes` is a WebP whose `ICCP` chunk declares more bytes than the file holds or than diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 8e57ef448..01746f19e 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -200,7 +200,7 @@ fn reduced_estimates(wants: &[Want]) -> Option<(usize, usize)> { return None; } let shrink = level.min(usize::from(designcraft_images::MAX_REDUCED_SHRINK)); - let (_, _, decode_peak) = designcraft_images::reduced_jpeg_size(&w.bytes, shrink as u8)?; + let (_, _, decode_peak) = designcraft_images::reduced_jpeg_estimate(&w.bytes, shrink as u8)?; for cached in levels.iter_mut().take(level + 1).skip(shrink) { *cached = true; } From 28d85282834b2861973b2b439e1d9cc639eabfd1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 15:23:04 -0800 Subject: [PATCH 1073/1349] Images: fit the one-at-a-time warm test to the decode headroom With the 3/2 headroom on each decode, a 6,500 pixel square PSD reserves more than half the budget, so the small image can no longer decode beside it and the test failed before calling warm. 5,000 pixel square images still reserve more than half the budget as a pair and leave room for the small image beside one. --- crates/render/src/images.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 01746f19e..16890b591 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -536,19 +536,19 @@ mod tests { #[test] fn warm_decodes_large_images_one_at_a_time() { - // Two 6,500 pixel square images fit the budget together, but decoding both at once would - // take more than half of it; the small image still decodes beside them. - let (d, e, small) = (psd(6500), psd(6500), png(8, 15)); + // Two 5,000 pixel square images take less than half the budget cached, but decoding both + // at once would reserve more than half of it; the small image still decodes beside one. + let (d, e, small) = (psd(5000), psd(5000), png(8, 15)); let since = mark(); let large = decoded_bytes(&d, 0); - assert!(large > BUDGET / 4 && 2 * large <= BUDGET * 3 / 4); + assert!(2 * large <= BUDGET / 2); let decoding = decode_peak_bytes(&d, 0); let reserved = decoding * 3 / 2; assert!(admits(0, reserved) && !admits(reserved, reserved) && admits(reserved, decode_peak_bytes(&small, 0) * 3 / 2)); assert!(admits(0, usize::MAX), "an image over half the budget still decodes alone"); let peak = warm(vec![want(&d), want(&e), want(&small)]); - assert!(peak <= decoding * 3 / 2, "{peak} bytes decoding at once"); - assert!(peak >= decoding, "the large images were decoded ahead"); + assert!(peak <= BUDGET / 2, "{peak} bytes decoding at once"); + assert!(peak >= reserved, "the large images were decoded ahead"); let me = std::thread::current().id(); for img in [&d, &e, &small] { let on = decoders(img, since); From dbb334c529d76e4f3d22afaa86c0a8b10f3a0216 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 15:27:11 -0800 Subject: [PATCH 1074/1349] Images: pick the images to decode ahead with the scaled stroke and effect bounds The draw path scales an item's stroke extent and effect outset by its transform before culling; the pass that picks images to decode ahead used the unscaled values, so a scaled image whose stroke or shadow reaches the view decoded on the render thread. --- crates/render/src/draw.rs | 7 +++++-- crates/render/src/tests.rs | 9 +++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 91a492b2e..95e0a159c 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -99,8 +99,11 @@ fn wanted_in(f: &Frame, it: &Item, parent: Affine, depth: usize, out: &mut Vec
  • {n}