DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge #469: feat(ui): Lay out Document Setup like InDesign's
aiongg76450c630a71
diff --cc ROADMAP.mdindex 5937ee56d,3843047f8..c34a8674d--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -129,21 -129,8 +129,23 @@@ list) · [roadmap.md](docs/roadmap.md)Newest first.+- **2026-10-11** · Japanese captions now cover print ranges, imported style handling and table+ row/column movement, including row-height distribution. Existing translation and RTL helpers+ handle the display; command IDs, stored option values and user-defined style names are unchanged.+- **2026-10-11** · Moving a sheared and rotated text frame no longer leaves trails of text behind: canvas repaints cover the frame's whole text box, not just its outline. No readiness percentage change.+- **2026-10-11** · Live corners: the yellow widget on a selected rectangle frame shows corner+ diamonds; dragging one rounds the corners, Alt-click steps the corner shape (#186).+- **2026-10-11** · Optical kerning (#181): pairs are spaced from their outlines (ink gap per band,+ pulled towards the font's stem gap, bounded) instead of silently using the font's kern pairs.+- **2026-10-11** · New Document laid out like InDesign's (#325): Recent, Saved, Print, Web and+ Mobile preset tabs beside the preset's details; saved document presets live in the engine+ (`file.savePreset`, `file.deletePreset`, `file.new {preset}`); `file.new` takes intent, units,+ start page and per-edge bleed and slug.+- **2026-10-11** · macOS: fonts that font services and managers activate (Adobe Fonts,+ RightFont) are listed, read from the files CoreText has available (#261, #327).+- **2026-10-11:** Document pages take their parent page's margins and columns (left or right parent page by side) and follow its changes unless they have their own; parent ruler guides draw and snap on the pages based on it. IDML import marks a page margin preference that differs from its parent as the page's own. No readiness percentage change.+ - **2026-10-11** · Document Setup laid out like InDesign's: Page Size, Margins (new: every+ page's, `layout.documentSetup {margins}`), Bleed and Slug with links, Adjust Layout.- **2026-10-10 (UI.4–UI.5):** Panel tabs can move into other groups, split the dock, float, resize and return to their saved locations through shared docking transactions. Layouts persist in custom workspaces; UI and control commands share the same validated action path. Shared pane geometry and widget-state theme application retain all five palettes and local fonts. Split panes send keyboard input only to the focused canvas and scope contextual toolbar IDs per pane. No readiness percentage change.- **2026-10-10** · Version 0.6.0; releases add a Linux riscv64 tar.gz (cross-compiled, CLIsmoke-tested under QEMU).diff --cc crates/engine/src/cmd/layout.rsindex 4e69230a2,117b49a3f..d76ea7e4b--- a/crates/engine/src/cmd/layout.rs+++ b/crates/engine/src/cmd/layout.rs@@@ -804,104 -730,48 +829,139 @@@ fn document_setup(d: &designcraft_doc::let st = &d.settings;let start = d.sections.iter().find(|x| x.start == 0).and_then(|x| x.start_number).unwrap_or(1);json!({"width": st.page_width, "height": st.page_height, "pages": d.page_count(), "startPage": start, "facingPages": st.facing_pages,- "binding": if st.right_to_left_binding { "rightToLeft" } else { "leftToRight" }, "intent": st.intent, "bleed": st.bleed, "slug": st.slug})+ "binding": if st.right_to_left_binding { "rightToLeft" } else { "leftToRight" }, "intent": st.intent, "bleed": st.bleed, "slug": st.slug,+ "margins": d.page(0).map(|p| p.margins), "primaryTextFrame": st.primary_text_frame})}+/// The largest chapter number (as for page numbers).+const MAX_CHAPTER: u64 = 99_999;++/// The active document's chapter numbering, and the open book that holds it (what+/// `layout.chapterNumbering {}` reports, read without running a command).+pub fn chapter_numbering(s: &Session) -> Result<Value> {+ let st = s.doc()?;+ let set = &st.doc.settings;+ let book = s+ .book+ .as_ref()+ .filter(|b| st.path.as_deref().is_some_and(|p| b.documents.iter().any(|d| std::path::Path::new(d) == std::path::Path::new(p))))+ .map(|b| std::path::Path::new(&b.path).file_stem().map_or_else(|| b.path.clone(), |n| n.to_string_lossy().to_string()));+ Ok(+ json!({"chapterNumber": set.chapter_number.max(1), "label": st.doc.chapter_label(), "style": set.chapter_style, "source": set.chapter_source, "book": book}),+ )+}++/// Layer Options: every field in one undo step; a bad name or colour changes nothing.+fn set_layer(s: &mut Session, p: &Value) -> Result<Value> {+ const ID: &str = "layer.set";+ let id = LayerId(p.get("id").and_then(Value::as_u64).ok_or_else(|| bad(ID, "missing id"))?);+ let name = match p.get("name") {+ Some(v) => Some(v.as_str().map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(ID, "a layer needs a name"))?.to_string()),+ None => None,+ };+ let color: Option<[u8; 3]> = match p.get("color") {+ None => None,+ Some(Value::String(n)) => Some(+ LAYER_COLORS+ .iter()+ .find(|(k, _)| k.eq_ignore_ascii_case(n))+ .map(|(_, c)| *c)+ .ok_or_else(|| bad(ID, format!("unknown layer colour `{n}`")))?,+ ),+ Some(v) => Some(serde_json::from_value(v.clone()).map_err(|_| bad(ID, "color is [r,g,b] (0–255) or a layer colour name"))?),+ };+ let flag = |k: &str| match p.get(k) {+ None => Ok(None),+ Some(v) => v.as_bool().map(Some).ok_or_else(|| bad(ID, format!("`{k}` is true or false"))),+ };+ let (visible, locked, printable) = (flag("visible")?, flag("locked")?, flag("printable")?);+ let (guides, wrap) = (flag("showGuides")?, flag("suppressWrapWhenHidden")?);+ s.edit(|d, _| {+ if let Some(n) = &name+ && d.layers.iter().any(|l| l.id != id && l.name == *n)+ {+ return Err(bad(ID, format!("a layer named `{n}` exists")));+ }+ let l = d.layer_mut(id).ok_or_else(|| bad(ID, "no such layer"))?;+ if let Some(n) = name {+ l.name = n;+ }+ if let Some(c) = color {+ l.color = c;+ }+ for (slot, v) in [+ (&mut l.visible, visible),+ (&mut l.locked, locked),+ (&mut l.printable, printable),+ (&mut l.show_guides, guides),+ (&mut l.suppress_wrap_when_hidden, wrap),+ ] {+ if let Some(v) = v {+ *slot = v;+ }+ }+ ok()+ })+}+#[cfg(test)]mod setup_tests {use serde_json::json;+ #[test]+ fn chapter_numbering_sets_style_and_start() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let r = s.execute("layout.chapterNumbering", &json!({})).unwrap();+ assert_eq!(r, json!({"chapterNumber": 1, "label": "1", "style": "arabic", "source": "automatic", "book": null}));+ let r = s.execute("layout.chapterNumbering", &json!({"start": 4, "style": "upperRoman"})).unwrap();+ assert_eq!((&r["label"], &r["source"]), (&json!("IV"), &json!("userDefined")), "a start number means Start Chapter Numbering at");+ s.execute("variables.define", &json!({"name": "Chapter", "type": "chapterNumber"})).unwrap();+ let d = &s.doc().unwrap().doc;+ let chapter = d.variable("Chapter").unwrap();+ assert_eq!(d.variable_value(chapter, Some(0)).as_deref(), Some("IV"), "the Chapter Number variable uses the style");+ for bad in [json!({"style": "symbols"}), json!({"start": 0}), json!({"start": 100_000}), json!({"source": "nextBook"})] {+ assert!(s.execute("layout.chapterNumbering", &bad).is_err(), "{bad}");+ }+ s.execute("layout.chapterNumbering", &json!({"source": "sameAsPrevious"})).unwrap();+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(s.execute("layout.chapterNumbering", &json!({})).unwrap()["source"], "userDefined", "undoable");+ }++ #[test]+ fn document_setup_sets_every_pages_margins_in_one_step() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"pages": 3, "margins": 36})).unwrap();+ let f = s.execute("frame.create", &json!({"rect": [36, 36, 576, 756], "content": "text"})).unwrap();+ let r = s.execute("layout.documentSetup", &json!({})).unwrap();+ assert_eq!(r["margins"], json!({"top": 36.0, "bottom": 36.0, "inside": 36.0, "outside": 36.0}));+ let m = json!({"top": 72, "bottom": 54, "inside": 72, "outside": 72});+ let r = s.execute("layout.documentSetup", &json!({"margins": m, "bleed": 9, "adjustLayout": true})).unwrap();+ assert_eq!(r["margins"]["bottom"], 54.0);+ let d = &s.doc().unwrap().doc;+ assert!(+ d.spreads.iter().chain(&d.parents).flat_map(|sp| &sp.pages).all(|pg| pg.margins.top == 72.0 && pg.margins.bottom == 54.0),+ "every page and parent page"+ );+ let b = d.item(designcraft_doc::ItemId(f["id"].as_u64().unwrap())).unwrap().bounds();+ assert!((b.y0 - 72.0).abs() < 1e-6, "Adjust Layout: the frame follows the margins ({b:?})");+ // One step: undo brings back the margins and the bleed.+ s.execute("edit.undo", &json!({})).unwrap();+ let r = s.execute("layout.documentSetup", &json!({})).unwrap();+ assert_eq!((r["margins"]["top"].clone(), r["bleed"][0].clone()), (json!(36.0), json!(0.0)));+ for bad in [+ json!({"width": 0}),+ json!({"height": -5}),+ json!({"width": 1e9}),+ json!({"width": "wide"}),+ json!({"margins": -1}),+ json!({"margins": {"top": 1}}),+ ] {+ assert!(s.execute("layout.documentSetup", &bad).is_err(), "{bad}");+ }+ assert_eq!(s.execute("layout.documentSetup", &json!({})).unwrap()["width"], 612.0, "refused values change nothing");+ }+#[test]fn document_setup_pages_start_bleed_slug() {let mut s = crate::Session::new();diff --cc crates/ui-egui/src/dialogs.rsindex 50bbc262d,2f1deecf8..923ffc64f--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@@ -1708,8 -1923,13 +1942,14 @@@ pub fn show(app: &mut DesignApp, ctx: &seed_text_frame_options(app, &mut d);text_frame_options_dialog(app, ui, &mut d);}- "documentSetup" => document_setup(app, ui, &mut d),+ "documentSetup" => {+ // Adjust Layout applies at once.+ let adjust = document_setup(app, ui, &mut d);+ if adjust {+ result = Some(true);+ }+ }+ "numberingSection" => crate::section_options::body(app, ui, &mut d),"pdfExport" => pdf_export(app, ui, &mut d),"alert" => {let file = d.s("file");@@@ -1970,40 -2039,62 +2210,41 @@@ pub fn confirm(app: &mut DesignApp) ->r}"documentSetup" => {- let edges = |k: &str| json!(["Top", "Bottom", "Inside", "Outside"].map(|e| d.m(&format!("{k}{e}")).unwrap_or(0.0)));- app.run(- "layout.documentSetup",- json!({"intent": d.s("intent"), "pages": d.n("pages").unwrap_or(1.0).max(1.0) as u64, "startPage": d.n("startPage").unwrap_or(1.0).max(1.0) as u64,- "facingPages": d.b("facingPages"), "binding": d.s("binding"), "width": d.m("width"), "height": d.m("height"), "bleed": edges("bleed"), "slug": edges("slug"), "adjustLayout": d.b("adjustLayout")}),- )+ // On an error the dialog stays open to be corrected.+ let r = confirm_document_setup(app, &d);+ if let Err(e) = &r {+ app.status(e.clone());+ app.ui.dialog = Some(d);+ }+ r}"paragraphStyleOptions" => {- let name = d.s("name");- let mut para = serde_json::Map::new();- let mut chars = serde_json::Map::new();- for (k, v) in &d.fields {- if let Some(a) = k.strip_prefix("p.") {- // `p.ruleAbove.weight`: one field of a rule (the command keeps the others).- match a.split_once('.') {- Some((attr, field)) => {- if let Value::Object(m) = para.entry(attr).or_insert_with(|| json!({})) {- m.insert(field.into(), v.clone());- }- }- None => {- para.insert(a.into(), v.clone());- }- }- } else if let Some(a) = k.strip_prefix("c.") {- chars.insert(a.into(), v.clone());+ let mut d = d;+ let r = confirm_paragraph_style_options(app, &mut d);+ if let Err(e) = &r {+ // Keep the dialog open with the reason, on the section it concerns.+ if e.contains("bad GREP") {+ d.fields.insert("section".into(), json!("grep"));}+ d.fields.insert("status".into(), json!(e));+ app.ui.dialog = Some(d);}- let based = d.s("basedOn");- let rename = d.s("rename");- let (r, style) = if d.b("new") {- let mut params = json!({"name": if rename.trim().is_empty() { "Paragraph Style 1" } else { rename.trim() }, "para": para, "chars": chars});- if !based.is_empty() && based != designcraft_doc::NO_PARA_STYLE {- params["basedOn"] = json!(based);- }- let r = app.run("style.paragraph.create", params)?;- let style = r["name"].as_str().unwrap_or_default().to_string();- (r, style)- } else {- let mut params = json!({"name": name, "para": para, "chars": chars});- if !based.is_empty() {- params["basedOn"] = if based == designcraft_doc::NO_PARA_STYLE { Value::Null } else { json!(based) };- }- if !rename.is_empty() && rename != name {- params["rename"] = json!(rename);- }- let style = if !rename.is_empty() && rename != name { rename } else { name };- (app.run("style.paragraph.edit", params)?, style)- };- if d.fields.contains_key("x.tag") {- let tag = d.s("x.tag");- let tag = if tag == "[Automatic]" { String::new() } else { tag };- app.run("style.exportTag", json!({"style": style, "tag": tag, "class": d.s("x.class")}))?;+ r+ }+ "deleteParagraphStyle" => {+ let name = d.s("name");+ let replace = d.s("replaceWith");+ app.run(+ "style.paragraph.delete",+ json!({"name": name, "replaceWith": if replace.is_empty() { json!(designcraft_doc::BASIC_PARAGRAPH) } else { json!(replace) }}),+ )+ }+ "paragraphLocal" => {+ let attrs: Map<String, Value> = d.fields.iter().filter_map(|(k, v)| k.strip_prefix("p.").map(|a| (a.to_string(), v.clone()))).collect();+ if attrs.is_empty() {+ return Ok(Value::Null);}- Ok(r)+ app.run("type.para", json!({"attrs": attrs}))}"paragraphRules" => {let attrs = rule_edits(&d, "");@@@ -3756,1576 -3537,450 +3997,1673 @@@ fn bullets_and_numbering(lang: &str, ui});}-/// Document Footnote Options: Numbering and Formatting / Layout tabs.-fn footnote_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {- ui.horizontal(|ui| {- for (tab, label) in [("numbering", "Numbering and Formatting"), ("layout", "Layout")] {- if ui.selectable_label(d.s("tab") == tab, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, label))).clicked() {- d.fields.insert("tab".into(), json!(tab));- }+/// Paragraph Borders and Shading, Span Columns, and Bullets and Numbering for the selected+/// paragraphs: the Paragraph Style Options sections over the paragraphs' attributes (`current`);+/// OK applies the edits (`p.<key>`) as local formatting.+fn paragraph_local(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {+ let Some(doc) = app.session.active().map(|s| s.doc.clone()) else { return };+ let pv = d.fields.get("current").cloned().unwrap_or_default();+ let lang = app.ui.language.clone();+ ui.set_min_width(480.0);+ match d.s("section").as_str() {+ "span" => span_columns(&lang, ui, d, &pv, &doc),+ "bullets" => {+ let (char_styles, families, fonts, scope) = ListUi::new_parts(app);+ let (family, style) = (d.s("family"), d.s("style"));+ let lu = ListUi { char_styles: &char_styles, families: &families, fonts: &fonts, scope, family: &family, style: &style };+ bullets_and_numbering(&lang, ui, d, &pv, &doc, &lu);}- });- ui.separator();- let head = |ui: &mut egui::Ui, t: &str| {- ui.add_space(4.0);- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, t)).font(semibold(12.0)));- };- if d.s("tab") == "layout" {- head(ui, "Spacing Options");- egui::Grid::new("fn_sp").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Minimum Space Before First Footnote:"));- text_field(ui, d, "spaceBefore", 70.0);- ui.end_row();- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Space Between Footnotes:"));- text_field(ui, d, "spaceBetween", 70.0);- ui.end_row();- });- head(ui, "First Baseline");- egui::Grid::new("fn_fb").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Offset:"));- translated_combo(- &app.ui.language,- ui,- d,- "firstBaseline",- &[("ascent", "Ascent"), ("capHeight", "Cap Height"), ("leading", "Leading"), ("xHeight", "x Height"), ("fixed", "Fixed")],- );- ui.end_row();- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Min:"));- text_field(ui, d, "firstBaselineMin", 70.0);- ui.end_row();- });- check(ui, d, "spanColumns", crate::i18n::tr(&app.ui.language, "Span Footnotes Across Columns"));- head(ui, "Rule Above");- check(ui, d, "rule.on", crate::i18n::tr(&app.ui.language, "Rule On"));- egui::Grid::new("fn_rule").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Weight:"));- text_field(ui, d, "rule.weight", 60.0);- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Color:"));- let swatches: Vec<String> = app.session.active().map(|st| st.doc.swatches.iter().map(|s| s.name.clone()).collect()).unwrap_or_default();- let opts: Vec<(&str, &str)> = swatches.iter().map(|n| (n.as_str(), n.as_str())).collect();- combo(ui, d, "rule.color", &opts);- ui.end_row();- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Width:"));- text_field(ui, d, "rule.width", 60.0);- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Offset:"));- text_field(ui, d, "rule.offset", 60.0);- ui.end_row();- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Left Indent:"));- text_field(ui, d, "rule.leftIndent", 60.0);- ui.end_row();+ section => {+ let border = section != "shading";+ ui.horizontal(|ui| {+ for (tab, label) in [("border", "Border"), ("shading", "Shading")] {+ if ui.selectable_label(section == tab, crate::rtl::widget(ui, crate::i18n::tr(&lang, label))).clicked() {+ d.fields.insert("section".into(), json!(tab));+ }+ }+ });+ ui.separator();+ border_shading(&lang, ui, d, &pv, &doc, border);+ }+ }+}++fn section_list(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cjk: bool, sections: &[(&str, &str)]) {+ let sections = style_cjk::sections(cjk, d.id == "paragraphStyleOptions", sections);+ ui.vertical(|ui| {+ ui.set_width(170.0);+ // The dialog has a fixed height; a long list scrolls.+ egui::ScrollArea::vertical().id_salt("style_sections").auto_shrink([false, true]).show(ui, |ui| {+ for (id, label) in §ions {+ if ui.selectable_label(d.s("section") == *id, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() {+ d.fields.insert("section".into(), json!(id));+ }+ }});+ });+}++/// "Paragraph Style n" / "Character Style n": the first name no style has.+fn next_style_name(styles: &designcraft_doc::Styles, para: bool) -> String {+ let (base, count) = if para { ("Paragraph Style", styles.paragraph.len()) } else { ("Character Style", styles.character.len()) };+ let taken = |n: &str| if para { styles.para(n).is_some() } else { styles.char_style(n).is_some() };+ // Among count + 1 numbers at least one is free.+ (1..=count + 1).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_else(|| format!("{base} {}", count + 1))+}++/// Paragraph or Character Style Options for an existing style (a double-click on it in the styles+/// panel, or Edit in its menu). [None] and [No Paragraph Style] have no options.+pub fn open_style_options(app: &mut DesignApp, para: bool, name: &str) {+ if name == if para { designcraft_doc::NO_PARA_STYLE } else { designcraft_doc::NO_CHAR_STYLE } {return;}- head(ui, "Numbering");- egui::Grid::new("fn_num").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Style:"));- translated_combo(- &app.ui.language,+ let id = if para { "paragraphStyleOptions" } else { "characterStyleOptions" };+ app.ui.dialog = Some(Dialog::new(id, json!({"name": name})));+}++/// New Paragraph Style… / New Character Style…: the style options for a style made on OK, named+/// with the next free "Paragraph Style n" / "Character Style n".+pub fn open_new_style(app: &mut DesignApp, para: bool) {+ let Some(st) = app.session.active() else { return };+ let name = next_style_name(&st.doc.styles, para);+ let id = if para { "paragraphStyleOptions" } else { "characterStyleOptions" };+ app.ui.dialog = Some(Dialog::new(id, json!({"new": true, "rename": name})));+}++/// Character Style Options: General, then the character sections it shares with Paragraph Style+/// Options. A character style sets only some attributes: the fields show those it and its Based+/// On set and leave the rest blank. Edits are `c.<attr>` fields (`null` = no longer set), applied+/// on OK; `new` makes the style instead of editing `name`.+fn character_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {+ let name = d.s("name");+ let new = d.b("new");+ let Some(doc) = app.session.active().map(|st| st.doc.clone()) else { return };+ let styles = &doc.styles;+ let style = match styles.char_style(&name) {+ _ if new => designcraft_doc::CharacterStyle { name: String::new(), based_on: None, chars: Default::default(), shortcut: String::new() },+ Some(s) if name != designcraft_doc::NO_CHAR_STYLE => s.clone(),+ _ => {+ crate::rtl::label(ui, format!("No style named {name}"));+ return;+ }+ };+ if !d.fields.contains_key("rename") {+ d.fields.insert("rename".into(), json!(if new { next_style_name(styles, false) } else { name.clone() }));+ }+ let based = d+ .fields+ .get("basedOn")+ .and_then(Value::as_str)+ .map(str::to_string)+ .or(style.based_on.clone())+ .unwrap_or_else(|| designcraft_doc::NO_CHAR_STYLE.into());+ // The fields show the style's own attributes over those its Based On gives it.+ let mut shown = styles.char_style_attrs(&based);+ shown.merge(&style.chars);+ let base = serde_json::to_value(&shown).unwrap_or_default();+ let cf = CharFields { base: &base, sparse: true };+ let lang = app.ui.language.clone();+ ui.set_min_width(560.0);+ ui.horizontal_top(|ui| {+ // A fixed height: the separator would otherwise stretch the dialog to the window.+ ui.set_min_height(380.0);+ ui.set_max_height(380.0);+ section_list(+ &lang,ui,d,- "style",+ crate::cjk_features(app),&[- ("arabic", "1, 2, 3, 4..."),- ("upperRoman", "I, II, III, IV..."),- ("lowerRoman", "i, ii, iii, iv..."),- ("upperLetters", "A, B, C, D..."),- ("lowerLetters", "a, b, c, d..."),- ("arabicLeadingZero", "01, 02, 03..."),- ("symbols", "*, †, ‡, §..."),+ ("general", "General"),+ ("chars", "Basic Character Formats"),+ ("advanced", "Advanced Character Formats"),+ ("color", "Character Color"),+ ("openType", "OpenType Features"),+ ("underline", "Underline Options"),+ ("strikethrough", "Strikethrough Options"),],);+ ui.separator();+ ui.vertical(|ui| match d.s("section").as_str() {+ "chars" => basic_character_formats(app, ui, d, &cf),+ "advanced" => advanced_character_formats(&lang, ui, d, &cf),+ "color" => character_color(&lang, ui, d, &cf, &doc),+ "openType" => open_type_features(&lang, ui, d, &cf),+ "underline" => line_options(&lang, ui, d, &cf, &doc, "underline"),+ "strikethrough" => line_options(&lang, ui, d, &cf, &doc, "strikethrough"),+ s if style_cjk::is_section(s) => style_cjk::section_ui(app, ui, d, s, &cf, None, &doc),+ _ => {+ egui::Grid::new("csg").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, crate::i18n::tr(&lang, "Style Name:"));+ text_field(ui, d, "rename", 220.0);+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(&lang, "Based On:"));+ egui::ComboBox::from_id_salt("csbased")+ .selected_text(crate::rtl::widget(ui, crate::i18n::style_name(&lang, &based)))+ .width(220.0)+ .show_ui(ui, |ui| {+ // Not itself, nor a style based on it.+ for s in styles.character.iter().filter(|s| new || !styles.char_based_on_cycles(&name, &s.name)) {+ if ui.selectable_label(s.name == based, crate::rtl::widget(ui, crate::i18n::style_name(&lang, &s.name))).clicked() {+ d.fields.insert("basedOn".into(), json!(s.name));+ }+ }+ });+ ui.end_row();+ });+ let status = d.s("status");+ if !status.is_empty() {+ crate::rtl::label(ui, egui::RichText::new(status).color(crate::theme::Tokens::get(ui.ctx()).text_strong));+ }+ ui.add_space(8.0);+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&lang, "Style Settings:")).font(semibold(12.0)));+ // What OK would leave the style setting, after its Based On.+ let mut own = serde_json::to_value(&style.chars).unwrap_or_default();+ if let Some(o) = own.as_object_mut() {+ for (k, v) in d.fields.iter().filter_map(|(k, v)| Some((k.strip_prefix("c.")?, v))) {+ if v.is_null() {+ o.remove(k);+ } else {+ o.insert(k.to_string(), v.clone());+ }+ }+ }+ let mut parts = vec![crate::i18n::style_name(&lang, &based).to_string()];+ parts.extend(own.as_object().into_iter().flatten().map(|(k, v)| format!("{}: {}", setting_label(&lang, k), setting_text(v))));+ ui.add(egui::Label::new(egui::RichText::new(parts.join(" + ")).color(crate::theme::Tokens::get(ui.ctx()).text_dim)).wrap());+ }+ });+ });+}++/// An attribute's name as Style Settings shows it: the field's label where the name reads poorly.+fn setting_label(lang: &str, key: &str) -> String {+ match key {+ "hScale" => crate::i18n::tr(lang, "Horizontal Scale:").trim_end_matches([':', ':']).to_string(),+ "vScale" => crate::i18n::tr(lang, "Vertical Scale:").trim_end_matches([':', ':']).to_string(),+ "capitalization" => crate::i18n::tr(lang, "Case:").trim_end_matches([':', ':']).to_string(),+ "otfFeatures" => crate::i18n::tr(lang, "OpenType Features").to_string(),+ _ => crate::i18n::tr(lang, &humanize(key)).to_string(),+ }+}++/// An attribute value as Style Settings shows it.+fn setting_text(v: &Value) -> String {+ match v {+ Value::String(s) => s.clone(),+ Value::Number(n) => n.as_f64().map_or_else(|| n.to_string(), |x| format!("{}", (x * 1000.0).round() / 1000.0)),+ Value::Bool(b) => if *b { "on" } else { "off" }.into(),+ Value::Array(a) => a.iter().map(setting_text).collect::<Vec<_>>().join(", "),+ Value::Object(o) => o.get("value").or_else(|| o.get("kind")).map(setting_text).unwrap_or_default(),+ Value::Null => String::new(),+ }+}++/// Where the character sections of the style options dialogs get the values they show: `base`+/// holds them by attribute name (resolved values for a paragraph style; for a character style the+/// attributes it sets, the others absent). `sparse` (a character style) lets a field be blank:+/// emptying it, or picking the blank entry, unsets the attribute.+struct CharFields<'a> {+ base: &'a Value,+ sparse: bool,+}++impl CharFields<'_> {+ /// The value shown for attribute `key`: the dialog's edit, else the base value.+ fn get(&self, d: &Dialog, key: &str) -> Value {+ d.fields.get(&format!("c.{key}")).cloned().unwrap_or_else(|| self.base.get(key).cloned().unwrap_or(Value::Null))+ }+ fn set(&self, d: &mut Dialog, key: &str, v: Value) {+ d.fields.insert(format!("c.{key}"), v);+ }+}++/// A number attribute shown multiplied by `scale` (100 for a fraction shown as a percentage).+fn char_number(ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, key: &str, suffix: &str, scale: f64, range: (f64, f64)) {+ let v = cf.get(d, key).as_f64().map(|x| x * scale);+ let field = crate::widgets::NumField::number(key, v, suffix, 2).width(80.0).range(range.0, range.1);+ let edit = if cf.sparse { field.show_or_clear(ui) } else { field.show(ui).map(Some) };+ if let Some(n) = edit {+ cf.set(d, key, n.map_or(Value::Null, |n| json!(n / scale)));+ }+}++/// An attribute chosen from `opts` (value, label); a character style also has a blank entry.+fn char_choice(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, key: &str, opts: &[(Value, &str)]) {+ let cur = cf.get(d, key);+ let shown = opts.iter().find(|o| o.0 == cur).map_or("", |o| crate::i18n::tr(lang, o.1));+ egui::ComboBox::from_id_salt(("cs", key)).selected_text(crate::rtl::widget(ui, shown)).width(200.0).show_ui(ui, |ui| {+ if cf.sparse && ui.selectable_label(cur.is_null(), " ").clicked() {+ cf.set(d, key, Value::Null);+ }+ for (v, label) in opts {+ if ui.selectable_label(*v == cur, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() {+ cf.set(d, key, v.clone());+ }+ }+ });+}++/// An on/off attribute; for a character style a third, mixed state leaves it unset (clicks go+/// unset → on → off → unset).+fn char_check(ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, key: &str, label: &str) {+ let cur = cf.get(d, key);+ let mut on = cur.as_bool().unwrap_or(false);+ let unset = cf.sparse && cur.is_null();+ if ui.add(egui::Checkbox::new(&mut on, crate::rtl::widget(ui, label)).indeterminate(unset)).clicked() {+ let next = match cur.as_bool() {+ _ if !cf.sparse => json!(on),+ None => json!(true),+ Some(true) => json!(false),+ Some(false) => Value::Null,+ };+ cf.set(d, key, next);+ }+}++/// A swatch attribute from a menu; `text_color` names the "" entry (the text's own colour).+fn char_swatch(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, doc: &designcraft_doc::Document, key: &str, text_color: Option<&str>) {+ let mut opts: Vec<(Value, &str)> = text_color.map(|l| (json!(""), l)).into_iter().collect();+ opts.extend(doc.swatches.iter().map(|w| (json!(w.name), w.name.as_str())));+ char_choice(lang, ui, d, cf, key, &opts);+}++/// Basic Character Formats: font, size, leading, kerning, tracking, case, position and the+/// underline, strikethrough, ligatures and no-break switches.+fn basic_character_formats(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields) {+ let lang = app.ui.language.clone();+ let lang = lang.as_str();+ let fonts = crate::panels::fonts(app);+ let menu = crate::panels::font_menu(app);+ egui::Grid::new("psc").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, crate::i18n::tr(lang, "Font Family:"));+ let fam = cf.get(d, "fontFamily").as_str().unwrap_or("").to_string();+ let shown = if fam.is_empty() { "—".to_string() } else { crate::panels::font_label(app, &menu, &fam) };+ egui::ComboBox::from_id_salt("psfam")+ .selected_text(shown)+ .width(200.0)+ .height(440.0)+ .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)+ .show_ui(ui, |ui| {+ if cf.sparse && ui.selectable_label(fam.is_empty(), " ").clicked() {+ cf.set(d, "fontFamily", Value::Null);+ }+ if let Some(f) = crate::panels::font_menu_body(app, ui, &menu, &fam, 200.0) {+ cf.set(d, "fontFamily", json!(f));+ }+ });ui.end_row();- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Start at:"));- text_field(ui, d, "startAt", 60.0);- ui.end_row();- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Restart Numbering Every:"));- translated_combo(- &app.ui.language,- ui,- d,- "restart",- &[("never", "Never (continuous)"), ("page", "Page"), ("spread", "Spread"), ("section", "Section")],- );- ui.end_row();- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Show Prefix/Suffix in:"));- translated_combo(- &app.ui.language,+ crate::rtl::label(ui, crate::i18n::tr(lang, "Font Style:"));+ let sty = cf.get(d, "fontStyle").as_str().unwrap_or("").to_string();+ if cf.sparse && fam.is_empty() {+ // No family to list styles of: type the style ("Italic" in whatever font the text has).+ let mut s = sty.clone();+ if ui.add(egui::TextEdit::singleline(&mut s).desired_width(200.0)).changed() {+ cf.set(d, "fontStyle", if s.trim().is_empty() { Value::Null } else { json!(s) });+ }+ } else {+ egui::ComboBox::from_id_salt("pssty").selected_text(&sty).width(200.0).show_ui(ui, |ui| {+ if cf.sparse && ui.selectable_label(sty.is_empty(), " ").clicked() {+ cf.set(d, "fontStyle", Value::Null);+ }+ for s in fonts.styles(&fam) {+ if ui.selectable_label(s == sty, &s).clicked() {+ cf.set(d, "fontStyle", json!(s));+ }+ }+ });+ }+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Size:"));+ char_number(ui, d, cf, "size", " pt", 1.0, (0.1, 1296.0));+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Leading:"));+ let lv = match cf.get(d, "leading") {+ v if v["kind"] == "points" => v["value"].as_f64(),+ _ => None,+ };+ let field = crate::widgets::NumField::number("pslead", lv, " pt", 2).width(80.0).range(0.0, 5000.0);+ let edit = if cf.sparse { field.show_or_clear(ui) } else { field.show(ui).map(Some) };+ if let Some(n) = edit {+ cf.set(d, "leading", n.map_or(Value::Null, |n| json!({"kind": "points", "value": n})));+ }+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Kerning:"));+ char_choice(+ lang,+ ui,+ d,+ cf,+ "kerning",+ &[(json!({"kind": "metrics"}), "Metrics"), (json!({"kind": "optical"}), "Optical"), (json!({"kind": "none"}), "0")],+ );+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Tracking:"));+ char_number(ui, d, cf, "tracking", "", 1.0, (-1000.0, 10000.0));+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Case:"));+ char_choice(+ lang,+ ui,+ d,+ cf,+ "capitalization",+ &[+ (json!("normal"), "Normal"),+ (json!("allCaps"), "All Caps"),+ (json!("smallCaps"), "Small Caps"),+ (json!("openTypeAllSmallCaps"), "OpenType All Small Caps"),+ ],+ );+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Position:"));+ char_choice(+ lang,+ ui,+ d,+ cf,+ "position",+ &[+ (json!("normal"), "Normal"),+ (json!("superscript"), "Superscript"),+ (json!("subscript"), "Subscript"),+ (json!("otSuperscript"), "OpenType Superscript"),+ (json!("otSubscript"), "OpenType Subscript"),+ (json!("otNumerator"), "OpenType Numerator"),+ (json!("otDenominator"), "OpenType Denominator"),+ ],+ );+ ui.end_row();+ });+ ui.add_space(4.0);+ egui::Grid::new("pscb").num_columns(2).spacing([16.0, 4.0]).show(ui, |ui| {+ char_check(ui, d, cf, "underline", crate::i18n::tr(lang, "Underline"));+ char_check(ui, d, cf, "ligatures", crate::i18n::tr(lang, "Ligatures"));+ ui.end_row();+ char_check(ui, d, cf, "strikethrough", crate::i18n::tr(lang, "Strikethrough"));+ char_check(ui, d, cf, "noBreak", crate::i18n::tr(lang, "No Break"));+ ui.end_row();+ });+}++/// Advanced Character Formats: scaling, baseline shift, skew and language.+fn advanced_character_formats(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields) {+ egui::Grid::new("csa").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, crate::i18n::tr(lang, "Horizontal Scale:"));+ char_number(ui, d, cf, "hScale", "%", 100.0, (1.0, 1000.0));+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Vertical Scale:"));+ char_number(ui, d, cf, "vScale", "%", 100.0, (1.0, 1000.0));+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Baseline Shift:"));+ char_number(ui, d, cf, "baselineShift", " pt", 1.0, (-5000.0, 5000.0));+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Skew:"));+ char_number(ui, d, cf, "skew", "°", 1.0, (-85.0, 85.0));+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Language:"));+ let opts: Vec<(Value, &str)> = crate::panels::properties::LANGUAGES.iter().map(|l| (json!(l), *l)).collect();+ char_choice(lang, ui, d, cf, "language", &opts);+ ui.end_row();+ });+}++/// Character Color: the fill or stroke swatch, its tint and the stroke weight.+fn character_color(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, doc: &designcraft_doc::Document) {+ let stroke = d.s("colorTarget") == "stroke";+ ui.horizontal(|ui| {+ for (target, label) in [("fill", "Fill"), ("stroke", "Stroke")] {+ if ui.selectable_label((target == "stroke") == stroke, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() {+ d.fields.insert("colorTarget".into(), json!(target));+ }+ }+ });+ let key = if stroke { "stroke" } else { "fill" };+ let cur = cf.get(d, key).as_str().unwrap_or("").to_string();+ egui::ScrollArea::vertical().id_salt(("cscolor", key)).max_height(220.0).show(ui, |ui| {+ for sw in &doc.swatches {+ let (c, g) = crate::widgets::swatch_colors(doc, &sw.name, 1.0);+ ui.horizontal(|ui| {+ let (r, _) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), egui::Sense::hover());+ crate::widgets::paint_chip(ui.painter(), r, c, g);+ if ui.selectable_label(sw.name == cur, &sw.name).clicked() {+ // A character style's chosen swatch, clicked again, is no longer set.+ cf.set(d, key, if cf.sparse && sw.name == cur { Value::Null } else { json!(sw.name) });+ }+ });+ }+ });+ egui::Grid::new("cscg").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, crate::i18n::tr(lang, "Tint:"));+ char_number(ui, d, cf, if stroke { "strokeTint" } else { "fillTint" }, "%", 100.0, (0.0, 100.0));+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Weight:"));+ char_number(ui, d, cf, "strokeWeight", " pt", 1.0, (0.0, 800.0));+ ui.end_row();+ });+}++/// OpenType Features: the feature switches, figure style and stylistic sets (one `otfFeatures`+/// list: changing any feature sets the whole list).+fn open_type_features(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields) {+ use designcraft_doc::otf;+ let mut list: Vec<String> =+ cf.get(d, "otfFeatures").as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default();+ let mut changed = false;+ egui::Grid::new("csot").num_columns(2).spacing([16.0, 4.0]).show(ui, |ui| {+ for (i, (tag, label, _)) in otf::TOGGLES.iter().enumerate() {+ let mut on = otf::is_on(&list, tag);+ if ui.checkbox(&mut on, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).changed() {+ otf::set(&mut list, tag, on);+ changed = true;+ }+ if i % 2 == 1 {+ ui.end_row();+ }+ }+ });+ ui.add_space(6.0);+ ui.horizontal(|ui| {+ crate::rtl::label(ui, crate::i18n::tr(lang, "Figure Style:"));+ let fig = otf::figures(&list);+ let shown = otf::FIGURES.iter().find(|f| f.0 == fig).map_or("", |f| f.1);+ egui::ComboBox::from_id_salt("csfig").selected_text(crate::rtl::widget(ui, crate::i18n::tr(lang, shown))).width(180.0).show_ui(ui, |ui| {+ for (id, label, ..) in otf::FIGURES {+ if ui.selectable_label(fig == *id, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() && otf::set_figures(&mut list, id)+ {+ changed = true;+ }+ }+ });+ });+ ui.add_space(4.0);+ crate::rtl::label(ui, crate::i18n::tr(lang, "Stylistic Sets"));+ let mask = otf::stylistic_sets(&list);+ egui::Grid::new("csss").num_columns(10).spacing([2.0, 2.0]).show(ui, |ui| {+ for n in 1..=20u32 {+ let bit = 1u32 << (n - 1);+ if ui.add_sized([28.0, 20.0], egui::Button::selectable(mask & bit != 0, format!("{n}"))).clicked() {+ otf::set_stylistic_sets(&mut list, mask ^ bit);+ changed = true;+ }+ if n % 10 == 0 {+ ui.end_row();+ }+ }+ });+ if changed {+ cf.set(d, "otfFeatures", json!(list));+ }+}++/// Underline Options / Strikethrough Options (`key` is `underline` or `strikethrough`).+fn line_options(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, doc: &designcraft_doc::Document, key: &str) {+ char_check(ui, d, cf, key, crate::i18n::tr(lang, if key == "underline" { "Underline On" } else { "Strikethrough On" }));+ ui.add_space(4.0);+ egui::Grid::new(("csline", key)).num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, crate::i18n::tr(lang, "Weight:"));+ char_number(ui, d, cf, &format!("{key}Weight"), " pt", 1.0, (0.0, 800.0));+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Offset:"));+ char_number(ui, d, cf, &format!("{key}Offset"), " pt", 1.0, (-800.0, 800.0));+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Color:"));+ char_swatch(lang, ui, d, cf, doc, &format!("{key}Color"), Some("(Text Color)"));+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Tint:"));+ char_number(ui, d, cf, &format!("{key}Tint"), "%", 100.0, (0.0, 100.0));+ ui.end_row();+ });+}++fn delete_character_style(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {+ let name = d.s("name");+ ui.set_min_width(380.0);+ crate::rtl::label(+ ui,+ egui::RichText::new(+ crate::i18n::tr(&app.ui.language, "Delete the character style \"{name}\"?")+ .replace("{name}", crate::i18n::style_name(&app.ui.language, &name)),+ )+ .size(12.5),+ );+ ui.add_space(8.0);+ let Some(st) = app.session.active() else { return };+ let in_use = st.doc.stories.values().any(|s| s.chars.iter().any(|r| r.format.style == name));+ let names: Vec<String> = st.doc.styles.character.iter().map(|c| c.name.clone()).filter(|n| *n != name).collect();+ if in_use {+ crate::rtl::label(+ ui,+ egui::RichText::new(crate::i18n::tr(&app.ui.language, "This style is in use. Text using it will be reassigned to:"))+ .size(11.0)+ .color(crate::theme::Tokens::get(ui.ctx()).text_dim),+ );+ } else {+ crate::rtl::label(+ ui,+ egui::RichText::new(crate::i18n::tr(&app.ui.language, "Replace with:")).size(11.0).color(crate::theme::Tokens::get(ui.ctx()).text_dim),+ );+ }+ ui.add_space(4.0);+ if !d.fields.contains_key("replaceWith") {+ d.fields.insert("replaceWith".into(), json!(designcraft_doc::NO_CHAR_STYLE));+ }+ let replace = d.s("replaceWith");+ egui::ComboBox::from_id_salt("del_char_replace")+ .selected_text(crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, &replace)))+ .width(260.0)+ .show_ui(ui, |ui| {+ for n in [designcraft_doc::NO_CHAR_STYLE].into_iter().chain(names.iter().map(String::as_str)) {+ if ui.selectable_label(n == replace, crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, n))).clicked() {+ d.fields.insert("replaceWith".into(), json!(n));+ }+ }+ });+}++fn combo(ui: &mut egui::Ui, d: &mut Dialog, key: &str, opts: &[(&str, &str)]) {+ let cur = d.s(key);+ let shown = opts.iter().find(|o| o.0 == cur).map_or(cur.as_str(), |o| o.1).to_string();+ egui::ComboBox::from_id_salt(key).selected_text(crate::rtl::widget(ui, &shown)).width(170.0).show_ui(ui, |ui| {+ for (v, label) in opts {+ if ui.selectable_label(cur == *v, crate::rtl::widget(ui, *label)).clicked() {+ d.fields.insert(key.into(), json!(v));+ }+ }+ });+}++/// Translate enum captions without changing serialized values or user-defined names.+fn translated_combo(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, key: &str, opts: &[(&str, &str)]) {+ let opts: Vec<_> = opts.iter().map(|(value, label)| (*value, crate::i18n::tr(lang, label))).collect();+ combo(ui, d, key, &opts);+}++/// Style name picker (paragraph or character styles of the active document).+fn style_combo(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, key: &str, character: bool) {+ let names: Vec<String> = app+ .session+ .active()+ .map(|st| {+ if character {+ st.doc.styles.character.iter().map(|s| s.name.clone()).collect()+ } else {+ st.doc.styles.paragraph.iter().map(|s| s.name.clone()).collect()+ }+ })+ .unwrap_or_default();+ let mut opts: Vec<(&str, &str)> = names.iter().map(|n| (n.as_str(), crate::i18n::style_name(&app.ui.language, n))).collect();+ if character && !names.iter().any(|n| n == designcraft_doc::NO_CHAR_STYLE) {+ opts.insert(0, (designcraft_doc::NO_CHAR_STYLE, crate::i18n::style_name(&app.ui.language, designcraft_doc::NO_CHAR_STYLE)));+ }+ combo(ui, d, key, &opts);+}++const RULES: [(&str, &str); 2] = [("ruleAbove", "Rule Above"), ("ruleBelow", "Rule Below")];++/// A rule as the dialog shows it: `current[which]` (the resolved rule, inherited values included)+/// with the fields edited in the dialog (`{prefix}{which}.{field}`) on top.+fn shown_rule(d: &Dialog, prefix: &str, which: &str, current: &Value) -> Value {+ let mut r = match current.get(which) {+ Some(Value::Object(m)) => m.clone(),+ _ => Map::new(),+ };+ let edited = format!("{prefix}{which}.");+ for (k, v) in &d.fields {+ if let Some(field) = k.strip_prefix(&edited) {+ r.insert(field.into(), v.clone());+ }+ }+ Value::Object(r)+}++/// The rule fields edited in the dialog, as `type.para` attrs: `{ruleAbove?: {…}, ruleBelow?: {…}}`.+fn rule_edits(d: &Dialog, prefix: &str) -> Map<String, Value> {+ let mut out = Map::new();+ for (which, _) in RULES {+ let edited = format!("{prefix}{which}.");+ let fields: Map<String, Value> = d.fields.iter().filter_map(|(k, v)| k.strip_prefix(&edited).map(|f| (f.to_string(), v.clone()))).collect();+ if !fields.is_empty() {+ out.insert(which.into(), Value::Object(fields));+ }+ }+ out+}++/// Paragraph Rules (the dialog, and the Paragraph Style Options section): Rule Above or Rule Below,+/// chosen at the top. `current` holds the resolved `ruleAbove` / `ruleBelow`; each edit is stored as+/// `{prefix}{rule}.{field}`, so OK changes only the fields edited.+fn paragraph_rules(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, prefix: &str, current: &Value) {+ let lang = app.ui.language.as_str();+ let (h_units, v_units) =+ app.session.active().map(|st| (st.doc.settings.horizontal_units, st.doc.settings.vertical_units)).unwrap_or((Unit::Points, Unit::Points));+ let which = if d.s("rule") == "ruleBelow" { "ruleBelow" } else { "ruleAbove" };+ let rule = shown_rule(d, prefix, which, current);+ let key = |field: &str| format!("{prefix}{which}.{field}");+ // A number field takes the rest of the row; keep its grid column to the field's width.+ let sized = |ui: &mut egui::Ui, add: &mut dyn FnMut(&mut egui::Ui) -> Option<f64>| {+ ui.allocate_ui_with_layout(egui::vec2(80.0, 22.0), egui::Layout::left_to_right(egui::Align::Center), |ui| add(ui)).inner+ };+ ui.horizontal(|ui| {+ let shown = RULES.iter().find(|r| r.0 == which).map_or(which, |r| r.1);+ egui::ComboBox::from_id_salt("rule_which").selected_text(crate::rtl::widget(ui, crate::i18n::tr(lang, shown))).width(130.0).show_ui(+ ui,+ |ui| {+ for (v, label) in RULES {+ if ui.selectable_label(v == which, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() {+ d.fields.insert("rule".into(), json!(v));+ }+ }+ },+ );+ ui.add_space(12.0);+ let mut on = rule["on"].as_bool().unwrap_or(false);+ if ui.checkbox(&mut on, crate::rtl::widget(ui, crate::i18n::tr(lang, "Rule On"))).changed() {+ d.fields.insert(key("on"), json!(on));+ }+ });+ ui.add_space(6.0);+ let on = rule["on"].as_bool().unwrap_or(false);+ ui.add_enabled_ui(on, |ui| {+ egui::Grid::new(("rules", which)).num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, crate::i18n::tr(lang, "Weight:"));+ if let Some(v) = sized(ui, &mut |ui| crate::widgets::number(ui, &key("weight"), rule["weight"].as_f64(), " pt", 80.0, 2)) {+ d.fields.insert(key("weight"), json!(v.clamp(0.0, 1000.0)));+ }+ crate::rtl::label(ui, crate::i18n::tr(lang, "Color:"));+ let color = rule["color"].as_str().unwrap_or("").to_string();+ if let Some(w) = app.session.active().and_then(|st| swatch_menu(ui, &st.doc, ("rule_color", which), &color, 130.0)) {+ d.fields.insert(key("color"), json!(w));+ }+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Tint:"));+ if let Some(v) = sized(ui, &mut |ui| crate::widgets::number(ui, &key("tint"), rule["tint"].as_f64().map(|t| t * 100.0), "%", 80.0, 0)) {+ d.fields.insert(key("tint"), json!((v / 100.0).clamp(0.0, 1.0)));+ }+ crate::rtl::label(ui, crate::i18n::tr(lang, "Width:"));+ let column = rule["columnWidth"].as_bool().unwrap_or(true);+ egui::ComboBox::from_id_salt(("rule_width", which))+ .selected_text(crate::rtl::widget(ui, crate::i18n::tr(lang, if column { "Column" } else { "Text" })))+ .width(130.0)+ .show_ui(ui, |ui| {+ for (v, label) in [(true, "Column"), (false, "Text")] {+ if ui.selectable_label(v == column, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() {+ d.fields.insert(key("columnWidth"), json!(v));+ }+ }+ });+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Offset:"));+ if let Some(v) = sized(ui, &mut |ui| crate::widgets::measure(ui, &key("offset"), rule["offset"].as_f64(), v_units, 80.0)) {+ d.fields.insert(key("offset"), json!(v));+ }+ ui.end_row();+ for (label, field) in [("Left Indent:", "leftIndent"), ("Right Indent:", "rightIndent")] {+ crate::rtl::label(ui, crate::i18n::tr(lang, label));+ if let Some(v) = sized(ui, &mut |ui| crate::widgets::measure(ui, &key(field), rule[field].as_f64(), h_units, 80.0)) {+ d.fields.insert(key(field), json!(v));+ }+ }+ ui.end_row();+ });+ });+}++/// Document Footnote Options: Numbering and Formatting / Layout tabs.+fn footnote_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {+ ui.horizontal(|ui| {+ for (tab, label) in [("numbering", "Numbering and Formatting"), ("layout", "Layout")] {+ if ui.selectable_label(d.s("tab") == tab, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, label))).clicked() {+ d.fields.insert("tab".into(), json!(tab));+ }+ }+ });+ ui.separator();+ let head = |ui: &mut egui::Ui, t: &str| {+ ui.add_space(4.0);+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, t)).font(semibold(12.0)));+ };+ if d.s("tab") == "layout" {+ head(ui, "Spacing Options");+ egui::Grid::new("fn_sp").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Minimum Space Before First Footnote:"));+ text_field(ui, d, "spaceBefore", 70.0);+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Space Between Footnotes:"));+ text_field(ui, d, "spaceBetween", 70.0);+ ui.end_row();+ });+ head(ui, "First Baseline");+ egui::Grid::new("fn_fb").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Offset:"));+ translated_combo(+ &app.ui.language,+ ui,+ d,+ "firstBaseline",+ &[+ ("ascent", "Ascent"),+ ("capHeight", "Cap Height"),+ ("leading", "Leading"),+ ("xHeight", "x Height"),+ ("emboxHeight", "Em Box Height"),+ ("fixed", "Fixed"),+ ],+ );+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Min:"));+ text_field(ui, d, "firstBaselineMin", 70.0);+ ui.end_row();+ });+ check(ui, d, "spanColumns", crate::i18n::tr(&app.ui.language, "Span Footnotes Across Columns"));+ head(ui, "Rule Above");+ check(ui, d, "rule.on", crate::i18n::tr(&app.ui.language, "Rule On"));+ egui::Grid::new("fn_rule").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Weight:"));+ text_field(ui, d, "rule.weight", 60.0);+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Color:"));+ let swatches: Vec<String> = app.session.active().map(|st| st.doc.swatches.iter().map(|s| s.name.clone()).collect()).unwrap_or_default();+ let opts: Vec<(&str, &str)> = swatches.iter().map(|n| (n.as_str(), n.as_str())).collect();+ combo(ui, d, "rule.color", &opts);+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Width:"));+ text_field(ui, d, "rule.width", 60.0);+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Offset:"));+ text_field(ui, d, "rule.offset", 60.0);+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Left Indent:"));+ text_field(ui, d, "rule.leftIndent", 60.0);+ ui.end_row();+ });+ return;+ }+ head(ui, "Numbering");+ egui::Grid::new("fn_num").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Style:"));+ translated_combo(+ &app.ui.language,+ ui,+ d,+ "style",+ &[+ ("arabic", "1, 2, 3, 4..."),+ ("upperRoman", "I, II, III, IV..."),+ ("lowerRoman", "i, ii, iii, iv..."),+ ("upperLetters", "A, B, C, D..."),+ ("lowerLetters", "a, b, c, d..."),+ ("arabicLeadingZero", "01, 02, 03..."),+ ("symbols", "*, †, ‡, §..."),+ ("kanji", "一, 二, 三, 四..."),+ ],+ );+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Start at:"));+ text_field(ui, d, "startAt", 60.0);+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Restart Numbering Every:"));+ translated_combo(+ &app.ui.language,+ ui,+ d,+ "restart",+ &[("never", "Never (continuous)"), ("page", "Page"), ("spread", "Spread"), ("section", "Section")],+ );+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Show Prefix/Suffix in:"));+ translated_combo(+ &app.ui.language,+ ui,+ d,+ "affixIn",+ &[("none", "None"), ("reference", "Footnote Reference"), ("text", "Footnote Text"), ("both", "Both")],+ );+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Prefix:"));+ text_field(ui, d, "prefix", 60.0);+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Suffix:"));+ text_field(ui, d, "suffix", 60.0);+ ui.end_row();+ });+ head(ui, "Footnote Reference Number in Text");+ egui::Grid::new("fn_ref").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Position:"));+ translated_combo(+ &app.ui.language,+ ui,+ d,+ "refPosition",+ &[+ ("superscript", "Apply Superscript"),+ ("subscript", "Apply Subscript"),+ ("normal", "Apply Normal"),+ ("otSuperscript", "OpenType Superscript"),+ ],+ );+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Character Style:"));+ style_combo(app, ui, d, "refCharStyle", true);+ ui.end_row();+ });+ head(ui, "Footnote Formatting");+ egui::Grid::new("fn_fmt").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Paragraph Style:"));+ style_combo(app, ui, d, "paraStyle", false);+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Separator:"));+ text_field(ui, d, "separator", 60.0);+ ui.end_row();+ });+}++/// One parameter of a command, parsed from its params documentation+/// (`{name, type?: a|b|c, count?, flag?: bool, …}`).+#[derive(Clone, Debug, PartialEq)]+pub struct CommandField {+ pub key: String,+ pub optional: bool,+ /// Enumerated values (`a|b|c`).+ pub choices: Vec<String>,+ pub boolean: bool,+ /// The documented value spec (shown as a hint).+ pub hint: String,+}++/// Parameters of a command from its documentation string: the top-level keys of the first `{…}`.+pub fn command_fields(doc: &str) -> Vec<CommandField> {+ let Some(start) = doc.find('{') else { return vec![] };+ let mut depth = 0i32;+ let mut end = doc.len();+ for (i, c) in doc[start..].char_indices() {+ match c {+ '{' | '[' | '(' => depth += 1,+ '}' | ']' | ')' => {+ depth -= 1;+ if depth == 0 {+ end = start + i;+ break;+ }+ }+ _ => {}+ }+ }+ let body = &doc[start + 1..end];+ let mut parts = Vec::new();+ let (mut depth, mut from) = (0i32, 0usize);+ for (i, c) in body.char_indices() {+ match c {+ '{' | '[' | '(' => depth += 1,+ '}' | ']' | ')' => depth -= 1,+ ',' if depth == 0 => {+ parts.push(&body[from..i]);+ from = i + 1;+ }+ _ => {}+ }+ }+ parts.push(&body[from..]);+ let ident = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') && !s.starts_with(|c: char| c.is_ascii_digit());+ let mut out = Vec::new();+ for part in parts {+ // `key`, `key?`, `key: spec` or `key (spec)`: the key is the leading word.+ let part = part.trim();+ let k_end = part.find(|c: char| c.is_whitespace() || c == ':' || c == '(').unwrap_or(part.len());+ let (k, rest) = part.split_at(k_end);+ let rest = rest.trim_start();+ let spec = match rest.strip_prefix(':') {+ Some(v) => v.trim(),+ None => rest.strip_prefix('(').and_then(|r| r.strip_suffix(')')).unwrap_or(rest).trim(),+ };+ let optional = k.ends_with('?');+ let key = k.trim_end_matches('?');+ if !ident(key) || out.iter().any(|f: &CommandField| f.key == key) {+ continue;+ }+ let word = spec.split_whitespace().next().unwrap_or("");+ let choices: Vec<String> =+ if word.contains('|') && word.split('|').all(ident) { word.split('|').map(str::to_string).collect() } else { vec![] };+ let boolean = spec.starts_with("bool") || spec.starts_with("true|false") || spec.starts_with("true") && spec.len() <= 5;+ out.push(CommandField { key: key.into(), optional, choices: if boolean { vec![] } else { choices }, boolean, hint: spec.into() });+ }+ out+}++fn humanize(key: &str) -> String {+ let mut s = String::new();+ for (i, c) in key.chars().enumerate() {+ if i == 0 {+ s.extend(c.to_uppercase());+ } else if c.is_uppercase() {+ s.push(' ');+ s.extend(c.to_lowercase());+ } else {+ s.push(c);+ }+ }+ s+}++/// A form for any command, from its parameter documentation.+fn command_form(app: &crate::DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {+ let doc = designcraft_engine::find_command(&d.id[4..]).map_or("", |c| c.params);+ let fields = command_fields(doc);+ let dim = crate::theme::Tokens::get(ui.ctx()).text_dim;+ egui::Grid::new("cmdform").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ for f in &fields {+ ui.label(crate::rtl::widget(+ ui,+ format!("{}{}", crate::i18n::tr(&app.ui.language, &humanize(&f.key)), if f.optional { "" } else { " *" }),+ ));+ if f.boolean {+ check(ui, d, &f.key, "");+ } else if !f.choices.is_empty() {+ let mut opts: Vec<(&str, &str)> = vec![("", "—")];+ let labels: Vec<_> = f.choices.iter().map(|c| humanize(c)).collect();+ opts.extend(f.choices.iter().zip(&labels).map(|(value, label)| (value.as_str(), crate::i18n::tr(&app.ui.language, label))));+ combo(ui, d, &f.key, &opts);+ } else {+ let mut s = d.s(&f.key);+ let hint = if f.hint.is_empty() { String::new() } else { f.hint.clone() };+ if ui.add(egui::TextEdit::singleline(&mut s).hint_text(egui::RichText::new(hint).color(dim)).desired_width(240.0)).changed() {+ d.fields.insert(f.key.clone(), Value::String(s));+ }+ }+ ui.end_row();+ }+ });+ if let Some(st) = d.fields.get("status").and_then(Value::as_str) {+ ui.label(egui::RichText::new(st).color(crate::theme::Tokens::get(ui.ctx()).text_dim));+ }+}++/// New Cross-Reference: link to a paragraph (paragraph styles on the left, their paragraphs on+/// the right) or a text anchor, with a cross-reference format.+fn insert_xref(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {+ let Some(st) = app.session.active() else { return };+ let doc = &st.doc;+ let all = "[All Paragraphs]";+ ui.horizontal(|ui| {+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Link To:"));+ translated_combo(&app.ui.language, ui, d, "linkTo", &[("paragraph", "Paragraph"), ("anchor", "Text Anchor")]);+ });+ ui.add_space(6.0);+ let dim = crate::theme::Tokens::get(ui.ctx()).text_dim;+ if d.s("linkTo") == "anchor" {+ egui::ScrollArea::vertical().id_salt("xr_anchors").max_height(220.0).max_width(460.0).show(ui, |ui| {+ let mut any = false;+ for st in doc.stories.values() {+ for a in &st.anchors {+ any = true;+ let key = format!("a:{}", a.id);+ if ui.selectable_label(d.s("target") == key, &a.name).clicked() {+ d.fields.insert("target".into(), json!(key));+ }+ }+ }+ if !any {+ ui.label(crate::rtl::widget(+ ui,+ egui::RichText::new(crate::i18n::tr(&app.ui.language, "No text anchors in this document.")).color(dim),+ ));+ }+ });+ } else {+ let mut styles: Vec<String> = vec![all.to_string()];+ styles.extend(doc.styles.paragraph.iter().map(|s| s.name.clone()));+ let cur_style = if d.s("style").is_empty() { all.to_string() } else { d.s("style") };+ ui.horizontal_top(|ui| {+ let col = |w: f32| (egui::vec2(w, 240.0), egui::Layout::top_down(egui::Align::Min));+ let (sz, lay) = col(180.0);+ ui.allocate_ui_with_layout(sz, lay, |ui| {+ egui::ScrollArea::vertical().id_salt("xr_styles").auto_shrink([false, false]).show(ui, |ui| {+ for name in &styles {+ if ui.selectable_label(*name == cur_style, name).clicked() {+ d.fields.insert("style".into(), json!(name));+ }+ }+ })+ });+ ui.add_space(8.0);+ let (sz, lay) = col(330.0);+ ui.allocate_ui_with_layout(sz, lay, |ui| {+ egui::ScrollArea::vertical().id_salt("xr_paras").auto_shrink([false, false]).show(ui, |ui| {+ for st in doc.stories.values().filter(|s| !s.frames.is_empty()) {+ for (pi, r) in st.para_ranges().into_iter().enumerate() {+ if cur_style != all && st.paras[pi].style != cur_style {+ continue;+ }+ let text = designcraft_doc::xref::clean(&st.text[r]);+ if text.is_empty() {+ continue;+ }+ let short: String = text.chars().take(52).collect();+ let key = format!("{}:{pi}", st.id.0);+ if ui.selectable_label(d.s("target") == key, short).clicked() {+ d.fields.insert("target".into(), json!(key));+ }+ }+ }+ })+ });+ });+ }+ ui.add_space(8.0);+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Cross-Reference Format")).font(semibold(12.0)));+ let names: Vec<String> = doc.xref_formats.iter().map(|f| f.name.clone()).collect();+ if d.s("format").is_empty() {+ d.fields.insert("format".into(), json!(names.first().cloned().unwrap_or_default()));+ }+ let opts: Vec<(&str, &str)> = names.iter().map(|n| (n.as_str(), n.as_str())).collect();+ ui.horizontal(|ui| {+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Format:"));+ combo(ui, d, "format", &opts);+ });+ if let Some(m) = d.fields.get("status").and_then(Value::as_str) {+ ui.label(egui::RichText::new(m).color(dim));+ }+}++/// Color Picker: saturation/brightness field and hue slider, with RGB, CMYK and hex fields.+fn color_picker(ui: &mut egui::Ui, d: &mut Dialog) {+ let hex = d.s("hex");+ let mut c = designcraft_color::Color::from_hex(&hex).map(|c| c.to_rgb()).map_or(egui::Color32::BLACK, |[r, g, b]| {+ egui::Color32::from_rgb((r * 255.0).round() as u8, (g * 255.0).round() as u8, (b * 255.0).round() as u8)+ });+ let before = c;+ ui.horizontal_top(|ui| {+ egui::color_picker::color_picker_color32(ui, &mut c, egui::color_picker::Alpha::Opaque);+ ui.vertical(|ui| {+ let mut rgb = [c.r() as f32, c.g() as f32, c.b() as f32];+ egui::Grid::new("cp_rgb").num_columns(2).spacing([6.0, 4.0]).show(ui, |ui| {+ for (k, l) in ["R", "G", "B"].iter().enumerate() {+ ui.label(*l);+ ui.add(egui::DragValue::new(&mut rgb[k]).range(0.0..=255.0));+ ui.end_row();+ }+ });+ c = egui::Color32::from_rgb(rgb[0] as u8, rgb[1] as u8, rgb[2] as u8);+ let col = designcraft_color::Color::rgb8(c.r(), c.g(), c.b());+ let [cc, m, y, k] = col.to_cmyk();+ ui.add_space(6.0);+ ui.label(format!("C {:.0}% M {:.0}% Y {:.0}% K {:.0}%", cc * 100.0, m * 100.0, y * 100.0, k * 100.0));+ ui.add_space(6.0);+ ui.horizontal(|ui| {+ ui.label("#");+ let mut h = format!("{:02x}{:02x}{:02x}", c.r(), c.g(), c.b());+ if ui.add(egui::TextEdit::singleline(&mut h).desired_width(70.0)).changed()+ && let Some(n) = designcraft_color::Color::from_hex(&h)+ {+ let [r, g, b] = n.to_rgb();+ c = egui::Color32::from_rgb((r * 255.0).round() as u8, (g * 255.0).round() as u8, (b * 255.0).round() as u8);+ }+ });+ });+ });+ if c != before {+ d.fields.insert("hex".into(), json!(format!("#{:02x}{:02x}{:02x}", c.r(), c.g(), c.b())));+ }+}++/// Find/Replace Font: the document's fonts (missing ones first, flagged) and a replacement.+fn find_font(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {+ // Listed once when the dialog opens (it scans every story).+ if !d.fields.contains_key("_fonts") {+ let list = app.session.execute("font.list", &json!({})).unwrap_or_default();+ d.fields.insert("_fonts".into(), list);+ }+ let fonts = d.fields.get("_fonts").and_then(Value::as_array).cloned().unwrap_or_default();+ if !fonts.iter().any(|font| font["family"] == d.s("family") && font["style"] == d.s("style"))+ && let Some(font) = fonts.first()+ {+ d.fields.insert("family".into(), font["family"].clone());+ d.fields.insert("style".into(), font["style"].clone());+ }+ if d.b("onOpen") && fonts.iter().any(|f| f["missing"] == true || f["styleMissing"] == true) {+ crate::rtl::label(ui,- d,- "affixIn",- &[("none", "None"), ("reference", "Footnote Reference"), ("text", "Footnote Text"), ("both", "Both")],+ crate::i18n::tr(+ &app.ui.language,+ "This document uses unavailable fonts. Choose replacements, or select Done to continue with fallback fonts.",+ ),);- ui.end_row();- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Prefix:"));- text_field(ui, d, "prefix", 60.0);- ui.end_row();- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Suffix:"));- text_field(ui, d, "suffix", 60.0);- ui.end_row();+ }+ if !d.s("error").is_empty() {+ crate::rtl::label(ui, d.s("error"));+ }+ let missing = fonts.iter().filter(|f| f["missing"] == true || f["styleMissing"] == true).count();+ crate::rtl::label(+ ui,+ crate::i18n::tr(&app.ui.language, "Fonts in Document: {count} Missing: {missing}")+ .replace("{count}", &fonts.len().to_string())+ .replace("{missing}", &missing.to_string()),+ );+ egui::ScrollArea::vertical().id_salt("ff_list").max_height(180.0).show(ui, |ui| {+ for f in &fonts {+ let (fam, st) = (f["family"].as_str().unwrap_or(""), f["style"].as_str().unwrap_or(""));+ let warn = f["missing"] == true || f["styleMissing"] == true;+ let label = format!("{}{fam} {st}", if warn { "\u{26A0} " } else { "" });+ let on = d.s("family") == fam && d.s("style") == st;+ let mut text = egui::RichText::new(label);+ if warn && !on {+ text = text.color(crate::theme::Tokens::get(ui.ctx()).text_strong);+ }+ if ui.selectable_label(on, text).clicked() {+ d.fields.insert("family".into(), json!(fam));+ d.fields.insert("style".into(), json!(st));+ }+ }});- head(ui, "Footnote Reference Number in Text");- egui::Grid::new("fn_ref").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Position:"));- translated_combo(- &app.ui.language,+ let key = format!("{}\n{}", d.s("family"), d.s("style"));+ if let Some(font) = fonts.iter().find(|f| f["family"] == d.s("family") && f["style"] == d.s("style")) {+ if d.s("_fontKey") != key {+ d.fields.insert("_fontKey".into(), json!(key));+ d.fields.insert("toFamily".into(), font["replacementFamily"].clone());+ d.fields.insert("toStyle".into(), font["replacementStyle"].clone());+ }+ crate::rtl::label(ui,- d,- "refPosition",- &[- ("superscript", "Apply Superscript"),- ("subscript", "Apply Subscript"),- ("normal", "Apply Normal"),- ("otSuperscript", "OpenType Superscript"),- ],+ format!(+ "{}: {} {}",+ crate::i18n::tr(&app.ui.language, "Currently Rendered With"),+ font["resolvedFamily"].as_str().unwrap_or(""),+ font["resolvedStyle"].as_str().unwrap_or("")+ ),);+ }+ ui.add_space(8.0);+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Replace With")).font(semibold(12.0)));+ let db = crate::panels::fonts(app);+ if d.s("toFamily").is_empty() {+ d.fields.insert("toFamily".into(), json!(designcraft_fonts::FALLBACK_FAMILY));+ }+ egui::Grid::new("ff_to").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Font Family:"));+ if let Some(f) = crate::panels::font_combo(app, ui, "toFamily", &d.s("toFamily"), 170.0) {+ d.fields.insert("toFamily".into(), json!(f));+ }ui.end_row();- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Character Style:"));- style_combo(app, ui, d, "refCharStyle", true);- ui.end_row();- });- head(ui, "Footnote Formatting");- egui::Grid::new("fn_fmt").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Paragraph Style:"));- style_combo(app, ui, d, "paraStyle", false);- ui.end_row();- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Separator:"));- text_field(ui, d, "separator", 60.0);+ let styles = db.styles(&d.s("toFamily"));+ if !styles.iter().any(|style| style == &d.s("toStyle")) {+ let preferred = d.s("style");+ let style = styles+ .iter()+ .find(|s| s.eq_ignore_ascii_case(&preferred))+ .or_else(|| styles.iter().find(|s| s.eq_ignore_ascii_case("Regular")))+ .or_else(|| styles.first());+ if let Some(style) = style {+ d.fields.insert("toStyle".into(), json!(style));+ }+ }+ let st_opts: Vec<(&str, &str)> = styles.iter().map(|s| (s.as_str(), s.as_str())).collect();+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Font Style:"));+ combo(ui, d, "toStyle", &st_opts);ui.end_row();});+ ui.label(crate::rtl::widget(+ ui,+ egui::RichText::new(crate::i18n::tr(+ &app.ui.language,+ "Replace All updates this font throughout text and styles. Done keeps remaining fallback fonts.",+ ))+ .color(crate::theme::Tokens::get(ui.ctx()).text_dim)+ .size(11.0),+ ));}-/// One parameter of a command, parsed from its params documentation-/// (`{name, type?: a|b|c, count?, flag?: bool, …}`).-#[derive(Clone, Debug, PartialEq)]-pub struct CommandField {- pub key: String,- pub optional: bool,- /// Enumerated values (`a|b|c`).- pub choices: Vec<String>,- pub boolean: bool,- /// The documented value spec (shown as a hint).- pub hint: String,-}+#[cfg(test)]+mod tests {+ use super::*;-/// Parameters of a command from its documentation string: the top-level keys of the first `{…}`.-pub fn command_fields(doc: &str) -> Vec<CommandField> {- let Some(start) = doc.find('{') else { return vec![] };- let mut depth = 0i32;- let mut end = doc.len();- for (i, c) in doc[start..].char_indices() {- match c {- '{' | '[' | '(' => depth += 1,- '}' | ']' | ')' => {- depth -= 1;- if depth == 0 {- end = start + i;- break;- }- }- _ => {}- }++ /// A three-page document in `units` with Document Setup open.++ fn document_setup_app(units: &str) -> DesignApp {++ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());++ app.run("file.new", json!({"pages": 3})).unwrap();++ app.run("document.preferences", json!({"horizontalUnits": units, "verticalUnits": units})).unwrap();++ crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null);++ app+ }- let body = &doc[start + 1..end];- let mut parts = Vec::new();- let (mut depth, mut from) = (0i32, 0usize);- for (i, c) in body.char_indices() {- match c {- '{' | '[' | '(' => depth += 1,- '}' | ']' | ')' => depth -= 1,- ',' if depth == 0 => {- parts.push(&body[from..i]);- from = i + 1;- }- _ => {}++++ fn setup_fields(app: &mut DesignApp, fields: Value) {++ let d = app.ui.dialog.as_mut().unwrap();++ for (k, v) in fields.as_object().unwrap() {++ d.fields.insert(k.clone(), v.clone());+ }+ }- parts.push(&body[from..]);- let ident = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') && !s.starts_with(|c: char| c.is_ascii_digit());- let mut out = Vec::new();- for part in parts {- // `key`, `key?`, `key: spec` or `key (spec)`: the key is the leading word.- let part = part.trim();- let k_end = part.find(|c: char| c.is_whitespace() || c == ':' || c == '(').unwrap_or(part.len());- let (k, rest) = part.split_at(k_end);- let rest = rest.trim_start();- let spec = match rest.strip_prefix(':') {- Some(v) => v.trim(),- None => rest.strip_prefix('(').and_then(|r| r.strip_suffix(')')).unwrap_or(rest).trim(),- };- let optional = k.ends_with('?');- let key = k.trim_end_matches('?');- if !ident(key) || out.iter().any(|f: &CommandField| f.key == key) {- continue;++++ #[test]++ fn document_setup_ok_applies_margins_bleed_and_size_in_one_step() {++ let mut app = document_setup_app("millimeters");++ let d = app.ui.dialog.as_ref().unwrap();++ assert_eq!(d.id, "documentSetup");++ assert_eq!((d.s("marginTop"), d.b("marginLinked")), ("12.7 mm".to_string(), true), "the document's margins, in its units");++ setup_fields(++ &mut app,++ json!({"marginTop": "20 mm", "marginBottom": "20 mm", "marginInside": "20 mm", "marginOutside": "20 mm", "bleedTop": "3 mm",++ "bleedBottom": "3 mm", "bleedInside": "3 mm", "bleedOutside": "3 mm", "width": "210 mm", "height": "297 mm"}),++ );++ confirm(&mut app).unwrap();++ assert!(app.ui.dialog.is_none());++ let mm = designcraft_geom::units::PT_PER_MM;++ let doc = &app.session.active().unwrap().doc;++ assert!((doc.settings.page_width - 210.0 * mm).abs() < 1e-6 && (doc.settings.bleed[2] - 3.0 * mm).abs() < 1e-6);++ assert!(doc.spreads.iter().flat_map(|s| &s.pages).all(|p| (p.margins.top - 20.0 * mm).abs() < 1e-6), "every page");++ app.run("edit.undo", json!({})).unwrap();++ let doc = &app.session.active().unwrap().doc;++ assert!((doc.settings.page_width - 612.0).abs() < 1e-6 && doc.settings.bleed[0] == 0.0, "one undo step");++ }++++ #[test]++ fn document_setup_keeps_each_pages_margins_unless_they_are_edited() {++ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());++ app.run("file.new", json!({"pages": 3, "margins": 36})).unwrap();++ app.run("layout.marginsAndColumns", json!({"pages": [1], "margins": 90})).unwrap();++ let margins =++ |app: &DesignApp| app.session.active().unwrap().doc.spreads.iter().flat_map(|s| &s.pages).map(|p| p.margins.top).collect::<Vec<_>>();++ // Only the page count changes: every page keeps its own margins.++ crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null);++ setup_fields(&mut app, json!({"pages": "4"}));++ confirm(&mut app).unwrap();++ assert_eq!(margins(&app), [36.0, 90.0, 36.0, 36.0]);++ // Edited margins go to every page.++ crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null);++ setup_fields(&mut app, json!({"marginTop": "1p0"}));++ confirm(&mut app).unwrap();++ assert_eq!(margins(&app), [12.0; 4]);++ }++++ #[test]++ fn document_setup_keeps_a_value_it_cannot_read_and_changes_nothing() {++ for (key, value) in [("width", "wide"), ("marginTop", "-"), ("pages", "0"), ("bleedTop", "x")] {++ let mut app = document_setup_app("points");++ setup_fields(&mut app, json!({key: value, "bleedInside": "9"}));++ assert!(confirm(&mut app).is_err(), "{key}");++ assert!(app.ui.dialog.is_some(), "{key}: the dialog stays open");++ assert_eq!(app.session.active().unwrap().doc.settings.bleed, [0.0; 4], "{key}: nothing changed");+ }- let word = spec.split_whitespace().next().unwrap_or("");- let choices: Vec<String> =- if word.contains('|') && word.split('|').all(ident) { word.split('|').map(str::to_string).collect() } else { vec![] };- let boolean = spec.starts_with("bool") || spec.starts_with("true|false") || spec.starts_with("true") && spec.len() <= 5;- out.push(CommandField { key: key.into(), optional, choices: if boolean { vec![] } else { choices }, boolean, hint: spec.into() });+ }- out-}+-fn humanize(key: &str) -> String {- let mut s = String::new();- for (i, c) in key.chars().enumerate() {- if i == 0 {- s.extend(c.to_uppercase());- } else if c.is_uppercase() {- s.push(' ');- s.extend(c.to_lowercase());- } else {- s.push(c);++ #[test]++ fn document_setup_links_edges_and_adjust_layout_applies() {++ let mut app = document_setup_app("points");++ let f = app.run("frame.create", json!({"rect": [36, 36, 576, 756], "content": "text"})).unwrap();++ crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null);++ let ctx = dialog_context("en");++ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 900.0));++ for _ in 0..3 {++ dialog_frame(&mut app, &ctx, screen, vec![]);+ }++ // Typing in a linked margin sets all four.++ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);++ let top = labels.iter().filter(|(t, _, _)| t == "36 pt").map(|(_, r, _)| *r).next().expect("the top margin");++ click_dialog(&mut app, &ctx, screen, top.center());++ let select_all =++ egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND };++ dialog_frame(&mut app, &ctx, screen, vec![select_all, egui::Event::Text("72 pt".into())]);++ dialog_frame(&mut app, &ctx, screen, vec![]);++ let d = app.ui.dialog.as_ref().unwrap();++ assert!(["Top", "Bottom", "Inside", "Outside"].iter().all(|e| d.s(&format!("margin{e}")) == "72 pt"), "linked: {:?}", d.fields);++ // Adjust Layout applies at once, and the frame follows the margins.++ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);++ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "Adjust Layout").center());++ assert!(app.ui.dialog.is_none(), "applied");++ let doc = &app.session.active().unwrap().doc;++ let b = doc.item(designcraft_doc::ItemId(f["id"].as_u64().unwrap())).unwrap().bounds();++ assert!((b.y0 - 72.0).abs() < 1e-6 && doc.page(0).unwrap().margins.outside == 72.0, "{b:?}");++ }+++ #[test]+ fn cell_options_dialog_draws_and_applies_only_changed_values_to_the_chosen_edges() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();+ let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();+ app.run("table.select", json!({"what": "table"})).unwrap();+ app.run("app.cellOptionsDialog", json!({})).unwrap();+ let ctx = dialog_context("");+ dialog_frame(&mut app, &ctx, egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0)), vec![]);+ let d = app.ui.dialog.as_mut().unwrap();+ assert_eq!(d.id, "cellOptions");+ assert_eq!(d.fields["weight"], json!(1.0));+ d.fields.insert("edges".into(), json!(["top", "bottom", "left", "right"]));+ d.fields.insert("gapColor".into(), json!("[Paper]"));+ d.fields.insert("fill".into(), json!("[Black]"));+ d.fields.insert("fillTint".into(), json!(0.2));+ confirm(&mut app).unwrap();+ let st = app.session.active().unwrap();+ let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap();+ let gap = |r: usize, c: usize, side: usize| t.cell(r, c).unwrap().strokes[side].gap_color.clone();+ assert_eq!([gap(0, 0, 0), gap(0, 0, 1), gap(1, 1, 2), gap(1, 1, 3)], ["[Paper]"; 4].map(String::from), "outer edges");+ assert_eq!([gap(0, 0, 2), gap(0, 0, 3)], ["[None]"; 2].map(String::from), "inner edges keep theirs");+ assert!(t.cells.iter().all(|c| c.fill == "[Black]" && (c.fill_tint - 0.2).abs() < 1e-6));+ assert!(t.cells.iter().all(|c| c.strokes.iter().all(|e| e.weight == 1.0)), "unchanged values are not applied");+ }++ #[test]+ fn cell_options_edge_changes_reseed_every_stroke_field_and_survive_a_bad_seed() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();+ let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();+ app.run("table.select", json!({"what": "table"})).unwrap();+ app.run("table.setCell", json!({"stroke": {"weight": 3, "edges": "innerHorizontal"}})).unwrap();+ app.run("app.cellOptionsDialog", json!({})).unwrap();+ let mut d = app.ui.dialog.take().unwrap();+ d.fields.insert("seed".into(), json!(5));+ let outer = [true, true, true, true, false, false];+ cell_options_edges_changed(&mut app, &mut d, &outer);+ assert_eq!((&d.fields["weight"], &d.fields["seed"]["weight"]), (&json!(1.0), &json!(1.0)));+ // A weight typed for the outer edges, then the inner horizontal edges (3 pt) chosen+ // and 1 pt typed: 1 pt differs from what those edges show, so OK applies it.+ d.fields.insert("weight".into(), json!(5.0));+ cell_options_edges_changed(&mut app, &mut d, &[false, false, false, false, true, false]);+ assert_eq!((&d.fields["weight"], &d.fields["seed"]["weight"]), (&json!(5.0), &json!(3.0)));+ d.fields.insert("weight".into(), json!(1.0));+ app.ui.dialog = Some(d);+ confirm(&mut app).unwrap();+ let st = app.session.active().unwrap();+ let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap();+ assert_eq!([t.cell(0, 0).unwrap().strokes[2].weight, t.cell(1, 1).unwrap().strokes[0].weight], [1.0; 2]);}- s-}-/// A form for any command, from its parameter documentation.-fn command_form(app: &crate::DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {- let doc = designcraft_engine::find_command(&d.id[4..]).map_or("", |c| c.params);- let fields = command_fields(doc);- let dim = crate::theme::Tokens::get(ui.ctx()).text_dim;- egui::Grid::new("cmdform").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {- for f in &fields {- ui.label(crate::rtl::widget(- ui,- format!("{}{}", crate::i18n::tr(&app.ui.language, &humanize(&f.key)), if f.optional { "" } else { " *" }),- ));- if f.boolean {- check(ui, d, &f.key, "");- } else if !f.choices.is_empty() {- let mut opts: Vec<(&str, &str)> = vec![("", "—")];- let labels: Vec<_> = f.choices.iter().map(|c| humanize(c)).collect();- opts.extend(f.choices.iter().zip(&labels).map(|(value, label)| (value.as_str(), crate::i18n::tr(&app.ui.language, label))));- combo(ui, d, &f.key, &opts);- } else {- let mut s = d.s(&f.key);- let hint = if f.hint.is_empty() { String::new() } else { f.hint.clone() };- if ui.add(egui::TextEdit::singleline(&mut s).hint_text(egui::RichText::new(hint).color(dim)).desired_width(240.0)).changed() {- d.fields.insert(f.key.clone(), Value::String(s));+ #[test]+ fn numbering_and_section_options_keep_their_actions_in_view() {+ for language in ["en", "ar"] {+ for size in [egui::vec2(1178.0, 814.0), egui::vec2(392.0, 271.0)] {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.ui.language = language.into();+ app.run("file.new", json!({"pages": 2})).unwrap();+ crate::menus::activate(&mut app, "layout.section", &Value::Null);+ let ctx = dialog_context(language);+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size);+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let tr = |s| crate::i18n::tr(language, s);+ for expected in [tr("Numbering & Section Options…").trim_end_matches('…'), tr("OK"), tr("Cancel"), tr("Start Section")] {+ visible_label(&labels, screen, expected);+ }+ if size.x > 1000.0 {+ // Every option fits without scrolling, and choosing one then OK applies it.+ visible_label(&labels, screen, &format!("{} {}", tr("Book Name:"), tr("N/A")));+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, tr("Automatic Page Numbering")).center());+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, tr("OK")).center());+ assert!(app.ui.dialog.is_none(), "{language}: OK closes the dialog");+ let doc = &app.session.active().unwrap().doc;+ assert!(doc.sections.iter().all(|s| s.start != 0 || s.start_number.is_none()), "{language}: page 1 numbers automatically");}}- ui.end_row();}- });- if let Some(st) = d.fields.get("status").and_then(Value::as_str) {- ui.label(egui::RichText::new(st).color(crate::theme::Tokens::get(ui.ctx()).text_dim));}-}-/// New Cross-Reference: link to a paragraph (paragraph styles on the left, their paragraphs on-/// the right) or a text anchor, with a cross-reference format.-fn insert_xref(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {- let Some(st) = app.session.active() else { return };- let doc = &st.doc;- let all = "[All Paragraphs]";- ui.horizontal(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Link To:"));- combo(ui, d, "linkTo", &[("paragraph", "Paragraph"), ("anchor", "Text Anchor")]);- });- ui.add_space(6.0);- let dim = crate::theme::Tokens::get(ui.ctx()).text_dim;- if d.s("linkTo") == "anchor" {- egui::ScrollArea::vertical().id_salt("xr_anchors").max_height(220.0).max_width(460.0).show(ui, |ui| {- let mut any = false;- for st in doc.stories.values() {- for a in &st.anchors {- any = true;- let key = format!("a:{}", a.id);- if ui.selectable_label(d.s("target") == key, &a.name).clicked() {- d.fields.insert("target".into(), json!(key));- }- }- }- if !any {- ui.label(crate::rtl::widget(- ui,- egui::RichText::new(crate::i18n::tr(&app.ui.language, "No text anchors in this document.")).color(dim),- ));- }- });- } else {- let mut styles: Vec<String> = vec![all.to_string()];- styles.extend(doc.styles.paragraph.iter().map(|s| s.name.clone()));- let cur_style = if d.s("style").is_empty() { all.to_string() } else { d.s("style") };- ui.horizontal_top(|ui| {- let col = |w: f32| (egui::vec2(w, 240.0), egui::Layout::top_down(egui::Align::Min));- let (sz, lay) = col(180.0);- ui.allocate_ui_with_layout(sz, lay, |ui| {- egui::ScrollArea::vertical().id_salt("xr_styles").auto_shrink([false, false]).show(ui, |ui| {- for name in &styles {- if ui.selectable_label(*name == cur_style, name).clicked() {- d.fields.insert("style".into(), json!(name));- }- }- })- });- ui.add_space(8.0);- let (sz, lay) = col(330.0);- ui.allocate_ui_with_layout(sz, lay, |ui| {- egui::ScrollArea::vertical().id_salt("xr_paras").auto_shrink([false, false]).show(ui, |ui| {- for st in doc.stories.values().filter(|s| !s.frames.is_empty()) {- for (pi, r) in st.para_ranges().into_iter().enumerate() {- if cur_style != all && st.paras[pi].style != cur_style {- continue;- }- let text = designcraft_doc::xref::clean(&st.text[r]);- if text.is_empty() {- continue;- }- let short: String = text.chars().take(52).collect();- let key = format!("{}:{pi}", st.id.0);- if ui.selectable_label(d.s("target") == key, short).clicked() {- d.fields.insert("target".into(), json!(key));- }- }- }- })- });+ fn draw(app: &mut DesignApp, ctx: &egui::Context) {+ let input =+ egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);});+ out.textures_delta.clear();}- ui.add_space(8.0);- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Cross-Reference Format")).font(semibold(12.0)));- let names: Vec<String> = doc.xref_formats.iter().map(|f| f.name.clone()).collect();- if d.s("format").is_empty() {- d.fields.insert("format".into(), json!(names.first().cloned().unwrap_or_default()));++ /// A paragraph styled "Ruled Child", whose Rule Below comes from its parent "Ruled".+ fn ruled_paragraph() -> (DesignApp, Value) {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let rule = json!({"on": true, "weight": 3.0, "color": "[Black]", "tint": 0.5, "columnWidth": false, "offset": 4.0, "leftIndent": 6.0, "rightIndent": 2.0});+ app.run("style.paragraph.create", json!({"name": "Ruled", "para": {"ruleBelow": rule}})).unwrap();+ app.run("style.paragraph.create", json!({"name": "Ruled Child", "basedOn": "Ruled"})).unwrap();+ let r = app.run("frame.create", json!({"rect": [72, 72, 300, 400], "content": "text", "text": "One"})).unwrap();+ app.run("text.select", json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();+ app.run("style.paragraph.apply", json!({"name": "Ruled Child"})).unwrap();+ (app, rule)}- let opts: Vec<(&str, &str)> = names.iter().map(|n| (n.as_str(), n.as_str())).collect();- ui.horizontal(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Format:"));- combo(ui, d, "format", &opts);- });- if let Some(m) = d.fields.get("status").and_then(Value::as_str) {- ui.label(egui::RichText::new(m).color(dim));++ fn undo_steps(app: &DesignApp) -> usize {+ app.session.doc().map_or(0, |st| st.history.undo.len())}-}-/// Color Picker: saturation/brightness field and hue slider, with RGB, CMYK and hex fields.-fn color_picker(ui: &mut egui::Ui, d: &mut Dialog) {- let hex = d.s("hex");- let mut c = designcraft_color::Color::from_hex(&hex).map(|c| c.to_rgb()).map_or(egui::Color32::BLACK, |[r, g, b]| {- egui::Color32::from_rgb((r * 255.0).round() as u8, (g * 255.0).round() as u8, (b * 255.0).round() as u8)- });- let before = c;- ui.horizontal_top(|ui| {- egui::color_picker::color_picker_color32(ui, &mut c, egui::color_picker::Alpha::Opaque);- ui.vertical(|ui| {- let mut rgb = [c.r() as f32, c.g() as f32, c.b() as f32];- egui::Grid::new("cp_rgb").num_columns(2).spacing([6.0, 4.0]).show(ui, |ui| {- for (k, l) in ["R", "G", "B"].iter().enumerate() {- ui.label(*l);- ui.add(egui::DragValue::new(&mut rgb[k]).range(0.0..=255.0));- ui.end_row();- }- });- c = egui::Color32::from_rgb(rgb[0] as u8, rgb[1] as u8, rgb[2] as u8);- let col = designcraft_color::Color::rgb8(c.r(), c.g(), c.b());- let [cc, m, y, k] = col.to_cmyk();- ui.add_space(6.0);- ui.label(format!("C {:.0}% M {:.0}% Y {:.0}% K {:.0}%", cc * 100.0, m * 100.0, y * 100.0, k * 100.0));- ui.add_space(6.0);- ui.horizontal(|ui| {- ui.label("#");- let mut h = format!("{:02x}{:02x}{:02x}", c.r(), c.g(), c.b());- if ui.add(egui::TextEdit::singleline(&mut h).desired_width(70.0)).changed()- && let Some(n) = designcraft_color::Color::from_hex(&h)- {- let [r, g, b] = n.to_rgb();- c = egui::Color32::from_rgb((r * 255.0).round() as u8, (g * 255.0).round() as u8, (b * 255.0).round() as u8);- }- });- });- });- if c != before {- d.fields.insert("hex".into(), json!(format!("#{:02x}{:02x}{:02x}", c.r(), c.g(), c.b())));+ #[test]+ fn paragraph_rules_dialog_shows_the_rule_and_applies_one_field() {+ let (mut app, rule) = ruled_paragraph();+ let ctx = egui::Context::default();+ app.run("app.paragraphRulesDialog", json!({"rule": "ruleBelow"})).unwrap();+ draw(&mut app, &ctx);+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!(d.id, "paragraphRules");+ let current = d.fields["current"].clone();+ assert_eq!(shown_rule(&d, "", "ruleBelow", ¤t), rule, "the inherited rule");+ assert_eq!(shown_rule(&d, "", "ruleAbove", ¤t)["on"], false);+ // Pick a colour, as the Color menu does.+ app.ui.dialog.as_mut().unwrap().fields.insert("ruleBelow.color".into(), json!("[Registration]"));+ draw(&mut app, &ctx);+ let before = undo_steps(&app);+ confirm(&mut app).unwrap();+ assert_eq!(undo_steps(&app), before + 1, "one undo step");+ let mut want = rule.clone();+ want["color"] = json!("[Registration]");+ assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], want);+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], rule);+ }++ #[test]+ fn paragraph_style_options_edit_one_rule_field() {+ let (mut app, rule) = ruled_paragraph();+ let ctx = egui::Context::default();+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "rules", "rule": "ruleBelow"})));+ draw(&mut app, &ctx);+ let resolved = |app: &DesignApp| serde_json::to_value(app.session.doc().unwrap().doc.styles.resolve_para_style("Ruled Child").0).unwrap();+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!(shown_rule(&d, "p.", "ruleBelow", &resolved(&app)), rule, "inherited from the parent style");+ app.ui.dialog.as_mut().unwrap().fields.insert("p.ruleBelow.weight".into(), json!(1.5));+ draw(&mut app, &ctx);+ let before = undo_steps(&app);+ confirm(&mut app).unwrap();+ assert_eq!(undo_steps(&app), before + 1, "one undo step");+ let mut want = rule.clone();+ want["weight"] = json!(1.5);+ assert_eq!(resolved(&app)["ruleBelow"], want);+ assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], want, "the paragraph follows its style");+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(resolved(&app)["ruleBelow"], rule);+ }++ /// Opens Paragraph Style Options on "Ruled Child" at each of `sections`, sets `fields` and+ /// clicks OK; returns the resolved attributes of the paragraph styled with it.+ fn style_section_edit(sections: &[&str], fields: Value) -> Value {+ let (mut app, _) = ruled_paragraph();+ let ctx = egui::Context::default();+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child"})));+ for section in sections {+ app.ui.dialog.as_mut().unwrap().fields.insert("section".into(), json!(section));+ draw(&mut app, &ctx);+ }+ for (k, v) in fields.as_object().unwrap() {+ app.ui.dialog.as_mut().unwrap().fields.insert(k.clone(), v.clone());+ }+ draw(&mut app, &ctx);+ let before = undo_steps(&app);+ confirm(&mut app).unwrap();+ assert_eq!(undo_steps(&app), before + 1, "one undo step");+ let style = app.session.doc().unwrap().doc.styles.para("Ruled Child").cloned().unwrap();+ let own = serde_json::to_value(&style.para).unwrap();+ for (k, v) in fields.as_object().unwrap() {+ assert_eq!(own[k.trim_start_matches("p.")], *v, "the style sets {k}");+ }+ app.run("type.selectionAttrs", json!({})).unwrap()["para"].clone()+ }++ #[test]+ fn paragraph_style_options_keep_and_border_sections_reach_the_styled_paragraph() {+ let para = style_section_edit(+ &["keep", "border"],+ json!({"p.keepWithNext": 2, "p.keepLinesTogether": true, "p.keepAllLines": false, "p.keepFirst": 3,+ "p.startParagraph": "nextPage", "p.borderOn": true, "p.borderWeights": [2.0, 0.0, 2.0, 0.0]}),+ );+ assert_eq!(para["keepWithNext"], 2);+ assert_eq!(para["keepLinesTogether"], true);+ assert_eq!(para["keepAllLines"], false);+ assert_eq!(para["keepFirst"], 3);+ assert_eq!(para["startParagraph"], "nextPage");+ assert_eq!(para["borderOn"], true);+ assert_eq!(para["borderWeights"], json!([2.0, 0.0, 2.0, 0.0]));+ // Fields not edited keep the resolved value.+ assert_eq!(para["keepLast"], 2);+ assert_eq!(para["ruleBelow"]["weight"], 3.0);+ }++ #[test]+ fn paragraph_style_options_bullets_and_span_sections_reach_the_styled_paragraph() {+ let para = style_section_edit(+ &["bullets", "span"],+ json!({"p.listType": "numbers", "p.numberStyle": "upperRoman", "p.numberExpression": "^#)^t", "p.startAt": 3,+ "p.spanColumns": {"kind": "split", "columns": 3}}),+ );+ assert_eq!(para["listType"], "numbers");+ assert_eq!(para["numberStyle"], "upperRoman");+ assert_eq!(para["numberExpression"], "^#)^t");+ assert_eq!(para["startAt"], 3);+ assert_eq!(para["spanColumns"], json!({"kind": "split", "columns": 3}));+ let props: designcraft_doc::ParaProps = serde_json::from_value(para).unwrap();+ assert_eq!(props.number_label(3), "III)\t");+ }++ #[test]+ fn paragraph_style_options_keep_a_bad_grep_pattern_open_with_the_error() {+ let (mut app, _) = ruled_paragraph();+ let ctx = egui::Context::default();+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled", "section": "general"})));+ draw(&mut app, &ctx);+ app.ui.dialog.as_mut().unwrap().fields.insert("p.grepStyles".into(), json!([{"style": "[None]", "pattern": "(?<=x"}]));+ let e = confirm(&mut app).unwrap_err();+ assert!(e.contains("bad GREP"), "{e}");+ let d = app.ui.dialog.clone().expect("the dialog stays open");+ assert_eq!((d.s("section").as_str(), d.s("status").contains("bad GREP")), ("grep", true));+ assert!(app.session.doc().unwrap().doc.styles.para("Ruled").unwrap().para.grep_styles.is_none(), "nothing saved");+ draw(&mut app, &ctx);}-}-/// Find/Replace Font: the document's fonts (missing ones first, flagged) and a replacement.-fn find_font(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {- // Listed once when the dialog opens (it scans every story).- if !d.fields.contains_key("_fonts") {- let list = app.session.execute("font.list", &json!({})).unwrap_or_default();- d.fields.insert("_fonts".into(), list);+ fn command_app(id: &str, fields: Value) -> DesignApp {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.ui.dialog = Some(Dialog::new(&format!("cmd:{id}"), fields));+ app}- let fonts = d.fields.get("_fonts").and_then(Value::as_array).cloned().unwrap_or_default();- let missing = fonts.iter().filter(|f| f["missing"] == true || f["styleMissing"] == true).count();- crate::rtl::label(- ui,- crate::i18n::tr(&app.ui.language, "Fonts in Document: {count} Missing: {missing}")- .replace("{count}", &fonts.len().to_string())- .replace("{missing}", &missing.to_string()),- );- egui::ScrollArea::vertical().id_salt("ff_list").max_height(180.0).show(ui, |ui| {- for f in &fonts {- let (fam, st) = (f["family"].as_str().unwrap_or(""), f["style"].as_str().unwrap_or(""));- let warn = f["missing"] == true || f["styleMissing"] == true;- let label = format!("{}{fam} {st}", if warn { "\u{26A0} " } else { "" });- let on = d.s("family") == fam && d.s("style") == st;- let mut text = egui::RichText::new(label);- if warn {- text = text.color(egui::Color32::from_rgb(0xe5, 0x4b, 0x4b));- }- if ui.selectable_label(on, text).clicked() {- d.fields.insert("family".into(), json!(fam));- d.fields.insert("style".into(), json!(st));++ #[test]+ fn generic_new_document_preserves_typed_values_and_text_entry() {+ for pages in [json!(2), json!(" 2 ")] {+ let mut app = command_app(+ "file.new",+ json!({+ "preset": "A4", "pages": pages, "facingPages": false, "gutter": 0,+ "margins": {"top": 10, "bottom": 20, "inside": 30, "outside": 40},+ "title": " ", "status": "internal", "primaryTextFrame": true+ }),+ );+ confirm(&mut app).unwrap();+ let doc = &app.session.active().unwrap().doc;+ assert_eq!(doc.page_count(), 2);+ assert!(!doc.settings.facing_pages);+ assert!(doc.title.starts_with("Untitled-"));+ for page in doc.spreads.iter().flat_map(|s| &s.pages) {+ assert!((page.width - 595.2755905511812).abs() < 0.01);+ assert!((page.height - 841.8897637795277).abs() < 0.01);+ assert_eq!(page.columns.gutter, 0.0);+ assert_eq!(page.margins.top, 10.0);+ assert_eq!(page.margins.outside, 40.0);}+ assert!(doc.spreads.iter().all(|s| s.items.is_empty()), "undocumented fields stay excluded");+ assert!(app.ui.dialog.is_none());}- });- ui.add_space(8.0);- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Replace With")).font(semibold(12.0)));- let db = crate::panels::fonts(app);- egui::Grid::new("ff_to").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Font Family:"));- if let Some(f) = crate::panels::font_combo(app, ui, "toFamily", &d.s("toFamily"), 170.0) {- d.fields.insert("toFamily".into(), json!(f));+ }++ #[test]+ fn numbering_commands_document_their_fields() {+ let names = |id: &str| command_fields(designcraft_engine::find_command(id).unwrap().params).into_iter().map(|f| f.key).collect::<Vec<_>>();+ assert_eq!(names("layout.section"), ["page", "startNumber", "style", "prefix", "includePrefix", "marker", "remove"]);+ assert_eq!(names("layout.chapterNumbering"), ["style", "start", "source"]);+ }++ #[test]+ fn generic_command_preserves_array_geometry() {+ let mut app = command_app("file.new", json!({}));+ confirm(&mut app).unwrap();+ app.ui.dialog = Some(Dialog::new("cmd:frame.create", json!({"rect": [10, 20, 110, 220]})));+ confirm(&mut app).unwrap();+ let doc = &app.session.active().unwrap().doc;+ let item = doc.spreads.iter().flat_map(|s| &s.items).next().unwrap();+ assert_eq!(item.bounds(), designcraft_geom::Rect::new(10.0, 20.0, 110.0, 220.0));+ }++ #[test]+ fn generic_explicit_null_uses_the_commands_existing_semantics() {+ // file.new accepts null width by using the selected preset's width.+ for width in [Value::Null, json!("null")] {+ let mut app = command_app("file.new", json!({"preset": "A4", "width": width, "title": " Sample layout "}));+ confirm(&mut app).unwrap();+ let doc = &app.session.active().unwrap().doc;+ assert_eq!(doc.title, "Sample layout");+ assert!((doc.settings.page_width - 595.2755905511812).abs() < 0.01);}- ui.end_row();- let styles = db.styles(&d.s("toFamily"));- let st_opts: Vec<(&str, &str)> = styles.iter().map(|s| (s.as_str(), s.as_str())).collect();- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Font Style:"));- combo(ui, d, "toStyle", &st_opts);- ui.end_row();- });- ui.label(crate::rtl::widget(- ui,- egui::RichText::new(crate::i18n::tr(&app.ui.language, "OK changes all: text and paragraph/character styles."))- .color(crate::theme::Tokens::get(ui.ctx()).text_dim)- .size(11.0),- ));-}+ }-#[cfg(test)]-mod tests {- use super::*;+ #[test]+ fn generic_invalid_number_retains_dialog_without_creating_document() {+ let mut app = command_app("file.new", json!({"width": 0}));+ assert!(confirm(&mut app).is_err());+ assert!(app.session.active().is_none());+ let dialog = app.ui.dialog.as_ref().unwrap();+ assert_eq!(dialog.fields["width"], 0);+ assert!(dialog.fields["status"].as_str().unwrap().contains("page size out of range"));+ }++ #[test]+ fn text_frame_options_change_only_what_was_edited() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let r = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "content": "text", "text": "Hello"})).unwrap();+ let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap());+ app.run("object.textFrameOptions", json!({"ids": [id.0], "columns": 2, "inset": [1, 2, 3, 4]})).unwrap();+ let opts = |app: &DesignApp| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.clone();+ let before = opts(&app);+ let open = |app: &mut DesignApp, fields: &[(&str, Value)]| {+ app.ui.dialog = Some(Dialog::new("textFrameOptions", json!({})));+ let mut d = app.ui.dialog.take().unwrap();+ seed_text_frame_options(app, &mut d);+ for (k, v) in fields {+ d.fields.insert((*k).into(), v.clone());+ }+ app.ui.dialog = Some(d);+ confirm(app)+ };+ // OK without edits changes nothing (no undo step either).+ assert_eq!(open(&mut app, &[]).unwrap(), Value::Null);+ assert_eq!(opts(&app), before);+ // The rule's weight is in points; unequal insets the user didn't touch stay.+ open(&mut app, &[("columnRule", json!(true)), ("columnRuleWeight", json!("6"))]).unwrap();+ let o = opts(&app);+ assert!(o.column_rule && o.column_rule_weight == 6.0, "{o:?}");+ assert_eq!((o.inset, o.columns, o.gutter), (before.inset, before.columns, before.gutter));+ // One of the rule's insets edited: the other rule settings stay.+ open(&mut app, &[("columnRuleBottomInset", json!("0p9")), ("columnRuleTint", json!("40"))]).unwrap();+ let o = opts(&app);+ assert_eq!((o.column_rule_bottom_inset, o.column_rule_top_inset, o.column_rule_offset, o.column_rule_weight), (9.0, 0.0, 0.0, 6.0));+ assert!((o.column_rule_tint - 0.4).abs() < 1e-6 && o.column_rule);+ // One inset side edited: the others keep their values.+ open(&mut app, &[("insetLeft", json!("1p0"))]).unwrap();+ assert_eq!(opts(&app).inset, [1.0, 12.0, 3.0, 4.0]);+ // An unknown swatch is an error and the dialog stays open.+ let e = open(&mut app, &[("columnRuleColor", json!("Mauve"))]).unwrap_err();+ assert!(e.contains("Mauve") && app.ui.dialog.is_some(), "{e}");+ assert_eq!(opts(&app).column_rule_color, designcraft_color::swatch::BLACK);+ // Each OK is one undo step.+ for _ in 0..3 {+ app.run("edit.undo", json!({})).unwrap();+ }+ assert_eq!(opts(&app), before);+ }fn dialog_context(language: &str) -> egui::Context {let ctx = egui::Context::default();diff --cc crates/ui-egui/src/i18n.rsindex 040a4196b,e494078b0..e3530bc9c--- a/crates/ui-egui/src/i18n.rs+++ b/crates/ui-egui/src/i18n.rs@@@ -3163,377 -2811,36 +3163,403 @@@ const TABLE: &[(&str, [&str; 5])] = &("Rule Below", ["Linie unterhalb", "Filet après", "Filete después", "後境界線", "下方横线"]),("Tint:", ["Farbton:", "Teinte:", "Matiz:", "濃淡:", "色调:"]),("Column", ["Spalte", "Colonne", "Columna", "段", "栏"]),+ // File › New › Document+ ("Recent", ["Zuletzt verwendet", "Récents", "Recientes", "最近使用", "最近"]),+ ("Saved", ["Gespeichert", "Enregistrés", "Guardados", "保存済み", "已保存"]),+ ("[Default]", ["[Standard]", "[Par défaut]", "[Predeterminado]", "[初期設定]", "[默认]"]),+ ("Your Recent Items", ["Zuletzt verwendete Elemente", "Éléments récents", "Elementos recientes", "最近使用した項目", "最近使用的项目"]),+ (+ "Saved Presets",+ ["Gespeicherte Vorgaben", "Paramètres prédéfinis enregistrés", "Ajustes preestablecidos guardados", "保存済みプリセット", "已保存的预设"],+ ),+ (+ "Blank Document Presets",+ [+ "Vorgaben für leere Dokumente",+ "Paramètres prédéfinis de document vierge",+ "Ajustes preestablecidos de documento en blanco",+ "空のドキュメントプリセット",+ "空白文档预设",+ ],+ ),+ (+ "No saved presets yet. Set the details, then click Save Document Preset.",+ [+ "Noch keine gespeicherten Vorgaben. Legen Sie die Details fest und klicken Sie auf Dokumentvorgabe speichern.",+ "Aucun paramètre prédéfini enregistré. Définissez les détails, puis cliquez sur Enregistrer le paramètre prédéfini de document.",+ "Aún no hay ajustes preestablecidos guardados. Defina los detalles y haga clic en Guardar ajuste preestablecido de documento.",+ "保存済みのプリセットはありません。詳細を設定してから「ドキュメントプリセットを保存」をクリックしてください。",+ "尚无已保存的预设。请设置详细信息,然后单击“存储文档预设”。",+ ],+ ),+ ("Delete Preset", ["Vorgabe löschen", "Supprimer le paramètre prédéfini", "Eliminar ajuste preestablecido", "プリセットを削除", "删除预设"]),+ (+ "Preset Details",+ ["Vorgabedetails", "Détails du paramètre prédéfini", "Detalles del ajuste preestablecido", "プリセットの詳細", "预设详细信息"],+ ),+ ("Document Name", ["Dokumentname", "Nom du document", "Nombre del documento", "ドキュメント名", "文档名称"]),+ (+ "Save Document Preset",+ [+ "Dokumentvorgabe speichern",+ "Enregistrer le paramètre prédéfini de document",+ "Guardar ajuste preestablecido de documento",+ "ドキュメントプリセットを保存",+ "存储文档预设",+ ],+ ),+ (+ "Save Document Preset As:",+ [+ "Dokumentvorgabe speichern unter:",+ "Enregistrer le paramètre prédéfini de document sous :",+ "Guardar ajuste preestablecido de documento como:",+ "ドキュメントプリセットの保存名:",+ "存储文档预设为:",+ ],+ ),+ ("Preset Name", ["Vorgabename", "Nom du paramètre prédéfini", "Nombre del ajuste preestablecido", "プリセット名", "预设名称"]),+ ("Save Preset", ["Vorgabe speichern", "Enregistrer le paramètre prédéfini", "Guardar ajuste preestablecido", "プリセットを保存", "存储预设"]),+ ("Start #", ["Startseitennr.", "N° de début", "N.º inicial", "開始ページ番号", "起始页码"]),+ ("Column Gutter", ["Spaltenabstand", "Gouttière", "Medianil", "列間隔", "栏间距"]),+ // Layout › Numbering & Section Options+ ("Start Section", ["Abschnittsanfang", "Début de section", "Iniciar sección", "セクション開始", "开始新章节"]),+ (+ "Automatic Page Numbering",+ [+ "Automatische Seitennummerierung",+ "Numérotation automatique des pages",+ "Numeración de páginas automática",+ "自動ページ番号",+ "自动编排页码",+ ],+ ),+ (+ "Start Page Numbering at:",+ ["Seitennummerierung beginnen bei:", "Commencer la numérotation à :", "Iniciar numeración de páginas en:", "開始ページ番号:", "起始页码:"],+ ),+ ("Section Prefix:", ["Abschnittspräfix:", "Préfixe de section :", "Prefijo de sección:", "セクションプレフィックス:", "章节前缀:"]),+ ("Section Marker:", ["Abschnittsmarke:", "Marqueur de section :", "Marcador de sección:", "セクションマーカー:", "章节标志符:"]),+ (+ "Include Prefix when Numbering Pages",+ [+ "Präfix in Seitennummerierung einschließen",+ "Inclure le préfixe lors de la numérotation des pages",+ "Incluir prefijo al numerar páginas",+ "ページ番号にプレフィックスを含める",+ "编排页码时包含前缀",+ ],+ ),+ (+ "Document Chapter Numbering",+ [+ "Kapitelnummerierung des Dokuments",+ "Numérotation des chapitres du document",+ "Numeración de capítulos del documento",+ "ドキュメントの章番号",+ "文档章节编号",+ ],+ ),+ (+ "Automatic Chapter Numbering",+ [+ "Automatische Kapitelnummerierung",+ "Numérotation automatique des chapitres",+ "Numeración de capítulos automática",+ "自動章番号",+ "自动为章节编号",+ ],+ ),+ (+ "Start Chapter Numbering at:",+ [+ "Kapitelnummerierung beginnen bei:",+ "Commencer la numérotation des chapitres à :",+ "Iniciar numeración de capítulos en:",+ "開始章番号:",+ "起始章节编号:",+ ],+ ),+ (+ "Same as Previous Document in the Book",+ [+ "Wie vorheriges Dokument im Buch",+ "Identique au document précédent du livre",+ "Igual que el documento anterior del libro",+ "ブック内の前のドキュメントと同じ",+ "与书籍中的上一文档相同",+ ],+ ),+ ("Book Name:", ["Buchname:", "Nom du livre :", "Nombre del libro:", "ブック名:", "书籍名称:"]),+ ("N/A", ["–", "S.O.", "N/D", "なし", "不适用"]),+ // Paragraph Style Options: Paragraph Border, Paragraph Shading, Keep Options, Span Columns, Bullets and Numbering.+ ("Paragraph Border", ["Absatzrahmen", "Contour de paragraphe", "Borde de párrafo", "段落囲み罫", "段落边框"]),+ ("Paragraph Shading", ["Absatzschattierung", "Ombrage de paragraphe", "Sombreado de párrafo", "段落の背景色", "段落底纹"]),+ ("Keep Options", ["Umbruchoptionen", "Options d'enchaînement", "Opciones de separación", "段落分離禁止オプション", "保持选项"]),+ ("Span Columns", ["Spalten überspannen", "Étendre sur les colonnes", "Abarcar columnas", "段抜きと段分割", "跨栏"]),+ ("Top:", ["Oben:", "Haut:", "Arriba:", "上:", "上:"]),+ ("Left:", ["Links:", "Gauche:", "Izquierda:", "左:", "左:"]),+ ("Bottom:", ["Unten:", "Bas:", "Abajo:", "下:", "下:"]),+ ("Right:", ["Rechts:", "Droite:", "Derecha:", "右:", "右:"]),+ ("Keep with Next:", ["Nicht trennen von nächsten:", "Lier aux suivantes:", "Conservar con siguientes:", "次の段落と分離禁止:", "与下一段保持:"]),+ ("Keep Lines Together", ["Zeilen nicht trennen", "Lignes solidaires", "Conservar líneas juntas", "行を分離しない", "保持各行同页"]),+ (+ "All Lines in Paragraph",+ ["Alle Zeilen im Absatz", "Toutes les lignes du paragraphe", "Todas las líneas del párrafo", "段落のすべての行", "段落中所有行"],+ ),+ (+ "At Start/End of Paragraph",+ ["Am Anfang/Ende des Absatzes", "Au début/à la fin du paragraphe", "Al inicio/final del párrafo", "段落の始めと終わり", "在段落开头/结尾"],+ ),+ ("End:", ["Ende:", "Fin:", "Final:", "終了位置:", "结束:"]),+ ("Start Paragraph:", ["Absatzbeginn:", "Début de paragraphe:", "Inicio de párrafo:", "段落の開始位置:", "段落开始:"]),+ ("Anywhere", ["Überall", "N'importe où", "En cualquier lugar", "任意の位置", "任意位置"]),+ ("In Next Column", ["In nächster Spalte", "Dans la colonne suivante", "En la siguiente columna", "次の段", "于下一栏"]),+ ("In Next Frame", ["In nächstem Rahmen", "Dans le bloc suivant", "En el siguiente marco", "次のフレーム", "于下一框架"]),+ ("On Next Page", ["Auf nächster Seite", "Sur la page suivante", "En la página siguiente", "次のページ", "于下一页"]),+ (+ "On Next Odd Page",+ ["Auf nächster ungerader Seite", "Sur la page impaire suivante", "En la siguiente página impar", "次の奇数ページ", "于下一奇数页"],+ ),+ (+ "On Next Even Page",+ ["Auf nächster gerader Seite", "Sur la page paire suivante", "En la siguiente página par", "次の偶数ページ", "于下一偶数页"],+ ),+ ("Paragraph Layout:", ["Absatzlayout:", "Disposition du paragraphe:", "Diseño de párrafo:", "段落レイアウト:", "段落版面:"]),+ ("Single Column", ["Eine Spalte", "Colonne simple", "Una columna", "単一段", "单栏"]),+ ("Split Column", ["Spalte unterteilen", "Diviser la colonne", "Dividir columna", "段分割", "拆分栏"]),+ ("Columns:", ["Spalten:", "Colonnes:", "Columnas:", "段:", "栏数:"]),+ ("All", ["Alle", "Toutes", "Todas", "すべて", "全部"]),+ ("Inside Gutter:", ["Innerer Spaltenabstand:", "Gouttière intérieure:", "Medianil interior:", "内側の間隔:", "内栏间距:"]),+ ("Outside Gutter:", ["Äußerer Spaltenabstand:", "Gouttière extérieure:", "Medianil exterior:", "外側の間隔:", "外栏间距:"]),+ ("List Type:", ["Listentyp:", "Type de liste:", "Tipo de lista:", "リストタイプ:", "列表类型:"]),+ ("Bullets", ["Aufzählungszeichen", "Puces", "Viñetas", "箇条書き記号", "项目符号"]),+ ("Numbers", ["Nummerierung", "Numéros", "Números", "自動番号", "编号"]),+ ("Bullet Character:", ["Aufzählungszeichen:", "Caractère de puce:", "Carácter de viñeta:", "箇条書き記号:", "项目符号字符:"]),+ ("Text After:", ["Text danach:", "Texte après:", "Texto después:", "後続テキスト:", "后续文本:"]),+ ("Gap Tint:", ["Lückenfarbton:", "Teinte de l'espace:", "Matiz del hueco:", "すき間の濃淡:", "间隙色调:"]),+ (+ "Corner Size and Shape",+ ["Eckengröße und -form", "Taille et forme des angles", "Tamaño y forma de esquinas", "角のサイズとシェイプ", "角大小和形状"],+ ),+ ("Top Left:", ["Oben links:", "En haut à gauche:", "Superior izquierda:", "左上:", "左上:"]),+ ("Top Right:", ["Oben rechts:", "En haut à droite:", "Superior derecha:", "右上:", "右上:"]),+ ("Bottom Right:", ["Unten rechts:", "En bas à droite:", "Inferior derecha:", "右下:", "右下:"]),+ ("Bottom Left:", ["Unten links:", "En bas à gauche:", "Inferior izquierda:", "左下:", "左下:"]),+ ("Rounded", ["Abgerundet", "Arrondi", "Redondeado", "角丸", "圆角"]),+ ("Inverse Rounded", ["Umgekehrt abgerundet", "Arrondi inversé", "Redondeado inverso", "逆角丸", "反向圆角"]),+ ("Inset", ["Eingezogen", "En retrait", "Hundido", "内側に切り欠き", "内凹"]),+ ("Fancy", ["Verziert", "Fantaisie", "Decorativo", "装飾", "花式"]),+ ("Top Edge:", ["Obere Kante:", "Bord supérieur:", "Borde superior:", "上端:", "上边缘:"]),+ ("Bottom Edge:", ["Untere Kante:", "Bord inférieur:", "Borde inferior:", "下端:", "下边缘:"]),+ ("Em Box Top", ["Geviert oben", "Haut du cadratin", "Parte superior del cuadratín", "仮想ボディの上", "全角框顶部"]),+ ("Descent", ["Unterlänge", "Jambage inférieur", "Descendente", "ディセント", "下伸部"]),+ ("Em Box Bottom", ["Geviert unten", "Bas du cadratin", "Parte inferior del cuadratín", "仮想ボディの下", "全角框底部"]),+ (+ "Display Border if Paragraph Splits Across Frames/Columns",+ [+ "Rahmen anzeigen, wenn der Absatz auf Rahmen/Spalten verteilt ist",+ "Afficher le contour si le paragraphe est réparti sur plusieurs blocs/colonnes",+ "Mostrar borde si el párrafo se divide entre marcos/columnas",+ "段落がフレームや段をまたぐときに囲み罫を表示",+ "段落跨框架/栏拆分时显示边框",+ ],+ ),+ (+ "Merge Consecutive Borders and Shading",+ [+ "Aufeinanderfolgende Rahmen und Schattierungen zusammenführen",+ "Fusionner les contours et trames consécutifs",+ "Combinar bordes y sombreados consecutivos",+ "連続する囲み罫と背景色を結合",+ "合并连续的边框和底纹",+ ],+ ),+ ("Clip to Frame", ["Auf Rahmen beschneiden", "Découper selon le bloc", "Recortar al marco", "フレームでクリップ", "剪切到框架"]),+ (+ "Do not Print or Export",+ ["Nicht drucken oder exportieren", "Ne pas imprimer ni exporter", "No imprimir ni exportar", "印刷・書き出ししない", "不打印或导出"],+ ),+ ("Space Before Span:", ["Abstand vor Überspannung:", "Espace avant l'étendue:", "Espacio antes de abarcar:", "段抜き前のアキ:", "跨栏前间距:"]),+ (+ "Space After Span:",+ ["Abstand nach Überspannung:", "Espace après l'étendue:", "Espacio después de abarcar:", "段抜き後のアキ:", "跨栏后间距:"],+ ),+ ("Space Before Split:", ["Abstand vor Teilung:", "Espace avant la division:", "Espacio antes de dividir:", "段分割前のアキ:", "拆分前间距:"]),+ ("Space After Split:", ["Abstand nach Teilung:", "Espace après la division:", "Espacio después de dividir:", "段分割後のアキ:", "拆分后间距:"]),+ ("Level:", ["Ebene:", "Niveau:", "Nivel:", "レベル:", "级别:"]),+ ("Glyphs…", ["Glyphen…", "Glyphes…", "Glifos…", "字形…", "字形…"]),+ ("(Paragraph Font)", ["(Absatzschrift)", "(Police du paragraphe)", "(Fuente del párrafo)", "(段落のフォント)", "(段落字体)"]),+ (+ "Restart Numbers at This Level After:",+ [+ "Nummerierung auf dieser Ebene neu beginnen nach:",+ "Recommencer la numérotation à ce niveau après:",+ "Reiniciar números en este nivel después de:",+ "このレベルの番号を振り直すきっかけ:",+ "在此级别后重新编号:",+ ],+ ),+ (+ "Any Previous Level",+ ["Einer beliebigen höheren Ebene", "Tout niveau précédent", "Cualquier nivel anterior", "任意の上位レベル", "任何上一级别"],+ ),+ ("Tab Position:", ["Tabulatorposition:", "Position de la tabulation:", "Posición de tabulación:", "タブ位置:", "制表符位置:"]),+ (+ "Paragraph Borders and Shading…",+ [+ "Absatzrahmen und -schattierung…",+ "Contours et trames de paragraphe…",+ "Bordes y sombreado de párrafo…",+ "段落囲み罫と段落背景色…",+ "段落边框和底纹…",+ ],+ ),+ (+ "Paragraph Borders and Shading",+ [+ "Absatzrahmen und -schattierung",+ "Contours et trames de paragraphe",+ "Bordes y sombreado de párrafo",+ "段落囲み罫と段落背景色",+ "段落边框和底纹",+ ],+ ),+ ("Span Columns…", ["Spalten überspannen…", "Étendre sur les colonnes…", "Abarcar columnas…", "段抜きと段分割…", "跨栏…"]),+ (+ "Bullets and Numbering…",+ ["Aufzählungszeichen und Nummerierung…", "Puces et numérotation…", "Viñetas y numeración…", "箇条書き記号と番号付け…", "项目符号和编号…"],+ ),+ ("List:", ["Liste:", "Liste:", "Lista:", "リスト:", "列表:"]),+ ("Number:", ["Zahl:", "Numéro:", "Número:", "番号:", "编号:"]),+ ("Mode:", ["Modus:", "Mode:", "Modo:", "モード:", "模式:"]),+ (+ "Continue from Previous Number",+ [+ "Ab vorheriger Zahl fortfahren",+ "Continuer à partir du numéro précédent",+ "Continuar desde el número anterior",+ "前の番号から継続",+ "从上一编号继续",+ ],+ ),+ ("Start At", ["Beginnen bei", "Commencer à", "Empezar en", "開始番号", "起始编号"]),+ // Cell strokes.+ ("Strokes and Fills…", ["Konturen und Flächen …", "Contours et fonds…", "Trazos y rellenos…", "線と塗り…", "描边和填色…"]),+ ("Cell Stroke", ["Zellkontur", "Contour de cellule", "Trazo de celda", "セルの線", "单元格描边"]),+ ("Cell Fill", ["Zellfläche", "Fond de cellule", "Relleno de celda", "セルの塗り", "单元格填色"]),+ ("Cell edges", ["Zellkanten", "Bords de cellule", "Bordes de celda", "セルの境界線", "单元格边缘"]),+ (+ "Click a line to include or exclude it. Double-click selects all outer or all inner lines; triple-click selects or clears all.",+ [+ "Klicken Sie auf eine Linie, um sie ein- oder auszuschließen. Doppelklick wählt alle äußeren oder alle inneren Linien; Dreifachklick wählt alle aus oder hebt die Auswahl auf.",+ "Cliquez sur une ligne pour l'inclure ou l'exclure. Un double-clic sélectionne toutes les lignes extérieures ou intérieures ; un triple-clic sélectionne ou désélectionne tout.",+ "Haga clic en una línea para incluirla o excluirla. Doble clic selecciona todas las líneas exteriores o interiores; triple clic selecciona o borra todas.",+ "線をクリックすると、含めるか除外するかを切り替えます。ダブルクリックで外側または内側の線をすべて選択し、トリプルクリックですべてを選択または解除します。",+ "单击线条可将其包含或排除。双击选择所有外侧或所有内侧线条;三击选择或清除全部。",+ ],+ ),+ ("Swatch Options…", ["Farbfeldoptionen …", "Options de nuance…", "Opciones de muestra…", "スウォッチオプション…", "色板选项…"]),+ ("Swatch Options", ["Farbfeldoptionen", "Options de nuance", "Opciones de muestra", "スウォッチオプション", "色板选项"]),+ (+ "Color Group Options…",+ ["Farbgruppenoptionen …", "Options du groupe de couleurs…", "Opciones de grupo de colores…", "カラーグループオプション…", "颜色组选项…"],+ ),+ ("Layer Options", ["Ebenenoptionen", "Options de calque", "Opciones de capa", "レイヤーオプション", "图层选项"]),+ (+ "Layer Options for \"{name}\"…",+ [+ "Ebenenoptionen für „{name}“ …",+ "Options du calque « {name} »…",+ "Opciones de capa para «{name}»…",+ "「{name}」のレイヤーオプション…",+ "“{name}”的图层选项…",+ ],+ ),+ ("Swatch Name:", ["Farbfeldname:", "Nom de la nuance :", "Nombre de muestra:", "スウォッチ名:", "色板名称:"]),+ (+ "Name with Color Value",+ ["Name mit Farbwert", "Nommer d'après la valeur chromatique", "Nombre con valor de color", "カラー値を名前にする", "以颜色值命名"],+ ),+ ("Color Type:", ["Farbtyp:", "Type de couleur :", "Tipo de color:", "カラータイプ:", "颜色类型:"]),+ ("Process", ["Prozessfarbe", "Quadrichromie", "Cuatricromía", "プロセス", "印刷色"]),+ ("Spot", ["Volltonfarbe", "Ton direct", "Tinta plana", "特色", "专色"]),+ ("Color Mode:", ["Farbmodus:", "Mode colorimétrique :", "Modo de color:", "カラーモード:", "颜色模式:"]),+ ("Base Color:", ["Grundfarbe:", "Couleur de base :", "Color base:", "ベースカラー:", "基准颜色:"]),+ (+ "Edit the gradient's stops in the Gradient panel.",+ [+ "Die Verlaufsregler bearbeiten Sie im Verlaufsbedienfeld.",+ "Modifiez les arrêts du dégradé dans le panneau Dégradé.",+ "Edite las paradas del degradado en el panel Degradado.",+ "グラデーションの分岐点はグラデーションパネルで編集します。",+ "在“渐变”面板中编辑渐变的色标。",+ ],+ ),+ (+ "This swatch can't be edited.",+ [+ "Dieses Farbfeld kann nicht bearbeitet werden.",+ "Cette nuance ne peut pas être modifiée.",+ "Esta muestra no se puede editar.",+ "このスウォッチは編集できません。",+ "此色板无法编辑。",+ ],+ ),+ ("Light Blue", ["Hellblau", "Bleu clair", "Azul claro", "ライトブルー", "浅蓝色"]),+ ("Red", ["Rot", "Rouge", "Rojo", "レッド", "红色"]),+ ("Green", ["Grün", "Vert", "Verde", "グリーン", "绿色"]),+ ("Blue", ["Blau", "Bleu", "Azul", "ブルー", "蓝色"]),+ ("Yellow", ["Gelb", "Jaune", "Amarillo", "イエロー", "黄色"]),+ ("Magenta", ["Magenta", "Magenta", "Magenta", "マゼンタ", "洋红色"]),+ ("Cyan", ["Cyan", "Cyan", "Cian", "シアン", "青色"]),+ ("Black", ["Schwarz", "Noir", "Negro", "ブラック", "黑色"]),+ ("Orange", ["Orange", "Orange", "Naranja", "オレンジ", "橙色"]),+ ("Dark Green", ["Dunkelgrün", "Vert foncé", "Verde oscuro", "ダークグリーン", "深绿色"]),+ ("Teal", ["Blaugrün", "Bleu canard", "Verde azulado", "ティール", "蓝绿色"]),+ ("Tan", ["Hellbraun", "Fauve", "Tostado", "タン", "棕褐色"]),+ ("Brown", ["Braun", "Marron", "Marrón", "ブラウン", "褐色"]),+ ("Violet", ["Violett", "Violet", "Violeta", "バイオレット", "紫罗兰色"]),+ ("Gold", ["Gold", "Or", "Dorado", "ゴールド", "金色"]),+ ("Show Layer", ["Ebene einblenden", "Afficher le calque", "Mostrar capa", "レイヤーを表示", "显示图层"]),+ ("Lock Layer", ["Ebene fixieren", "Verrouiller le calque", "Bloquear capa", "レイヤーをロック", "锁定图层"]),+ ("Print Layer", ["Ebene drucken", "Imprimer le calque", "Imprimir capa", "レイヤーをプリント", "打印图层"]),+ (+ "Suppress Text Wrap When Layer is Hidden",+ [+ "Textumfluss bei ausgeblendeter Ebene unterdrücken",+ "Supprimer l'habillage quand le calque est masqué",+ "Suprimir ceñir texto cuando la capa está oculta",+ "非表示レイヤーのテキストの回り込みを無視",+ "图层隐藏时禁止文本绕排",+ ],+ ),+ // Document Setup+ ("Page Size:", ["Seitenformat:", "Format de page :", "Tamaño de página:", "ページサイズ:", "页面大小:"]),+ (+ "Adjust page elements to document changes",+ [+ "Seitenelemente an Dokumentänderungen anpassen",+ "Adapter les éléments de page aux modifications du document",+ "Ajustar los elementos de página a los cambios del documento",+ "ページ要素をドキュメントの変更に合わせて調整",+ "根据文档更改调整页面元素",+ ],+ ),+ (+ "Apply the changes; objects follow the new page size and margins",+ [+ "Änderungen anwenden; Objekte folgen dem neuen Seitenformat und den Rändern",+ "Appliquer les modifications ; les objets suivent le nouveau format et les marges",+ "Aplicar los cambios; los objetos siguen el nuevo tamaño de página y los márgenes",+ "変更を適用し、オブジェクトを新しいページサイズとマージンに合わせます",+ "应用更改;对象跟随新的页面大小和边距",+ ],+ ),- ("Top:", ["Oben:", "Haut :", "Superior:", "天:", "上:"]),- ("Bottom:", ["Unten:", "Bas :", "Inferior:", "地:", "下:"]),+ ("Inside:", ["Innen:", "Intérieur :", "Interior:", "ノド:", "内:"]),+ ("Outside:", ["Außen:", "Extérieur :", "Exterior:", "小口:", "外:"]),- ("Left:", ["Links:", "Gauche :", "Izquierda:", "左:", "左:"]),- ("Right:", ["Rechts:", "Droite :", "Derecha:", "右:", "右:"]),+ ("Bleed:", ["Anschnitt:", "Fond perdu :", "Sangrado:", "裁ち落とし:", "出血:"]),+ ("Slug:", ["Infobereich:", "Ligne-bloc :", "Indicaciones:", "印刷可能領域:", "辅助信息区:"]),];/// Interface direction; independent of document binding and paragraph direction.diff --cc crates/ui-egui/src/i18n/it.rsindex 2953693b3,f4017d555..af6199a9f--- a/crates/ui-egui/src/i18n/it.rs+++ b/crates/ui-egui/src/i18n/it.rs@@@ -1503,170 -1492,16 +1503,178 @@@ pub(super) const TABLE: &[(&str, &str)("Paragraph Rules", "Filetti paragrafo"),("Rule Below", "Filetto sotto"),("Tint:", "Tinta:"),+ // Machine-translated; not yet reviewed by a native speaker.+ ("Align Left Edge", "Allinea bordo sinistro"),+ ("Characters:", "Caratteri:"),+ ("Drop Caps", "Capilettera"),+ ("Drop Chars", "Caratteri capolettera"),+ ("Drop Lines", "Righe capolettera"),+ ("Lines:", "Righe:"),+ ("Scale for Descenders", "Ridimensiona per i discendenti"),+ ("Select an object or text to color its fill or stroke.", "Seleziona un oggetto o del testo per colorarne il riempimento o la traccia."),+ ("dropcap", "capolettera"),+ ("Left-aligned tab", "Tabulazione allineata a sinistra"),+ ("Centered tab", "Tabulazione centrata"),+ ("Right-aligned tab", "Tabulazione allineata a destra"),+ ("Tab aligned on a character", "Tabulazione allineata a un carattere"),+ ("X:", "X:"),+ ("Leader:", "Carattere di riempimento:"),+ ("Align On:", "Allinea a:"),+ ("Position panel above text frame", "Posiziona il pannello sopra la cornice di testo"),+ ("Clear All", "Cancella tutto"),+ ("Delete Tab", "Elimina tabulazione"),+ ("Repeat Tab", "Ripeti tabulazione"),+ ("Reset Indents", "Ripristina rientri"),+ // File › New › Document+ ("Recent", "Recenti"),+ ("Saved", "Salvati"),+ ("[Default]", "[Predefinito]"),+ ("Your Recent Items", "Elementi recenti"),+ ("Saved Presets", "Predefiniti salvati"),+ ("Blank Document Presets", "Predefiniti documento vuoto"),+ (+ "No saved presets yet. Set the details, then click Save Document Preset.",+ "Nessun predefinito salvato. Imposta i dettagli, poi fai clic su Salva predefinito documento.",+ ),+ ("Delete Preset", "Elimina predefinito"),+ ("Preset Details", "Dettagli predefinito"),+ ("Document Name", "Nome documento"),+ ("Save Document Preset", "Salva predefinito documento"),+ ("Save Document Preset As:", "Salva predefinito documento come:"),+ ("Preset Name", "Nome predefinito"),+ ("Save Preset", "Salva predefinito"),+ ("Start #", "N. iniziale"),+ ("Column Gutter", "Spazio tra colonne"),+ // Layout › Numbering & Section Options+ ("Start Section", "Inizia sezione"),+ ("Automatic Page Numbering", "Numerazione automatica delle pagine"),+ ("Start Page Numbering at:", "Inizia numerazione pagine da:"),+ ("Section Prefix:", "Prefisso sezione:"),+ ("Section Marker:", "Marcatore sezione:"),+ ("Include Prefix when Numbering Pages", "Includi prefisso nella numerazione delle pagine"),+ ("Document Chapter Numbering", "Numerazione capitoli del documento"),+ ("Automatic Chapter Numbering", "Numerazione automatica dei capitoli"),+ ("Start Chapter Numbering at:", "Inizia numerazione capitoli da:"),+ ("Same as Previous Document in the Book", "Uguale al documento precedente nel libro"),+ ("Book Name:", "Nome libro:"),+ ("N/A", "N/D"),+ ("Paragraph Border", "Bordo paragrafo"),+ ("Paragraph Shading", "Ombreggiatura paragrafo"),+ ("Keep Options", "Opzioni di unione"),+ ("Span Columns", "Estendi su colonne"),+ ("Top:", "Superiore:"),+ ("Left:", "Sinistra:"),+ ("Bottom:", "Inferiore:"),+ ("Right:", "Destra:"),+ ("Keep with Next:", "Unisci alle successive:"),+ ("Keep Lines Together", "Mantieni le righe unite"),+ ("All Lines in Paragraph", "Tutte le righe del paragrafo"),+ ("At Start/End of Paragraph", "All'inizio/alla fine del paragrafo"),+ ("End:", "Fine:"),+ ("Start Paragraph:", "Inizio paragrafo:"),+ ("Anywhere", "Ovunque"),+ ("In Next Column", "Nella colonna successiva"),+ ("In Next Frame", "Nella cornice successiva"),+ ("On Next Page", "Nella pagina successiva"),+ ("On Next Odd Page", "Nella pagina dispari successiva"),+ ("On Next Even Page", "Nella pagina pari successiva"),+ ("Paragraph Layout:", "Layout paragrafo:"),+ ("Single Column", "Colonna singola"),+ ("Split Column", "Dividi colonna"),+ ("Columns:", "Colonne:"),+ ("All", "Tutte"),+ ("Inside Gutter:", "Spaziatura interna:"),+ ("Outside Gutter:", "Spaziatura esterna:"),+ ("List Type:", "Tipo di elenco:"),+ ("Bullets", "Punti elenco"),+ ("Numbers", "Numeri"),+ ("Bullet Character:", "Carattere punto elenco:"),+ ("Text After:", "Testo dopo:"),+ ("Gap Tint:", "Tinta spazio:"),+ ("Corner Size and Shape", "Dimensione e forma angoli"),+ ("Top Left:", "In alto a sinistra:"),+ ("Top Right:", "In alto a destra:"),+ ("Bottom Right:", "In basso a destra:"),+ ("Bottom Left:", "In basso a sinistra:"),+ ("Rounded", "Arrotondato"),+ ("Inverse Rounded", "Arrotondato inverso"),+ ("Inset", "Rientrato"),+ ("Fancy", "Decorativo"),+ ("Top Edge:", "Bordo superiore:"),+ ("Bottom Edge:", "Bordo inferiore:"),+ ("Em Box Top", "Parte superiore del quadratone"),+ ("Descent", "Discendente"),+ ("Em Box Bottom", "Parte inferiore del quadratone"),+ ("Display Border if Paragraph Splits Across Frames/Columns", "Mostra bordo se il paragrafo si divide tra cornici/colonne"),+ ("Merge Consecutive Borders and Shading", "Unisci bordi e ombreggiature consecutivi"),+ ("Clip to Frame", "Ritaglia alla cornice"),+ ("Do not Print or Export", "Non stampare né esportare"),+ ("Space Before Span:", "Spazio prima dell'estensione:"),+ ("Space After Span:", "Spazio dopo l'estensione:"),+ ("Space Before Split:", "Spazio prima della divisione:"),+ ("Space After Split:", "Spazio dopo la divisione:"),+ ("Level:", "Livello:"),+ ("Glyphs…", "Glifi…"),+ ("(Paragraph Font)", "(Font del paragrafo)"),+ ("Restart Numbers at This Level After:", "Riavvia numerazione a questo livello dopo:"),+ ("Any Previous Level", "Qualsiasi livello precedente"),+ ("Tab Position:", "Posizione tabulazione:"),+ ("Paragraph Borders and Shading…", "Bordi e ombreggiatura paragrafo…"),+ ("Paragraph Borders and Shading", "Bordi e ombreggiatura paragrafo"),+ ("Span Columns…", "Estendi su colonne…"),+ ("Bullets and Numbering…", "Elenchi puntati e numerati…"),+ ("List:", "Elenco:"),+ ("Number:", "Numero:"),+ ("Mode:", "Modalità:"),+ ("Continue from Previous Number", "Continua dal numero precedente"),+ ("Start At", "Inizia da"),+ ("Strokes and Fills…", "Tracce e riempimenti…"),+ ("Cell Stroke", "Traccia cella"),+ ("Cell Fill", "Riempimento cella"),+ ("Cell edges", "Bordi cella"),+ (+ "Click a line to include or exclude it. Double-click selects all outer or all inner lines; triple-click selects or clears all.",+ "Fai clic su una linea per includerla o escluderla. Il doppio clic seleziona tutte le linee esterne o interne; il triplo clic seleziona o deseleziona tutte.",+ ),+ ("Swatch Options…", "Opzioni campione…"),+ ("Swatch Options", "Opzioni campione"),+ ("Color Group Options…", "Opzioni gruppo colori…"),+ ("Layer Options", "Opzioni livello"),+ ("Layer Options for \"{name}\"…", "Opzioni livello \"{name}\"…"),+ ("Swatch Name:", "Nome campione:"),+ ("Name with Color Value", "Nome con valore colore"),+ ("Color Type:", "Tipo colore:"),+ ("Process", "Quadricromia"),+ ("Spot", "Tinta piatta"),+ ("Color Mode:", "Metodo colore:"),+ ("Base Color:", "Colore base:"),+ ("Edit the gradient's stops in the Gradient panel.", "Modifica le interruzioni della sfumatura nel pannello Sfumatura."),+ ("This swatch can't be edited.", "Questo campione non può essere modificato."),+ ("Light Blue", "Azzurro"),+ ("Red", "Rosso"),+ ("Green", "Verde"),+ ("Blue", "Blu"),+ ("Yellow", "Giallo"),+ ("Magenta", "Magenta"),+ ("Cyan", "Ciano"),+ ("Black", "Nero"),+ ("Orange", "Arancione"),+ ("Dark Green", "Verde scuro"),+ ("Teal", "Verde acqua"),+ ("Tan", "Marrone chiaro"),+ ("Brown", "Marrone"),+ ("Violet", "Viola"),+ ("Gold", "Oro"),+ ("Show Layer", "Mostra livello"),+ ("Lock Layer", "Blocca livello"),+ ("Print Layer", "Stampa livello"),+ ("Suppress Text Wrap When Layer is Hidden", "Elimina contorna con testo se il livello è nascosto"),+ // Document Setup+ ("Page Size:", "Dimensioni pagina:"),+ ("Adjust page elements to document changes", "Adatta gli elementi della pagina alle modifiche del documento"),+ ("Apply the changes; objects follow the new page size and margins", "Applica le modifiche; gli oggetti seguono le nuove dimensioni e i margini"),- ("Top:", "Alto:"),- ("Bottom:", "Basso:"),+ ("Inside:", "Interno:"),+ ("Outside:", "Esterno:"),- ("Left:", "Sinistra:"),- ("Right:", "Destra:"),+ ("Bleed:", "Pagina al vivo:"),+ ("Slug:", "Indicazioni:"),];diff --cc docs/target-app-parity.mdindex 832ee8343,4b4431db1..893e2838f--- a/docs/target-app-parity.md+++ b/docs/target-app-parity.md@@@ -420,8 -418,7 +420,8 @@@ It is evidence of breadth: each item ex- OpenType menu (Character panel): discretionary ligatures, fractions, ordinal, swash, titling, contextual alternates, slashed zero, the four figure styles and stylistic sets 1–20; `type.openType`; mapped to IDML's OTF attributes.- Add Anchor Point (=), Delete Anchor Point (-) and Convert Direction Point (⇧C) tools (click toggles smooth/corner, drag pulls out handles), with `path.addAnchor`, `path.deleteAnchor`, `path.convertAnchor`.- Gradients: the Gradient Swatch tool (G) drags a gradient's start and end across objects (Shift: 45°); the Gradient panel sets type, angle, reverse and edits stops on a ramp (drag, add, drag off to remove, location, colour). Edited gradients are unnamed swatches; `object.gradient`; the vector round-trips through IDML.+- New Document (⌘N) as in InDesign: Recent, Saved, Print, Web and Mobile tabs of page cards (double-click creates) beside the preset's details: document name, size with arrows, units, orientation, pages, start page #, facing pages, primary text frame, columns, margins, bleed and slug per edge (linked or not); Save Document Preset (`file.savePreset`, `file.deletePreset`; saved presets are kept with the preferences, listed by `file.presets` and made by `file.new {preset: name}`); `file.new` takes `intent`, `units`, `startPage` and per-edge `bleed`/`slug`.- - Document Setup (⌥⌘P): intent, number of pages, start page # (an even start begins with a left page), facing pages, size presets and orientation, bleed and slug per edge; `layout.documentSetup {}` reports the setup.+ - Document Setup (⌥⌘P), laid out like InDesign's: intent, number of pages, start page # (an even start begins with a left page), facing pages, binding, Page Size (presets keeping the orientation, width and height with arrows, orientation), margins for every page and parent page, bleed and slug per edge (each group linked or not), and Adjust Layout (objects follow the new page size and margins), all in one undo step; measures are read in the document's units, and a value that can't be read keeps the dialog open; `layout.documentSetup {}` reports the setup, margins included.- Stroke panel: cap, join, miter limit, alignment, type, Start/End arrowheads (12 kinds, drawn on screen and in PDF; the path is shortened under pointed heads) and gap colour under dashes and dots.- Preferences (⌘K: General, Type, Units & Increments, Grids, Guides & Pasteboard, Display Performance) backed by `prefs.set` (application) and `document.preferences` (units, increments, grids — undoable, saved with the document; right-click a ruler to pick its units, the horizontal and vertical rulers each have their own); scaling applies to content and scales stroke weights (Include Stroke Weight), and X/Y/W/H measure the stroke's outer edge (Dimensions Include Stroke Weight). Quick Apply (⌘Return) finds paragraph, character and object styles as well as commands.- Parent item overrides: Cmd+Shift-click a parent item on a page (or Override All Parent Page Items, ⌥⇧⌘L) makes an editable local copy that hides the parent's; Remove All Local Overrides and Detach All Objects from Parent in the Pages panel menu.