diff --git a/crates/doc/src/text/para_style.rs b/crates/doc/src/text/para_style.rs index 3b0847d8fb..c332d28708 100644 --- a/crates/doc/src/text/para_style.rs +++ b/crates/doc/src/text/para_style.rs @@ -317,6 +317,41 @@ impl ParaStyle { } } + /// The paragraph style attributes as a reusable text-style definition, including defaults + /// omitted by saved paragraph JSON but understood by paraStyle.apply. + pub fn style_attrs(&self) -> serde_json::Map { + let mut attrs = match serde_json::to_value(self) { + Ok(serde_json::Value::Object(attrs)) => attrs, + _ => serde_json::Map::new(), + }; + if attrs.remove("justify_auto") == Some(serde_json::Value::Bool(true)) { + attrs.insert("justify".into(), serde_json::Value::String("Auto".into())); + } + attrs.remove("style_name"); + for (key, value) in [ + ("hyphenation", serde_json::json!(self.hyphenation)), + ("justification", serde_json::json!(self.justification)), + ("composer", serde_json::json!(self.composer)), + ("tabs", serde_json::json!(self.tabs)), + ("list", serde_json::json!(self.list)), + ("mojikumi", serde_json::json!(self.mojikumi)), + ("direction", serde_json::json!(self.direction)), + ("leading_model", serde_json::json!(self.leading_model)), + ("burasagari", serde_json::json!(self.burasagari)), + ("kinsoku", serde_json::json!(self.kinsoku)), + ("kinsoku_set", serde_json::json!(self.kinsoku_set)), + ("kinsoku_type", serde_json::json!(self.kinsoku_type)), + ("bunri_kinshi", serde_json::json!(self.bunri_kinshi)), + ("kurikaeshi_moji_shori", serde_json::json!(self.kurikaeshi_moji_shori)), + ("roman_hanging", serde_json::json!(self.roman_hanging)), + ("kashida", serde_json::json!(self.kashida)), + ("korean_line_break_anywhere", serde_json::json!(self.korean_line_break_anywhere)), + ] { + attrs.insert(key.into(), value); + } + attrs + } + /// Does kinsoku apply: a custom set, or a Kinsoku Set other than None? pub fn kinsoku_on(&self) -> bool { self.kinsoku_set.is_some() || self.kinsoku != Kinsoku::None diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 47eccccba9..3cd5ffd068 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -268,29 +268,7 @@ pub fn char_attrs(v: &CharStyle) -> Map { /// JSON leaves out at their defaults (the Hyphenation and Justification options, the Every-line Composer, no tab /// stops, no list, Auto direction…) are written out, as [`char_attrs`] does for characters. pub fn para_attrs(v: &ParaStyle) -> Map { - let mut m = to_attrs(v); - for (k, x) in [ - ("hyphenation", json!(v.hyphenation)), - ("justification", json!(v.justification)), - ("composer", json!(v.composer)), - ("tabs", json!(v.tabs)), - ("list", json!(v.list)), - ("mojikumi", json!(v.mojikumi)), - ("direction", json!(v.direction)), - ("leading_model", json!(v.leading_model)), - ("burasagari", json!(v.burasagari)), - ("kinsoku", json!(v.kinsoku)), - ("kinsoku_set", json!(v.kinsoku_set)), - ("kinsoku_type", json!(v.kinsoku_type)), - ("bunri_kinshi", json!(v.bunri_kinshi)), - ("kurikaeshi_moji_shori", json!(v.kurikaeshi_moji_shori)), - ("roman_hanging", json!(v.roman_hanging)), - ("kashida", json!(v.kashida)), - ("korean_line_break_anywhere", json!(v.korean_line_break_anywhere)), - ] { - m.insert(k.into(), x); - } - m + v.style_attrs() } /// Every attribute name `T` reads, including those its JSON leaves out at their defaults (Auto diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index a444f593b6..e0663d07a7 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -30,12 +30,43 @@ use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::text::MAX_AKI; use vectorcraft_doc::{ Burasagari, CharStyle, HyphenationOptions, JustificationOptions, Justify, Kinsoku, KinsokuShoriType, LineCap, LineJoin, Node, NodeId, NodeKind, - ParaDirection, ParaStyle, PathAlign, PathEffect, TabAlign, TabStop, TextKind, TextObject, TextRun, + ParaDirection, ParaStyle, PathAlign, PathEffect, TabAlign, TabStop, TextKind, TextObject, TextRun, TextStyleDef, }; use vectorcraft_geom::{Affine, PathData, Point, Rect}; mod names; +/// The unique names of paragraph sheets. Names have a per-sheet byte bound; `MAX_SHEETS` also +/// bounds the total retained name bytes. The first sheet is always the stable built-in Normal. +fn paragraph_style_names(sheets: &[Val]) -> Vec> { + let names: Vec> = sheets + .iter() + .enumerate() + .map(|(index, sheet)| { + if index == 0 { + Some(NORMAL_PARA_STYLE.to_string()) + } else { + sheet.get("0").and_then(Val::str).filter(|name| !name.is_empty() && name.len() <= MAX_PARA_STYLE_NAME_BYTES).map(str::to_string) + } + }) + .collect(); + let mut counts = HashMap::::new(); + for name in names.iter().skip(1).flatten().filter(|name| name.as_str() != NORMAL_PARA_STYLE) { + *counts.entry(name.clone()).or_default() += 1; + } + names + .into_iter() + .enumerate() + .map(|(index, name)| { + if index == 0 { + Some(NORMAL_PARA_STYLE.to_string()) + } else { + name.filter(|name| name != NORMAL_PARA_STYLE && counts.get(name) == Some(&1)) + } + }) + .collect() +} + /// Longest story read (bytes). pub(crate) const MAX_STORY: usize = 1 << 20; /// Biggest text document read (bytes, decoded). @@ -264,6 +295,10 @@ fn read(bytes: &[u8]) -> Option { /// through to the ones they are based on. const MAX_SHEETS: usize = 4096; const MAX_SHEETS_BASED_ON: usize = 16; +const MAX_PARA_STYLE_NAME_BYTES: usize = 256; +/// The catalog stores tabs as JSON objects, unlike the story's compact tab vectors. +const MAX_PARA_STYLE_TABS: usize = 1 << 16; +const NORMAL_PARA_STYLE: &str = "[Normal Paragraph Style]"; /// Most runs of manual kerning read of one story; the characters past them keep the automatic /// kerning. @@ -426,6 +461,7 @@ impl AreaFrame { /// A paragraph's attributes, as the text document keeps them. #[derive(Clone, Debug, Default, PartialEq)] struct Para { + style_name: Option, justify: u8, /// A right-to-left paragraph: its left and right alignments are each other's (the line of /// "left"-aligned type ends at its anchor). @@ -642,6 +678,8 @@ pub(super) struct Texts { /// The document's paragraph styles (`[Normal Paragraph Style]` first), each a name, its /// attributes (key 5) and the paragraph style it is based on (key 6, an index into these). para_sheets: Vec, + /// The unique names at their ATE sheet indices; duplicates are left unbound. + para_style_names: Vec>, frames: Vec, /// The paints characters take in place of their colours, by the name of the art style that /// gives each ([`Self::with_paints`]). @@ -680,6 +718,33 @@ impl Texts { self } + /// The unique named paragraph styles, with inherited attributes flattened at the same scale + /// used for the text's effective paragraph styles. A duplicate name is not safely applicable. + pub(super) fn paragraph_style_defs(&self, scale: f64) -> Vec { + self.para_sheets + .iter() + .zip(&self.para_style_names) + .filter_map(|(sheet, name)| { + let name = name.as_ref()?; + let style = para_style(&self.para(Some(sheet)), scale); + Some(TextStyleDef { name: name.clone(), attrs: style.style_attrs() }) + }) + .collect() + } + + /// Omit definitions that exceed the catalog tab budget and keep affected text formatted locally. + fn bound_named_paragraph_tabs(&mut self, mut budget: usize) { + for index in 0..self.para_sheets.len() { + if self.para_style_names[index].is_none() { + continue; + } + let mut tabs = self.para(Some(&self.para_sheets[index])).tabs; + if spend_tabs(&mut tabs, &mut budget) { + self.para_style_names[index] = None; + } + } + } + /// The text document in the editing copy `data`, if it has one that can be read. pub(super) fn read(data: &[u8]) -> Option { fn find(h: &[u8], n: &[u8], from: usize) -> Option { @@ -734,22 +799,26 @@ impl Texts { }; let char_sheets = sheets("5"); let para_sheets = sheets("6"); + let para_style_names = paragraph_style_names(¶_sheets); let kinsoku_sets = kinsoku_sets(&doc); // Every path is there (looked up above), so the stories, defaults and frames move out of the // document without a copy. let mut doc = doc; let mut main = doc.take("1")?; - Some(Texts { + let mut texts = Texts { stories: main.take("1")?.into_list(), fonts, defaults: main.take("2")?, para_defaults: main.take("3").unwrap_or(Val::Dict(BTreeMap::new())), char_sheets, para_sheets, + para_style_names, frames: doc.take("0")?.take("8")?.take("0")?.into_list(), paints: HashMap::new(), kinsoku_sets, - }) + }; + texts.bound_named_paragraph_tabs(MAX_PARA_STYLE_TABS); + Some(texts) } /// Frame `i` of the document, if it is of a kind this reads. @@ -904,6 +973,13 @@ impl Texts { _ => None, }; Para { + style_name: run + .and_then(|style| style.get("6")) + .and_then(Val::num) + .filter(|i| i.is_finite() && i.fract() == 0.0 && *i >= 0.0) + .and_then(|i| self.para_style_names.get(i as usize)) + .and_then(Clone::clone) + .filter(|name| name != NORMAL_PARA_STYLE), kinsoku: levels().find_map(|s| s.get("27").and_then(set).flatten()), kinsoku_custom: levels().find_map(|s| s.get("27").and_then(set)).is_some_and(|k| k.is_none()), kinsoku_type: choice("25").map(|v| match v { @@ -1635,6 +1711,7 @@ fn para_style(p: &Para, scale: f64) -> ParaStyle { // A right-to-left paragraph lays its text out from the right whatever letters it has // (" 120.5 mm " reads "mm 120.5"); without the key, from its first strong letter. direction: p.rtl.then_some(ParaDirection::RightToLeft), + style_name: p.style_name.clone(), justification: JustificationOptions { // Rounded, so the file's 1.2 is the default 120% exactly. auto_leading: p.auto_leading.map_or(JustificationOptions::default().auto_leading, |a| (a * 1e6).round() / 1e4), @@ -1700,7 +1777,7 @@ fn char_style(s: &Style, scale: f64, to_text: Affine) -> CharStyle { /// How many document points one unit of the art is: `to_doc`'s scale, which carries the art's /// lengths onto the document (10 for a Large Canvas copy written at 1:10; see `ai::read`). -fn art_scale(to_doc: Affine) -> f64 { +pub(super) fn art_scale(to_doc: Affine) -> f64 { let [a, b, ..] = to_doc.as_coeffs(); (a * a + b * b).sqrt().max(1e-9) } @@ -1752,6 +1829,7 @@ mod tests { para_defaults: read(b"/33 1").unwrap(), char_sheets: vec![], para_sheets: vec![], + para_style_names: vec![], frames: vec![], paints: HashMap::new(), kinsoku_sets: vec![], @@ -1777,6 +1855,7 @@ mod tests { para_defaults: read(b"/7 1.2").unwrap(), char_sheets: vec![], para_sheets: vec![], + para_style_names: vec![], frames: vec![], paints: HashMap::new(), kinsoku_sets: vec![], @@ -1801,6 +1880,7 @@ mod tests { para_defaults: read(b"/10 6 /11 2 /12 2 /13 0 /14 36.0 /15 true").unwrap(), char_sheets: vec![], para_sheets: vec![], + para_style_names: vec![], frames: vec![], paints: HashMap::new(), kinsoku_sets: vec![], @@ -1820,6 +1900,7 @@ mod tests { para_defaults: Val::Dict(BTreeMap::new()), char_sheets: vec![], para_sheets: vec![], + para_style_names: vec![], frames: vec![], paints: HashMap::new(), kinsoku_sets: vec![], @@ -1862,6 +1943,7 @@ mod tests { char_sheets: vec![], // [Normal Paragraph Style] has the Soft set; the second style has Force burasagari. para_sheets: vec![read(b"/5 << /27 1 >>").unwrap(), read(b"/5 << /24 2 /23 true >>").unwrap()], + para_style_names: vec![], frames: vec![], paints: HashMap::new(), kinsoku_sets: vec![Some(Kinsoku::Hard), Some(Kinsoku::Soft), None], @@ -1921,6 +2003,7 @@ mod tests { para_defaults: Val::Dict(BTreeMap::new()), char_sheets: vec![], para_sheets: vec![], + para_style_names: vec![], frames: vec![], paints: HashMap::new(), kinsoku_sets: vec![], @@ -1957,6 +2040,64 @@ mod tests { ); } + #[test] + fn named_paragraph_sheets_keep_names_associations_overrides_and_flattened_parents() { + let para_sheets = vec![ + read(b"/0 (Normal, localized) /5 << /2 1 >>").unwrap(), + read(b"/0 (Heading) /5 << /1 2 >> /6 2").unwrap(), + read(b"/0 (Parent) /5 << /2 8 /30 << /0 [ << /0 10 >> ] >> >> /6 3").unwrap(), + read(b"/0 (Cycle) /5 << /5 3 >> /6 2").unwrap(), + ]; + let texts = Texts { + stories: vec![], + fonts: vec![], + defaults: Val::Dict(BTreeMap::new()), + para_defaults: Val::Dict(BTreeMap::new()), + char_sheets: vec![], + para_sheets: para_sheets.clone(), + para_style_names: paragraph_style_names(¶_sheets), + frames: vec![], + paints: HashMap::new(), + kinsoku_sets: vec![], + }; + let style = |run: &[u8]| para_style(&texts.para(Some(&read(run).unwrap())), 1.0); + let effective = style(b"/5 << /2 19 >> /6 1"); + assert_eq!(effective.style_name.as_deref(), Some("Heading")); + assert_eq!((effective.left_indent, effective.first_line_indent, effective.space_after), (19.0, 2.0, 3.0)); + assert_eq!(style(b"/5 << >> /6 0").style_name, None); + assert_eq!(style(b"/5 << /2 19 >>").style_name, None); + + let defs = texts.paragraph_style_defs(1.0); + let heading = defs.iter().find(|def| def.name == "Heading").unwrap(); + assert_eq!(heading.attrs.get("left_indent"), Some(&serde_json::json!(8.0))); + assert_eq!(heading.attrs.get("first_line_indent"), Some(&serde_json::json!(2.0))); + assert_eq!(heading.attrs.get("space_after"), Some(&serde_json::json!(3.0))); + assert_eq!(defs.first().map(|def| def.name.as_str()), Some(NORMAL_PARA_STYLE)); + assert_eq!(defs.len(), 4); + + let mut texts = texts; + texts.bound_named_paragraph_tabs(1); + let names: Vec<_> = texts.paragraph_style_defs(1.0).into_iter().map(|def| def.name).collect(); + assert_eq!(names, [NORMAL_PARA_STYLE, "Heading"]); + let parent = texts.para(Some(&read(b"/5 << >> /6 2").unwrap())); + assert!(parent.style_name.is_none()); + assert_eq!(parent.tabs.len(), 1); + } + + #[test] + fn duplicate_paragraph_style_names_are_not_bound() { + let sheets = vec![ + read(b"/0 (Normal)").unwrap(), + read(b"/0 (Shared) /5 << /2 4 >>").unwrap(), + read(b"/0 (Shared) /5 << /2 9 >>").unwrap(), + read(b"/0 ([Normal Paragraph Style])").unwrap(), + read(format!("/0 ({})", "x".repeat(MAX_PARA_STYLE_NAME_BYTES + 1)).as_bytes()).unwrap(), + ]; + let names = paragraph_style_names(&sheets); + assert_eq!(names[0].as_deref(), Some(NORMAL_PARA_STYLE)); + assert!(names[1..].iter().all(Option::is_none)); + } + /// A story's paragraphs take at most [`MAX_STORY_TABS`] tab stops in all (a paragraph style's /// are copied into each paragraph): those past it take the default stops, and the story says so. #[test] @@ -1989,6 +2130,7 @@ mod tests { para_defaults: Val::Dict(BTreeMap::new()), char_sheets: vec![], para_sheets: vec![], + para_style_names: vec![], frames: vec![], paints: HashMap::new(), kinsoku_sets: vec![], @@ -2038,6 +2180,7 @@ mod tests { para_defaults: Val::Dict(BTreeMap::new()), char_sheets: vec![], para_sheets: vec![], + para_style_names: vec![], frames: cases.iter().map(|c| frame(c)).collect(), paints: HashMap::new(), kinsoku_sets: vec![], @@ -2057,6 +2200,7 @@ mod tests { para_defaults: Val::Dict(BTreeMap::new()), char_sheets: vec![read(b"/0 ([Normal Character Style]) /6 << >>").unwrap(), read(b"/0 (Block) /6 << /35 3 >>").unwrap()], para_sheets: vec![], + para_style_names: vec![], frames: vec![], paints: HashMap::new(), kinsoku_sets: vec![], @@ -2082,6 +2226,7 @@ mod tests { para_defaults: Val::Dict(BTreeMap::new()), char_sheets: vec![read(b"/0 ([Normal Character Style]) /6 << >>").unwrap(), read(b"/0 (Rotated) /6 << /35 2 >>").unwrap()], para_sheets: vec![], + para_style_names: vec![], frames: vec![], paints: HashMap::new(), kinsoku_sets: vec![], @@ -2118,6 +2263,7 @@ mod tests { read(b"/0 (Spaced) /5 1 /6 << /50 500.0 >>").unwrap(), ], para_sheets: vec![], + para_style_names: vec![], frames: vec![], paints: HashMap::new(), kinsoku_sets: vec![], @@ -2156,6 +2302,7 @@ mod tests { para_defaults: Val::Dict(BTreeMap::new()), char_sheets: vec![read(b"/0 ([Normal Character Style]) /6 << >>").unwrap(), read(b"/0 (Rounded) /6 << /61 1 /62 1 >>").unwrap()], para_sheets: vec![], + para_style_names: vec![], frames: vec![], paints: HashMap::new(), kinsoku_sets: vec![], @@ -2199,6 +2346,7 @@ mod tests { para_defaults: Val::Dict(BTreeMap::new()), char_sheets: vec![], para_sheets: vec![], + para_style_names: vec![], frames: vec![], paints: HashMap::new(), kinsoku_sets: vec![], @@ -2302,6 +2450,7 @@ mod tests { para_defaults: Val::Dict(BTreeMap::new()), char_sheets: vec![], para_sheets: vec![], + para_style_names: vec![], frames: vec![read(b"/0 << /0 [ 0 0 ] /2 << /0 0 >> >>").unwrap()], paints: HashMap::new(), kinsoku_sets: vec![], @@ -2370,6 +2519,7 @@ mod tests { para_defaults: read(b"/33 1").unwrap(), char_sheets: vec![], para_sheets: vec![], + para_style_names: vec![], frames: vec![], paints: HashMap::new(), kinsoku_sets: vec![], @@ -2425,6 +2575,7 @@ mod tests { para_defaults: Val::Dict(BTreeMap::new()), char_sheets: vec![], para_sheets: vec![], + para_style_names: vec![], frames: vec![read(doc.as_bytes()).unwrap()], paints: HashMap::new(), kinsoku_sets: vec![], @@ -3112,6 +3263,7 @@ mod tests { para_defaults: Val::Dict(BTreeMap::new()), char_sheets: vec![], para_sheets: vec![], + para_style_names: vec![], frames: vec![read(doc.as_bytes()).unwrap()], paints: HashMap::new(), kinsoku_sets: vec![], diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 9daa57bfd8..62effde955 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -661,6 +661,9 @@ pub(super) fn build_weighing( if small.is_some() { scale_read_document(&mut doc, unit, styles_read, symbols_own_size); } + if let Some(texts) = texts { + doc.para_styles = texts.paragraph_style_defs(crate::import::ate::art_scale(to_doc)).into(); + } Ok((doc, notes)) } diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index d4c066dd95..76cbb32828 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -3375,6 +3375,39 @@ fn type_on_a_hidden_layer_comes_from_the_text_document() { assert!(!r.warnings.iter().any(|w| w.contains("couldn't be read")), "{:?}", r.warnings); } +#[test] +fn editing_data_keeps_named_paragraph_styles_and_local_overrides() { + let stories = [("Styled\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Plain\r", 0, (8200.0, 8160.0), (0.0, 0.0), 0.0)]; + let mut doc = text_document(&stories) + .replacen( + "/0 << /1 ", + r"/0 << /6 << /0 [ << /0 << /0 (Normal) /5 << /4 3 /9 false >> >> >> + << /0 << /0 (\376\377\000H\000e\000a\000d\000i\000n\000g) /5 << /2 8 >> /6 0 >> >> ] >> /1 ", + 1, + ) + .replacen("/5 << /0 0 >> /6 0", "/5 << /0 0 /2 19 >> /6 1", 1); + // Keep ASCII85's end marker on one line after inserting the style definitions. + while ascii85(doc.as_bytes()).len() % 60 == 1 { + doc.push('\n'); + } + let layers = layer("Back", true, &square(10, 10)) + &layer("Spare", false, &(text_object(0) + &text_object(1))); + let art = native_with_text(&layers, &doc); + let result = import(&eps(&page_square(10, 10), &art)).unwrap(); + assert_eq!(names(&result.document), ["Back", "Spare"], "{:?}", result.warnings); + let catalog = &result.document.para_styles; + let heading = catalog.iter().find(|style| style.name == "Heading").expect("the named sheet is in the document catalog"); + assert_eq!(heading.attrs["left_indent"], serde_json::json!(8.0)); + assert_eq!(heading.attrs["space_before"], serde_json::json!(3.0)); + assert_eq!(heading.attrs["hyphenate"], serde_json::json!(false)); + let texts = text_of(&result.document.layers[1]); + assert_eq!(texts.len(), 2); + assert_eq!(texts[0].para.style_name.as_deref(), Some("Heading")); + assert_eq!(texts[0].para.left_indent, 19.0); + assert_eq!(texts[0].para.space_before, 3.0); + assert!(!texts[0].para.hyphenate); + assert!(texts[1].para.style_name.is_none(), "source Normal keeps normal paragraph identity"); +} + /// A run that sets no colour of its own takes its character style's (here `[Normal Character /// Style]`, black), not the text document's base attributes (here white, which hid the type). /// A style takes what it doesn't set from the style it is based on, and a run's own setting wins.