DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Refactor engine for strict Clippy checks
Dylan M. Taylor5b21472180ec
diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rsindex 5cee93730..79e16027e 100644--- a/crates/engine/src/cmd/datamerge/tests.rs+++ b/crates/engine/src/cmd/datamerge/tests.rs@@ -814,30 +814,7 @@ fn an_ime_delete_ends_a_preview_and_edits_the_template() {assert!(s.doc().unwrap().preview_stash.is_none());}-#[test]-fn update_remove_preview_inline_rows_and_old_files() {- let dir = scratch("update");- let csv = dir.join("people.csv");- write(&csv, "Name\nAda\nGrace\n");- let mut s = Session::new();- new_doc(&mut s, 1);- text_frame(&mut s, [36.0, 36.0, 240.0, 80.0], "", None);- exec(&mut s, "data.source.select", json!({"path": csv}));- let id = exec(&mut s, "data.placeholder.add", json!({"field": "Name"}))["id"].clone();- let undo = s.documents()[0].history.undo.len();- let fingerprint = s.documents()[0].doc.data_merge.sources[0].fingerprint;- let mut body = std::fs::read(&csv).unwrap();- body.extend_from_slice(b"Kai\n");- std::fs::write(&csv, &body).unwrap();- let r = exec(&mut s, "data.merge", json!({}));- assert_eq!(r["records"], 2);- assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap_or("").contains("changed")));- assert_eq!(texts(&s), vec!["Ada".to_string(), "Grace".to_string()]);- assert_eq!(s.documents()[0].doc.data_merge.sources[0].status, SourceStatus::Modified);- assert_eq!(s.documents()[0].doc.data_merge.sources[0].fingerprint, fingerprint);- assert_eq!(s.documents()[0].history.undo.len(), undo);- assert_eq!(s.documents()[s.active_index().unwrap()].doc.data_merge.sources[0].status, SourceStatus::Modified);-+fn check_missing_merge_source(dir: &Path) {let gone = dir.join("gone.csv");write(&gone, "Name\nAda\nGrace\n");let mut missing = Session::new();@@ -853,7 +830,9 @@ fn update_remove_preview_inline_rows_and_old_files() {assert_eq!(texts(&missing), vec!["Ada".to_string(), "Grace".to_string()]);assert_eq!(missing.documents()[0].doc.data_merge.sources[0].status, SourceStatus::Missing);assert_eq!(missing.documents()[0].history.undo.len(), missing_undo);+}+fn check_refused_facing_page_merge(dir: &Path) {let refuse = dir.join("refuse.csv");write(&refuse, "Name\nAda\nGrace\n");let mut refused = Session::new();@@ -870,49 +849,56 @@ fn update_remove_preview_inline_rows_and_old_files() {assert_eq!(refused.documents().len(), 1);assert_eq!(refused.documents()[0].doc.data_merge.sources[0].status, SourceStatus::Ok);assert_eq!(refused.documents()[0].history.undo.len(), refuse_undo);+}- exec(&mut s, "file.activate", json!({"index": 0}));- exec(&mut s, "data.source.update", json!({}));- let r = exec(&mut s, "data.merge", json!({}));+fn check_preview_update_save(session: &mut Session, dir: &Path, csv: &Path, id: &Value) {+ exec(session, "file.activate", json!({"index": 0}));+ exec(session, "data.source.update", json!({}));+ let r = exec(session, "data.merge", json!({}));assert_eq!(r["records"], 3);- assert!(texts(&s).iter().any(|t| t == "Kai"));-- exec(&mut s, "file.activate", json!({"index": 0}));- exec(&mut s, "data.source.remove", json!({}));- assert!(s.documents()[0].doc.data_merge.sources.is_empty());- assert!(s.documents()[0].doc.data_merge.placeholders.iter().any(|ph| ph.id == id.as_u64().unwrap()));- assert_eq!(exec(&mut s, "data.fields", json!({})), json!([]));-- select_csv(&mut s, "Name\nAda\nGrace\n");- exec(&mut s, "data.preview", json!({"record": 2}));- assert!(texts(&s).iter().any(|t| t.contains("Grace")));- assert!(!texts(&s).iter().any(|t| t.contains("<<Name>>")));- let ser = exec(&mut s, "file.serialize", json!({}));+ assert!(texts(session).iter().any(|t| t == "Kai"));++ exec(session, "file.activate", json!({"index": 0}));+ exec(session, "data.source.remove", json!({}));+ assert!(session.documents()[0].doc.data_merge.sources.is_empty());+ assert!(session.documents()[0].doc.data_merge.placeholders.iter().any(|ph| ph.id == id.as_u64().unwrap()));+ assert_eq!(exec(session, "data.fields", json!({})), json!([]));++ select_csv(session, "Name\nAda\nGrace\n");+ exec(session, "data.preview", json!({"record": 2}));+ assert!(texts(session).iter().any(|t| t.contains("Grace")));+ assert!(!texts(session).iter().any(|t| t.contains("<<Name>>")));+ let ser = exec(session, "file.serialize", json!({}));let saved = crate::cmd::from_bytes(&crate::cmd::base64_decode(ser["base64"].as_str().unwrap())).unwrap();assert!(saved.stories.values().any(|st| st.text.contains("<<Name>>")));assert!(!saved.stories.values().any(|st| st.text.contains("Grace")));- exec(&mut s, "data.preview.stop", json!({}));- assert!(texts(&s).iter().any(|t| t.contains("<<Name>>")));+ exec(session, "data.preview.stop", json!({}));+ assert!(texts(session).iter().any(|t| t.contains("<<Name>>")));- exec(&mut s, "data.preview", json!({"record": 2}));+ exec(session, "data.preview", json!({"record": 2}));let path = dir.join("saved.designcraft");- exec(&mut s, "file.save", json!({"path": path}));+ exec(session, "file.save", json!({"path": path}));let saved = crate::cmd::from_bytes(&std::fs::read(&path).unwrap()).unwrap();assert!(!saved.stories.values().any(|st| st.text.contains("Grace")));assert!(saved.stories.values().any(|st| st.text.contains("<<Name>>")));- exec(&mut s, "data.preview", json!({"record": 2}));+ exec(session, "data.preview", json!({"record": 2}));let rec = dir.join("recovery");- s.recovery_dir = Some(rec.clone());- crate::recovery::save(&s, &rec).unwrap();- let uid = s.documents()[0].uid;+ session.recovery_dir = Some(rec.clone());+ crate::recovery::save(session, &rec).unwrap();+ let uid = session.documents()[0].uid;let recovered = crate::cmd::from_bytes(&std::fs::read(rec.join(format!("{uid}.designcraft"))).unwrap()).unwrap();assert!(!recovered.stories.values().any(|st| st.text.contains("Grace")));- assert!(texts(&s).iter().any(|t| t.contains("Grace")), "recovery writes the stash and leaves the preview on screen");- exec(&mut s, "file.new", json!({}));- exec(&mut s, "file.activate", json!({"index": 0}));- assert!(texts(&s).iter().any(|t| t.contains("<<Name>>")));+ assert!(texts(session).iter().any(|t| t.contains("Grace")), "recovery writes the stash and leaves the preview on screen");+ exec(session, "file.new", json!({}));+ exec(session, "file.activate", json!({"index": 0}));+ assert!(texts(session).iter().any(|t| t.contains("<<Name>>")));+ check_inline_rows_and_invalid_requests();+ check_saved_relative_source(dir, csv);+}++fn check_inline_rows_and_invalid_requests() {let mut s = Session::new();new_doc(&mut s, 1);text_frame(&mut s, [36.0, 36.0, 300.0, 80.0], "<<Name>> <<Qty>>", None);@@ -940,7 +926,9 @@ fn update_remove_preview_inline_rows_and_old_files() {let msg = err(&mut s, "data.merge", json!({"csv": "Name\nAda\n", "limit": 4_294_967_296u64}));assert!(msg.contains("too large"), "{msg}");assert_eq!(s.documents().len(), before);+}+fn check_saved_relative_source(dir: &Path, csv: &Path) {let fresh = dir.join("fresh.designcraft");let mut s = Session::new();new_doc(&mut s, 1);@@ -953,6 +941,35 @@ fn update_remove_preview_inline_rows_and_old_files() {assert_eq!(opened.data_merge.sources[0].relative_path.as_deref(), Some("people.csv"));}+#[test]+fn update_remove_preview_inline_rows_and_old_files() {+ let dir = scratch("update");+ let csv = dir.join("people.csv");+ write(&csv, "Name\nAda\nGrace\n");+ let mut s = Session::new();+ new_doc(&mut s, 1);+ text_frame(&mut s, [36.0, 36.0, 240.0, 80.0], "", None);+ exec(&mut s, "data.source.select", json!({"path": csv}));+ let id = exec(&mut s, "data.placeholder.add", json!({"field": "Name"}))["id"].clone();+ let undo = s.documents()[0].history.undo.len();+ let fingerprint = s.documents()[0].doc.data_merge.sources[0].fingerprint;+ let mut body = std::fs::read(&csv).unwrap();+ body.extend_from_slice(b"Kai\n");+ std::fs::write(&csv, &body).unwrap();+ let r = exec(&mut s, "data.merge", json!({}));+ assert_eq!(r["records"], 2);+ assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap_or("").contains("changed")));+ assert_eq!(texts(&s), vec!["Ada".to_string(), "Grace".to_string()]);+ assert_eq!(s.documents()[0].doc.data_merge.sources[0].status, SourceStatus::Modified);+ assert_eq!(s.documents()[0].doc.data_merge.sources[0].fingerprint, fingerprint);+ assert_eq!(s.documents()[0].history.undo.len(), undo);+ assert_eq!(s.documents()[s.active_index().unwrap()].doc.data_merge.sources[0].status, SourceStatus::Modified);++ check_missing_merge_source(&dir);+ check_refused_facing_page_merge(&dir);+ check_preview_update_save(&mut s, &dir, &csv, &id);+}+#[test]fn parent_placeholder_is_copied_unfilled() {let mut s = Session::new();diff --git a/crates/engine/src/cmd/export/flatten.rs b/crates/engine/src/cmd/export/flatten.rsindex 23059d8f4..b32d54383 100644--- a/crates/engine/src/cmd/export/flatten.rs+++ b/crates/engine/src/cmd/export/flatten.rs@@ -1,4 +1,4 @@-use super::*;+use super::{EngineError, Result};/// Does this object (or anything in it) need the transparency flattener?pub(super) fn transparent(it: &designcraft_doc::Item) -> bool {@@ -100,8 +100,7 @@ pub(super) fn flatten(d: &designcraft_doc::Document, cache: &designcraft_compose&below,cache,&[designcraft_render::Placed { spread: SpreadRef::Doc(si), xf: designcraft_geom::Affine::translate(designcraft_geom::Vec2::ZERO) }],- w,- h,+ (w, h),view,&opts,);@@ -220,7 +219,7 @@ pub(super) fn shadow_masks(let view = designcraft_geom::Affine::scale(k) * designcraft_geom::Affine::translate((-reach.x0, -reach.y0));let opts = designcraft_render::RenderOptions { paper: false, background: None, printing_only: true, ..Default::default() };let placed = [designcraft_render::Placed { spread: SpreadRef::Doc(si), xf: designcraft_geom::Affine::IDENTITY }];- rr.render(&solo, cache, &placed, w, h, view, &opts).pixels.as_chunks::<4>().0.iter().map(|px| px[3]).collect::<Vec<u8>>()+ rr.render(&solo, cache, &placed, (w, h), view, &opts).pixels.as_chunks::<4>().0.iter().map(|px| px[3]).collect::<Vec<u8>>()};let (with, without) = (alpha(true), alpha(false));let n = w as usize * h as usize;@@ -289,8 +288,7 @@ pub(super) fn rasterize_where(&solo,cache,&[designcraft_render::Placed { spread: SpreadRef::Doc(si), xf: designcraft_geom::Affine::translate(designcraft_geom::Vec2::ZERO) }],- w,- h,+ (w, h),view,&opts,);diff --git a/crates/engine/src/cmd/export/formats.rs b/crates/engine/src/cmd/export/formats.rsindex 025bcdac4..31885bee2 100644--- a/crates/engine/src/cmd/export/formats.rs+++ b/crates/engine/src/cmd/export/formats.rs@@ -1,6 +1,6 @@use super::flatten::{rasterize_where, threaded};use super::pdf::pages_param;-use super::*;+use super::{Arc, Cow, EngineError, Result, Session, Value, bad, json, str_param};pub(super) fn print_booklet(s: &mut Session, p: &Value) -> Result<Value> {const ID: &str = "file.printBooklet";diff --git a/crates/engine/src/cmd/export/pdf.rs b/crates/engine/src/cmd/export/pdf.rsindex 64011fa3c..903639ff9 100644--- a/crates/engine/src/cmd/export/pdf.rs+++ b/crates/engine/src/cmd/export/pdf.rs@@ -1,6 +1,6 @@use super::flatten::{flatten, rasterize_effects, rasterize_layered, shadow_masks, transparent};use super::formats::write_file;-use super::*;+use super::{EngineError, Marks, PdfOptions, Result, Session, Standard, Value, bad, json, str_param};/// The `pages` parameter: a range string ("1-3,5"), a list or a number of 1-based positions.pub(super) fn pages_param(id: &str, p: &Value, page_count: usize) -> Result<Option<Vec<usize>>> {diff --git a/crates/engine/src/cmd/export/registry.rs b/crates/engine/src/cmd/export/registry.rsindex dfa126b89..5f7f1d013 100644--- a/crates/engine/src/cmd/export/registry.rs+++ b/crates/engine/src/cmd/export/registry.rs@@ -1,6 +1,6 @@use super::formats::{epub_split_param, export_epub, export_html, export_pptx, export_text, has_story_target, print_booklet};use super::pdf::export_pdf;-use super::*;+use super::{CommandSpec, Value, cmd, has_doc, json};pub fn specs() -> Vec<CommandSpec> {vec![diff --git a/crates/engine/src/cmd/file/bytes.rs b/crates/engine/src/cmd/file/bytes.rsindex d21105206..0946205a8 100644--- a/crates/engine/src/cmd/file/bytes.rs+++ b/crates/engine/src/cmd/file/bytes.rs@@ -1,4 +1,6 @@-use super::*;+#[cfg(test)]+use super::FAIL_TO_BYTES;+use super::{Document, EngineError, Result};/// The document as `.designcraft` bytes, or an error when it can't be written; never an empty file.pub fn to_bytes(d: &Document) -> Result<Vec<u8>> {diff --git a/crates/engine/src/cmd/file/new.rs b/crates/engine/src/cmd/file/new.rsindex 5847442d3..6614a2323 100644--- a/crates/engine/src/cmd/file/new.rs+++ b/crates/engine/src/cmd/file/new.rs@@ -1,6 +1,6 @@#[cfg(test)]use super::bytes::base64_encode;-use super::*;+use super::{Arc, DocState, Document, NewDocument, Result, Session, Value, bad, f64_or, json, str_param};/// The longest saved preset name, and how many presets are kept.const MAX_PRESET_NAME: usize = 100;diff --git a/crates/engine/src/cmd/file/open.rs b/crates/engine/src/cmd/file/open.rsindex d593267a5..75a7ce627 100644--- a/crates/engine/src/cmd/file/open.rs+++ b/crates/engine/src/cmd/file/open.rs@@ -1,7 +1,7 @@#[cfg(test)]use super::bytes::{PREVIEW_PX, to_bytes};use super::bytes::{base64_decode, load_bytes};-use super::*;+use super::{Arc, DocState, Document, EngineError, Result, Session, Value, bad, json, str_param};pub(super) fn has_recent(s: &Session) -> std::result::Result<(), String> {if s.prefs.recent_files.is_empty() { Err("no recent files".into()) } else { Ok(()) }diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rsindex d9ecb3ad0..44f993a64 100644--- a/crates/engine/src/cmd/file/place.rs+++ b/crates/engine/src/cmd/file/place.rs@@ -1,7 +1,12 @@+#[cfg(not(target_arch = "wasm32"))]+use super::EngineError;#[cfg(test)]use super::bytes::base64_encode;use super::bytes::{base64_decode, from_bytes};-use super::*;+use super::{+ Affine, Arc, Asset, AssetId, Content, Graphic, Item, ItemId, PdfCrop, Rect, Result, Selection, Session, Shape, Value, bad, json, ok, shapes,+ str_param,+};pub(super) fn file_place(s: &mut Session, p: &Value) -> Result<Value> {// The file's size and time before it is read (a linked text file remembers them).diff --git a/crates/engine/src/cmd/file/registry.rs b/crates/engine/src/cmd/file/registry.rsindex 3d2e58093..216f12bdb 100644--- a/crates/engine/src/cmd/file/registry.rs+++ b/crates/engine/src/cmd/file/registry.rs@@ -1,10 +1,12 @@+#[cfg(not(target_arch = "wasm32"))]+use super::EngineError;use super::bytes::{base64_encode, to_bytes, to_bytes_with_preview, with_document_extension};use super::new::{file_new, file_sample, save_preset};use super::open::{file_open, file_open_bytes, file_open_recent, has_recent, recent_entry};use super::place::{file_place, place_drop, place_load, read_source};use super::save::{FolderAccess, can_revert, file_revert, file_save, recovery_dir};use super::snippets::{snippet_export, snippet_place};-use super::*;+use super::{CommandSpec, PRESETS, Value, always, bad, cmd, has_doc, json, ok, str_param};pub fn specs() -> Vec<CommandSpec> {vec![diff --git a/crates/engine/src/cmd/file/save.rs b/crates/engine/src/cmd/file/save.rsindex 38b3f8d46..d94a02ab9 100644--- a/crates/engine/src/cmd/file/save.rs+++ b/crates/engine/src/cmd/file/save.rs@@ -1,11 +1,13 @@#[cfg(not(target_arch = "wasm32"))]+use super::DocState;+#[cfg(not(target_arch = "wasm32"))]use super::bytes::from_bytes;use super::bytes::{to_bytes_with_preview, with_document_extension};#[cfg(not(target_arch = "wasm32"))]use super::open::load_document_fonts;#[cfg(test)]use super::place::image_place_tests;-use super::*;+use super::{Arc, EngineError, Result, Session, Value, bad, json, str_param};pub(super) fn file_save(s: &mut Session, p: &Value) -> Result<Value> {let st = s.doc_mut()?;@@ -118,6 +120,7 @@ mod save_tests {use serde_json::json;use crate::Session;+ use crate::cmd::file::FAIL_TO_BYTES;/// Saving over an existing document replaces it whole and leaves nothing beside it.#[test]@@ -161,12 +164,12 @@ mod save_tests {let checkpoint = recovery.join(format!("{}.designcraft", s.doc().unwrap().uid));assert!(checkpoint.exists());- super::FAIL_TO_BYTES.with(|f| f.set(true));+ FAIL_TO_BYTES.with(|f| f.set(true));let save = s.execute("file.save", &json!({}));let copy = s.execute("file.saveACopy", &json!({"path": dir.join("copy.designcraft").to_string_lossy()}));let save_as = s.execute("file.saveAs", &json!({"path": dir.join("other.designcraft").to_string_lossy()}));let serialized = s.execute("file.serialize", &json!({}));- super::FAIL_TO_BYTES.with(|f| f.set(false));+ FAIL_TO_BYTES.with(|f| f.set(false));let e = save.unwrap_err();assert!(e.to_string().contains("could not write the document"), "{e}");diff --git a/crates/engine/src/cmd/file/snippets.rs b/crates/engine/src/cmd/file/snippets.rsindex 231e2196b..5ff1f3795 100644--- a/crates/engine/src/cmd/file/snippets.rs+++ b/crates/engine/src/cmd/file/snippets.rs@@ -1,6 +1,8 @@+#[cfg(not(target_arch = "wasm32"))]+use super::EngineError;use super::bytes::{base64_encode, from_bytes, to_bytes};use super::place::read_source;-use super::*;+use super::{ItemId, Rect, Result, Selection, Session, Value, bad, json, str_param};/// The selection as `.designcraft` snippet bytes.pub(crate) fn snippet_bytes(s: &mut Session) -> Result<Vec<u8>> {diff --git a/crates/engine/src/cmd/find/tests.rs b/crates/engine/src/cmd/find/tests.rsindex 47d685e19..5914c2e51 100644--- a/crates/engine/src/cmd/find/tests.rs+++ b/crates/engine/src/cmd/find/tests.rs@@ -58,8 +58,7 @@ fn scope_hit(s: &mut Session, p: &serde_json::Value, sid: designcraft_doc::Storyassert_eq!((selected.story, selected.range(), selected.cell), (sid, a..b, None));}-#[test]-fn find_scope_first_change_stops_after_first_matching_story_and_repairs_selection() {+fn assert_document_change_scenarios() {for (texts, first, explicit, grep, expected, count) in [(vec!["red red", "red"], Some(true), false, false, vec!["blue red", "red"], 1),(vec!["keep", "red red", "red"], Some(true), false, false, vec!["keep", "blue red", "red"], 1),@@ -119,6 +118,11 @@ fn find_scope_first_change_stops_after_first_matching_story_and_repairs_selectio}st.doc.check().unwrap();}+}++#[test]+fn find_scope_first_change_stops_after_first_matching_story_and_repairs_selection() {+ assert_document_change_scenarios();// Identical replacement is still one counted match, not a reason to visit another story.let (mut s, sid) = scope_session("red red");diff --git a/crates/engine/src/cmd/layout/layers.rs b/crates/engine/src/cmd/layout/layers.rsindex 52fa0ea71..80fbc9d28 100644--- a/crates/engine/src/cmd/layout/layers.rs+++ b/crates/engine/src/cmd/layout/layers.rs@@ -1,4 +1,4 @@-use super::*;+use super::{LAYER_COLORS, LayerId, Result, Session, Value, bad, 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<Value> {diff --git a/crates/engine/src/cmd/layout/margins.rs b/crates/engine/src/cmd/layout/margins.rsindex 41d30557b..bcfa6c431 100644--- a/crates/engine/src/cmd/layout/margins.rs+++ b/crates/engine/src/cmd/layout/margins.rs@@ -1,5 +1,5 @@use super::parents::parent_spread_index;-use super::*;+use super::{Margins, Result, Session, Value, bad, has_doc, json};/// Each page's margin box, by spread and page id.pub(super) fn margin_boxes(d: &designcraft_doc::Document) -> Vec<(designcraft_doc::SpreadRef, designcraft_doc::PageId, designcraft_geom::Rect)> {diff --git a/crates/engine/src/cmd/layout/pages.rs b/crates/engine/src/cmd/layout/pages.rsindex d5d01423a..0417f1ff6 100644--- a/crates/engine/src/cmd/layout/pages.rs+++ b/crates/engine/src/cmd/layout/pages.rs@@ -1,5 +1,5 @@use super::margins::set_page_width;-use super::*;+use super::{Result, Value, bad, json, str_param};#[allow(dead_code)]fn _r(_: Result<()>) {}diff --git a/crates/engine/src/cmd/layout/parents.rs b/crates/engine/src/cmd/layout/parents.rsindex 4e464d5af..f53d774f4 100644--- a/crates/engine/src/cmd/layout/parents.rs+++ b/crates/engine/src/cmd/layout/parents.rs@@ -1,4 +1,4 @@-use super::*;+use super::{Result, SpreadId, Value, bad, json};/// A parent spread named by prefix, label (`A-Parent`) or index.pub(super) fn parent_spread_index(d: &designcraft_doc::Document, v: &Value) -> Option<usize> {@@ -399,7 +399,7 @@ mod parent_base_tests {rr.threads = 0;let placed = [designcraft_render::Placed { spread: designcraft_doc::SpreadRef::Parent(1), xf: designcraft_geom::Affine::IDENTITY }];let opts = designcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };- let img = rr.render(&s.doc().unwrap().doc, &s.cache, &placed, 400, 400, designcraft_geom::Affine::IDENTITY, &opts);+ let img = rr.render(&s.doc().unwrap().doc, &s.cache, &placed, (400, 400), designcraft_geom::Affine::IDENTITY, &opts);assert!(black(img.pixel(50, 100)) && cyan(img.pixel(150, 150)), "{:?} {:?}", img.pixel(50, 100), img.pixel(150, 150));let inspect = s.execute("document.inspect", &json!({})).unwrap();assert_eq!(inspect["parents"][1]["basedOn"], "A-Parent");diff --git a/crates/engine/src/cmd/layout/registry.rs b/crates/engine/src/cmd/layout/registry.rsindex 8f0d2405f..4826f9273 100644--- a/crates/engine/src/cmd/layout/registry.rs+++ b/crates/engine/src/cmd/layout/registry.rs@@ -3,7 +3,7 @@ use super::margins::{adjust_layout, column_guides_unlocked, margin_boxes, move_cuse super::pages::{document_setup, page_options, page_size};use super::parents::{parent_options, parent_ref, parent_spread_index};use super::sections::{ChapterEdit, SectionEdit, chapter_numbering, start_number};-use super::*;+use super::{CommandSpec, LAYER_COLORS, Layer, LayerId, Margins, SpreadId, Value, bad, cmd, has_doc, json, ok, str_param};pub fn specs() -> Vec<CommandSpec> {vec![diff --git a/crates/engine/src/cmd/layout/sections.rs b/crates/engine/src/cmd/layout/sections.rsindex 11ef139bc..3a388743d 100644--- a/crates/engine/src/cmd/layout/sections.rs+++ b/crates/engine/src/cmd/layout/sections.rs@@ -1,4 +1,4 @@-use super::*;+use super::{Result, Session, Value, bad, json};/// A start page number parameter: a whole number in 1..=[`designcraft_doc::MAX_PAGE_NUMBER`].pub(super) fn start_number(cmd: &str, key: &str, v: &Value) -> Result<u32> {diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rsindex 7a6d3a001..3fc67f822 100644--- a/crates/engine/src/cmd/links.rs+++ b/crates/engine/src/cmd/links.rs@@ -934,6 +934,47 @@ mod text_link_tests {st.paras.iter().map(|p| p.style.clone()).collect()}+ fn assert_link_update_replaces_and_warns(s: &mut Session, path: &std::path::Path, sid: StoryId, a: u64, b: u64) {+ // The file changes (with tracked changes): Modified; Update imports it as if accepted, with+ // the saved style map, into the same frames, without new renamed styles.+ std::fs::write(+ path,+ docx(r#"<w:r><w:t xml:space="preserve">Second </w:t></w:r><w:ins w:id="1" w:author="A"><w:r><w:t>revised </w:t></w:r></w:ins><w:del w:id="2" w:author="A"><w:r><w:delText>old </w:delText></w:r></w:del><w:r><w:t>draft.</w:t></w:r>"#),+ )+ .unwrap();+ assert_eq!(text_rows(s)[0]["status"], "modified");+ let r = s.execute("links.update", &json!({"story": sid.0})).unwrap();+ assert_eq!(r["updated"], 1);+ assert_eq!(r["warnings"], json!([]), "no edits in the layout to replace");+ let updated = story(s, sid);+ assert_eq!(updated.text, "Head\nSecond revised draft.");+ assert_eq!(styles(&updated), ["Headline", "Body_wrd_1"]);+ assert_eq!(updated.frames, [ItemId(a), ItemId(b)], "frames and thread kept");+ assert!(s.doc().unwrap().doc.styles.para("Body_wrd_2").is_none());+ assert!(s.doc().unwrap().doc.styles.para("Title").is_none(), "mapped styles aren't imported");+ assert_eq!(text_rows(s)[0]["status"], "ok");++ // An edit in the layout, then the file changes again: Update replaces the edit and warns.+ s.execute("story.setText", &json!({"story": sid.0, "text": "Fixed in layout"})).unwrap();+ assert_eq!(text_rows(s)[0]["edited"], true);+ std::fs::write(path, docx("<w:r><w:t>Third draft.</w:t></w:r>")).unwrap();+ let r = s.execute("links.update", &json!({})).unwrap();+ assert_eq!(r["updated"], 1);+ let w = r["warnings"][0].as_str().unwrap();+ assert!(w.contains("chapter.docx") && w.contains("replaced"), "{w}");+ assert_eq!(story(s, sid).text, "Head\nThird draft.");+ assert_eq!(text_rows(s)[0]["edited"], false);+ // Undo brings the edit back.+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(story(s, sid).text, "Fixed in layout");+ s.execute("edit.redo", &json!({})).unwrap();++ // Saved and opened again: the link and its options are kept.+ let back = designcraft_format::load(&designcraft_format::save(&s.doc().unwrap().doc).unwrap()).unwrap();+ assert_eq!(back.story(sid).unwrap().file_link, story(s, sid).file_link);+ assert_eq!(super::text_status(back.story(sid).unwrap().file_link.as_ref().unwrap(), &mut Default::default(), None), "ok");+ }+#[test]fn linked_word_file_status_update_relink_and_unlink() {let dir = std::env::temp_dir().join(format!("dc-text-link-{}", std::process::id()));@@ -973,44 +1014,7 @@ mod text_link_tests {assert_eq!((rows[0]["status"].as_str(), rows[0]["edited"].as_bool()), (Some("ok"), Some(false)));assert_eq!(rows[0]["uses"].as_array().unwrap().len(), 2, "both threaded frames");- // The file changes (with tracked changes): Modified; Update imports it as if accepted, with- // the saved style map, into the same frames, without new renamed styles.- std::fs::write(- &path,- docx(r#"<w:r><w:t xml:space="preserve">Second </w:t></w:r><w:ins w:id="1" w:author="A"><w:r><w:t>revised </w:t></w:r></w:ins><w:del w:id="2" w:author="A"><w:r><w:delText>old </w:delText></w:r></w:del><w:r><w:t>draft.</w:t></w:r>"#),- )- .unwrap();- assert_eq!(text_rows(&mut s)[0]["status"], "modified");- let r = s.execute("links.update", &json!({"story": sid.0})).unwrap();- assert_eq!(r["updated"], 1);- assert_eq!(r["warnings"], json!([]), "no edits in the layout to replace");- let updated = story(&s, sid);- assert_eq!(updated.text, "Head\nSecond revised draft.");- assert_eq!(styles(&updated), ["Headline", "Body_wrd_1"]);- assert_eq!(updated.frames, [ItemId(a), ItemId(b)], "frames and thread kept");- assert!(s.doc().unwrap().doc.styles.para("Body_wrd_2").is_none());- assert!(s.doc().unwrap().doc.styles.para("Title").is_none(), "mapped styles aren't imported");- assert_eq!(text_rows(&mut s)[0]["status"], "ok");-- // An edit in the layout, then the file changes again: Update replaces the edit and warns.- s.execute("story.setText", &json!({"story": sid.0, "text": "Fixed in layout"})).unwrap();- assert_eq!(text_rows(&mut s)[0]["edited"], true);- std::fs::write(&path, docx("<w:r><w:t>Third draft.</w:t></w:r>")).unwrap();- let r = s.execute("links.update", &json!({})).unwrap();- assert_eq!(r["updated"], 1);- let w = r["warnings"][0].as_str().unwrap();- assert!(w.contains("chapter.docx") && w.contains("replaced"), "{w}");- assert_eq!(story(&s, sid).text, "Head\nThird draft.");- assert_eq!(text_rows(&mut s)[0]["edited"], false);- // Undo brings the edit back.- s.execute("edit.undo", &json!({})).unwrap();- assert_eq!(story(&s, sid).text, "Fixed in layout");- s.execute("edit.redo", &json!({})).unwrap();-- // Saved and opened again: the link and its options are kept.- let back = designcraft_format::load(&designcraft_format::save(&s.doc().unwrap().doc).unwrap()).unwrap();- assert_eq!(back.story(sid).unwrap().file_link, story(&s, sid).file_link);- assert_eq!(super::text_status(back.story(sid).unwrap().file_link.as_ref().unwrap(), &mut Default::default(), None), "ok");+ assert_link_update_replaces_and_warns(&mut s, &path, sid, a, b);// The file moves: Missing; Relink to it imports it into the story.let moved = dir.join("moved").join("chapter.docx");diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rsindex 90b958207..ad8b25213 100644--- a/crates/engine/src/cmd/object.rs+++ b/crates/engine/src/cmd/object.rs@@ -2639,17 +2639,7 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result<Value> {if let Some(v) = rule_bottom {o.column_rule_bottom_inset = v;}- match custom_grid {- Some(Some((start, increment, relative_to))) => {- let mut g = o.baseline_grid.unwrap_or(doc_grid);- g.start = start.unwrap_or(g.start);- g.increment = increment.unwrap_or(g.increment);- g.relative_to = relative_to.unwrap_or(g.relative_to);- o.baseline_grid = Some(g);- }- Some(None) => o.baseline_grid = None,- None => {}- }+ apply_custom_frame_grid(o, custom_grid, doc_grid);// Fixed Width columns set the frame's width: n columns, the gutters between them and// the left and right insets.let fixed_width = o.columns_kind == designcraft_doc::ColumnsKind::FixedWidth && o.column_width > 0.0;@@ -2671,6 +2661,24 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result<Value> {})}+fn apply_custom_frame_grid(+ options: &mut TextFrameOptions,+ custom: Option<Option<(Option<f64>, Option<f64>, Option<designcraft_doc::FrameGridRelative>)>>,+ document_grid: designcraft_doc::FrameBaselineGrid,+) {+ match custom {+ Some(Some((start, increment, relative_to))) => {+ let mut grid = options.baseline_grid.unwrap_or(document_grid);+ grid.start = start.unwrap_or(grid.start);+ grid.increment = increment.unwrap_or(grid.increment);+ grid.relative_to = relative_to.unwrap_or(grid.relative_to);+ options.baseline_grid = Some(grid);+ }+ Some(None) => options.baseline_grid = None,+ None => {}+ }+}+/// The gap at `p` on spread `sr`: (vertical gap?, edge a, edge b, ids ending at a, ids starting at b).pub(crate) fn find_gap(d: &Document, sr: designcraft_doc::SpreadRef, p: Point) -> Option<(bool, f64, f64, Vec<ItemId>, Vec<ItemId>)> {let sp = d.spread(sr)?;diff --git a/crates/engine/src/cmd/paste_svg.rs b/crates/engine/src/cmd/paste_svg.rsindex 92e37b6f1..a5d738cef 100644--- a/crates/engine/src/cmd/paste_svg.rs+++ b/crates/engine/src/cmd/paste_svg.rs@@ -8,7 +8,7 @@ use designcraft_geom::{Affine, BezPath, PathData, Point, Rect};use designcraft_images::usvg;use serde_json::{Value, json};-use super::*;+use super::{CommandSpec, Result, Session, bad, cmd, has_doc, spread_param, str_param};pub fn specs() -> Vec<CommandSpec> {vec![cmd!(diff --git a/crates/engine/src/cmd/style/color.rs b/crates/engine/src/cmd/style/color.rsindex ebefbd0f3..e212bd3b6 100644--- a/crates/engine/src/cmd/style/color.rs+++ b/crates/engine/src/cmd/style/color.rs@@ -1,5 +1,5 @@use super::swatches::{parse_color, value_name};-use super::*;+use super::{CharAttrs, Result, Session, Styles, Swatch, SwatchValue, Value, bad, has_doc, json, str_param};fn gradient_json(name: &str, g: &designcraft_color::Gradient) -> Value {let stops: Vec<Value> = gdiff --git a/crates/engine/src/cmd/style/object.rs b/crates/engine/src/cmd/style/object.rsindex e00eca1b7..0eebe1748 100644--- a/crates/engine/src/cmd/style/object.rs+++ b/crates/engine/src/cmd/style/object.rs@@ -1,4 +1,4 @@-use super::*;+use super::{Effects, Item, ObjectStyle, Result, Session, Styles, Value, bad, json, str_param};pub(super) fn apply_object(s: &mut Session, p: &Value) -> Result<Value> {let name = str_param(p, "name").ok_or_else(|| bad("style.object.apply", "missing name"))?.to_string();diff --git a/crates/engine/src/cmd/style/paragraph.rs b/crates/engine/src/cmd/style/paragraph.rsindex f39e89e78..81711ff10 100644--- a/crates/engine/src/cmd/style/paragraph.rs+++ b/crates/engine/src/cmd/style/paragraph.rs@@ -1,4 +1,4 @@-use super::*;+use super::{CharAttrs, CharacterStyle, ParaAttrs, ParagraphStyle, Result, Session, Styles, Value, bad, json, ok, str_param};#[cfg(test)]mod redefine_tests {diff --git a/crates/engine/src/cmd/style/swatches.rs b/crates/engine/src/cmd/style/swatches.rsindex 74d7a2bdb..3b73138f9 100644--- a/crates/engine/src/cmd/style/swatches.rs+++ b/crates/engine/src/cmd/style/swatches.rs@@ -1,5 +1,5 @@use super::color::check_text_nesting;-use super::*;+use super::{Result, Session, Styles, Swatch, SwatchValue, Value, bad, json, str_param};pub(super) fn create_swatch(s: &mut Session, p: &Value) -> Result<Value> {if let Some(g) = p.get("gradient") {diff --git a/crates/engine/src/cmd/table/cell.rs b/crates/engine/src/cmd/table/cell.rsindex 6d65348e1..93a1f3dab 100644--- a/crates/engine/src/cmd/table/cell.rs+++ b/crates/engine/src/cmd/table/cell.rs@@ -1,5 +1,5 @@use super::target::{edit_table, target};-use super::*;+use super::{CellRange, CellStroke, Document, Result, Session, StrokeType, Table, Value, VerticalJustification, bad, compose, json, ok, str_param};/// Cell edges chosen for a stroke edit: the target range's four outer sides (physical left and/// right) and the lines between its rows and columns.@@ -169,6 +169,47 @@ pub(super) fn first_baseline_params(p: &Value, id: &str) -> Result<(Option<desigOk((fb, min))}+fn mirror_edited_cell_edges(+ table: &mut Table,+ range: CellRange,+ table_size: (usize, usize, bool),+ stroke: Option<&(StrokeEdit, EdgeSel)>,+ edited: &std::collections::HashSet<(usize, usize, usize)>,+ owners: &[(usize, usize)],+) {+ let (rows, columns, rtl) = table_size;+ let mirror = |table: &mut Table, from: (usize, usize), edge: usize, to: (usize, usize), opposite: usize| {+ if edited.contains(&(from.0, from.1, edge)) {+ mirror_cell_edge(table, owners, from, edge, to, opposite);+ }+ };+ let Some((_, edges)) = stroke else { return };+ if edges.top+ && let Some(row) = range.r0.checked_sub(1)+ {+ for column in range.c0..=range.c1 {+ mirror(table, (range.r0, column), 0, (row, column), 2);+ }+ }+ if edges.bottom && range.r1.saturating_add(1) < rows {+ for column in range.c0..=range.c1 {+ mirror(table, (range.r1, column), 2, (range.r1 + 1, column), 0);+ }+ }+ if (if rtl { edges.right } else { edges.left })+ && let Some(column) = range.c0.checked_sub(1)+ {+ for row in range.r0..=range.r1 {+ mirror(table, (row, range.c0), if rtl { 3 } else { 1 }, (row, column), if rtl { 1 } else { 3 });+ }+ }+ if (if rtl { edges.left } else { edges.right }) && range.c1.saturating_add(1) < columns {+ for row in range.r0..=range.r1 {+ mirror(table, (row, range.c1), if rtl { 1 } else { 3 }, (row, range.c1 + 1), if rtl { 3 } else { 1 });+ }+ }+}+pub(super) fn set_cell(s: &mut Session, p: &Value) -> Result<Value> {const ID: &str = "table.setCell";let g = target(s, p, ID)?;@@ -270,39 +311,8 @@ pub(super) fn set_cell(s: &mut Session, p: &Value) -> Result<Value> {}}}- // Keep both copies of unmerged shared boundaries consistent: each edited edge is- // copied to its neighbour. Left/right name physical sides, also in RTL tables.- let mirror = |t: &mut Table, from: (usize, usize), edge: usize, to: (usize, usize), opposite: usize| {- if edited.contains(&(from.0, from.1, edge)) {- mirror_cell_edge(t, &owners, from, edge, to, opposite);- }- };- if let Some((_, edges)) = &stroke {- if edges.top- && let Some(row) = rg.r0.checked_sub(1)- {- for c in rg.c0..=rg.c1 {- mirror(t, (rg.r0, c), 0, (row, c), 2);- }- }- if edges.bottom && rg.r1.saturating_add(1) < nr {- for c in rg.c0..=rg.c1 {- mirror(t, (rg.r1, c), 2, (rg.r1 + 1, c), 0);- }- }- if (if rtl { edges.right } else { edges.left })- && let Some(col) = rg.c0.checked_sub(1)- {- for r in rg.r0..=rg.r1 {- mirror(t, (r, rg.c0), if rtl { 3 } else { 1 }, (r, col), if rtl { 1 } else { 3 });- }- }- if (if rtl { edges.left } else { edges.right }) && rg.c1.saturating_add(1) < nc {- for r in rg.r0..=rg.r1 {- mirror(t, (r, rg.c1), if rtl { 1 } else { 3 }, (r, rg.c1 + 1), if rtl { 3 } else { 1 });- }- }- }+ // Keep both copies of unmerged shared boundaries consistent, including in RTL tables.+ mirror_edited_cell_edges(t, rg, (nr, nc, rtl), stroke.as_ref(), &edited, &owners);ok()})}diff --git a/crates/engine/src/cmd/table/content.rs b/crates/engine/src/cmd/table/content.rsindex aef552732..2d306c811 100644--- a/crates/engine/src/cmd/table/content.rs+++ b/crates/engine/src/cmd/table/content.rs@@ -1,6 +1,6 @@use super::selection::cell_at;use super::target::{clamp_selection, edit_table, target};-use super::*;+use super::{CellRange, Result, Session, TableSel, Value, bad, json};pub(super) fn drop_cells(s: &mut Session, p: &Value) -> Result<Value> {const ID: &str = "table.dropCells";diff --git a/crates/engine/src/cmd/table/options.rs b/crates/engine/src/cmd/table/options.rsindex 5cf82d87d..7f9ed7786 100644--- a/crates/engine/src/cmd/table/options.rs+++ b/crates/engine/src/cmd/table/options.rs@@ -1,6 +1,6 @@use super::cell::StrokeEdit;use super::target::{color_param, edit_table, target};-use super::*;+use super::{AltFills, Result, Session, Value, bad, f64_or, json};fn parse_alt(v: &Value) -> Option<AltFills> {if v.is_null() {diff --git a/crates/engine/src/cmd/table/registry.rs b/crates/engine/src/cmd/table/registry.rsindex af2708e23..28d451ced 100644--- a/crates/engine/src/cmd/table/registry.rs+++ b/crates/engine/src/cmd/table/registry.rs@@ -9,7 +9,7 @@ use super::structure::{};use super::styles::{cell_style_apply, cell_style_create, cell_style_edit, table_style_apply, table_style_create, table_style_edit};use super::target::{edit_table, in_cell, in_table, in_table_or_ids, target};-use super::*;+use super::{CommandSpec, RowKind, cmd, has_doc, has_text, json, ok};pub fn specs() -> Vec<CommandSpec> {let mut v = style_specs();diff --git a/crates/engine/src/cmd/table/selection.rs b/crates/engine/src/cmd/table/selection.rsindex 2fab01e9f..9e0a11d0e 100644--- a/crates/engine/src/cmd/table/selection.rs+++ b/crates/engine/src/cmd/table/selection.rs@@ -1,5 +1,5 @@use super::target::{Tgt, edit_table, target};-use super::*;+use super::{CellAddr, CellRange, Result, Selection, Session, StoryId, TableSel, TextSel, Value, bad, json, ok, str_param};// ---------- selection ----------diff --git a/crates/engine/src/cmd/table/sizing.rs b/crates/engine/src/cmd/table/sizing.rsindex cd1d1af53..b097af87f 100644--- a/crates/engine/src/cmd/table/sizing.rs+++ b/crates/engine/src/cmd/table/sizing.rs@@ -1,5 +1,5 @@use super::target::{edit_table, target};-use super::*;+use super::{Result, RowHeightMode, Session, Table, Value, bad, compose, json, ok, str_param};pub(super) fn set_row_height(s: &mut Session, p: &Value) -> Result<Value> {let g = target(s, p, "table.setRowHeight")?;diff --git a/crates/engine/src/cmd/table/structure.rs b/crates/engine/src/cmd/table/structure.rsindex 65bcdb3d6..174704c4a 100644--- a/crates/engine/src/cmd/table/structure.rs+++ b/crates/engine/src/cmd/table/structure.rs@@ -1,5 +1,5 @@use super::target::{column_width, count, edit_table, in_cell, para_direction, target};-use super::*;+use super::{CellAddr, Result, RowKind, Selection, Session, Table, TextSel, Value, bad, json, ok, str_param};pub(super) fn insert(s: &mut Session, p: &Value) -> Result<Value> {let t = s.doc()?.selection.text.ok_or_else(|| bad("table.insert", "no insertion point"))?;diff --git a/crates/engine/src/cmd/table/styles.rs b/crates/engine/src/cmd/table/styles.rsindex 098ae406d..fa3717977 100644--- a/crates/engine/src/cmd/table/styles.rs+++ b/crates/engine/src/cmd/table/styles.rs@@ -1,6 +1,6 @@use super::cell::{StrokeEdit, first_baseline_params};use super::target::{color_param, edit_table, target};-use super::*;+use super::{CellStroke, Document, Result, Session, Value, bad, json, ok, str_param};// ---------- cell and table styles ----------diff --git a/crates/engine/src/cmd/table/target.rs b/crates/engine/src/cmd/table/target.rsindex ee3b9c785..beaa1c8b0 100644--- a/crates/engine/src/cmd/table/target.rs+++ b/crates/engine/src/cmd/table/target.rs@@ -1,4 +1,7 @@-use super::*;+use super::{+ CellAddr, CellRange, Document, Result, Selection, Session, StoryId, Table, TableSel, TextSel, Value, bad, compose, floor_char_boundary, has_doc,+ str_param,+};// ---------- enablement and targeting ----------diff --git a/crates/engine/src/cmd/text/asian.rs b/crates/engine/src/cmd/text/asian.rsindex 93dcfd7bf..8192bcad4 100644--- a/crates/engine/src/cmd/text/asian.rs+++ b/crates/engine/src/cmd/text/asian.rs@@ -1,5 +1,5 @@use super::format::{char_flag_on, format_chars, format_paras, format_targets};-use super::*;+use super::{Result, Session, Value, bad, json};pub(super) fn warichu_cmd(s: &mut Session, p: &Value) -> Result<Value> {let has_opts = ["lines", "size", "lineSpacing", "align", "charsBeforeBreak", "charsAfterBreak"].iter().any(|k| p.get(k).is_some());diff --git a/crates/engine/src/cmd/text/caret.rs b/crates/engine/src/cmd/text/caret.rsindex ebdda0189..670de4049 100644--- a/crates/engine/src/cmd/text/caret.rs+++ b/crates/engine/src/cmd/text/caret.rs@@ -1,4 +1,7 @@-use super::*;+use super::{+ CellAddr, Content, ItemId, Point, Result, Selection, Session, StoryId, TextSel, Value, bad, bool_or, compose, floor_char_boundary, id_param,+ json, ok, point_param, str_param,+};pub(crate) fn story_of(s: &Session, p: &Value) -> Option<StoryId> {let st = s.active()?;diff --git a/crates/engine/src/cmd/text/edit.rs b/crates/engine/src/cmd/text/edit.rsindex 627255d31..fc3f5dddf 100644--- a/crates/engine/src/cmd/text/edit.rs+++ b/crates/engine/src/cmd/text/edit.rs@@ -1,6 +1,8 @@use super::caret::{next_char, next_word, prev_char, prev_word, story_of};use super::format::{apply_typing_format, format_targets, typing_format};-use super::*;+use super::{Result, Session, TextSel, Value, bad, bool_or, compose, floor_char_boundary, id_param, json, ok, str_param};+#[cfg(test)]+use designcraft_doc::StoryId;// Each command edits a copy-on-write Story snapshot. Reserving its known final text growth// avoids retaining geometric String spare capacity in every independent undo snapshot.diff --git a/crates/engine/src/cmd/text/format.rs b/crates/engine/src/cmd/text/format.rsindex 0ab69db26..7e1833c0a 100644--- a/crates/engine/src/cmd/text/format.rs+++ b/crates/engine/src/cmd/text/format.rs@@ -1,7 +1,9 @@use super::asian::bool_param;use super::caret::hit_byte_with;use super::story::selection_attrs;-use super::*;+use super::{+ CellAddr, CharAttrs, ParaAttrs, Result, Session, StoryId, TextSel, Value, bad, compose, floor_char_boundary, id_param, json, ok, point_param,+};/// The Eyedropper with text selected: the formatting of the text under `point` in `frame` goes to/// the selection, as InDesign's does (character style and overrides on the selected characters,diff --git a/crates/engine/src/cmd/text/opentype.rs b/crates/engine/src/cmd/text/opentype.rsindex 9808a94f4..f918c1cfe 100644--- a/crates/engine/src/cmd/text/opentype.rs+++ b/crates/engine/src/cmd/text/opentype.rs@@ -2,7 +2,7 @@ use super::format::{Target, format_chars, format_targets};use super::story::selection_attrs;#[cfg(test)]use super::story::{SELECTED_TEXT_CHARS, selected_text_preview};-use super::*;+use super::{Result, Session, Value, bad, json, ok};pub(super) fn open_type(s: &mut Session, p: &Value) -> Result<Value> {use designcraft_doc::otf;diff --git a/crates/engine/src/cmd/text/story.rs b/crates/engine/src/cmd/text/story.rsindex c096280ea..e3547f88d 100644--- a/crates/engine/src/cmd/text/story.rs+++ b/crates/engine/src/cmd/text/story.rs@@ -1,6 +1,6 @@use super::caret::story_of;use super::format::{Target, effective_char_format, format_targets};-use super::*;+use super::{ItemId, Result, Session, StoryId, Value, bad, bool_or, json};/// The stories of the text selection, the selected cells and the selected text frames.fn selected_stories(s: &Session) -> Result<Vec<StoryId>> {diff --git a/crates/engine/src/tests/idml.rs b/crates/engine/src/tests/idml.rsindex 3a49168be..e8766d091 100644--- a/crates/engine/src/tests/idml.rs+++ b/crates/engine/src/tests/idml.rs@@ -30,6 +30,13 @@ fn magazine_round_trips_through_idml() {assert_eq!(back.page_count(), d.page_count());assert_eq!(back.spreads.len(), d.spreads.len());assert_eq!(back.parents.len(), d.parents.len());+ assert_magazine_stories(&d, &back);+ assert_magazine_styles(&d, &back);+ assert_magazine_geometry(&d, &back);+ assert_magazine_assets(&d, &back);+}++fn assert_magazine_stories(d: &Document, back: &Document) {// Stories: same text in the same order, same styles applied.let ta: Vec<&str> = d.stories.values().map(|s| s.text.as_str()).collect();let tb: Vec<&str> = back.stories.values().map(|s| s.text.as_str()).collect();@@ -48,6 +55,9 @@ fn magazine_round_trips_through_idml() {assert_eq!(pa.para, pb.para);}}+}++fn assert_magazine_styles(d: &Document, back: &Document) {// Styles and swatches by name.for s in &d.styles.paragraph {let b = back.styles.para(&s.name).unwrap_or_else(|| panic!("paragraph style {}", s.name));@@ -64,6 +74,9 @@ fn magazine_round_trips_through_idml() {let b = back.swatch(&s.name).unwrap_or_else(|| panic!("swatch {}", s.name));assert_eq!(b.value, s.value, "{}", s.name);}+}++fn assert_magazine_geometry(d: &Document, back: &Document) {// Frame geometry (document and parent spreads), pages.for (sa, sb) in [(&d.spreads, &back.spreads), (&d.parents, &back.parents)] {let (ia, ib) = (items(sa), items(sb));@@ -78,8 +91,11 @@ fn magazine_round_trips_through_idml() {}}// Threads: the same frames in the same order.- assert_eq!(positions(&d), positions(&back));+ assert_eq!(positions(d), positions(back));assert!(back.stories.values().any(|s| s.frames.len() == 2));+}++fn assert_magazine_assets(d: &Document, back: &Document) {// Images are embedded.assert_eq!(back.assets.len(), d.assets.len());for (a, b) in d.assets.values().zip(back.assets.values()) {@@ -87,7 +103,7 @@ fn magazine_round_trips_through_idml() {assert_eq!(a.pixels, b.pixels);}// A second round trip is stable.- let again = designcraft_idml::import_idml(&designcraft_idml::export_idml(&back)).unwrap();+ let again = designcraft_idml::import_idml(&designcraft_idml::export_idml(back)).unwrap();assert_eq!(items(&again.spreads).len(), items(&back.spreads).len());}diff --git a/crates/engine/src/tests/table.rs b/crates/engine/src/tests/table.rsindex acb0d2352..ecf0b9bbe 100644--- a/crates/engine/src/tests/table.rs+++ b/crates/engine/src/tests/table.rs@@ -911,100 +911,115 @@ fn split_selected_row_or_column_splits_both_cells() {fn split_selected_block_and_merged_cells_preserves_geometry_and_history() {for horizontal in [true, false] {for merged in [false, true] {- let (mut s, sid, _) = session_with_frame();- let tid = s.execute("table.insert", &json!({"rows": 4, "cols": 4, "width": 240})).unwrap()["table"].as_u64().unwrap();- s.execute("table.setRowHeight", &json!({"table": tid, "height": 60, "mode": "exactly"})).unwrap();- s.execute("style.cell.create", &json!({"name": "Neighbor", "fill": "[Paper]", "insets": 3})).unwrap();- s.execute("style.cell.create", &json!({"name": "Chosen", "fill": "[Black]", "tint": 0.15, "insets": 2})).unwrap();- s.execute("style.cell.apply", &json!({"table": tid, "name": "Neighbor"})).unwrap();- for r in 0..4 {- for c in 0..4 {- s.execute("table.setCell", &json!({"row": r, "col": c, "text": format!("{r},{c}")})).unwrap();- }- }- let range = if !merged {- doc::CellRange::new(1, 1, 2, 2)- } else if horizontal {- doc::CellRange::new(0, 0, 2, 1)- } else {- doc::CellRange::new(0, 0, 1, 2)- };- let selection = json!({"rows": [range.r0, range.r1], "cols": [range.c0, range.c1]});- s.execute("table.select", &selection).unwrap();- s.execute("style.cell.apply", &json!({"name": "Chosen"})).unwrap();- if merged {- let merge = if horizontal { json!({"rows": [0, 2], "cols": [1, 1]}) } else { json!({"rows": [1, 1], "cols": [0, 2]}) };- s.execute("table.merge", &merge).unwrap();- s.execute("table.select", &selection).unwrap();- }- let before_doc = s.doc().unwrap().doc.clone();- let before_selection = s.doc().unwrap().selection.clone();- let before = table_for(&s, sid, tid).clone();- let before_layout = s.cache.get(&before_doc, doc::StoryId(sid), None);- let before_fragment = before_layout.frames.iter().flat_map(|f| &f.tables).find(|t| t.table == tid).unwrap();- let undo_len = s.doc().unwrap().history.undo.len();- let command = if horizontal { "table.splitHorizontally" } else { "table.splitVertically" };- s.execute(command, &json!({})).unwrap();- assert_eq!(s.doc().unwrap().history.undo.len(), undo_len + 1, "one split command creates one undo entry");- let after_doc = s.doc().unwrap().doc.clone();- let after_selection = s.doc().unwrap().selection.clone();- let after = table_for(&s, sid, tid).clone();- let after_layout = s.cache.get(&after_doc, doc::StoryId(sid), None);- let after_fragment = after_layout.frames.iter().flat_map(|f| &f.tables).find(|t| t.table == tid).unwrap();- assert_eq!(after_fragment.rect, before_fragment.rect, "splitting does not resize the table");- assert_eq!(after_fragment.cells.len(), before_fragment.cells.len() + 4, "four original owners split once");- for placed in &before_fragment.cells {- let original = before.cell(placed.row, placed.col).unwrap();- let matches: Vec<_> = after_fragment.cells.iter().filter(|c| c.source == placed.source).collect();- assert_eq!(matches.len(), 1, "original cell text survives once: {}", placed.source);- let surviving = matches[0];- let cell = after.cell(surviving.row, surviving.col).unwrap();- let mut normalized = cell.clone();- normalized.row_span = original.row_span;- normalized.col_span = original.col_span;- assert_eq!(&normalized, original, "existing cell text and formatting are preserved");- if !range.contains(placed.row, placed.col) {- assert_eq!(surviving.rect, placed.rect, "unselected neighbor geometry is unchanged");- continue;- }- let second_addr = if horizontal {- (surviving.row + cell.row_span as usize, surviving.col)- } else {- (surviving.row, surviving.col + cell.col_span as usize)- };- let second = after.cell(second_addr.0, second_addr.1).unwrap();- assert_eq!(after.owner(second_addr.0, second_addr.1), second_addr);- assert!(second.text.is_empty());- assert_eq!(second.style, original.style);- assert_eq!(second.insets, original.insets);- assert_eq!(second.fill, original.fill);- assert_eq!(second.fill_tint, original.fill_tint);- let second_rect = after_fragment.cell(second_addr.0, second_addr.1).unwrap().rect;- assert_eq!(surviving.rect.union(second_rect), placed.rect, "the halves exactly cover the original cell");- if horizontal {- assert_eq!(surviving.rect.y1, second_rect.y0);- } else {- assert_eq!(surviving.rect.x1, second_rect.x0);- }- }- let text = s.doc().unwrap().selection.text.unwrap();- let address = text.cell.unwrap();- assert_eq!(after.owner(address.row, address.col), (address.row, address.col));- assert!(text.focus <= after.cell(address.row, address.col).unwrap().text.len());- let cells = s.doc().unwrap().selection.cells.unwrap();- assert!(cells.range.r1 < after.nrows() && cells.range.c1 < after.ncols());- check(&s);- s.execute("edit.undo", &json!({})).unwrap();- assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &before_doc));- assert_eq!(s.doc().unwrap().selection, before_selection);- assert_eq!(s.doc().unwrap().history.undo.len(), undo_len);- s.execute("edit.redo", &json!({})).unwrap();- assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &after_doc));- assert_eq!(s.doc().unwrap().selection, after_selection);- let bytes = crate::cmd::file_bytes(&s.doc().unwrap().doc).unwrap();- let reopened = crate::cmd::file_from(&bytes).unwrap();- reopened.check().unwrap();- assert_eq!(reopened.story(doc::StoryId(sid)).unwrap().tables.get(&tid).unwrap().as_ref(), &after);+ assert_split_case(horizontal, merged);+ }+ }+}++fn assert_split_case(horizontal: bool, merged: bool) {+ let (mut s, sid, _) = session_with_frame();+ let tid = s.execute("table.insert", &json!({"rows": 4, "cols": 4, "width": 240})).unwrap()["table"].as_u64().unwrap();+ s.execute("table.setRowHeight", &json!({"table": tid, "height": 60, "mode": "exactly"})).unwrap();+ s.execute("style.cell.create", &json!({"name": "Neighbor", "fill": "[Paper]", "insets": 3})).unwrap();+ s.execute("style.cell.create", &json!({"name": "Chosen", "fill": "[Black]", "tint": 0.15, "insets": 2})).unwrap();+ s.execute("style.cell.apply", &json!({"table": tid, "name": "Neighbor"})).unwrap();+ for r in 0..4 {+ for c in 0..4 {+ s.execute("table.setCell", &json!({"row": r, "col": c, "text": format!("{r},{c}")})).unwrap();+ }+ }+ let range = if !merged {+ doc::CellRange::new(1, 1, 2, 2)+ } else if horizontal {+ doc::CellRange::new(0, 0, 2, 1)+ } else {+ doc::CellRange::new(0, 0, 1, 2)+ };+ let selection = json!({"rows": [range.r0, range.r1], "cols": [range.c0, range.c1]});+ s.execute("table.select", &selection).unwrap();+ s.execute("style.cell.apply", &json!({"name": "Chosen"})).unwrap();+ if merged {+ let merge = if horizontal { json!({"rows": [0, 2], "cols": [1, 1]}) } else { json!({"rows": [1, 1], "cols": [0, 2]}) };+ s.execute("table.merge", &merge).unwrap();+ s.execute("table.select", &selection).unwrap();+ }+ let before_doc = s.doc().unwrap().doc.clone();+ let before_selection = s.doc().unwrap().selection.clone();+ let before = table_for(&s, sid, tid).clone();+ let before_layout = s.cache.get(&before_doc, doc::StoryId(sid), None);+ let before_fragment = before_layout.frames.iter().flat_map(|f| &f.tables).find(|t| t.table == tid).unwrap();+ let undo_len = s.doc().unwrap().history.undo.len();+ let command = if horizontal { "table.splitHorizontally" } else { "table.splitVertically" };+ s.execute(command, &json!({})).unwrap();+ assert_eq!(s.doc().unwrap().history.undo.len(), undo_len + 1, "one split command creates one undo entry");+ let after_doc = s.doc().unwrap().doc.clone();+ let after_selection = s.doc().unwrap().selection.clone();+ let after = table_for(&s, sid, tid).clone();+ let after_layout = s.cache.get(&after_doc, doc::StoryId(sid), None);+ let after_fragment = after_layout.frames.iter().flat_map(|f| &f.tables).find(|t| t.table == tid).unwrap();+ assert_eq!(after_fragment.rect, before_fragment.rect, "splitting does not resize the table");+ assert_eq!(after_fragment.cells.len(), before_fragment.cells.len() + 4, "four original owners split once");+ assert_split_cells(&before, &after, before_fragment, after_fragment, range, horizontal);+ let text = s.doc().unwrap().selection.text.unwrap();+ let address = text.cell.unwrap();+ assert_eq!(after.owner(address.row, address.col), (address.row, address.col));+ assert!(text.focus <= after.cell(address.row, address.col).unwrap().text.len());+ let cells = s.doc().unwrap().selection.cells.unwrap();+ assert!(cells.range.r1 < after.nrows() && cells.range.c1 < after.ncols());+ check(&s);+ s.execute("edit.undo", &json!({})).unwrap();+ assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &before_doc));+ assert_eq!(s.doc().unwrap().selection, before_selection);+ assert_eq!(s.doc().unwrap().history.undo.len(), undo_len);+ s.execute("edit.redo", &json!({})).unwrap();+ assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &after_doc));+ assert_eq!(s.doc().unwrap().selection, after_selection);+ let bytes = crate::cmd::file_bytes(&s.doc().unwrap().doc).unwrap();+ let reopened = crate::cmd::file_from(&bytes).unwrap();+ reopened.check().unwrap();+ assert_eq!(reopened.story(doc::StoryId(sid)).unwrap().tables.get(&tid).unwrap().as_ref(), &after);+}++fn assert_split_cells(+ before: &designcraft_doc::Table,+ after: &designcraft_doc::Table,+ before_fragment: &designcraft_compose::TableFrag,+ after_fragment: &designcraft_compose::TableFrag,+ range: doc::CellRange,+ horizontal: bool,+) {+ for placed in &before_fragment.cells {+ let original = before.cell(placed.row, placed.col).unwrap();+ let matches: Vec<_> = after_fragment.cells.iter().filter(|c| c.source == placed.source).collect();+ assert_eq!(matches.len(), 1, "original cell text survives once: {}", placed.source);+ let surviving = matches[0];+ let cell = after.cell(surviving.row, surviving.col).unwrap();+ let mut normalized = cell.clone();+ normalized.row_span = original.row_span;+ normalized.col_span = original.col_span;+ assert_eq!(&normalized, original, "existing cell text and formatting are preserved");+ if !range.contains(placed.row, placed.col) {+ assert_eq!(surviving.rect, placed.rect, "unselected neighbor geometry is unchanged");+ continue;+ }+ let second_addr = if horizontal {+ (surviving.row + cell.row_span as usize, surviving.col)+ } else {+ (surviving.row, surviving.col + cell.col_span as usize)+ };+ let second = after.cell(second_addr.0, second_addr.1).unwrap();+ assert_eq!(after.owner(second_addr.0, second_addr.1), second_addr);+ assert!(second.text.is_empty());+ assert_eq!(second.style, original.style);+ assert_eq!(second.insets, original.insets);+ assert_eq!(second.fill, original.fill);+ assert_eq!(second.fill_tint, original.fill_tint);+ let second_rect = after_fragment.cell(second_addr.0, second_addr.1).unwrap().rect;+ assert_eq!(surviving.rect.union(second_rect), placed.rect, "the halves exactly cover the original cell");+ if horizontal {+ assert_eq!(surviving.rect.y1, second_rect.y0);+ } else {+ assert_eq!(surviving.rect.x1, second_rect.x0);}}}diff --git a/crates/engine/tests/it/text_decorations.rs b/crates/engine/tests/it/text_decorations.rsindex c49c1d2cb..205bc97fb 100644--- a/crates/engine/tests/it/text_decorations.rs+++ b/crates/engine/tests/it/text_decorations.rs@@ -50,8 +50,8 @@ fn raster(d: &Document, threads: u16) -> Rendered {renderer.threads = threads;let placed = [Placed { spread: SpreadRef::Doc(0), xf: Affine::IDENTITY }];let options = RenderOptions { paper: false, background: Some([255; 4]), greek_below_px: 0.0, ..Default::default() };- let first = renderer.render(d, &cache, &placed, 480, 480, Affine::scale(2.0), &options);- let cached = renderer.render(d, &cache, &placed, 480, 480, Affine::scale(2.0), &options);+ let first = renderer.render(d, &cache, &placed, (480, 480), Affine::scale(2.0), &options);+ let cached = renderer.render(d, &cache, &placed, (480, 480), Affine::scale(2.0), &options);assert_eq!(first.pixels, cached.pixels, "decoration cache hits must retain paint order");first}@@ -185,7 +185,7 @@ fn an_underline_has_no_seams_between_letters() {let options = RenderOptions { paper: false, background: Some([255; 4]), greek_below_px: 0.0, ..Default::default() };// A fractional scale puts the letters' edges between pixels.let (w, h) = (543u32, 163u32);- let img = renderer.render(&d, &Cache::new(), &placed, w, h, Affine::scale(1.3579), &options);+ let img = renderer.render(&d, &Cache::new(), &placed, (w, h), Affine::scale(1.3579), &options);let px = |x: u32, y: u32| {let i = ((y * w + x) * 4) as usize;[img.pixels[i], img.pixels[i + 1], img.pixels[i + 2], img.pixels[i + 3]]