DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge PR #1062: Styles: preview paragraph and character style edits before applying them
aiongg5857f2d31ed7
diff --cc ROADMAP.mdindex 388fd5409,50f3cf8c7..0b08d8c95--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -345,12 -343,8 +345,14 @@@ list) · [roadmap.md](docs/roadmap.md)## Progress log+- **2026-10-15** · Applying text styles removes matching local formatting so capture sources+ inherit later edits; real overrides and named character styles remain.+- **2026-10-15** · Redefine paragraph and character styles from local formatting, including the+ Styles panel context menu, global updates and one-step undo.+- **2026-10-15** · Paragraph Styles marks local character overrides and offers Clear Overrides+ in the style row menu; named character styles and equal local values are not false overrides.+ - **2026-10-15** · Existing paragraph and character styles preview their attribute edits in+ Style Options; Cancel restores the document and OK records one edit.- **2026-10-13** · Switching between document and parent pages refreshes the canvas immediately, preventing black parent pages and stale document objects when the zoom stays the same. Ordinary edits retain partial repainting. No readiness percentage change.diff --cc crates/ui-egui/src/dialogs.rsindex aa2a903cb,a94bdbd6d..c5c90db83--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@@ -2586,142 -2016,202 +2586,146 @@@ pub fn show(app: &mut DesignApp, ctx: &}});});- }- }- "closeDocument" => {- let text = crate::i18n::tr(&app.ui.language, "“{}” has changes that are not saved. Save them before closing?")- .replace("{}", &d.s("title"));- crate::rtl::label(ui, text);- }- "updateLink" => {- let text = crate::i18n::tr(- &app.ui.language,- "“{}” has been edited in this layout. Updating replaces those edits with the text from the file.",- )- .replace("{}", &d.s("files"));- crate::rtl::label(ui, text);- }- "newWorkspace" => {- ui.horizontal(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Name:"));- text_field(ui, &mut d, "name", 220.0);- });- crate::rtl::label(- ui,- egui::RichText::new(crate::i18n::tr(&app.ui.language, "Saves which bars show and where the panels are.")).size(10.5),- );- }- "fittingOptions" => {- check(ui, &mut d, "autoFit", crate::i18n::tr(&app.ui.language, "Auto-Fit"));- ui.add_space(4.0);- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Content Fitting")).font(semibold(12.0)));- let cur = d.s("fitting");- let label = |v: &str| match v {- "fillProportionally" => crate::i18n::tr(&app.ui.language, "Fill Frame Proportionally"),- "fitProportionally" => crate::i18n::tr(&app.ui.language, "Fit Content Proportionally"),- "fitContentToFrame" => crate::i18n::tr(&app.ui.language, "Fit Content to Frame"),- "centerContent" => crate::i18n::tr(&app.ui.language, "Center Content"),- _ => crate::i18n::tr(&app.ui.language, "None"),- };- ui.horizontal(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Fitting:"));- egui::ComboBox::from_id_salt("ff_fit").selected_text(crate::rtl::widget(ui, label(&cur))).width(200.0).show_ui(ui, |ui| {- for v in ["none", "fillProportionally", "fitProportionally", "fitContentToFrame", "centerContent"] {- if ui.selectable_label(cur == v, crate::rtl::widget(ui, label(v))).clicked() {- d.fields.insert("fitting".into(), json!(v));- }+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Crop Amount")).font(semibold(12.0)));+ egui::Grid::new("ff_crop").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {+ for (k, l) in [("cropTop", "Top:"), ("cropLeft", "Left:")] {+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, l));+ text_field(ui, &mut d, k, 70.0);}+ ui.end_row();+ for (k, l) in [("cropBottom", "Bottom:"), ("cropRight", "Right:")] {+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, l));+ text_field(ui, &mut d, k, 70.0);+ }+ ui.end_row();});- });- ui.horizontal(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Align From:"));- let a = d.n("align").unwrap_or(4.0) as u8;- egui::Grid::new("ff_align").spacing([2.0, 2.0]).show(ui, |ui| {- for row in 0..3u8 {- for col in 0..3u8 {- let i = row * 3 + col;- let (r, resp) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), egui::Sense::click());- let c = ui.visuals().text_color();- if a == i {- ui.painter().rect_filled(r.shrink(2.0), 1.0, c);- } else {- ui.painter().rect_stroke(r.shrink(3.0), 1.0, egui::Stroke::new(1.0, c), egui::StrokeKind::Inside);- }- if resp.clicked() {- d.fields.insert("align".into(), json!(i));+ }+ "qrCode" => {+ let cur = d.s("type");+ ui.horizontal(|ui| {+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Type:"));+ let label = |v: &str| match v {+ "text" => crate::i18n::tr(&app.ui.language, "Plain Text"),+ "sms" => crate::i18n::tr(&app.ui.language, "Text Message"),+ "email" => crate::i18n::tr(&app.ui.language, "Email"),+ "vcard" => crate::i18n::tr(&app.ui.language, "Business Card"),+ _ => crate::i18n::tr(&app.ui.language, "Web Hyperlink"),+ };+ egui::ComboBox::from_id_salt("qr_type").selected_text(crate::rtl::widget(ui, label(&cur))).width(160.0).show_ui(+ ui,+ |ui| {+ for v in ["url", "text", "sms", "email", "vcard"] {+ if ui.selectable_label(cur == v, crate::rtl::widget(ui, label(v))).clicked() {+ d.fields.insert("type".into(), json!(v));+ }}- }- ui.end_row();- }+ },+ );});- });- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Crop Amount")).font(semibold(12.0)));- egui::Grid::new("ff_crop").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {- for (k, l) in [("cropTop", "Top:"), ("cropLeft", "Left:")] {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, l));- text_field(ui, &mut d, k, 70.0);- }- ui.end_row();- for (k, l) in [("cropBottom", "Bottom:"), ("cropRight", "Right:")] {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, l));- text_field(ui, &mut d, k, 70.0);- }- ui.end_row();- });- }- "qrCode" => {- let cur = d.s("type");- ui.horizontal(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Type:"));- let label = |v: &str| match v {- "text" => crate::i18n::tr(&app.ui.language, "Plain Text"),- "sms" => crate::i18n::tr(&app.ui.language, "Text Message"),- "email" => crate::i18n::tr(&app.ui.language, "Email"),- "vcard" => crate::i18n::tr(&app.ui.language, "Business Card"),- _ => crate::i18n::tr(&app.ui.language, "Web Hyperlink"),+ let fields: &[(&str, &str)] = match cur.as_str() {+ "sms" => &[("number", "Cell Number:"), ("message", "Message:")],+ "email" => &[("to", "Email Address:"), ("subject", "Subject:"), ("body", "Message:")],+ "vcard" => &[("name", "Name:"), ("org", "Organization:"), ("phone", "Phone:"), ("email", "Email:"), ("url", "URL:")],+ "text" => &[("content", "Text:")],+ _ => &[("content", "URL:")],};- egui::ComboBox::from_id_salt("qr_type").selected_text(crate::rtl::widget(ui, label(&cur))).width(160.0).show_ui(ui, |ui| {- for v in ["url", "text", "sms", "email", "vcard"] {- if ui.selectable_label(cur == v, crate::rtl::widget(ui, label(v))).clicked() {- d.fields.insert("type".into(), json!(v));- }+ egui::Grid::new("qr_fields").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ for (k, l) in fields {+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, l));+ text_field(ui, &mut d, k, 260.0);+ ui.end_row();}+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Color:"));+ text_field(ui, &mut d, "color", 160.0);+ ui.end_row();});- });- let fields: &[(&str, &str)] = match cur.as_str() {- "sms" => &[("number", "Cell Number:"), ("message", "Message:")],- "email" => &[("to", "Email Address:"), ("subject", "Subject:"), ("body", "Message:")],- "vcard" => &[("name", "Name:"), ("org", "Organization:"), ("phone", "Phone:"), ("email", "Email:"), ("url", "URL:")],- "text" => &[("content", "Text:")],- _ => &[("content", "URL:")],- };- egui::Grid::new("qr_fields").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {- for (k, l) in fields {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, l));- text_field(ui, &mut d, k, 260.0);+ }+ "polygonSettings" => {+ egui::Grid::new("poly").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Number of Sides:"));+ text_field(ui, &mut d, "sides", 60.0);ui.end_row();- }- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Color:"));- text_field(ui, &mut d, "color", 160.0);- ui.end_row();- });- }- "polygonSettings" => {- egui::Grid::new("poly").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Number of Sides:"));- text_field(ui, &mut d, "sides", 60.0);- ui.end_row();- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Star Inset:"));+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Star Inset:"));+ ui.horizontal(|ui| {+ text_field(ui, &mut d, "starInset", 60.0);+ ui.label("%");+ });+ ui.end_row();+ });+ }+ STEP_AND_REPEAT => step_and_repeat_dialog(app, ui, &mut d),+ TOC => toc_dialog(app, ui, &mut d),+ id if id.starts_with("cmd:") => command_form(app, ui, &mut d),+ "goToPage" => {ui.horizontal(|ui| {- text_field(ui, &mut d, "starInset", 60.0);- ui.label("%");+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Page"));+ text_field(ui, &mut d, "page", 80.0);});- ui.end_row();- });- }- STEP_AND_REPEAT => step_and_repeat_dialog(app, ui, &mut d),- TOC => toc_dialog(app, ui, &mut d),- id if id.starts_with("cmd:") => command_form(app, ui, &mut d),- "goToPage" => {- ui.horizontal(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Page"));- text_field(ui, &mut d, "page", 80.0);- });- }- "ruby" => {- ui.horizontal(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Ruby:"));- text_field(ui, &mut d, "text", 200.0);- });- crate::rtl::label(- ui,- egui::RichText::new(crate::i18n::tr(&app.ui.language, "Set over the selected text; empty removes it.")).size(11.0),- );- }- "insertTable" => {- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Table Dimensions")).font(semibold(12.0)));- egui::Grid::new("ins_table").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Body Rows"));- text_field(ui, &mut d, "bodyRows", 60.0);- crate::rtl::label(ui, crate::i18n::tr_context(&app.ui.language, "Columns", "table"));- text_field(ui, &mut d, "columns", 60.0);- ui.end_row();- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Header Rows"));- text_field(ui, &mut d, "headerRows", 60.0);- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Footer Rows"));- text_field(ui, &mut d, "footerRows", 60.0);- ui.end_row();- });- }- "createGuides" => create_guides_dialog(app, ui, &mut d),- "marginsAndColumns" => margins_and_columns_dialog(app, ui, &mut d),- "textFrameOptions" => {- seed_text_frame_options(app, &mut d);- text_frame_options_dialog(app, ui, &mut d);- }- "documentSetup" => document_setup(app, ui, &mut d),- "pdfExport" => pdf_export(app, ui, &mut d),- "alert" => {- let file = d.s("file");- if !file.is_empty() {- crate::rtl::label(ui, egui::RichText::new(crate::rtl::isolate(&file)).font(semibold(13.0)));- ui.add_space(4.0);}- crate::rtl::label(ui, d.s("message"));- }- _ => {}- });- ui.add_space(12.0);- let ok_label = match d.id.as_str() {- "closeDocument" => " Save ",- "updateLink" => " Update ",- _ => " OK ",- };- ui.horizontal(|ui| {+ "ruby" => style_cjk::ruby_dialog(app, ui, &mut d),+ "insertTable" => {+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Table Dimensions")).font(semibold(12.0)));+ egui::Grid::new("ins_table").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Body Rows"));+ text_field(ui, &mut d, "bodyRows", 60.0);+ crate::rtl::label(ui, crate::i18n::tr_context(&app.ui.language, "Columns", "table"));+ text_field(ui, &mut d, "columns", 60.0);+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Header Rows"));+ text_field(ui, &mut d, "headerRows", 60.0);+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Footer Rows"));+ text_field(ui, &mut d, "footerRows", 60.0);+ ui.end_row();+ });+ }+ "cellOptions" => cell_options(app, ui, &mut d),+ "createGuides" => create_guides_dialog(app, ui, &mut d),+ "marginsAndColumns" => margins_and_columns_dialog(app, ui, &mut d),+ "textFrameOptions" => {+ seed_text_frame_options(app, &mut d);+ text_frame_options_dialog(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");+ if !file.is_empty() {+ crate::rtl::label(ui, egui::RichText::new(crate::rtl::isolate(&file)).font(semibold(13.0)));+ ui.add_space(4.0);+ }+ crate::rtl::label(ui, d.s("message"));+ }+ _ => {}+ }+ });+ if side_actions {+ return;+ }+ ui.add_space(12.0);+ let ok_label = match d.id.as_str() {+ "closeDocument" => crate::i18n::tr(&app.ui.language, " Save ").to_string(),+ "updateLink" => crate::i18n::tr(&app.ui.language, " Update ").to_string(),+ "findFont" => crate::i18n::tr(&app.ui.language, "Replace All").to_string(),+ "newDocument" => format!(" {} ", crate::i18n::tr(&app.ui.language, "Create")),+ _ => crate::i18n::tr(&app.ui.language, " OK ").to_string(),+ };+ let cancel_label = match d.id.as_str() {+ "newDocument" => "Close",+ "findFont" => "Done",+ _ => "Cancel",+ };+ ui.horizontal(|ui| {+ if matches!(d.id.as_str(), "paragraphStyleOptions" | "characterStyleOptions") && !d.b("new") {+ check(ui, &mut d, "preview", crate::i18n::tr(&app.ui.language, "Preview"));+ style_options_preview(app, &mut d);+ }ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {if ui.add(@@@ -3498,80 -2797,74 +3506,138 @@@ pub fn confirm(app: &mut DesignApp) ->}}-/// Paragraph Style Options: sections in a left list (like InDesign), fields on the right.-/// Edited values are stored as `p.<attr>` / `c.<attr>` fields and applied on OK.-/// Is `p` a pattern the GREP styles can use? (Checked as the user types.)-fn regex_ok(p: &str) -> Result<(), ()> {+/// Why `p` is not a pattern the GREP styles can use, if it isn't. (Checked as the user types.)+fn grep_error(p: &str) -> Option<String> {if p.is_empty() {- return Ok(());+ return None;+ }+ designcraft_compose::grep::Grep::new(p, Default::default()).err().map(|e| e.to_string())+}++fn confirm_paragraph_style_options(app: &mut DesignApp, d: &mut Dialog) -> Result<Value, String> {+ let name = d.s("name");+ // What the Justification section showed: the style's own values, or a new style's Based On.+ let shown = if d.b("new") { d.s("basedOn") } else { name.clone() };+ let base =+ app.session.active().map(|st| serde_json::to_value(st.doc.styles.resolve_para_style(&shown).0).unwrap_or_default()).unwrap_or_default();+ if let Err(e) = check_justification(d, "p.", &base) {+ // The caller shows the reason in the dialog's status line.+ d.fields.insert("section".into(), json!("justify"));+ return Err(e);+ }+ 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());+ }}- regex::Regex::new(p).map(|_| ()).map_err(|_| ())+ 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)+ };+ // The style now exists under `style`: if a later step fails, the dialog stays open on it and+ // a second OK edits it rather than creating another one.+ d.fields.insert("new".into(), json!(false));+ d.fields.insert("name".into(), json!(&style));+ d.fields.insert("rename".into(), json!(&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")}))?;+ }+ Ok(r)}+ /// Preview the changed style attributes through the same engine commands as OK. Renaming and+ /// export tagging have no visual effect and wait for OK, so the dialog can keep looking up the+ /// original style while the preview is visible. The interaction restores its starting document+ /// before each update, including after a field is cleared or Preview is switched off.+ fn style_options_preview(app: &mut DesignApp, d: &mut Dialog) {+ let shown = d.fields.get(PREVIEWED).cloned();+ if !d.b("preview") || d.b("new") {+ if shown.is_some() {+ app.session.cancel_interaction();+ d.fields.remove(PREVIEWED);+ d.fields.remove("status");+ }+ return;+ }+ let paragraph = d.id == "paragraphStyleOptions";+ let mut params = json!({"name": d.s("name"), "chars": {}});+ if paragraph {+ params["para"] = json!({});+ }+ for (key, value) in &d.fields {+ if let Some(attr) = key.strip_prefix("c.") {+ params["chars"][attr] = value.clone();+ } else if paragraph && let Some(attr) = key.strip_prefix("p.") {+ if let Some((attr, field)) = attr.split_once('.') {+ if params["para"][attr].is_null() {+ params["para"][attr] = json!({});+ }+ if let Some(fields) = params["para"][attr].as_object_mut() {+ fields.insert(field.into(), value.clone());+ }+ } else {+ params["para"][attr] = value.clone();+ }+ }+ }+ if let Some(based) = d.fields.get("basedOn") {+ params["basedOn"] = match based.as_str() {+ Some(designcraft_doc::NO_PARA_STYLE | designcraft_doc::NO_CHAR_STYLE) => Value::Null,+ _ => based.clone(),+ };+ }+ if shown.as_ref() == Some(¶ms) {+ return;+ }+ if shown.is_none()+ && let Err(error) = app.session.begin_interaction("Style Options")+ {+ d.fields.insert("status".into(), json!(error.to_string()));+ return;+ }+ let command = if paragraph { "style.paragraph.edit" } else { "style.character.edit" };+ match app.session.preview(command, params.clone()) {+ Ok(()) => d.fields.remove("status"),+ Err(error) => d.fields.insert("status".into(), json!(error.to_string())),+ };+ d.fields.insert(PREVIEWED.into(), params);+ }++/// Paragraph Style Options: sections in a left list (like InDesign), fields on the right.+/// Edited values are stored as `p.<attr>` / `c.<attr>` fields and applied on OK.fn paragraph_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {let name = d.s("name");let new = d.b("new");@@@ -5570,1935 -4630,425 +5636,2036 @@@ fn justification(lang: &str, ui: &mut e}}-/// `edit.stepAndRepeat`'s params from the dialog: whole counts, offsets in the ruler units-/// (or any unit typed: "-0.75 in", "3p"). Empty fields are 1 copy and 1p0.-fn step_and_repeat_params(app: &DesignApp, d: &Dialog) -> Result<Value, String> {- let (hu, vu) = app.session.active().map_or((Unit::Picas, Unit::Picas), |s| (s.doc.settings.horizontal_units, s.doc.settings.vertical_units));- let invalid = |s: &str| format!("{}: {}", crate::i18n::tr(&app.ui.language, "Invalid value"), s.trim());- // Fields not shown yet (a dialog confirmed over the control channel) take the defaults.- let whole = |k: &str| {- let s = d.s(k);- if s.trim().is_empty() { Ok(1) } else { s.trim().parse::<u64>().map_err(|_| invalid(&s)) }- };- let measure = |k: &str, u: Unit| {- let s = d.s(k);- if s.trim().is_empty() {- return Ok(12.0);- }- parse_measure(&s, u).ok().filter(|v| v.is_finite()).ok_or_else(|| invalid(&s))- };- let (dx, dy) = (measure("horizontal", hu)?, measure("vertical", vu)?);- Ok(if d.b("grid") {- json!({"rows": whole("rows")?, "columns": whole("columns")?, "dx": dx, "dy": dy})- } else {- json!({"count": whole("count")?, "dx": dx, "dy": dy})- })-}--/// Preview on: the copies show on the page (redone when a field changes); off: they go.-fn step_and_repeat_preview(app: &mut DesignApp, d: &mut Dialog) {- let shown = d.fields.get(PREVIEWED).cloned();- if !d.b("preview") {- if shown.is_some() {- app.session.cancel_interaction();- d.fields.remove(PREVIEWED);- d.fields.remove("status");- }- return;- }- let params = match step_and_repeat_params(app, d) {- Ok(p) => p,- Err(e) => {- d.fields.insert("status".into(), json!(e));- return;+/// 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));}- };- if shown.as_ref() == Some(¶ms) {- return;- }- if shown.is_none()- && let Err(e) = app.session.begin_interaction("Step and Repeat")- {- d.fields.insert("status".into(), json!(e.to_string()));- return;}- match app.session.preview("edit.stepAndRepeat", params.clone()) {- Ok(()) => d.fields.remove("status"),- Err(e) => d.fields.insert("status".into(), json!(e.to_string())),- };- d.fields.insert(PREVIEWED.into(), params);+ out}-/// 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]";+/// 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| {- 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));+ 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)));}- 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),- ));+ 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));}- });- } 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.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();});- }- 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)+/// 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));+ }+ }});- 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);- }- });+ 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();});- });- if c != before {- d.fields.insert("hex".into(), json!(format!("#{:02x}{:02x}{:02x}", c.r(), c.g(), c.b())));+ 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));+ }+}++const STEP_AND_REPEAT: &str = "cmd:edit.stepAndRepeat";+const TOC: &str = "cmd:toc.generate";++/// One included style of the Table of Contents dialog, as `toc.generate` takes it, with the+/// separator in the dialog's notation (`^t` a tab).+#[derive(Clone, Debug, Default, Deserialize, Serialize)]+#[serde(rename_all = "camelCase", default)]+struct TocRow {+ style: String,+ level: u8,+ entry_style: String,+ page_number: String,+ separator: String,+}++fn toc_separator_shown(s: &str) -> String {+ s.replace('\t', "^t").replace('\u{2003}', "^m").replace('\u{2002}', "^>")+}++fn toc_separator_typed(s: &str) -> String {+ s.replace("^t", "\t").replace("^m", "\u{2003}").replace("^>", "\u{2002}")+}++fn toc_rows(d: &Dialog) -> Vec<TocRow> {+ d.fields.get("included").cloned().and_then(|v| serde_json::from_value(v).ok()).unwrap_or_default()+}++/// Layout › Table of Contents…: prefilled from the document's table of contents when it has one.+pub fn open_toc(app: &mut DesignApp) {+ let Some(st) = app.session.active() else { return };+ let d = &st.doc;+ let styles: Vec<&str> = d.styles.paragraph.iter().map(|p| p.name.as_str()).filter(|n| *n != designcraft_doc::NO_PARA_STYLE).collect();+ let toc = d.toc.as_ref().filter(|t| d.story(t.story).is_some());+ let rows: Vec<TocRow> = toc+ .map(|t| {+ t.entries+ .iter()+ .map(|e| TocRow {+ style: e.style.clone(),+ level: e.level,+ entry_style: e.entry_style.clone().unwrap_or_default(),+ page_number: match (t.page_numbers, e.page_number) {+ (false, _) | (_, designcraft_doc::TocPageNumber::None) => "none",+ (_, designcraft_doc::TocPageNumber::Before) => "before",+ _ => "after",+ }+ .into(),+ separator: toc_separator_shown(e.separator.as_deref().unwrap_or("\t")),+ })+ .collect()+ })+ .unwrap_or_default();+ let fields = json!({+ "title": toc.map_or("Contents", |t| t.title.as_str()),+ "titleStyle": toc.and_then(|t| t.title_style.clone()).unwrap_or_default(),+ "included": rows,+ "selected": 0,+ "styles": styles,+ "hasToc": toc.is_some(),+ "replace": toc.is_some(),+ });+ app.ui.dialog = Some(Dialog::new(TOC, fields));+}++/// The dialog's fields as `toc.generate` params. A new frame goes on the page in view.+fn toc_params(app: &DesignApp, d: &Dialog) -> Value {+ let entries: Vec<Value> = toc_rows(d)+ .iter()+ .map(|r| {+ let mut e = json!({"style": r.style, "level": r.level, "separator": toc_separator_typed(&r.separator)});+ if !r.entry_style.is_empty() {+ e["entryStyle"] = json!(r.entry_style);+ }+ if !r.page_number.is_empty() {+ e["pageNumber"] = json!(r.page_number);+ }+ e+ })+ .collect();+ let mut p = json!({"title": d.s("title"), "entries": entries, "replace": d.b("replace")});+ let title_style = d.s("titleStyle");+ if !title_style.is_empty() {+ p["titleStyle"] = json!(title_style);+ }+ if let Some(page) = crate::canvas::current_page(app) {+ p["page"] = json!(page + 1);+ }+ p+}++/// A paragraph style menu whose first choice, stored as "", is the generated style `auto`.+fn toc_style_combo(ui: &mut egui::Ui, salt: &str, styles: &[String], auto: &str, cur: &mut String) -> bool {+ let shown = if cur.is_empty() { auto.to_string() } else { cur.clone() };+ let mut changed = false;+ egui::ComboBox::from_id_salt(("toc_style", salt)).selected_text(shown).width(200.0).show_ui(ui, |ui| {+ if ui.selectable_label(cur.is_empty(), auto).clicked() {+ cur.clear();+ changed = true;+ }+ for n in styles.iter().filter(|n| *n != auto) {+ if ui.selectable_label(cur == n, n.as_str()).clicked() {+ *cur = n.clone();+ changed = true;+ }+ }+ });+ changed+}++/// Layout › Table of Contents: the title and its style, the paragraph styles to include (Add /+/// Remove between the two lists) and, for the selected one, its entry style, page number+/// position, separator and level.+fn toc_dialog(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {+ let lang = app.ui.language.clone();+ let tr = |s: &str| crate::i18n::tr(&lang, s).to_string();+ let styles: Vec<String> = d.fields.get("styles").cloned().and_then(|v| serde_json::from_value(v).ok()).unwrap_or_default();+ let mut rows = toc_rows(d);+ let mut sel = d.n("selected").map_or(0, |n| n.max(0.0) as usize);+ let mut other = d.s("other");+ let mut title_style = d.s("titleStyle");+ egui::Grid::new("toc_title").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, tr("Title:"));+ text_field(ui, d, "title", 200.0);+ crate::rtl::label(ui, tr("Style:"));+ toc_style_combo(ui, "title", &styles, "TOC Title", &mut title_style);+ ui.end_row();+ });+ ui.add_space(8.0);+ crate::rtl::label(ui, egui::RichText::new(tr("Styles in Table of Contents")).font(semibold(12.0)));+ let others: Vec<&String> = styles.iter().filter(|n| !rows.iter().any(|r| &r.style == *n)).collect();+ ui.horizontal_top(|ui| {+ ui.vertical(|ui| {+ crate::rtl::label(ui, tr("Include Paragraph Styles:"));+ egui::Frame::group(ui.style()).show(ui, |ui| {+ ui.set_width(200.0);+ egui::ScrollArea::vertical().id_salt("toc_included").max_height(150.0).min_scrolled_height(150.0).show(ui, |ui| {+ for (i, r) in rows.iter().enumerate() {+ let indent = " ".repeat(usize::from(r.level.saturating_sub(1)));+ if ui.selectable_label(i == sel, format!("{indent}{}", r.style)).clicked() {+ sel = i;+ }+ }+ });+ });+ });+ ui.vertical(|ui| {+ ui.add_space(40.0);+ if ui.button(tr("« Add")).clicked() && others.iter().any(|n| **n == other) {+ let level = u8::try_from(rows.len() + 1).unwrap_or(9).min(9);+ rows.push(TocRow { style: other.clone(), level, page_number: "after".into(), separator: "^t".into(), ..Default::default() });+ sel = rows.len() - 1;+ other.clear();+ }+ if ui.button(tr("Remove »")).clicked() && sel < rows.len() {+ other = rows.remove(sel).style;+ sel = sel.min(rows.len().saturating_sub(1));+ }+ });+ ui.vertical(|ui| {+ crate::rtl::label(ui, tr("Other Styles:"));+ egui::Frame::group(ui.style()).show(ui, |ui| {+ ui.set_width(200.0);+ egui::ScrollArea::vertical().id_salt("toc_other").max_height(150.0).min_scrolled_height(150.0).show(ui, |ui| {+ for n in styles.iter().filter(|n| !rows.iter().any(|r| &r.style == *n)) {+ if ui.selectable_label(*n == other, n.as_str()).clicked() {+ other = n.clone();+ }+ }+ });+ });+ });+ });+ if let Some(r) = rows.get_mut(sel) {+ ui.add_space(8.0);+ crate::rtl::label(ui, egui::RichText::new(format!("{} {}", tr("Style:"), r.style)).font(semibold(12.0)));+ egui::Grid::new("toc_entry").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, tr("Entry Style:"));+ let auto = format!("TOC Level {}", r.level.clamp(1, 9));+ toc_style_combo(ui, "entry", &styles, &auto, &mut r.entry_style);+ ui.end_row();+ crate::rtl::label(ui, tr("Page Number:"));+ let choices = [("after", "After Entry"), ("before", "Before Entry"), ("none", "No Page Number")];+ let cur = choices.iter().find(|(v, _)| *v == r.page_number).map_or("After Entry", |(_, l)| l);+ egui::ComboBox::from_id_salt("toc_page_number").selected_text(tr(cur)).width(200.0).show_ui(ui, |ui| {+ for (v, l) in choices {+ if ui.selectable_label(r.page_number == v, tr(l)).clicked() {+ r.page_number = v.into();+ }+ }+ });+ ui.end_row();+ crate::rtl::label(ui, tr("Between Entry and Number:"));+ ui.add(egui::TextEdit::singleline(&mut r.separator).desired_width(80.0).horizontal_align(egui::Align::Min));+ ui.end_row();+ crate::rtl::label(ui, tr("Level:"));+ egui::ComboBox::from_id_salt("toc_level").selected_text(r.level.to_string()).width(60.0).show_ui(ui, |ui| {+ for l in 1..=9u8 {+ if ui.selectable_label(r.level == l, l.to_string()).clicked() {+ r.level = l;+ }+ }+ });+ ui.end_row();+ });+ }+ ui.add_space(8.0);+ crate::rtl::label(ui, egui::RichText::new(tr("Options")).font(semibold(12.0)));+ let has_toc = d.b("hasToc");+ ui.add_enabled_ui(has_toc, |ui| check(ui, d, "replace", &tr("Replace Existing Table of Contents")));+ if let Some(st) = d.fields.get("status").and_then(Value::as_str) {+ ui.add_space(6.0);+ crate::rtl::label(ui, egui::RichText::new(st).color(crate::theme::Tokens::get(ui.ctx()).text_dim));+ }+ d.fields.insert("included".into(), json!(rows));+ d.fields.insert("selected".into(), json!(sel));+ d.fields.insert("other".into(), json!(other));+ d.fields.insert("titleStyle".into(), json!(title_style));+}+/// The params a previewing dialog shows on the page (its interaction is open while it is set).+const PREVIEWED: &str = "_previewed";++/// Edit › Step and Repeat, as in InDesign: Repeat (Count, or Rows and Columns with Create as a+/// grid), Offset (Vertical, Horizontal, in the document's ruler units) and Preview, which shows+/// the copies on the page while the dialog is open.+fn step_and_repeat_dialog(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {+ let (hu, vu) = app.session.active().map_or((Unit::Picas, Unit::Picas), |s| (s.doc.settings.horizontal_units, s.doc.settings.vertical_units));+ for (k, v) in [+ ("count", json!("1")),+ ("rows", json!("1")),+ ("columns", json!("1")),+ ("vertical", json!(format_measure(12.0, vu))),+ ("horizontal", json!(format_measure(12.0, hu))),+ ] {+ d.fields.entry(k).or_insert(v);+ }+ let lang = app.ui.language.clone();+ let tr = |s: &str| crate::i18n::tr(&lang, s).to_string();+ ui.horizontal_top(|ui| {+ ui.vertical(|ui| {+ crate::rtl::label(ui, egui::RichText::new(tr("Repeat")).font(semibold(12.0)));+ egui::Grid::new("sr_repeat").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ let grid = d.b("grid");+ let fields: &[(&str, &str)] = if grid { &[("rows", "Rows:"), ("columns", "Columns:")] } else { &[("count", "Count:")] };+ for (k, l) in fields {+ // A grid's columns, not a text frame's.+ crate::rtl::label(ui, crate::i18n::tr_context(&lang, l, "grid"));+ text_field(ui, d, k, 70.0);+ ui.end_row();+ }+ crate::rtl::label(ui, "");+ check(ui, d, "grid", &tr("Create as a grid"));+ ui.end_row();+ });+ ui.add_space(10.0);+ crate::rtl::label(ui, egui::RichText::new(tr("Offset")).font(semibold(12.0)));+ ui.horizontal(|ui| {+ for (k, l) in [("vertical", "Vertical:"), ("horizontal", "Horizontal:")] {+ crate::rtl::label(ui, tr(l));+ text_field(ui, d, k, 80.0);+ ui.add_space(12.0);+ }+ });+ });+ ui.add_space(32.0);+ check(ui, d, "preview", &tr("Preview"));+ });+ step_and_repeat_preview(app, d);+ if let Some(st) = d.fields.get("status").and_then(Value::as_str) {+ ui.add_space(6.0);+ crate::rtl::label(ui, egui::RichText::new(st).color(crate::theme::Tokens::get(ui.ctx()).text_dim));+ }+}++/// `edit.stepAndRepeat`'s params from the dialog: whole counts, offsets in the ruler units+/// (or any unit typed: "-0.75 in", "3p"). Empty fields are 1 copy and 1p0.+fn step_and_repeat_params(app: &DesignApp, d: &Dialog) -> Result<Value, String> {+ let (hu, vu) = app.session.active().map_or((Unit::Picas, Unit::Picas), |s| (s.doc.settings.horizontal_units, s.doc.settings.vertical_units));+ let invalid = |s: &str| format!("{}: {}", crate::i18n::tr(&app.ui.language, "Invalid value"), s.trim());+ // Fields not shown yet (a dialog confirmed over the control channel) take the defaults.+ let whole = |k: &str| {+ let s = d.s(k);+ if s.trim().is_empty() { Ok(1) } else { s.trim().parse::<u64>().map_err(|_| invalid(&s)) }+ };+ let measure = |k: &str, u: Unit| {+ let s = d.s(k);+ if s.trim().is_empty() {+ return Ok(12.0);+ }+ parse_measure(&s, u).ok().filter(|v| v.is_finite()).ok_or_else(|| invalid(&s))+ };+ let (dx, dy) = (measure("horizontal", hu)?, measure("vertical", vu)?);+ Ok(if d.b("grid") {+ json!({"rows": whole("rows")?, "columns": whole("columns")?, "dx": dx, "dy": dy})+ } else {+ json!({"count": whole("count")?, "dx": dx, "dy": dy})+ })+}++/// Preview on: the copies show on the page (redone when a field changes); off: they go.+fn step_and_repeat_preview(app: &mut DesignApp, d: &mut Dialog) {+ let shown = d.fields.get(PREVIEWED).cloned();+ if !d.b("preview") {+ if shown.is_some() {+ app.session.cancel_interaction();+ d.fields.remove(PREVIEWED);+ d.fields.remove("status");+ }+ return;+ }+ let params = match step_and_repeat_params(app, d) {+ Ok(p) => p,+ Err(e) => {+ d.fields.insert("status".into(), json!(e));+ return;+ }+ };+ if shown.as_ref() == Some(¶ms) {+ return;+ }+ if shown.is_none()+ && let Err(e) = app.session.begin_interaction("Step and Repeat")+ {+ d.fields.insert("status".into(), json!(e.to_string()));+ return;+ }+ match app.session.preview("edit.stepAndRepeat", params.clone()) {+ Ok(()) => d.fields.remove("status"),+ Err(e) => d.fields.insert("status".into(), json!(e.to_string())),+ };+ d.fields.insert(PREVIEWED.into(), params);+}++/// 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));+ }+}++/// `N` numbers from a dialog field holding a JSON array.+fn nums<const N: usize>(d: &Dialog, k: &str) -> Option<[f64; N]> {+ let a = d.fields.get(k)?.as_array()?;+ if a.len() != N {+ return None;+ }+ let mut out = [0.0; N];+ for (o, v) in out.iter_mut().zip(a) {+ *o = v.as_f64().filter(|x| x.is_finite())?;+ }+ Some(out)+}++/// What changed the Color Picker's colour this frame.+#[derive(Clone, Copy, PartialEq)]+enum ColorEdit {+ None,+ /// The saturation/brightness field, the hue slider or the hex field: keeps the colour's model.+ Picked,+ /// Typed R/G/B values: the colour becomes RGB.+ Rgb,+ /// Typed C/M/Y/K values: the colour becomes CMYK.+ Cmyk,+}++/// Color Picker: saturation/brightness field and hue slider, with R/G/B, C/M/Y/K and hex fields.+///+/// `rgb` (0-255) and `cmyk` (percent) hold the values as typed, so a field being edited is never+/// rebuilt from the colour; the hex field keeps its text in `hexEdit` while it has focus and shows+/// the colour again when focus leaves. `model` is what OK applies: picking keeps a CMYK colour CMYK+/// (converted through the CMYK working space); typing R/G/B or C/M/Y/K values chooses that model.+fn color_picker(ui: &mut egui::Ui, d: &mut Dialog) {+ use designcraft_color::Color;+ let to8 = |v: f64| v.clamp(0.0, 255.0).round() as u8;+ let display_rgb = |c: Color| c.to_rgb().map(|v| (f64::from(v) * 255.0).clamp(0.0, 255.0).round());+ let cmyk_of = |rgb: [f64; 3]| {+ let c = Color::rgb((rgb[0] / 255.0) as f32, (rgb[1] / 255.0) as f32, (rgb[2] / 255.0) as f32);+ c.to_cmyk_managed(designcraft_color::cms::active_settings().intent).map(|v| f64::from(v) * 100.0)+ };+ let hex_rgb = |s: &str| match Color::from_hex(s) {+ Some(Color::Rgb { r, g, b }) => Some([r, g, b].map(|v| (f64::from(v) * 255.0).round())),+ _ => None,+ };+ let mut rgb = nums::<3>(d, "rgb").unwrap_or_else(|| hex_rgb(&d.s("hex")).unwrap_or([0.0; 3]));+ let mut cmyk = nums::<4>(d, "cmyk").unwrap_or_else(|| cmyk_of(rgb));+ let mut model = if d.s("model") == "cmyk" || (!d.fields.contains_key("model") && d.fields.contains_key("cmyk")) { "cmyk" } else { "rgb" };+ let mut edit = ColorEdit::None;+ let hex_id = egui::Id::new("color_picker_hex");+ ui.horizontal_top(|ui| {+ let mut c = egui::Color32::from_rgb(to8(rgb[0]), to8(rgb[1]), to8(rgb[2]));+ let shown = c;+ if egui::color_picker::color_picker_color32(ui, &mut c, egui::color_picker::Alpha::Opaque) && c != shown {+ rgb = [c.r(), c.g(), c.b()].map(f64::from);+ edit = ColorEdit::Picked;+ }+ ui.vertical(|ui| {+ egui::Grid::new("cp_values").num_columns(4).spacing([6.0, 4.0]).show(ui, |ui| {+ let mut rgb_rows = rgb.iter_mut().zip(["R", "G", "B"]);+ for (v, l) in cmyk.iter_mut().zip(["C", "M", "Y", "K"]) {+ if let Some((rv, rl)) = rgb_rows.next() {+ ui.label(rl);+ if ui.add(egui::DragValue::new(rv).range(0.0..=255.0).max_decimals(1)).changed() {+ edit = ColorEdit::Rgb;+ }+ } else {+ ui.label("");+ ui.label("");+ }+ ui.label(l);+ if ui.add(egui::DragValue::new(v).range(0.0..=100.0).max_decimals(1).suffix("%")).changed() {+ edit = ColorEdit::Cmyk;+ }+ ui.end_row();+ }+ });+ ui.add_space(6.0);+ ui.horizontal(|ui| {+ ui.label("#");+ let editing = ui.memory(|m| m.has_focus(hex_id));+ let mut h = if editing { d.s("hexEdit") } else { format!("{:02x}{:02x}{:02x}", to8(rgb[0]), to8(rgb[1]), to8(rgb[2])) };+ if ui.add(egui::TextEdit::singleline(&mut h).id(hex_id).desired_width(70.0)).changed()+ && let Some(v) = hex_rgb(&h)+ {+ rgb = v;+ edit = ColorEdit::Picked;+ }+ d.fields.insert("hexEdit".into(), json!(h));+ });+ });+ });+ match edit {+ ColorEdit::None => {}+ ColorEdit::Picked => cmyk = cmyk_of(rgb),+ ColorEdit::Rgb => {+ model = "rgb";+ cmyk = cmyk_of(rgb);+ }+ ColorEdit::Cmyk => {+ model = "cmyk";+ let [c, m, y, k] = cmyk.map(|v| (v / 100.0) as f32);+ rgb = display_rgb(Color::cmyk(c, m, y, k));+ }+ }+ if edit != ColorEdit::None {+ d.fields.insert("edited".into(), json!(true));+ }+ d.fields.insert("rgb".into(), json!(rgb));+ d.fields.insert("cmyk".into(), json!(cmyk));+ d.fields.insert("model".into(), json!(model));+ d.fields.insert("hex".into(), json!(format!("#{:02x}{:02x}{:02x}", to8(rgb[0]), to8(rgb[1]), to8(rgb[2]))));+}++/// Find/Replace Font: the document's fonts (missing ones first, flagged) and a replacement.+/// Load Styles: a checkbox for each style of the picked file, and what happens to a style this+/// document defines differently under the same name.+fn load_styles(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {+ let lang = app.ui.language.as_str();+ let dim = crate::theme::Tokens::get(ui.ctx()).text_dim;+ ui.label(egui::RichText::new(d.s("path")).size(10.5));+ ui.horizontal(|ui| {+ for (label, on) in [("Select All", true), ("Deselect All", false)] {+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() {+ for key in ["paragraph", "character"] {+ for row in d.fields.get_mut(key).and_then(Value::as_array_mut).into_iter().flatten().filter_map(Value::as_object_mut) {+ row.insert("on".into(), json!(on));+ }+ }+ }+ }+ });+ let mut conflicts = 0;+ egui::ScrollArea::vertical().id_salt("load_styles").max_height(240.0).show(ui, |ui| {+ for (key, title) in [("paragraph", "Paragraph Styles"), ("character", "Character Styles")] {+ let Some(rows) = d.fields.get_mut(key).and_then(Value::as_array_mut).filter(|rows| !rows.is_empty()) else { continue };+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(lang, title)).font(semibold(12.0)));+ for row in rows.iter_mut().filter_map(Value::as_object_mut) {+ let Some(name) = row.get("name").and_then(Value::as_str).map(str::to_string) else { continue };+ let (mut on, conflict) = (row.get("on") != Some(&json!(false)), row.get("conflict") == Some(&json!(true)));+ ui.horizontal(|ui| {+ if ui.checkbox(&mut on, crate::rtl::widget(ui, crate::i18n::style_name(lang, &name))).changed() {+ row.insert("on".into(), json!(on));+ }+ if conflict {+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(lang, "Differs from this document")).size(10.5).color(dim));+ }+ });+ conflicts += usize::from(on && conflict);+ }+ }+ });+ ui.add_space(4.0);+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(lang, "Style Name Conflicts")).font(semibold(12.0)));+ if conflicts == 0 {+ crate::rtl::label(ui, crate::i18n::tr(lang, "No conflicts"));+ return;+ }+ let cur = d.s("conflicts");+ ui.horizontal(|ui| {+ for (v, l) in [("redefine", "Redefine Document Style"), ("useExisting", "Use Document Style Definition"), ("autoRename", "Auto Rename")] {+ if ui.radio(cur == v, crate::rtl::widget(ui, crate::i18n::tr(lang, l))).clicked() {+ d.fields.insert("conflicts".into(), json!(v));+ }+ }+ });+}++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,+ crate::i18n::tr(+ &app.ui.language,+ "This document uses unavailable fonts. Choose replacements, or select Done to continue with fallback fonts.",+ ),+ );+ }+ 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));+ }+ }+ });+ 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,+ 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) {+ let style = crate::panels::pick_style(app, &f);+ d.fields.insert("toFamily".into(), json!(f.family));+ d.fields.insert("toStyle".into(), json!(style));+ }+ ui.end_row();+ 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),+ ));+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn step_and_repeat_dialog_previews_and_makes_the_copies_as_one_undo_step() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let id = app.run("frame.create", json!({"rect": [72, 600, 540, 640]})).unwrap()["id"].as_u64().unwrap();+ app.run("selection.set", json!({"ids": [id]})).unwrap();+ let open = |app: &mut DesignApp| {+ crate::menus::activate(app, "edit.stepAndRepeat", &Value::Null);+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some(STEP_AND_REPEAT));+ };+ let set = |app: &mut DesignApp, k: &str, v: Value| {+ app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v);+ };+ let items = |app: &DesignApp| app.session.doc().unwrap().doc.spreads[0].items.len();+ let undo = |app: &DesignApp| app.session.doc().unwrap().history.undo.len();+ let (n0, u0) = (items(&app), undo(&app));+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0));+ open(&mut app);+ dialog_frame(&mut app, &ctx, screen, vec![]);+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ for expected in ["Step and Repeat", "Repeat", "Count:", "Create as a grid", "Offset", "Vertical:", "Horizontal:", "Preview", "OK", "Cancel"] {+ visible_label(&labels, screen, expected);+ }+ // Preview: the copies show, and change with the fields, without an undo step.+ set(&mut app, "count", json!("5"));+ set(&mut app, "vertical", json!("-0.75 in"));+ set(&mut app, "horizontal", json!("0"));+ set(&mut app, "preview", json!(true));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert_eq!((items(&app), undo(&app)), (n0 + 5, u0));+ set(&mut app, "count", json!("3"));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert_eq!(items(&app), n0 + 3);+ set(&mut app, "preview", json!(false));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert_eq!(items(&app), n0, "Preview off takes them away");+ set(&mut app, "preview", json!(true));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert_eq!(items(&app), n0 + 3);+ // Cancel puts the document back.+ cancel(&mut app);+ assert!(app.ui.dialog.is_none());+ assert_eq!((items(&app), undo(&app)), (n0, u0));+ // OK after a preview makes the copies once, as one undo step, 0.75 in apart.+ app.run("selection.set", json!({"ids": [id]})).unwrap();+ open(&mut app);+ set(&mut app, "count", json!("2"));+ set(&mut app, "vertical", json!("-0.75 in"));+ set(&mut app, "horizontal", json!("0"));+ set(&mut app, "preview", json!(true));+ dialog_frame(&mut app, &ctx, screen, vec![]);+ let r = confirm(&mut app).unwrap();+ assert_eq!((items(&app), undo(&app)), (n0 + 2, u0 + 1));+ let last = r["ids"][1].as_u64().unwrap();+ let top = app.session.doc().unwrap().doc.item(designcraft_doc::ItemId(last)).unwrap().bounds().min_y();+ assert!((top - (600.0 - 108.0)).abs() < 1e-6, "{top}");+ // Create as a grid: Rows × Columns cells, the original being one.+ app.run("selection.set", json!({"ids": [id]})).unwrap();+ open(&mut app);+ set(&mut app, "grid", json!(true));+ set(&mut app, "rows", json!("2"));+ set(&mut app, "columns", json!("3"));+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ visible_label(&labels, screen, "Rows:");+ visible_label(&labels, screen, "Columns:");+ assert_eq!(confirm(&mut app).unwrap()["created"], 5);+ // A value that isn't a measure keeps the dialog open and says so.+ open(&mut app);+ set(&mut app, "vertical", json!("up"));+ assert!(confirm(&mut app).is_err());+ let d = app.ui.dialog.as_ref().unwrap();+ assert_eq!(d.s("status"), "Invalid value: up");+ }++ /// 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+ }++ 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());+ }+ }++ #[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");+ }+ }++ #[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]);+ }++ #[test]+ fn preferences_ok_saves_a_story_editor_size_that_loads_back() {+ // `ui.dialog.set` takes any value; a size that isn't finite is saved as `null`.+ let sizes = [(json!("nan"), 20.0), (json!("inf"), 20.0), (json!(null), 20.0), (json!(1e39), 36.0), (json!(3), 8.0), (json!(11), 11.0)];+ for (size, want) in sizes {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.ui.story_editor_size = 20.0;+ app.run("app.preferences", json!({})).unwrap();+ app.ui.dialog.as_mut().unwrap().fields.insert("storyEditorSize".into(), size);+ confirm(&mut app).unwrap();+ let saved = serde_json::to_vec(&app.ui).unwrap();+ assert_eq!(crate::UiState::from_preferences_json(&saved).unwrap().story_editor_size, want);+ }+ }++ #[test]+ fn preferences_ok_sets_only_the_ruler_units_it_is_given() {+ // `ui.dialog.open` takes any fields, so the vertical units can be missing.+ for (vertical, want) in [(None, "inches"), (Some("points"), "points")] {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("document.preferences", json!({"verticalUnits": "inches"})).unwrap();+ let mut fields = json!({"horizontalUnits": "millimeters", "bg.relativeTo": "topOfPage"});+ if let Some(vertical) = vertical {+ fields["verticalUnits"] = json!(vertical);+ }+ app.ui.dialog = Some(Dialog::new("preferences", fields));+ confirm(&mut app).unwrap();+ let units = app.run("document.preferences", json!({})).unwrap();+ assert_eq!((units["horizontalUnits"].as_str(), units["verticalUnits"].as_str()), (Some("millimeters"), Some(want)));+ }+ }++ #[test]+ fn enter_and_escape_close_the_style_menu_not_numbering_and_section_options() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"pages": 2})).unwrap();+ crate::menus::activate(&mut app, "layout.section", &Value::Null);+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };+ for pressed in [egui::Key::Enter, egui::Key::Escape] {+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ // The section's Style menu (the first of the two).+ let style = labels.iter().filter(|(t, r, c)| t.trim() == "1, 2, 3, 4…" && c.contains_rect(*r)).map(|(_, r, _)| *r).next().unwrap();+ click_dialog(&mut app, &ctx, screen, style.center());+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert!(egui::Popup::is_any_open(&ctx), "the Style menu opened");+ dialog_frame(&mut app, &ctx, screen, vec![key(pressed)]);+ dialog_frame(&mut app, &ctx, screen, vec![]);+ assert!(app.ui.dialog.is_some(), "{pressed:?} with the menu open leaves the dialog open");+ assert!(app.session.active().unwrap().doc.sections.iter().all(|s| s.start_number != Some(0)));+ if egui::Popup::is_any_open(&ctx) {+ egui::Popup::close_all(&ctx);+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ }+ // With no menu open, Escape closes the dialog.+ dialog_frame(&mut app, &ctx, screen, vec![key(egui::Key::Escape)]);+ assert!(app.ui.dialog.is_none());+ }++ #[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");+ }+ }+ }+ }++ fn select_all_key() -> egui::Event {+ egui::Event::Key {+ key: egui::Key::A,+ physical_key: None,+ pressed: true,+ repeat: false,+ modifiers: egui::Modifiers { ctrl: true, command: true, ..Default::default() },+ }+ }++ /// The Color Picker over a new document's selected frame, a few frames in.+ fn picker(fields: Value) -> (DesignApp, egui::Context, egui::Rect, u64) {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let id = app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap();+ app.run("selection.set", json!({"ids": [id]})).unwrap();+ app.ui.dialog = Some(Dialog::new("colorPicker", fields));+ let ctx = dialog_context("en");+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(700.0, 500.0));+ for _ in 0..3 {+ dialog_frame(&mut app, &ctx, screen, vec![]);+ }+ (app, ctx, screen, id)+ }++ /// The rightmost painted `text`: the picker's own field, right of egui's colour editor (which+ /// has R/G/B fields of its own).+ fn rightmost(labels: &[(String, egui::Rect, egui::Rect)], text: &str) -> egui::Pos2 {+ labels+ .iter()+ .filter(|(t, _, _)| t.trim() == text)+ .map(|(_, r, _)| r.center())+ .max_by(|a, b| a.x.total_cmp(&b.x))+ .unwrap_or_else(|| panic!("{text} is painted"))+ }++ /// Types `text` one character per frame, with an idle frame after each.+ fn type_slowly(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, text: &str) {+ for ch in text.chars() {+ dialog_frame(app, ctx, screen, vec![egui::Event::Text(ch.into())]);+ dialog_frame(app, ctx, screen, vec![]);+ }+ }++ fn fill(app: &DesignApp, id: u64) -> designcraft_color::Color {+ let d = &app.session.active().unwrap().doc;+ d.resolve_color(&d.item(designcraft_doc::ItemId(id)).unwrap().fill.swatch, 1.0).unwrap()+ }++ #[test]+ fn the_hex_field_keeps_typed_text_and_commits_a_valid_code() {+ let (mut app, ctx, screen, _) = picker(json!({"target": "fill", "hex": "#ffffff"}));+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "ffffff").center());+ dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]);+ type_slowly(&mut app, &ctx, screen, "#f5");+ let d = app.ui.dialog.as_ref().unwrap();+ assert_eq!((d.s("hexEdit").as_str(), d.s("hex").as_str()), ("#f5", "#ffffff"), "half-typed text stays; the colour waits");+ type_slowly(&mut app, &ctx, screen, "9019");+ let d = app.ui.dialog.as_ref().unwrap();+ assert_eq!((d.s("hexEdit").as_str(), d.s("hex").as_str()), ("#f59019", "#f59019"), "a 7-character #rrggbb commits");+ // Invalid text is replaced by the colour when focus leaves.+ dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]);+ type_slowly(&mut app, &ctx, screen, "zz");+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, "#").center());+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ visible_label(&labels, screen, "f59019");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("hex"), "#f59019");+ }++ #[test]+ fn typed_channel_values_are_kept_while_typing() {+ let (mut app, ctx, screen, id) = picker(json!({"target": "fill", "hex": "#010203", "model": "rgb", "rgb": [1, 2, 3]}));+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, rightmost(&labels, "1"));+ dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]);+ type_slowly(&mut app, &ctx, screen, "12.5");+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ assert!(rightmost(&labels, "12.5").x > rightmost(&labels, "2").x - 1.0, "the typed text stays in the R field");+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("hex"), "#0d0203");+ confirm(&mut app).unwrap();+ let designcraft_color::Color::Rgb { r, .. } = fill(&app, id) else { panic!("not RGB") };+ assert!((r - 12.5 / 255.0).abs() < 1e-6, "{r}");+ }++ #[test]+ fn a_cmyk_colour_stays_cmyk_unless_rgb_values_are_typed() {+ let cmyk = json!({"target": "fill", "hex": "#ff8000", "model": "cmyk", "cmyk": [0, 50, 100, 0]});+ // Picked by hex: converted to CMYK.+ let (mut app, ctx, screen, id) = picker(cmyk.clone());+ let hex = app.ui.dialog.as_ref().unwrap().s("hex");+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, hex.trim_start_matches('#')).center());+ dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]);+ type_slowly(&mut app, &ctx, screen, "3366cc");+ confirm(&mut app).unwrap();+ assert!(matches!(fill(&app, id), designcraft_color::Color::Cmyk { .. }), "{:?}", fill(&app, id));+ // A typed C/M/Y/K percent is a percent: M 1 is 1 %.+ let (mut app, ctx, screen, id) = picker(cmyk.clone());+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, rightmost(&labels, "50"));+ dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]);+ type_slowly(&mut app, &ctx, screen, "1");+ confirm(&mut app).unwrap();+ let designcraft_color::Color::Cmyk { c, m, y, k } = fill(&app, id) else { panic!("not CMYK") };+ assert!(c == 0.0 && (m - 0.01).abs() < 1e-6 && (y - 1.0).abs() < 1e-6 && k == 0.0, "{c} {m} {y} {k}");+ // Typed R/G/B values: RGB.+ let (mut app, ctx, screen, id) = picker(cmyk);+ let r = app.ui.dialog.as_ref().unwrap().fields["rgb"][0].as_f64().unwrap();+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, rightmost(&labels, &r.to_string()));+ dialog_frame(&mut app, &ctx, screen, vec![select_all_key()]);+ type_slowly(&mut app, &ctx, screen, "10");+ confirm(&mut app).unwrap();+ assert!(matches!(fill(&app, id), designcraft_color::Color::Rgb { .. }), "{:?}", fill(&app, id));+ }++ #[test]+ fn ok_without_edits_leaves_the_fill_alone() {+ let (mut app, _, _, id) = picker(json!({"target": "fill", "hex": "#ff8000", "model": "cmyk", "cmyk": [0, 50, 100, 0]}));+ let before = app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().fill.clone();+ confirm(&mut app).unwrap();+ assert_eq!(app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().fill, before);+ }++ #[test]+ fn dialogs_do_not_dim_the_page() {+ let (mut app, ctx, screen, _) = picker(json!({"target": "fill", "hex": "#ff8000"}));+ let time = ctx.input(|i| i.time) + 1.0 / 60.0;+ let output = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), ..Default::default() }, |ui| show(&mut app, ui.ctx()));+ fn covers(shape: &egui::Shape, screen: egui::Rect) -> bool {+ match shape {+ egui::Shape::Rect(r) => r.rect.contains_rect(screen) && r.fill.a() > 0,+ egui::Shape::Vec(v) => v.iter().any(|s| covers(s, screen)),+ _ => false,+ }+ }+ assert!(app.ui.dialog.is_some());+ assert!(!output.shapes.iter().any(|s| covers(&s.shape, screen)), "nothing paints over the whole window");+ }++ 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();+ }++ /// 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)+ }++ fn undo_steps(app: &DesignApp) -> usize {+ app.session.doc().map_or(0, |st| st.history.undo.len())+ }++ #[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);+ }++ /// A frame with two paragraphs of [Basic Paragraph]; the first has a local Word Spacing minimum.+ fn two_paragraphs() -> (DesignApp, Value) {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let r = app.run("frame.create", json!({"rect": [72, 72, 300, 400], "content": "text", "text": "One\nTwo"})).unwrap();+ app.run("text.select", json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();+ app.run("type.para", json!({"attrs": {"wordSpaceMin": 0.7}})).unwrap();+ (app, r["story"].clone())+ }++ /// The resolved paragraph attribute `key` of the paragraph at byte `at`.+ fn para_attr(app: &mut DesignApp, story: &Value, at: usize, key: &str) -> Value {+ app.run("text.select", json!({"story": story, "anchor": at, "focus": at})).unwrap();+ app.run("type.selectionAttrs", json!({})).unwrap()["para"][key].clone()+ }++ #[test]+ fn justification_dialog_applies_to_a_local_paragraph_and_cancel_changes_nothing() {+ let (mut app, story) = two_paragraphs();+ let ctx = egui::Context::default();+ assert!(crate::menus::menu_enabled(&app, "app.justificationDialog"));+ app.run("app.justificationDialog", json!({})).unwrap();+ draw(&mut app, &ctx);+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!(d.id, "justification");+ assert_eq!(d.fields["current"]["wordSpaceMin"], 0.7);+ assert_eq!(d.fields["current"]["wordSpaceDesired"], 1.0);+ app.ui.dialog.as_mut().unwrap().fields.insert("wordSpaceDesired".into(), json!(1.1));+ draw(&mut app, &ctx);+ let before = undo_steps(&app);+ confirm(&mut app).unwrap();+ assert_eq!(undo_steps(&app), before + 1, "one undo step");+ assert_eq!(para_attr(&mut app, &story, 0, "wordSpaceDesired"), 1.1);+ assert_eq!(para_attr(&mut app, &story, 0, "wordSpaceMin"), 0.7, "unedited fields stay");+ assert_eq!(para_attr(&mut app, &story, 4, "wordSpaceDesired"), 1.0, "only the selected paragraph");+ let style = app.session.doc().unwrap().doc.styles.resolve_para_style(designcraft_doc::story::BASIC_PARAGRAPH).0.word_space_desired;+ assert_eq!(style, 1.0, "the paragraph style keeps its value");++ // Cancel (Escape) leaves the paragraph alone.+ app.run("text.select", json!({"story": story, "anchor": 0, "focus": 0})).unwrap();+ app.run("app.justificationDialog", json!({})).unwrap();+ app.ui.dialog.as_mut().unwrap().fields.insert("wordSpaceDesired".into(), json!(1.2));+ let before = undo_steps(&app);+ let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };+ let input = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),+ events: vec![escape],+ ..Default::default()+ };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ assert!(app.ui.dialog.is_none(), "cancelled");+ assert_eq!(undo_steps(&app), before);+ assert_eq!(para_attr(&mut app, &story, 0, "wordSpaceDesired"), 1.1);++ app.run("edit.deselectAll", json!({})).unwrap();+ assert!(!crate::menus::menu_enabled(&app, "app.justificationDialog"), "nothing to justify");+ assert!(app.run("app.justificationDialog", json!({})).is_err());}-}-/// 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);+ #[test]+ fn justification_dialog_leaves_mixed_fields_alone_and_refuses_bad_values() {+ let (mut app, story) = two_paragraphs();+ let ctx = egui::Context::default();+ app.run("text.select", json!({"story": story, "anchor": 0, "focus": 7})).unwrap();+ app.run("app.justificationDialog", json!({})).unwrap();+ draw(&mut app, &ctx);+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!(d.fields["current"]["wordSpaceMin"], Value::Null, "mixed shows empty");+ assert_eq!(d.fields["current"]["wordSpaceMax"], 1.33);++ // Out of range, and minimum above desired: an error, the dialog stays open, nothing changes.+ let before = undo_steps(&app);+ for (key, v) in [("wordSpaceMax", 20.0), ("glyphScaleMin", 0.2), ("letterSpaceDesired", f64::NAN)] {+ app.ui.dialog = Some(d.clone());+ app.ui.dialog.as_mut().unwrap().fields.insert(key.into(), json!(v));+ assert!(confirm(&mut app).is_err(), "{key} = {v}");+ assert!(app.ui.dialog.as_ref().is_some_and(|d| d.fields.contains_key("justifyError")), "{key}: the dialog shows why");+ }+ app.ui.dialog = Some(d.clone());+ app.ui.dialog.as_mut().unwrap().fields.insert("letterSpaceMin".into(), json!(0.1));+ assert!(confirm(&mut app).is_err(), "letter spacing minimum above desired");+ draw(&mut app, &ctx);+ assert_eq!(undo_steps(&app), before);++ app.ui.dialog = Some(d);+ app.ui.dialog.as_mut().unwrap().fields.insert("wordSpaceMax".into(), json!(1.5));+ confirm(&mut app).unwrap();+ assert_eq!(undo_steps(&app), before + 1);+ for (at, min) in [(0, 0.7), (4, 0.8)] {+ assert_eq!(para_attr(&mut app, &story, at, "wordSpaceMax"), 1.5);+ assert_eq!(para_attr(&mut app, &story, at, "wordSpaceMin"), min, "each paragraph keeps its own minimum");+ }}- 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));++ 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+ }++ #[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);}+ // `primaryTextFrame` is documented since #776, so the dialog passes it on (`status` isn't).+ assert!(doc.spreads.iter().any(|s| !s.items.is_empty()), "documented fields reach the command");+ 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 style_options_preview_updates_all_uses_cancels_and_commits_once() {+ use egui_kittest::{Harness, kittest::Queryable};+ for paragraph in [true, false] {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let f = app.run("frame.create", json!({"rect":[36,36,300,300],"content":"text","text":"First\nSecond"})).unwrap();+ app.run("text.select", json!({"story":f["story"],"anchor":0,"focus":12})).unwrap();+ let kind = if paragraph { "paragraph" } else { "character" };+ app.run(&format!("style.{kind}.create"), json!({"name":"Tutorial","chars":{"size":10}})).unwrap();+ app.run(&format!("style.{kind}.apply"), json!({"name":"Tutorial"})).unwrap();+ let before = app.session.doc().unwrap().doc.clone();+ let undo = app.session.doc().unwrap().history.undo.len();+ let journal = app.session.journal.len();+ open_style_options(&mut app, paragraph, "Tutorial");+ let mut h = Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let key = egui::Id::new("style_preview_test_fonts");+ if ui.data(|d| d.get_temp::<bool>(key)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(key, true));+ return;+ }+ show(app, ui.ctx());+ },+ app,+ );+ h.run_steps(3);+ h.get_by_label("Preview").click();+ h.run_steps(3);+ h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("c.size".into(), json!(18));+ h.run_steps(3);+ let app = h.state_mut();+ assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["chars"]["size"], 18.0);+ assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);+ assert_eq!(app.session.journal.len(), journal);+ // Repeated previews replace each other, never accumulate undo entries.+ app.ui.dialog.as_mut().unwrap().fields.insert("c.size".into(), json!(20));+ h.run_steps(3);+ assert_eq!(h.state_mut().run("type.selectionAttrs", json!({})).unwrap()["chars"]["size"], 20.0);+ h.get_by_label("Preview").click();+ h.run_steps(3);+ assert_eq!(h.state().session.doc().unwrap().doc, before);+ h.get_by_label("Preview").click();+ h.run_steps(3);+ cancel(h.state_mut());+ assert_eq!(h.state().session.doc().unwrap().doc, before);+ assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo);+ open_style_options(h.state_mut(), paragraph, "Tutorial");+ let d = h.state_mut().ui.dialog.as_mut().unwrap();+ d.fields.insert("preview".into(), json!(true));+ d.fields.insert("c.size".into(), json!(24));+ h.run_steps(3);+ confirm(h.state_mut()).unwrap();+ assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo + 1);+ // Both paragraphs/character runs still use the globally edited definition.+ for pos in [0, 6] {+ h.state_mut().run("text.select", json!({"story":f["story"],"anchor":pos,"focus":pos+1})).unwrap();+ assert_eq!(h.state_mut().run("type.selectionAttrs", json!({})).unwrap()["chars"]["size"], 24.0);+ }+ h.state_mut().run("edit.undo", json!({})).unwrap();+ assert_eq!(h.state().session.doc().unwrap().doc, before);+ }+ }++ #[test]+ fn invalid_style_preview_leaves_the_starting_document_and_can_be_cancelled() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("style.character.create", json!({"name":"Emphasis"})).unwrap();+ let before = app.session.doc().unwrap().doc.clone();+ let mut d = Dialog::new("characterStyleOptions", json!({"name":"Emphasis","preview":true,"basedOn":"Emphasis"}));+ style_options_preview(&mut app, &mut d);+ assert!(d.fields.contains_key("status"));+ assert_eq!(app.session.doc().unwrap().doc, before);+ app.ui.dialog = Some(d);+ cancel(&mut app);+ assert_eq!(app.session.doc().unwrap().doc, before);+ assert!(app.session.doc().unwrap().interaction.is_none());+ }++ #[test]+ fn style_preview_rejects_conflicting_scalar_and_nested_rule_fields_without_panicking() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let before = app.session.doc().unwrap().doc.clone();+ let mut dialog = Dialog::new(+ "paragraphStyleOptions",+ json!({+ "name": designcraft_doc::BASIC_PARAGRAPH, "preview": true,+ "p.ruleAbove": false, "p.ruleAbove.weight": 2+ }),+ );+ style_options_preview(&mut app, &mut dialog);+ assert!(dialog.fields.contains_key("status"));+ assert_eq!(app.session.doc().unwrap().doc, before);+ app.ui.dialog = Some(dialog);+ cancel(&mut app);+ assert!(app.session.doc().unwrap().interaction.is_none());+ }+#[test]- fn step_and_repeat_dialog_previews_and_makes_the_copies_as_one_undo_step() {- let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ fn text_frame_options_set_columns_baseline_and_wrap_as_indesign_does() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());app.run("file.new", json!({})).unwrap();- let id = app.run("frame.create", json!({"rect": [72, 600, 540, 640]})).unwrap()["id"].as_u64().unwrap();- app.run("selection.set", json!({"ids": [id]})).unwrap();- let open = |app: &mut DesignApp| {- crate::menus::activate(app, "edit.stepAndRepeat", &Value::Null);- assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some(STEP_AND_REPEAT));- };- let set = |app: &mut DesignApp, k: &str, v: Value| {- app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v);+ // A 300 pt frame, 2 columns, 12 pt gutter (picas in the dialog).+ 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, "gutter": 12})).unwrap();+ let opts = |app: &DesignApp| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.clone();+ let mut d = Dialog::new("textFrameOptions", json!({}));+ seed_text_frame_options(&app, &mut d);+ // Fixed Number shows each column's width: (300 - 12) / 2 = 144 pt.+ assert_eq!((d.s("columnsKind"), d.s("columnWidth"), d.s("firstBaseline")), ("fixedNumber".into(), "12p0".into(), "ascent".into()));+ for (k, v) in [+ ("columnsKind", json!("fixedWidth")),+ ("columnWidth", json!("10p0")),+ ("firstBaseline", json!("capHeight")),+ ("firstBaselineMin", json!("0p6")),+ ("balanceColumns", json!(true)),+ ("ignoreWrap", json!(true)),+ ] {+ d.fields.insert(k.into(), v);+ }+ app.ui.dialog = Some(d);+ confirm(&mut app).unwrap();+ let o = opts(&app);+ assert_eq!(o.columns_kind, designcraft_doc::ColumnsKind::FixedWidth);+ assert_eq!((o.column_width, o.first_baseline_min, o.columns), (120.0, 6.0, 2));+ assert_eq!(o.first_baseline, designcraft_doc::FirstBaseline::CapHeight);+ assert!(o.balance_columns && o.ignore_wrap);+ // Fixed Number again: the width isn't sent.+ let mut d = Dialog::new("textFrameOptions", json!({}));+ seed_text_frame_options(&app, &mut d);+ assert_eq!(d.s("columnWidth"), "10p0", "Fixed Width shows its own width");+ d.fields.insert("columnsKind".into(), json!("fixedNumber"));+ app.ui.dialog = Some(d);+ confirm(&mut app).unwrap();+ assert_eq!((opts(&app).columns_kind, opts(&app).column_width), (designcraft_doc::ColumnsKind::FixedNumber, 120.0));+ }++ #[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)};- let items = |app: &DesignApp| app.session.doc().unwrap().doc.spreads[0].items.len();- let undo = |app: &DesignApp| app.session.doc().unwrap().history.undo.len();- let (n0, u0) = (items(&app), undo(&app));- let ctx = dialog_context("en");- let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0));- open(&mut app);- dialog_frame(&mut app, &ctx, screen, vec![]);- let labels = dialog_frame(&mut app, &ctx, screen, vec![]);- for expected in ["Step and Repeat", "Repeat", "Count:", "Create as a grid", "Offset", "Vertical:", "Horizontal:", "Preview", "OK", "Cancel"] {- visible_label(&labels, screen, expected);+ // 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]);+ open(&mut app, &[("balanceColumns", json!(true))]).unwrap();+ let o = opts(&app);+ assert!(o.balance_columns && o.column_rule && o.columns == 2, "{o:?}");+ // 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..4 {+ app.run("edit.undo", json!({})).unwrap();}- // Preview: the copies show, and change with the fields, without an undo step.- set(&mut app, "count", json!("5"));- set(&mut app, "vertical", json!("-0.75 in"));- set(&mut app, "horizontal", json!("0"));- set(&mut app, "preview", json!(true));- dialog_frame(&mut app, &ctx, screen, vec![]);- assert_eq!((items(&app), undo(&app)), (n0 + 5, u0));- set(&mut app, "count", json!("3"));- dialog_frame(&mut app, &ctx, screen, vec![]);- assert_eq!(items(&app), n0 + 3);- set(&mut app, "preview", json!(false));- dialog_frame(&mut app, &ctx, screen, vec![]);- assert_eq!(items(&app), n0, "Preview off takes them away");- set(&mut app, "preview", json!(true));- dialog_frame(&mut app, &ctx, screen, vec![]);- assert_eq!(items(&app), n0 + 3);- // Cancel puts the document back.- cancel(&mut app);- assert!(app.ui.dialog.is_none());- assert_eq!((items(&app), undo(&app)), (n0, u0));- // OK after a preview makes the copies once, as one undo step, 0.75 in apart.- app.run("selection.set", json!({"ids": [id]})).unwrap();- open(&mut app);- set(&mut app, "count", json!("2"));- set(&mut app, "vertical", json!("-0.75 in"));- set(&mut app, "horizontal", json!("0"));- set(&mut app, "preview", json!(true));- dialog_frame(&mut app, &ctx, screen, vec![]);- let r = confirm(&mut app).unwrap();- assert_eq!((items(&app), undo(&app)), (n0 + 2, u0 + 1));- let last = r["ids"][1].as_u64().unwrap();- let top = app.session.doc().unwrap().doc.item(designcraft_doc::ItemId(last)).unwrap().bounds().min_y();- assert!((top - (600.0 - 108.0)).abs() < 1e-6, "{top}");- // Create as a grid: Rows × Columns cells, the original being one.- app.run("selection.set", json!({"ids": [id]})).unwrap();- open(&mut app);- set(&mut app, "grid", json!(true));- set(&mut app, "rows", json!("2"));- set(&mut app, "columns", json!("3"));- let labels = dialog_frame(&mut app, &ctx, screen, vec![]);- visible_label(&labels, screen, "Rows:");- visible_label(&labels, screen, "Columns:");- assert_eq!(confirm(&mut app).unwrap()["created"], 5);- // A value that isn't a measure keeps the dialog open and says so.- open(&mut app);- set(&mut app, "vertical", json!("up"));- assert!(confirm(&mut app).is_err());- let d = app.ui.dialog.as_ref().unwrap();- assert_eq!(d.s("status"), "Invalid value: up");+ assert_eq!(opts(&app), before);}#[test]diff --cc docs/ui-parity.mdindex 619acc1f2,ef004bf1c..42df992d0--- a/docs/ui-parity.md+++ b/docs/ui-parity.md@@@ -59,40 -59,18 +59,50 @@@ Counted 2026-10-11: 28 rows, 12 ✓, 1for real work is lower, ~45%, because threading is missing and three of the ~ rows (copy/paste,context menus, typing at a caret) are things a layout artist does every minute, and their failures stop work.+Navigation also supports held Space as Hand and held Cmd+Space as Zoom (Ctrl+Space on+Windows/Linux), with Alt-click zooming out. Releasing restores the previous tool and its state.+The temporary Zoom uses the selected Zoom tool's click and horizontal scrubby drag behavior;+marquee zoom is not implemented. It is suppressed while typing in a document text frame or a+focused text field, and does not interrupt an existing tool drag. Synthetic canvas input tests+cover the cursors, click anchors, scrub/release ownership, restoration, typing guards and undo+history (DC-1).+## Remaining effort+Applying a paragraph or character style now removes local values equal to the applied style,+so text used to capture a style follows later edits to that style. Different local formatting+and named character styles stay intact. Paragraph-style application treats selection endpoints+as exclusive; Clear Overrides removes character formatting only inside a nonempty selection.+Regressions cover the capture/edit workflow at 2:16 and 6:02 in+[Jessica Garrity's styles tutorial](https://www.youtube.com/watch?v=pG9JkAPLgs8).++Redefining a character style at a caret also normalizes the sampled source run, so subsequent+style edits reach that text while different local overrides in adjacent runs remain intact.++The selected style's context menu now offers Redefine Style for paragraph and character styles.+It incorporates the source text's local changes, updates every use, and removes matching source+overrides in one undo step. Named character styles remain separate when redefining a paragraph+style. Commands: `style.paragraph.redefine` and `style.character.redefine` (optional `name`,+which must match the source). This implements the global color, size and spacing updates at+about 5:10–6:00 in [Jessica Garrity's styles tutorial](https://www.youtube.com/watch?v=pG9JkAPLgs8).++The Paragraph Styles panel now includes character formatting in its `+` indicator, on both+the current-style summary and the selected row. The row menu offers Apply "name", Clear+Overrides through the existing command, retaining named character styles. Selection attribute+counts compare effective values with their style definitions, so equal local values and named+character styles alone do not report overrides. This covers the color-override/clear workflow+at 4:25–5:20 in [Jessica Garrity's styles tutorial](https://www.youtube.com/watch?v=pG9JkAPLgs8).- Style-dialog Preview remains a separate gap.+++ Style Preview rejects conflicting scalar/nested automation fields without a panic. Replacing a+ previewing dialog through the control channel cancels its transaction, restoring the original+ document and normal undo recording before the replacement opens.++ Paragraph and Character Style Options now preview edits to existing styles. Preview updates+ every use, remains outside undo history, and restores the starting document when disabled or+ cancelled. OK applies the final edit once. The color-preview step at about 4:00 in+ [Jessica Garrity's styles tutorial](https://www.youtube.com/watch?v=pG9JkAPLgs8) is reproducible+ offscreen. New-style creation, renaming and export tagging are committed on OK; they are not+ included in the visual preview.| Work | Opus 5.5 h ||---|---|