DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge remote-tracking branch 'origin/main' into codex/preserve-cjk-auto-overrides
moppeeer8e42d71af1ab
diff --cc crates/doc/src/attrs/char_attrs.rsindex 000000000,4f4cb9d52..154dbf741mode 000000,100644..100644--- a/crates/doc/src/attrs/char_attrs.rs+++ b/crates/doc/src/attrs/char_attrs.rs@@@ -1,0 -1,177 +1,177 @@@+ use super::{+ Capitalization, ChangeMark, Deserialize, Digits, Kerning, Leading, Position, Serialize, attr_key, deserialize_explicit_value, unknown_attribute,+ };++ attr_set! {+ /// Character attributes (Character panel / character styles / the character part of paragraph styles).+ CharAttrs / CharProps {+ font_family: String = "Source Serif 4".into(),+ font_style: String = "Regular".into(),+ /// Point size.+ size: f64 = 12.0,+ leading: Leading = Leading::Auto,+ kerning: Kerning = Kerning::Metrics,+ /// Tracking in 1/1000 em.+ tracking: f64 = 0.0,+ /// Explicit CJK aki, in em; None restores automatic spacing.+ leading_aki: Option<f64> = None => "deserialize_explicit_value",+ trailing_aki: Option<f64> = None => "deserialize_explicit_value",+ /// Proportional character compression, 0..1.+ tsume: f64 = 0.0,+ /// Target em cells for the contiguous formatted group (0 disables jidori).+ jidori: u32 = 0,+ character_alignment: crate::cjk::CharacterAlignment = crate::cjk::CharacterAlignment::Baseline,+ leading_model: crate::cjk::LeadingModel = crate::cjk::LeadingModel::Roman,+ /// The kenten mark's text: a custom mark, or the preset of `kenten_kind` (see+ /// [`crate::cjk_settings::kenten_mark`]); empty is the sesame dot.+ kenten_character: String = String::new(),+ /// Horizontal / vertical scale, 1.0 = 100%.+ h_scale: f64 = 1.0,+ v_scale: f64 = 1.0,+ baseline_shift: f64 = 0.0,+ /// Skew (false italic), degrees.+ skew: f64 = 0.0,+ fill: String = "[Black]".into(),+ fill_tint: f32 = 1.0,+ stroke: String = "[None]".into(),+ stroke_tint: f32 = 1.0,+ stroke_weight: f64 = 1.0,+ /// Stroke behind fill: the stroke is painted under the fill and lies wholly outside the+ /// letters at its full weight, so the letters keep their shape. Off, it straddles the outline.+ stroke_behind_fill: bool = false,+ capitalization: Capitalization = Capitalization::Normal,+ position: Position = Position::Normal,+ underline: bool = false,+ strikethrough: bool = false,+ /// Underline Options: weight and offset below the baseline (`None` = from the size),+ /// colour (empty = the text colour) and tint.+ underline_weight: Option<f64> = None => "deserialize_explicit_value",+ underline_offset: Option<f64> = None => "deserialize_explicit_value",+ underline_color: String = String::new(),+ underline_tint: f32 = 1.0,+ /// Strikethrough Options: offset above the baseline.+ strikethrough_weight: Option<f64> = None => "deserialize_explicit_value",+ strikethrough_offset: Option<f64> = None => "deserialize_explicit_value",+ strikethrough_color: String = String::new(),+ strikethrough_tint: f32 = 1.0,+ glyph_form: String = String::new(),+ ligatures: bool = true,+ no_break: bool = false,+ /// Tate-chu-yoko: in vertical text, the run is set horizontally within one em of the line.+ tate_chu_yoko: bool = false,+ tate_chu_yoko_x_offset: f64 = 0.0,+ tate_chu_yoko_y_offset: f64 = 0.0,+ /// Ruby: the reading set small above the text (to its right in vertical text). Group ruby+ /// sets it over the whole run; per-character ruby holds one reading per character,+ /// separated by U+3000. Its other settings are the `ruby_*` fields below.+ ruby: String = String::new(),+ /// Kenten: an emphasis dot above each character.+ kenten: bool = false,+ /// Warichu: the run is set in smaller lines stacked inside one line height.+ warichu: bool = false,+ /// How many warichu lines (InDesign's minimum is 2).+ warichu_lines: u32 = 2,+ /// Warichu size as a percentage of the parent size.+ warichu_size: f64 = 50.0,+ /// Extra points between warichu baselines. 0 is automatic (one small em).+ warichu_line_spacing: f64 = 0.0,+ warichu_alignment: crate::cjk::WarichuAlignment = crate::cjk::WarichuAlignment::Auto,+ /// Minimum characters on a warichu line before a break, and on the line after it.+ warichu_chars_before_break: u32 = 1,+ warichu_chars_after_break: u32 = 1,+ // Kenten Settings / Kenten Color (`kenten` switches the marks on).+ /// The mark; [`crate::cjk_settings::KentenKind::Custom`] draws `kenten_character`.+ kenten_kind: crate::cjk_settings::KentenKind = crate::cjk_settings::KentenKind::SesameDot,+ /// Font of a custom mark (empty = the text's font) and its style.+ kenten_font: String = String::new(),+ kenten_font_style: String = String::new(),+ /// Mark size in points; `None` is half the text size.- kenten_size: Option<f64> = None,++ kenten_size: Option<f64> = 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,+ /// Points between the text's em box and the mark's.+ kenten_distance: f64 = 0.0,+ kenten_position: crate::cjk_settings::KentenPosition = crate::cjk_settings::KentenPosition::AboveRight,+ kenten_alignment: crate::cjk_settings::KentenAlignment = crate::cjk_settings::KentenAlignment::Center,+ /// How a custom mark was entered (IDML `KentenCharacterSet`), kept for interchange.+ kenten_character_set: String = String::new(),+ /// 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<f32> = None,++ kenten_fill_tint: Option<f32> = None => "deserialize_explicit_value",+ kenten_stroke: String = String::new(),- kenten_stroke_tint: Option<f32> = None,- kenten_stroke_weight: Option<f64> = None,++ kenten_stroke_tint: Option<f32> = None => "deserialize_explicit_value",++ kenten_stroke_weight: Option<f64> = 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`.+ /// Compression in percent of the em (0 = off).+ shatai_magnification: f64 = 0.0,+ /// Degrees from the line direction, counter-clockwise.+ shatai_angle: f64 = 45.0,+ /// Turn the compressed character back so its edge along the line stays along the line.+ shatai_adjust_rotation: bool = false,+ /// Fit the advance to the compressed em box.+ shatai_adjust_tsume: bool = true,+ // Ruby settings (see [`crate::ruby`]). Defaults are the IDML text defaults.+ ruby_type: crate::ruby::RubyType = crate::ruby::RubyType::Group,+ /// How a ruby shorter than its parent is spread over it.+ ruby_alignment: crate::ruby::RubyAlignment = crate::ruby::RubyAlignment::Jis,+ ruby_position: crate::ruby::RubyPosition = crate::ruby::RubyPosition::AboveRight,+ /// Points along the line, and away from the parent text across it.+ ruby_x_offset: f64 = 0.0,+ ruby_y_offset: f64 = 0.0,+ /// Empty: the parent's font and style.+ ruby_font: String = String::new(),+ ruby_font_style: String = String::new(),+ /// Points; `None` is half the parent size.- ruby_font_size: Option<f64> = None,++ ruby_font_size: Option<f64> = None => "deserialize_explicit_value",+ /// 1.0 = 100%.+ ruby_x_scale: f64 = 1.0,+ ruby_y_scale: f64 = 1.0,+ /// Use the font's ruby glyphs (OpenType `ruby`).+ ruby_open_type_pro: bool = true,+ /// Tate-chu-yoko in vertical ruby for runs of up to this many digits (0 = off).+ ruby_auto_tcy_digits: u32 = 0,+ ruby_auto_tcy_include_roman: bool = false,+ ruby_auto_tcy_auto_scale: bool = true,+ /// IDML `RubyOverhang`, kept for round trips; `ruby_overhang_amount` sets the overhang.+ ruby_overhang: bool = false,+ ruby_overhang_amount: crate::ruby::RubyOverhang = crate::ruby::RubyOverhang::OneRuby,+ ruby_parent_spacing: crate::ruby::RubyParentSpacing = crate::ruby::RubyParentSpacing::Aki121,+ /// A longer ruby at a line's start or end is set flush with the line edge.+ ruby_auto_align: bool = true,+ /// A longer ruby is narrowed first, down to `ruby_scaling_min` (1.0 = 100%).+ ruby_auto_scaling: bool = false,+ 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<f32> = None,++ ruby_fill_tint: Option<f32> = None => "deserialize_explicit_value",+ ruby_stroke: String = String::new(),- ruby_stroke_tint: Option<f32> = None,- ruby_stroke_weight: Option<f64> = None,++ ruby_stroke_tint: Option<f32> = None => "deserialize_explicit_value",++ ruby_stroke_weight: Option<f64> = 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.+ digits: Digits = Digits::Default,+ character_direction: crate::arabic::CharacterDirection = crate::arabic::CharacterDirection::Default,+ /// Character-level permission, additionally gated by paragraph kashidas.+ allow_kashidas: bool = true,+ diacritic_position: crate::arabic::DiacriticPosition = crate::arabic::DiacriticPosition::Default,+ /// Additional mark offsets, in thousandths of an em. Positive y is up.+ diacritic_x_offset: f64 = 0.0,+ diacritic_y_offset: f64 = 0.0,+ /// IDML contextual-form request, separate from general OpenType features.+ positional_form: String = String::new(),+ language: String = "English: USA".into(),+ /// Additional OpenType features, e.g. `["onum", "ss01"]`.+ otf_features: Vec<String> = Vec::new(),+ /// Conditional text: the conditions applied (Window › Type & Tables › Conditional Text).+ conditions: Vec<String> = Vec::new(),+ /// Track Changes: text added or deleted while tracking (deleted text isn't laid out).+ change: ChangeMark = ChangeMark::None,+ /// XML: the element this text is tagged with (Tags panel, inline).+ xml_tag: String = String::new(),+ }+ }diff --cc crates/doc/src/attrs/para_attrs.rsindex 000000000,17edc8cc1..2e07c10c6mode 000000,100644..100644--- a/crates/doc/src/attrs/para_attrs.rs+++ b/crates/doc/src/attrs/para_attrs.rs@@@ -1,0 -1,254 +1,254 @@@+ use super::{+ Align, BoxBottom, BoxTop, BoxWidth, Composer, Deserialize, GrepStyle, GridAlign, ListAlign, ListCounter, ListType, MAX_TAB_STOPS,+ NestedLineStyle, NestedStyle, NumberStyle, Rule, Serialize, SpanColumns, StartParagraph, TabStop, TextDirection, attr_key,+ deserialize_explicit_value, expand_list_levels, expand_list_text, list_level_index, sanitized_tabs, unknown_attribute,+ };++ attr_set! {+ /// Paragraph attributes (Paragraph panel / paragraph styles).+ ParaAttrs / ParaProps {+ align: Align = Align::Left,+ /// Paragraph Direction (World-Ready): the base direction lines are ordered in.+ direction: TextDirection = TextDirection::LeftToRight,+ left_indent: f64 = 0.0,+ right_indent: f64 = 0.0,+ first_line_indent: f64 = 0.0,+ last_line_indent: f64 = 0.0,+ space_before: f64 = 0.0,+ space_after: f64 = 0.0,+ /// Space between consecutive paragraphs of the same style; replaces space after/before there (None = ignore).+ same_para_style_spacing: Option<f64> = None => "deserialize_explicit_value",+ /// Drop cap: the paragraph's first `drop_cap_chars` characters (code points, never+ /// splitting a base from its combining marks) set `drop_cap_lines` lines tall, in the+ /// character style `drop_cap_style` ("" or `[None]`: the text's own formatting).+ drop_cap_lines: u32 = 0,+ drop_cap_chars: u32 = 0,+ drop_cap_style: String = String::new(),+ /// Align Left Edge: the drop cap's ink starts at the indent (its first letter's left side+ /// bearing is taken off), and the lines beside it start where its advance ends.+ drop_cap_align_left: bool = true,+ /// Scale for Descenders (kept and round-tripped; doesn't change the layout).+ drop_cap_scale_descenders: bool = false,+ /// Nested styles, in order from the paragraph start.+ nested_styles: Vec<NestedStyle> = Vec::new(),+ /// GREP styles: a character style for every match of a pattern (applied after nested).+ grep_styles: Vec<GrepStyle> = Vec::new(),+ /// Nested line styles: a character style for the paragraph's first lines, in order.+ nested_line_styles: Vec<NestedLineStyle> = Vec::new(),+ grid_align: GridAlign = GridAlign::None,+ composer: Composer = Composer::Paragraph,+ // Hyphenation+ hyphenate: bool = true,+ hyph_min_word: u32 = 5,+ hyph_after_first: u32 = 2,+ hyph_before_last: u32 = 2,+ /// Max consecutive hyphenated lines (0 = unlimited).+ hyph_limit: u32 = 3,+ hyph_zone: f64 = 36.0,+ hyph_capitalized: bool = true,+ hyph_last_word: bool = true,+ hyph_across_column: bool = true,+ /// Better spacing (0) ↔ fewer hyphens (1).+ hyph_weight: f64 = 0.5,+ // Justification (percent as fractions)+ word_space_min: f64 = 0.8,+ word_space_desired: f64 = 1.0,+ word_space_max: f64 = 1.33,+ letter_space_min: f64 = 0.0,+ letter_space_desired: f64 = 0.0,+ letter_space_max: f64 = 0.0,+ glyph_scale_min: f64 = 1.0,+ glyph_scale_desired: f64 = 1.0,+ glyph_scale_max: f64 = 1.0,+ auto_leading: f64 = 1.2,+ single_word_justify: Align = Align::FullyJustified,+ /// Insert Kashidas (World-Ready): justified Arabic lines stretch at joins before spaces.+ kashidas: bool = true,+ /// Preserved vendor policy; non-default policies require a dedicated composer.+ arabic_justification: String = String::new(),+ paragraph_kashida_width: Option<f64> = None => "deserialize_explicit_value",+ /// Korean text breaks between any two syllables (character-based breaking); otherwise+ /// it breaks at spaces, word by word.+ korean_char_breaks: bool = false,+ // Keeps+ keep_with_next: u32 = 0,+ keep_lines_together: bool = false,+ /// All lines in paragraph (true) or at start/end of paragraph (false).+ keep_all_lines: bool = false,+ keep_first: u32 = 2,+ keep_last: u32 = 2,+ start_paragraph: StartParagraph = StartParagraph::Anywhere,+ span_columns: SpanColumns = SpanColumns::Single,+ /// Split Columns: the space between sub-columns and the inset from the column's edges.+ split_inside_gutter: f64 = 6.0,+ split_outside_gutter: f64 = 0.0,+ rule_above: Rule = Rule::default(),+ rule_below: Rule = Rule::default(),+ #[serde(deserialize_with = "sanitized_tabs")]+ tabs: Vec<TabStop> = Vec::new(),+ list_type: ListType = ListType::None,+ /// Named list (Define Lists) the numbers belong to ("" = the story's own list).+ list_name: String = String::new(),+ /// Start At: restart the numbering at this number.+ start_at: Option<u32> = None => "deserialize_explicit_value",+ bullet_char: String = "\u{2022}".into(),+ number_style: NumberStyle = NumberStyle::Arabic,+ /// A numbered paragraph's label: `^#` is the number, other metacharacters expand as in+ /// [`expand_list_text`].+ number_expression: String = "^#.^t".into(),+ /// Text after the bullet (metacharacters expand as in [`expand_list_text`]).+ list_separator: String = "\t".into(),+ /// The hanging indent was set by the Bulleted or Numbered List button, which takes it away+ /// again with the list (an indent the paragraph had before stays).+ list_hang: bool = false,+ balance_ragged: bool = false,+ /// Hang punctuation outside the measure in this paragraph, at each character's own size+ /// (DesignCraft's own per-paragraph switch; a story with Optical Margin Alignment on+ /// overrides it with the story's size).+ optical_margin: bool = false,+ /// Ignore Optical Margin: no hang in this paragraph, whatever the story or+ /// `optical_margin` say.+ ignore_optical_margin: bool = false,+ /// None uses the legacy built-in rules; an empty set explicitly disables kinsoku.+ kinsoku: Option<crate::cjk::Kinsoku> = None => "deserialize_explicit_value",+ /// Preserved spacing-table reference; compatibility audit reports unsupported composition.+ mojikumi: String = String::new(),+ /// Preserved priority policy; the current breaker does not implement these priorities.+ kinsoku_type: String = String::new(),+ kinsoku_hang: crate::cjk::KinsokuHang = crate::cjk::KinsokuHang::None,+ bunri_kinshi: bool = false,+ rensuuji: bool = true,+ treat_ideographic_space_as_space: bool = false,+ // Auto Tate-chu-yoko, Japanese Composition and Grid Settings.+ /// Auto tate-chu-yoko: in vertical text, runs of up to this many half-width digits are set+ /// across one em (0 = off).+ auto_tcy: u32 = 0,+ /// Auto tate-chu-yoko also takes runs of half-width roman letters.+ auto_tcy_include_roman: bool = false,+ /// Rotate Roman Characters in Vertical Text (縦組み中の欧文回転): half-width characters+ /// stand upright one by one instead of lying along the line.+ rotate_roman: bool = false,+ /// Roman word break (欧文泣き別れ): roman words may break between any two letters,+ /// without a hyphen.+ roman_word_break: bool = false,+ /// The point of a line that sits on the grid while `grid_align` is on.+ grid_reference: crate::cjk::CharacterAlignment = crate::cjk::CharacterAlignment::Baseline,+ /// Gyoudori (行取り): grid lines each line takes (0 = as many as its leading needs).+ grid_gyoudori: u32 = 0,+ /// Paragraph gyoudori: the paragraph as a whole, not each line, takes `grid_gyoudori` lines.+ paragraph_gyoudori: bool = false,+ /// Paragraph shading, and how far it reaches past the text: top, left, bottom, right.+ shading_on: bool = false,+ shading_color: String = "[Black]".into(),+ shading_tint: f32 = 0.2,+ shading_offsets: [f64; 4] = [0.0; 4],+ /// Paragraph border: stroke weights (top, left, bottom, right), colour, and offsets past the+ /// text (top, left, bottom, right).+ border_on: bool = false,+ border_weights: [f64; 4] = [1.0; 4],+ border_color: String = "[Black]".into(),+ border_tint: f32 = 1.0,+ border_offsets: [f64; 4] = [0.0; 4],+ /// The border's stroke type (a document stroke style by name, or a built-in type), cap and+ /// join.+ border_type: crate::item::StrokeType = crate::item::StrokeType::Solid,+ border_cap: crate::item::Cap = crate::item::Cap::Butt,+ border_join: crate::item::Join = crate::item::Join::Miter,+ /// Corner shape and size: top left, top right, bottom right, bottom left.+ border_corners: [designcraft_geom::corners::Corner; 4] = [designcraft_geom::corners::Corner::default(); 4],+ border_width: BoxWidth = BoxWidth::Column,+ border_top: BoxTop = BoxTop::Ascent,+ border_bottom: BoxBottom = BoxBottom::Descent,+ /// A paragraph split across frames or columns gets a closed box in each part (otherwise the+ /// box is open where it splits).+ border_display_if_splits: bool = false,+ /// Consecutive paragraphs with the same border and shading share one box.+ border_merge: bool = true,+ /// The colour between the dashes, dots or stripes of a border that isn't solid.+ border_gap_color: String = "[None]".into(),+ border_gap_tint: f32 = 1.0,+ /// Shading corners: top left, top right, bottom right, bottom left.+ shading_corners: [designcraft_geom::corners::Corner; 4] = [designcraft_geom::corners::Corner::default(); 4],+ shading_width: BoxWidth = BoxWidth::Column,+ shading_top: BoxTop = BoxTop::Ascent,+ shading_bottom: BoxBottom = BoxBottom::Descent,+ /// The shading stops at the edges of the text frame.+ shading_clip: bool = false,+ /// The shading shows on screen only: not printed or exported.+ shading_nonprinting: bool = false,+ /// Least space between a spanning or split paragraph and the column text above and below it.+ span_space_before: f64 = 0.0,+ span_space_after: f64 = 0.0,+ /// List level (1–9): each level numbers on its own, and `^1`…`^9` in a number's text are the+ /// current numbers of those levels.+ list_level: u32 = 1,+ /// Character styles of the bullet and of the number.+ bullet_char_style: String = crate::story::NO_CHAR_STYLE.into(),+ number_char_style: String = crate::story::NO_CHAR_STYLE.into(),+ 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<f64> = None,++ list_tab: Option<f64> = 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,+ restart_after_level: u32 = 0,+ /// The bullet's font family and style ("" = the paragraph's).+ bullet_font: String = String::new(),+ bullet_font_style: String = String::new(),+ }+ }++ impl ParaAttrs {+ /// [`set_json`](Self::set_json), except that a `ruleAbove` / `ruleBelow` object names only the+ /// rule fields to change; the others keep their values in `current` (the resolved attributes+ /// of the paragraph or style being edited). A `tabs` list is checked and sorted as+ /// [`TabStop::checked_list`] does.+ pub fn set_json_over(&mut self, key: &str, value: &serde_json::Value, current: &ParaProps) -> Result<(), String> {+ let rule = match key.chars().filter(|c| *c != '_').collect::<String>().to_ascii_lowercase().as_str() {+ "ruleabove" => ¤t.rule_above,+ "rulebelow" => ¤t.rule_below,+ "tabs" if !value.is_null() => {+ // Count before deserializing: the list may be arbitrarily long.+ if value.as_array().is_some_and(|a| a.len() > MAX_TAB_STOPS) {+ return Err(format!("{key}: a paragraph holds at most {MAX_TAB_STOPS} tab stops"));+ }+ let tabs: Vec<TabStop> = serde_json::from_value(value.clone()).map_err(|e| format!("{key}: {e}"))?;+ self.tabs = Some(TabStop::checked_list(tabs).map_err(|e| format!("{key}: {e}"))?);+ return Ok(());+ }+ _ => return self.set_json(key, value),+ };+ let serde_json::Value::Object(patch) = value else { return self.set_json(key, value) };+ let mut merged = serde_json::to_value(rule).map_err(|e| format!("{key}: {e}"))?;+ let serde_json::Value::Object(fields) = &mut merged else { return Err(format!("{key}: not an object")) };+ for (k, v) in patch {+ if !fields.contains_key(k) {+ return Err(format!("{key}: unknown rule field `{k}`"));+ }+ fields.insert(k.clone(), v.clone());+ }+ self.set_json(key, &merged)+ }+ }++ impl ParaProps {+ /// The label of a numbered paragraph with number `n`.+ pub fn number_label(&self, n: u32) -> String {+ expand_list_text(&self.number_expression, &self.number_style.format(n))+ }++ /// The label of a numbered paragraph that `list` has just numbered ([`ListCounter::advance`]).+ pub fn number_label_in(&self, list: &ListCounter) -> String {+ let level = list_level_index(self.list_level);+ let number = list.labels.get(level).map_or("", String::as_str);+ expand_list_levels(&self.number_expression, number, &list.labels)+ }++ /// The label of a bulleted paragraph.+ pub fn bullet_label(&self) -> String {+ let mut s: String = self.bullet_char.chars().filter(|c| *c != '\n' && *c != '\r').collect();+ s.push_str(&expand_list_text(&self.list_separator, ""));+ s+ }+ }diff --cc crates/format/src/tests.rsindex 000000000,981898a45..170e8be9amode 000000,100644..100644--- a/crates/format/src/tests.rs+++ b/crates/format/src/tests.rs@@@ -1,0 -1,736 +1,763 @@@+ use super::*;+ use designcraft_doc::build::NewDocument;+ use designcraft_doc::geom::Rect;+ use designcraft_doc::{Asset, ParaFormat, SpreadRef};++ fn png_asset(d: &mut Document, data: &[u8]) -> AssetId {+ let aid = AssetId(d.alloc());+ let a =+ Asset { id: aid, name: "x.png".into(), mime: "image/png".into(), data: Arc::new(data.to_vec()), pixels: Some((1, 1)), ..Default::default() };+ d.assets.insert(aid, Arc::new(a));+ aid+ }++ fn place(d: &mut Document, asset: AssetId, crop: f64) -> designcraft_doc::ItemId {+ use designcraft_doc::geom::{Affine, shapes};+ use designcraft_doc::{Content, Graphic, Item, ItemId, Shape};+ let id = ItemId(d.alloc());+ let mut it = Item::new(id, d.default_layer(), Shape::Rectangle, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)));+ it.content = Content::Graphic(Graphic {+ layer_options: None,+ asset,+ size: (1.0, 1.0),+ xf: Affine::translate((crop, crop)),+ clip: None,+ auto_fit: Default::default(),+ fit_align: 4,+ crop: [crop; 4],+ wrap: Default::default(),+ fill: Default::default(),+ });+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();+ id+ }++ fn asset_entries(bytes: &[u8]) -> usize {+ let z = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();+ z.file_names().filter(|n| n.starts_with("assets/")).count()+ }++ /// Zip `d` the way files were saved with one asset per placement (nothing merged or pruned).+ fn save_uncompacted(d: &Document) -> Vec<u8> {+ let mut buf = Cursor::new(Vec::new());+ let mut z = zip::ZipWriter::new(&mut buf);+ let opts = zip::write::SimpleFileOptions::default();+ z.start_file("mimetype", opts).unwrap();+ z.write_all(MIME.as_bytes()).unwrap();+ z.start_file("document.json", opts).unwrap();+ z.write_all(&serde_json::to_vec(d).unwrap()).unwrap();+ for (id, a) in &d.assets {+ z.start_file(format!("assets/{}.png", id.0), opts).unwrap();+ z.write_all(&a.data).unwrap();+ }+ z.finish().unwrap();+ buf.into_inner()+ }++ #[test]+ fn explicit_all_on_pdf_layers_require_a_capable_reader_only_when_needed() {+ let mut d = Document::new(&NewDocument::default());+ let aid = AssetId(d.alloc());+ d.assets.insert(+ aid,+ Arc::new(Asset {+ id: aid,+ name: "art.pdf".into(),+ mime: "application/pdf".into(),+ data: Arc::new(b"%PDF-1.7".to_vec()),+ ..Default::default()+ }),+ );+ let id = place(&mut d, aid, 0.0);+ let version = |d: &Document| {+ let bytes = save(d).unwrap();+ let mut z = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();+ let mut meta = String::new();+ z.by_name("meta.json").unwrap().read_to_string(&mut meta).unwrap();+ serde_json::from_str::<Value>(&meta).unwrap()["version"].as_u64().unwrap()+ };+ assert_eq!(version(&d), 2);+ d.item_mut(id).unwrap().pdf_layer_override = true;+ assert_eq!(version(&d), 4);+ assert!(load(&save(&d).unwrap()).unwrap().item(id).unwrap().pdf_layer_override);+ d.item_mut(id).unwrap().pdf_hidden_layers = vec!["Red".into()];+ assert_eq!(version(&d), 2, "legacy nonempty overrides remain readable");+ }++ #[test]+ fn one_version_4_reader_keeps_both_explicit_all_on_and_graphic_layer_options() {+ use designcraft_doc::{Content, GraphicLayerOptions};+ let mut d = Document::new(&NewDocument::default());+ let pdf = AssetId(d.alloc());+ d.assets.insert(+ pdf,+ Arc::new(Asset {+ id: pdf,+ name: "art.pdf".into(),+ mime: "application/pdf".into(),+ data: Arc::new(b"%PDF-1.7".to_vec()),+ ..Default::default()+ }),+ );+ let eps = AssetId(d.alloc());+ let source = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n%%EOF\n".to_vec();+ d.assets.insert(+ eps,+ Arc::new(Asset { id: eps, name: "logo.eps".into(), mime: "application/postscript".into(), data: Arc::new(source), ..Default::default() }),+ );+ let all_on = place(&mut d, pdf, 0.0);+ let layered = place(&mut d, eps, 0.0);+ assert_eq!(required_version(&d), 3, "neither feature: EPS documents keep version 3");+ let options = GraphicLayerOptions { layers: vec![[("Name".to_string(), "Art".to_string())].into()], ..Default::default() };+ let set_options = |d: &mut Document, value: Option<GraphicLayerOptions>| {+ let Some(Content::Graphic(g)) = d.item_mut(layered).map(|it| &mut it.content) else { panic!("placed graphic") };+ g.layer_options = value;+ };+ set_options(&mut d, Some(options.clone()));+ d.item_mut(all_on).unwrap().pdf_layer_override = true;+ let bytes = save(&d).unwrap();+ let mut z = zip::ZipArchive::new(Cursor::new(&bytes)).unwrap();+ let mut meta = String::new();+ z.by_name("meta.json").unwrap().read_to_string(&mut meta).unwrap();+ assert_eq!(serde_json::from_str::<Value>(&meta).unwrap()["version"], 4);+ let reopened = load(&bytes).unwrap();+ let it = reopened.item(all_on).unwrap();+ assert!(it.pdf_layer_override && it.pdf_hidden_layers.is_empty(), "explicit all-on survives");+ assert_eq!(reopened.item(layered).unwrap().graphic().unwrap().layer_options.as_ref(), Some(&options), "graphic layer options survive");+ assert_eq!(required_version(&reopened), 4);+ // Either feature alone needs version 4; dropping both restores the older requirement.+ set_options(&mut d, None);+ assert_eq!(required_version(&d), 4, "explicit all-on alone");+ d.item_mut(all_on).unwrap().pdf_layer_override = false;+ assert_eq!(required_version(&d), 3);+ set_options(&mut d, Some(options));+ assert_eq!(required_version(&d), 4, "graphic layer options alone");+ set_options(&mut d, None);+ d.assets.remove(&eps);+ d.remove_item(layered).unwrap();+ assert_eq!(required_version(&d), 2, "neither feature and no EPS: version 2");+ // An explicit all-on choice on a parent spread also needs the version 4 reader.+ let mut parent_item = (*d.remove_item(all_on).unwrap()).clone();+ parent_item.pdf_layer_override = true;+ d.insert_item(SpreadRef::Parent(0), parent_item, None).unwrap();+ assert_eq!(required_version(&d), 4, "parent-spread placements are not skipped");+ }++ #[test]+ fn eps_source_requires_new_reader_but_preview_documents_keep_the_older_one() {+ let mut d = Document::new(&NewDocument::default());+ let version = |d: &Document| {+ let bytes = save(d).unwrap();+ let mut z = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();+ let mut meta = String::new();+ z.by_name("meta.json").unwrap().read_to_string(&mut meta).unwrap();+ serde_json::from_str::<Value>(&meta).unwrap()["version"].as_u64().unwrap()+ };+ assert_eq!(version(&d), 2);+ let aid = AssetId(d.alloc());+ let source = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n%%EOF\n".to_vec();+ d.assets.insert(+ aid,+ Arc::new(Asset {+ id: aid,+ name: "logo.eps".into(),+ mime: "image/png".into(),+ link: None,+ data: Arc::new(source.clone()),+ pixels: Some((40, 20)),+ page: 0,+ ..Default::default()+ }),+ );+ place(&mut d, aid, 0.0);+ assert_eq!(version(&d), 3, "sniff source even when legacy metadata says PNG");+ assert_eq!(load(&save(&d).unwrap()).unwrap().assets[&aid].data.as_slice(), source);+ Arc::make_mut(d.assets.get_mut(&aid).unwrap()).data = Arc::new(b"\x89PNG\r\n\x1a\npreview".to_vec());+ assert_eq!(version(&d), 2, "legacy EPS previews stay compatible");+ }++ #[test]+ fn one_place_picks_the_oldest_reader_that_keeps_the_document() {+ use designcraft_doc::{Content, GraphicLayerOptions};+ let mut d = Document::new(&NewDocument::default());+ assert_eq!(required_version(&d), 2, "plain documents keep the version 2 reader");+ let aid = AssetId(d.alloc());+ let eps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n%%EOF\n".to_vec();+ d.assets.insert(+ aid,+ Arc::new(Asset { id: aid, name: "logo.eps".into(), mime: "application/postscript".into(), data: Arc::new(eps), ..Default::default() }),+ );+ let id = place(&mut d, aid, 0.0);+ assert_eq!(required_version(&d), 3, "EPS sources alone keep the version 3 reader");+ let Some(Content::Graphic(g)) = d.item_mut(id).map(|it| &mut it.content) else { panic!("placed graphic") };+ g.layer_options = Some(GraphicLayerOptions { layers: vec![[("Name".to_string(), "Art".to_string())].into()], ..Default::default() });+ assert_eq!(required_version(&d), 4, "retained graphic layer options need version 4 even with EPS");+ assert_eq!(required_version(&load(&save(&d).unwrap()).unwrap()), 4);+ }++ #[test]+ fn roundtrip_with_assets() {+ let mut d = Document::new(&NewDocument { pages: 3, ..Default::default() });+ let lid = d.default_layer();+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 200.0, 200.0), lid, "héllo\nworld", ParaFormat::default()).unwrap();+ let aid = png_asset(&mut d, &[1, 2, 3, 4]);+ place(&mut d, aid, 0.0);+ let bytes = save(&d).unwrap();+ assert!(bytes.starts_with(b"PK"));+ let back = load(&bytes).unwrap();+ assert_eq!(back.page_count(), 3);+ assert_eq!(*back.assets[&aid].data, vec![1, 2, 3, 4]);+ assert_eq!(back.stories, d.stories);+ }++ /// `doc` as format 1 wrote it.+ fn save_v1(doc: &Document) -> Vec<u8> {+ let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));+ z.start_file("meta.json", zip::write::SimpleFileOptions::default()).unwrap();+ z.write_all(br#"{"format": "designcraft", "version": 1}"#).unwrap();+ z.start_file("document.json", zip::write::SimpleFileOptions::default()).unwrap();+ z.write_all(&serde_json::to_vec(doc).unwrap()).unwrap();+ z.finish().unwrap().into_inner()+ }++ fn para_style(name: &str, based_on: Option<&str>, keep_all_lines: Option<bool>) -> designcraft_doc::ParagraphStyle {+ designcraft_doc::ParagraphStyle {+ name: name.into(),+ based_on: based_on.map(str::to_string),+ next_style: None,+ para: designcraft_doc::ParaAttrs { keep_lines_together: Some(true), keep_all_lines, ..Default::default() },+ chars: Default::default(),+ shortcut: String::new(),+ }+ }++ /// Format 1 resolved an unset Keep Lines Together mode as all lines: those documents still+ /// do after loading, wherever the mode comes from. New documents keep lines at start/end.+ #[test]+ fn format_1_keep_lines_without_mode_stays_all_lines() {+ let mut d = Document::new(&NewDocument::default());+ let st = d.styles_mut();+ st.paragraph.push(para_style("Root", None, None));+ st.paragraph.push(para_style("Child", Some("Root"), None));+ st.paragraph.push(para_style("Explicit", None, Some(false)));+ st.paragraph.push(para_style("Under explicit", Some("Explicit"), None));+ st.paragraph.push(para_style("Loop A", Some("Loop B"), None));+ st.paragraph.push(para_style("Loop B", Some("Loop A"), None));+ let lid = d.default_layer();+ let names = [designcraft_doc::story::BASIC_PARAGRAPH, "Root", "Child", "Explicit", "Under explicit", "Loop A", "Loop B", "Missing"];+ let text = names.join("\n");+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 200.0, 200.0), lid, &text, ParaFormat::default()).unwrap();+ {+ let s = d.story_mut(sid).unwrap();+ for (p, name) in s.paras.iter_mut().zip(names) {+ p.style = name.into();+ p.para.keep_lines_together = Some(true);+ }+ s.insert_note(1, "Note", ParaFormat { style: "Missing".into(), ..Default::default() });+ }+ let back = load(&save_v1(&d)).unwrap();+ let resolve = |f: &ParaFormat| back.styles.resolve_para(f).0;+ let story = back.story(sid).unwrap();+ for (p, name) in story.paras.iter().zip(names) {+ let pp = resolve(p);+ assert!(pp.keep_lines_together);+ assert_eq!(pp.keep_all_lines, !name.contains("xplicit"), "{name}");+ }+ assert!(resolve(&story.notes[0].text.paras[0]).keep_all_lines, "footnote with a missing style");+ assert!(back.styles.resolve_para_style("Loop A").0.keep_all_lines && back.styles.resolve_para_style("Loop B").0.keep_all_lines);+ // Pinned where the chains start; explicit and inheriting styles are left as they were.+ assert_eq!(back.styles.para("Root").unwrap().para.keep_all_lines, Some(true));+ assert_eq!(back.styles.para("Child").unwrap().para.keep_all_lines, None);+ assert_eq!(back.styles.para("Under explicit").unwrap().para.keep_all_lines, None);+ // The current format keeps the new default: at start/end of paragraph.+ let now = load(&save(&d).unwrap()).unwrap();+ let p = &now.story(sid).unwrap().paras[0];+ assert!(!now.styles.resolve_para(p).0.keep_all_lines);+ assert!(!designcraft_doc::ParaProps::default().keep_all_lines);+ }++ /// 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.+ #[test]+ fn format_1_rules_frames_and_lists_load_as_saved() {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let old_rule = designcraft_doc::Rule { on: true, color: designcraft_doc::color::swatch::BLACK.into(), ..Default::default() };+ let (fid, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 200.0, 200.0), lid, "Ruled", ParaFormat::default()).unwrap();+ d.story_mut(sid).unwrap().paras[0].para.rule_above = Some(old_rule.clone());+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.auto_size_ref = 1;+ d.settings.lists.push(designcraft_doc::NumberedList { name: "Steps".into(), continue_across_stories: true });+ let back = load(&save_v1(&d)).unwrap();+ assert_eq!(back.story(sid).unwrap().paras[0].para.rule_above, Some(old_rule));+ assert_eq!(back.item(fid).unwrap().text_frame().unwrap().options.auto_size_ref, 1);+ assert!(back.settings.lists[0].continue_across_stories);+ assert_eq!(designcraft_doc::Rule::default().color, designcraft_doc::TEXT_COLOR);+ assert_eq!(designcraft_doc::TextFrameOptions::default().auto_size_ref, 4);+ assert!(!designcraft_doc::NumberedList::default().continue_across_stories);+ }++ /// Format 1 set drop caps without Align Left Edge: those documents still do where nothing set+ /// it. New documents align the drop cap's left edge.+ #[test]+ fn format_1_drop_caps_stay_unaligned() {+ let mut d = Document::new(&NewDocument::default());+ let st = d.styles_mut();+ st.paragraph.push(para_style("Opener", None, None));+ st.paragraph.push(designcraft_doc::ParagraphStyle {+ para: designcraft_doc::ParaAttrs { drop_cap_align_left: Some(true), ..Default::default() },+ ..para_style("Aligned", None, None)+ });+ 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, "One\nTwo\nThree", ParaFormat::default()).unwrap();+ {+ let s = d.story_mut(sid).unwrap();+ for (p, name) in s.paras.iter_mut().zip(["Opener", "Aligned", "Missing"]) {+ p.style = name.into();+ p.para.drop_cap_lines = Some(2);+ p.para.drop_cap_chars = Some(1);+ }+ }+ let back = load(&save_v1(&d)).unwrap();+ let aligned: Vec<bool> = back.story(sid).unwrap().paras.iter().map(|p| back.styles.resolve_para(p).0.drop_cap_align_left).collect();+ assert_eq!(aligned, [false, true, false]);+ let now = load(&save(&d).unwrap()).unwrap();+ assert!(now.styles.resolve_para(&now.story(sid).unwrap().paras[0]).0.drop_cap_align_left);+ }++ /// Assets over the zip size limit are written with zip64 sizes (scaled down here: the real+ /// threshold is near 4 GiB); smaller ones are written exactly as before.+ #[test]+ fn large_assets_are_written_with_zip64_sizes_and_open_again() {+ let mut d = Document::new(&NewDocument::default());+ let aid = png_asset(&mut d, &[5; 64]);+ place(&mut d, aid, 0.0);+ let normal = save(&d).unwrap();+ assert_eq!(normal, save_with_large_entries_from(&d, None, 65).unwrap(), "an asset under the threshold is unchanged");+ let large = save_with_large_entries_from(&d, None, 64).unwrap();+ assert!(large.len() > normal.len(), "the asset entry carries zip64 sizes");+ assert_eq!(*load(&large).unwrap().assets[&aid].data, vec![5; 64]);+ }++ #[test]+ fn saves_hold_each_used_file_once() {+ let mut d = Document::new(&NewDocument::default());+ let first = png_asset(&mut d, &[7; 64]);+ let copy = png_asset(&mut d, &[7; 64]);+ let replaced = png_asset(&mut d, &[9; 64]);+ let a = place(&mut d, first, 1.0);+ let b = place(&mut d, copy, 2.0);+ assert_eq!(d.assets.len(), 3);++ // Duplicates merge into the first asset, the unreferenced one is left out, and every+ // placement keeps its own crop and transform.+ let bytes = save(&d).unwrap();+ assert_eq!(asset_entries(&bytes), 1);+ assert_eq!(d.assets.len(), 3, "the open document keeps its assets");+ let back = load(&bytes).unwrap();+ assert_eq!(back.assets.keys().copied().collect::<Vec<_>>(), vec![first]);+ assert!(!back.assets.contains_key(&replaced));+ for (id, crop) in [(a, 1.0), (b, 2.0)] {+ let g = back.item(id).and_then(|i| i.graphic()).unwrap();+ assert_eq!((g.asset, g.crop, g.xf), (first, [crop; 4], d.item(id).unwrap().graphic().unwrap().xf));+ }+ }++ #[test]+ fn files_with_identical_bytes_at_different_paths_keep_their_paths() {+ let mut d = Document::new(&NewDocument::default());+ let ids: Vec<AssetId> = (0..3).map(|_| png_asset(&mut d, &[3; 32])).collect();+ for (id, link) in ids.iter().zip(["/p/a.png", "/q/b.png"]) {+ if let Some(a) = d.assets.get_mut(id) {+ Arc::make_mut(a).link = Some(link.into());+ }+ }+ let items: Vec<_> = ids.iter().enumerate().map(|(k, id)| place(&mut d, *id, k as f64)).collect();+ for bytes in [save(&d).unwrap(), save_uncompacted(&d)] {+ let back = load(&bytes).unwrap();+ assert_eq!(back.assets.len(), 3);+ let links: Vec<Option<&str>> =+ items.iter().map(|i| back.item(*i).and_then(|i| i.graphic()).and_then(|g| back.assets.get(&g.asset)).unwrap().link.as_deref()).collect();+ assert_eq!(links, [Some("/p/a.png"), Some("/q/b.png"), None]);+ }+ }++ #[test]+ fn equal_size_archive_assets_preserve_content_and_share_only_identical_buffers() {+ let mut d = Document::new(&NewDocument::default());+ let mut pairs = Vec::new();+ for n in 0..128u64 {+ let mut bytes = vec![42; 1024];+ bytes[1016..].copy_from_slice(&n.to_le_bytes());+ let a = png_asset(&mut d, &bytes);+ let b = png_asset(&mut d, &bytes);+ // Distinct links must remain independently relinkable even when their bytes match.+ Arc::make_mut(d.assets.get_mut(&a).unwrap()).link = Some(format!("/a/{n}.png"));+ Arc::make_mut(d.assets.get_mut(&b).unwrap()).link = Some(format!("/b/{n}.png"));+ place(&mut d, a, 1.0);+ place(&mut d, b, 2.0);+ pairs.push((a, b));+ }+ let back = load(&save_uncompacted(&d)).unwrap();+ assert_eq!(back.assets.len(), 256);+ for (n, (a, b)) in pairs.into_iter().enumerate() {+ assert_eq!(back.assets[&a].data[1016..], (n as u64).to_le_bytes());+ assert!(Arc::ptr_eq(&back.assets[&a].data, &back.assets[&b].data));+ assert_eq!(back.assets[&a].link, d.assets[&a].link);+ assert_eq!(back.assets[&b].link, d.assets[&b].link);+ }+ assert_eq!(back.spreads, d.spreads);+ }++ #[test]+ fn older_files_with_one_asset_per_placement_open_with_one() {+ let mut d = Document::new(&NewDocument::default());+ let ids: Vec<AssetId> = (0..3).map(|_| png_asset(&mut d, &[5; 32])).collect();+ for (k, id) in ids.iter().enumerate() {+ place(&mut d, *id, k as f64);+ }+ let back = load(&save_uncompacted(&d)).unwrap();+ assert_eq!(back.assets.len(), 1);+ assert_eq!(asset_entries(&save(&back).unwrap()), 1);+ }++ /// The object of the item `id` in a document's JSON.+ fn item_json(v: &mut Value, id: u64) -> Option<&mut Value> {+ if v.get("id").and_then(Value::as_u64) == Some(id) && v.get("content").is_some() {+ return Some(v);+ }+ match v {+ Value::Object(m) => m.values_mut().find_map(|c| item_json(c, id)),+ Value::Array(a) => a.iter_mut().find_map(|c| item_json(c, id)),+ _ => None,+ }+ }++ #[test]+ fn frame_level_vertical_text_opens_as_a_vertical_story() {+ // Documents that set Vertical on the frame: the story takes its first frame's direction.+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let (a, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(72.0, 72.0, 200.0, 400.0), lid, "縦書き", ParaFormat::default()).unwrap();+ let (b, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(300.0, 72.0, 428.0, 400.0), lid, "", ParaFormat::default()).unwrap();+ d.thread(a, b).unwrap();+ let (c, other) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(450.0, 72.0, 550.0, 400.0), lid, "横", ParaFormat::default()).unwrap();+ let mut v = serde_json::to_value(&d).unwrap();+ item_json(&mut v, a.0).unwrap()["content"]["options"]["vertical"] = json!(true);+ item_json(&mut v, c.0).unwrap()["content"]["options"]["vertical"] = json!(false);+ let json = serde_json::to_vec(&v).unwrap();+ let mut zipped = Cursor::new(Vec::new());+ {+ let mut z = zip::ZipWriter::new(&mut zipped);+ z.start_file("document.json", zip::write::SimpleFileOptions::default()).unwrap();+ z.write_all(&json).unwrap();+ z.finish().unwrap();+ }+ for bytes in [json.clone(), zipped.into_inner()] {+ let back = load(&bytes).unwrap();+ assert!(back.stories[&sid].vertical);+ assert!(!back.stories[&other].vertical);+ // Saved again, the direction is the story's.+ let again = load(&save(&back).unwrap()).unwrap();+ assert!(again.stories[&sid].vertical && !again.stories[&other].vertical);+ }+ }++ #[test]+ fn documents_saved_before_glyph_fallback_keep_their_fallback_fonts() {+ let d = Document::new(&NewDocument::default());+ assert!(!d.settings.glyph_fallback);+ assert!(!load(&save(&d).unwrap()).unwrap().settings.glyph_fallback, "saved and read as off");+ let mut on = d.clone();+ on.settings.glyph_fallback = true;+ assert!(load(&save(&on).unwrap()).unwrap().settings.glyph_fallback);+ // Written before the setting existed: drawn from fallback fonts, as they were.+ let mut v = serde_json::to_value(&d).unwrap();+ v["settings"].as_object_mut().unwrap().remove("glyphFallback").unwrap();+ assert!(load(&serde_json::to_vec(&v).unwrap()).unwrap().settings.glyph_fallback);+ }++ /// A saved tab list over the limits loads repaired, as an imported one does: a non-finite+ /// position (saved as `null`) dropped, positions clamped, leaders cut, the count capped.+ #[test]+ fn saved_tab_lists_load_sanitized() {+ use designcraft_doc::{MAX_TAB_LEADER, MAX_TAB_POSITION, MAX_TAB_STOPS, TabAlign, TabStop};+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(72.0, 72.0, 300.0, 300.0), lid, "a\tb", ParaFormat::default()).unwrap();+ let stop = |position: f64| TabStop { position, align: TabAlign::Right, leader: "0123456789".into(), align_on: String::new() };+ let mut tabs: Vec<TabStop> = (0..500).rev().map(|i| stop(i as f64 * 40.0)).collect();+ tabs.push(stop(f64::NAN));+ d.story_mut(sid).unwrap().paras[0].para.tabs = Some(tabs);+ let bytes = save(&d).unwrap();+ let back = load(&bytes).unwrap();+ let tabs = back.stories[&sid].paras[0].para.tabs.clone().unwrap();+ assert_eq!(tabs.len(), MAX_TAB_STOPS);+ assert!(tabs.windows(2).all(|w| w[0].position < w[1].position), "sorted");+ assert!(tabs.iter().all(|t| t.position.is_finite() && t.position <= MAX_TAB_POSITION && t.leader.chars().count() <= MAX_TAB_LEADER));+ assert_eq!(tabs.last().map(|t| t.position), Some(3960.0), "the first stops by position");+ }++ #[test]+ fn the_preview_is_read_back_without_the_document() {+ let d = Document::new(&NewDocument::default());+ let png = b"\x89PNG fake".to_vec();+ let bytes = save_with_preview(&d, Some(&png)).unwrap();+ assert_eq!(read_preview(Cursor::new(&bytes)), Some(png));+ assert!(load(&bytes).is_ok(), "the preview doesn't get in the way of opening");+ // Files without one, legacy JSON and garbage have none.+ assert_eq!(read_preview(Cursor::new(save(&d).unwrap())), None);+ assert_eq!(read_preview(Cursor::new(b"{}".to_vec())), None);+ assert_eq!(read_preview(Cursor::new(Vec::new())), None);+ }++ #[test]+ fn a_preview_that_inflates_past_its_declared_size_is_refused() {+ use std::io::Write;+ let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));+ let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);+ z.start_file(PREVIEW, opts).unwrap();+ z.write_all(&vec![0u8; usize::try_from(MAX_PREVIEW_BYTES).unwrap() + 4096]).unwrap();+ let mut bytes = z.finish().unwrap().into_inner();+ // Declare the entry tiny in the local header and the central directory.+ let patch = |bytes: &mut Vec<u8>, sig: &[u8], at: usize| {+ let start = bytes.windows(4).position(|w| w == sig).unwrap();+ bytes[start + at..start + at + 4].copy_from_slice(&16u32.to_le_bytes());+ };+ patch(&mut bytes, b"PK\x03\x04", 22);+ patch(&mut bytes, b"PK\x01\x02", 24);+ assert_eq!(read_preview(Cursor::new(&bytes)), None);+ }++ #[test]+ fn rejects_garbage_and_newer_versions() {+ assert!(load(b"nope").is_err());+ for version in [99u64, u64::from(u32::MAX) + 2] {+ let mut buf = Cursor::new(Vec::new());+ {+ let mut z = zip::ZipWriter::new(&mut buf);+ z.start_file("meta.json", zip::write::SimpleFileOptions::default()).unwrap();+ z.write_all(json!({"version": version}).to_string().as_bytes()).unwrap();+ z.finish().unwrap();+ }+ assert!(matches!(load(&buf.into_inner()), Err(FormatError::TooNew(v)) if v == version));+ }+ }++ fn r7a_nullable_document(local_clear: bool, style_clear: bool) -> Document {+ use designcraft_doc::{CharAttrs, ParaAttrs};+ let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() });+ let base = d.styles.default_paragraph.clone();+ let chars = CharAttrs {+ leading_aki: Some(Some(4.0)),+ trailing_aki: Some(Some(3.0)),+ underline_weight: Some(Some(2.0)),+ 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+ // Edge where a style chain leaves them unset; the base style sets them so both+ // formats resolve the same.+ let para = ParaAttrs {+ 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()+ };+ let style = std::sync::Arc::make_mut(&mut d.styles).paragraph.iter_mut().find(|s| s.name == base).unwrap();+ style.chars = chars;+ style.para = para;+ let clear_chars = CharAttrs {+ leading_aki: Some(None),+ trailing_aki: Some(None),+ underline_weight: Some(None),+ 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(),+ based_on: Some(base.clone()),+ next_style: None,+ para: clear_para.clone(),+ chars: clear_chars.clone(),+ shortcut: String::new(),+ });+ "Defaults".to_string()+ } else {+ base+ };+ let format = ParaFormat {+ style: selected,+ para: if local_clear { clear_para } else { ParaAttrs::default() },+ chars: if local_clear { clear_chars } else { CharAttrs::default() },+ table: None,+ };+ // Pin legacy paragraph defaults so both formats isolate nullable overrides.+ for style in &mut d.styles_mut().paragraph {+ style.para.keep_all_lines = Some(true);+ style.para.drop_cap_align_left = Some(false);+ }+ let layer = d.default_layer();+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 400.0), layer, "clear", format).unwrap();+ d+ }++ fn r7a_nullable_resolution(d: &Document) -> (designcraft_doc::ParaProps, designcraft_doc::CharProps) {+ let s = d.stories.values().find(|s| s.text == "clear").unwrap();+ d.styles.resolve_para(s.paras.first().unwrap())+ }++ fn r7a_assert_nullable_defaults_survive(d: &Document) {+ let expected = r7a_nullable_resolution(d);+ assert_eq!(expected.0.start_at, None);+ 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)] {+ let back = load(&bytes).unwrap();+ assert_eq!(r7a_nullable_resolution(&back), expected, "saved explicit defaults must not become inherited values");+ if native {+ assert_eq!(back, *d, "the native ZIP preserves the complete document");+ }+ }+ }++ #[test]+ fn r7a_native_local_default_text_overrides_survive_zip_and_legacy_json() {+ r7a_assert_nullable_defaults_survive(&r7a_nullable_document(true, false));+ }++ #[test]+ fn r7a_native_named_style_default_overrides_survive_zip_and_legacy_json() {+ r7a_assert_nullable_defaults_survive(&r7a_nullable_document(false, true));+ }++ #[test]+ fn r7a_native_nullable_missing_and_explicit_value_controls() {+ let d = r7a_nullable_document(false, false);+ assert_eq!(r7a_nullable_resolution(&d).0.start_at, Some(7));+ assert_eq!(r7a_nullable_resolution(&d).1.leading_aki, Some(4.0));+ for (bytes, native) in [(save(&d).unwrap(), true), (serde_json::to_vec(&d).unwrap(), false)] {+ let back = load(&bytes).unwrap();+ assert_eq!(r7a_nullable_resolution(&back), r7a_nullable_resolution(&d));+ if native {+ assert_eq!(back, d);+ }+ }+ let attrs: designcraft_doc::CharAttrs = serde_json::from_value(json!({"size":null})).unwrap();+ assert!(attrs.size.is_none(), "nonnullable fields retain their existing null contract");+ let props: designcraft_doc::CharProps = serde_json::from_value(json!({"leadingAki":null})).unwrap();+ assert_eq!(props.leading_aki, None);+ }++ /// Write `len` bytes of `fill` to the current entry of `z`.+ fn write_fill(z: &mut zip::ZipWriter<Cursor<Vec<u8>>>, len: usize, fill: u8) {+ let chunk = vec![fill; 1 << 20];+ let mut left = len;+ while left > 0 {+ let n = left.min(chunk.len());+ z.write_all(&chunk[..n]).unwrap();+ left -= n;+ }+ }++ /// Make the archive claim that entry `name` expands to `size` bytes, in both its local header+ /// and its central directory record (the archive has no ZIP64 fields or data descriptors).+ fn claim_size(bytes: &mut [u8], name: &str, size: u32) {+ let mut patched = 0;+ for i in 0..bytes.len().saturating_sub(46) {+ let (size_at, len_at, name_at) = match &bytes[i..i + 4] {+ b"PK\x03\x04" => (22, 26, 30),+ b"PK\x01\x02" => (24, 28, 46),+ _ => continue,+ };+ let len = u16::from_le_bytes([bytes[i + len_at], bytes[i + len_at + 1]]) as usize;+ if bytes.get(i + name_at..i + name_at + len) == Some(name.as_bytes()) {+ bytes[i + size_at..i + size_at + 4].copy_from_slice(&size.to_le_bytes());+ patched += 1;+ }+ }+ assert_eq!(patched, 2, "{name} not found in both headers");+ }++ /// A small archive whose `document.json` expands past the 256 MiB limit while claiming to+ /// hold one byte is refused once the limit is reached, with an error that says so, instead of+ /// being read whole into memory.+ #[test]+ fn oversized_document_json_is_refused() {+ let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));+ z.start_file("document.json", zip::write::SimpleFileOptions::default()).unwrap();+ write_fill(&mut z, (256 << 20) + 1, b' ');+ let mut bytes = z.finish().unwrap().into_inner();+ assert!(bytes.len() < 4 << 20, "{}", bytes.len());+ claim_size(&mut bytes, "document.json", 1);+ let Err(err) = load(&bytes) else { panic!("an oversized document.json loaded") };+ assert!(err.to_string().contains("limit"), "{err}");+ }++ /// An embedded file that expands past the 1 GiB limit (and says so) is refused too.+ #[test]+ fn oversized_asset_is_refused() {+ let mut d = Document::new(&NewDocument::default());+ let aid = png_asset(&mut d, &[1]);+ place(&mut d, aid, 0.0);+ let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));+ z.start_file("document.json", zip::write::SimpleFileOptions::default()).unwrap();+ z.write_all(&serde_json::to_vec(&d).unwrap()).unwrap();+ z.start_file(format!("assets/{}.png", aid.0), zip::write::SimpleFileOptions::default()).unwrap();+ write_fill(&mut z, (1 << 30) + 1, 0);+ let Err(err) = load(&z.finish().unwrap().into_inner()) else { panic!("an oversized asset loaded") };+ assert!(err.to_string().contains("limit"), "{err}");+ }++ /// An archive with more entries than any document needs is refused before any is read.+ #[test]+ fn too_many_entries_are_refused() {+ let d = Document::new(&NewDocument::default());+ let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));+ let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);+ z.start_file("document.json", stored).unwrap();+ z.write_all(&serde_json::to_vec(&d).unwrap()).unwrap();+ for i in 0..100_000 {+ z.start_file(format!("junk/{i}"), stored).unwrap();+ }+ 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}");+ }