DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
PR-1080: refresh against main and resolve review findings
moppeeer3b53f45b3b76
diff --cc crates/ui-egui/src/dialogs.rsindex 6e8fe34b5,8b4043787..6a546ade7--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@@ -1537,9 -2100,10 +2100,11 @@@ pub fn show(app: &mut DesignApp, ctx: &let available = (ctx.content_rect().size() - frame_margin - egui::vec2(16.0, 16.0)).max(egui::Vec2::splat(1.0));let preferred_width: f32 = match d.id.as_str() {"alert" => 440.0,- "closeDocument" | "updateLink" => 380.0,+ "closeDocument" | "updateLink" | "deletePages" | "newWorkspace" | "pagesPanelOptions" => 380.0,+ "newDocument" => 960.0,+ "numberingSection" => 560.0,+ crate::effects_dialog::ID => 720.0,+ "colorPicker" => 580.0,- "newDocument" if crate::i18n::is_rtl(&app.ui.language) => 380.0,_ => 640.0,};let width = preferred_width.min(available.x);@@@ -1716,67 -2301,143 +2302,143 @@@}});ui.end_row();+ });+ ui.horizontal(|ui| {+ check(ui, &mut d, "caseSensitive", crate::i18n::tr(&app.ui.language, "Case sensitive"));+ check(ui, &mut d, "wholeWord", crate::i18n::tr(&app.ui.language, "Whole word"));+ });+ ui.horizontal(|ui| {+ let params0 = find_change_params(&d);+ let params = || params0.clone();+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Find Next"))).clicked() {+ let r = app.run("find.next", params());+ let msg = match r {+ Ok(Value::Null) => crate::i18n::tr(&app.ui.language, "No matches").to_string(),+ Ok(_) => crate::i18n::tr(&app.ui.language, "Found").to_string(),+ Err(e) => e,+ };+ d.fields.insert("status".into(), json!(msg));+ }+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Change All"))).clicked() {+ let msg = match app.run("find.change", params()) {+ Ok(v) => crate::i18n::tr(&app.ui.language, "{count} replacement(s) made")+ .replace("{count}", &v["count"].to_string()),+ Err(e) => e,+ };+ d.fields.insert("status".into(), json!(msg));+ }+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Count"))).clicked() {+ let msg = match app.run("find.find", params()) {+ Ok(v) => crate::i18n::tr(&app.ui.language, "{count} match(es)")+ .replace("{count}", &v.as_array().map_or(0, |a| a.len()).to_string()),+ Err(e) => e,+ };+ d.fields.insert("status".into(), json!(msg));+ }+ });+ 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));}- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Kind:"));- let cur = d.s("objKind");- egui::ComboBox::from_id_salt("objKind").selected_text(if cur.is_empty() { "(any)" } else { cur.as_str() }).show_ui(+ }+ }+ "paragraphStyleOptions" => paragraph_style_options(app, ui, &mut d),+ "deleteParagraphStyle" => delete_paragraph_style(app, ui, &mut d),+ "characterStyleOptions" => character_style_options(app, ui, &mut d),+ "deleteCharacterStyle" => delete_character_style(app, ui, &mut d),+ "footnoteOptions" => footnote_options(app, ui, &mut d),+ "paragraphRules" => {+ let current = d.fields.get("current").cloned().unwrap_or_default();+ paragraph_rules(app, ui, &mut d, "", ¤t);+ }+ "paragraphLocal" => paragraph_local(app, ui, &mut d),+ "justification" => {+ let current = d.fields.get("current").cloned().unwrap_or_default();+ justification(&app.ui.language, ui, &mut d, "", ¤t);+ }+ "insertXref" => insert_xref(app, ui, &mut d),+ "findFont" => find_font(app, ui, &mut d),- "colorPicker" => color_picker(ui, &mut d),++ "colorPicker" => color_picker(app, ui, &mut d),+ "swatchOptions" => options::swatch_options(app, ui, &mut d),+ "colorGroupOptions" => options::color_group_options(app, ui, &mut d),+ "layerSettings" => options::layer_options(app, ui, &mut d),+ crate::effects_dialog::ID => crate::effects_dialog::show(app, ui, &mut d),+ "preferences" => preferences(app, ui, &mut d, body_height),+ "print" => print_dialog(app, ui, &mut d),+ "pdfImport" => {+ ui.label(egui::RichText::new(if d.b("async") { d.s("name") } else { d.s("path") }).size(11.0));+ ui.horizontal(|ui| {+ crate::rtl::label(ui,- |ui| {- for v in ["", "text", "graphic", "shape", "line", "group"] {- if ui- .selectable_label(- cur == v,- crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, if v.is_empty() { "(any)" } else { v })),- )- .clicked()- {- d.fields.insert("objKind".into(), json!(v));- }- }- },+ crate::i18n::tr(&app.ui.language, "Page (1–{count}):").replace("{count}", &d.n("pages").unwrap_or(1.0).to_string()),);- ui.end_row();+ text_field(ui, &mut d, "page", 60.0);});- let mut crit = json!({});- if !d.s("objFill").is_empty() {- crit["fill"] = json!(d.s("objFill"));- }- if !d.s("objKind").is_empty() {- crit["kind"] = json!(d.s("objKind"));- }ui.horizontal(|ui| {- if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Find All"))).clicked() {- let n = app.run("find.objects", crit.clone()).ok().and_then(|r| r["ids"].as_array().map(Vec::len)).unwrap_or(0);- d.fields.insert("status".into(), json!(format!("{n} found")));- }- if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Change All"))).clicked()- && !d.s("objChangeFill").is_empty()+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Crop to:"));+ let cur = d.s("crop");+ let label = |v: &str| match v {+ "contentVisible" => crate::i18n::tr(&app.ui.language, "Bounding Box (Visible Layers Only)"),+ "contentAll" => crate::i18n::tr(&app.ui.language, "Bounding Box (All Layers)"),+ "trim" => crate::i18n::tr(&app.ui.language, "Trim"),+ "bleed" => crate::i18n::tr(&app.ui.language, "Bleed"),+ "art" => crate::i18n::tr(&app.ui.language, "Art"),+ "media" => crate::i18n::tr(&app.ui.language, "Media"),+ _ => crate::i18n::tr(&app.ui.language, "Crop"),+ };+ egui::ComboBox::from_id_salt("pdf_crop").selected_text(crate::rtl::widget(ui, label(&cur))).show_ui(ui, |ui| {+ for v in designcraft_doc::PdfCrop::ALL.map(designcraft_doc::PdfCrop::name) {+ if ui.selectable_label(label(&cur) == label(v), label(v)).clicked() {+ d.fields.insert("crop".into(), json!(v));+ }+ }+ });+ });+ }+ "layerOptions" => {+ let mut layers = d.fields.get("layers").and_then(Value::as_array).cloned().unwrap_or_default();+ if layers.is_empty() {+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "This PDF has no layers."));+ }+ for l in &mut layers {+ let mut on = l["visible"].as_bool().unwrap_or(true);+ if ui.checkbox(&mut on, l["name"].as_str().unwrap_or("")).changed()+ && let Some(o) = l.as_object_mut(){- let mut p = crit.clone();- p["change"] = json!({"fill": d.s("objChangeFill")});- let n = app.run("find.changeObjects", p).ok().and_then(|r| r["changed"].as_u64()).unwrap_or(0);- d.fields.insert("status".into(), json!(format!("{n} changed")));+ o.insert("visible".into(), json!(on));}- });- ui.label(d.s("status"));- } else {- egui::Grid::new("fc").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Find what:"));- text_field(ui, &mut d, "find", 260.0);- ui.end_row();- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Change to:"));- text_field(ui, &mut d, "change", 260.0);- ui.end_row();- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Search:"));- let cur = d.s("scope");- egui::ComboBox::from_id_salt("fcscope")- .selected_text(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, &cur)))+ }+ d.fields.insert("layers".into(), json!(layers));+ }+ "colorSettings" => {+ let profiles = d.fields.get("profiles").and_then(Value::as_array).cloned().unwrap_or_default();+ egui::Grid::new("color_settings").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ for (key, label, kind) in [("rgb", "RGB:", "rgb"), ("cmyk", "CMYK:", "cmyk")] {+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, label));+ let cur = d.s(key);+ egui::ComboBox::from_id_salt(("ws", key)).selected_text(&cur).width(260.0).show_ui(ui, |ui| {+ for pr in profiles.iter().filter(|p| p["kind"] == kind) {+ let name = pr["name"].as_str().unwrap_or("");+ if ui.selectable_label(name == cur, name).clicked() {+ d.fields.insert(key.into(), json!(name));+ }+ }+ });+ ui.end_row();+ }+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Intent:"));+ let cur = d.s("intent");+ egui::ComboBox::from_id_salt("ws_intent")+ .selected_text(crate::rtl::widget(+ ui,+ crate::i18n::tr(&app.ui.language, designcraft_color::cms::Intent::parse(&cur).map_or("", |i| i.label())),+ )).show_ui(ui, |ui| {- for v in ["document", "story", "selection"] {- if ui.selectable_label(cur == v, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, v))).clicked()- && d.set_field("scope", json!(v))+ for i in designcraft_color::cms::Intent::ALL {+ if ui+ .selectable_label(i.id() == cur, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, i.label())))+ .clicked(){- app.session.reset_find_scope();+ d.fields.insert("intent".into(), json!(i.id()));}}});@@@ -2017,207 -2689,148 +2690,156 @@@}});});- }- }- "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();}- });- });- 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);+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Color:"));+ text_field(ui, &mut d, "color", 160.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:"));+ });+ }+ "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:"));+ 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"));+ "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);+ }+ "colorTheme" => color_theme(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"));+ }+ _ => {}}- _ => {}});- // The Color Picker has its own OK and Cancel, at the top right as InDesign's.+ if d.id == "colorPicker" {+ match d.fields.remove("_close").as_ref().and_then(Value::as_str) {+ Some("ok") => result = Some(true),+ Some("cancel") => result = Some(false),+ _ => {}+ }+ return;+ }+ if side_actions {+ return;+ }ui.add_space(12.0);let ok_label = match d.id.as_str() {- "closeDocument" => " Save ",- "updateLink" => " Update ",- _ => " OK ",+ "colorTheme" => crate::i18n::tr(&app.ui.language, "Add to Swatches").to_string(),+ "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(@@@ -4507,249 -6626,496 +6635,635 @@@ fn insert_xref(app: &mut DesignApp, ui});}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));+ 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));}- 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);+ /// `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)++/// The Color Picker, laid out as InDesign's: the colour space view (a field of two components,++/// a slider for the third: the one whose radio button is on, R at first), the new colour over the++/// one it replaces, OK / Cancel / Add CMYK Swatch at the top right, H/S/B beside L/a/b, R/G/B++/// beside C/M/Y/K, and the hex code. Its buttons replace the dialog's own.++fn color_picker(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {++ use picker_layout as at;+ 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 {- crate::rtl::label(ui, tr(l));- text_field(ui, d, k, 70.0);- ui.end_row();++ if !d.fields.contains_key("old") {++ let old = d.s("hex");++ d.fields.insert("old".into(), json!(old));++ }++ let comp = PickComp::from_key(&d.s("component"));++ let mut p = picked_of(d);++ let before = p;++ if !d.fields.contains_key("rgb") {++ d.fields.insert("rgb".into(), json!(p.rgb.map(|x| x * 255.0)));++ }++ if !d.fields.contains_key("cmyk") {++ d.fields.insert(++ "cmyk".into(),++ json!(++ designcraft_color::Color::Rgb { r: p.rgb[0], g: p.rgb[1], b: p.rgb[2] }++ .to_cmyk_managed(designcraft_color::cms::active_settings().intent)++ .map(|x| x * 100.0)++ ),++ );++ }++ let mut exact_cmyk = None;++ let t = crate::theme::Tokens::get(ui.ctx());++ let (area, _) = ui.allocate_exact_size(at::SIZE, egui::Sense::hover());++ let o = area.min.to_vec2();++ let put = |r: egui::Rect| r.translate(o);++ let font = egui::FontId::proportional(11.5);++ let text = |ui: &egui::Ui, pos: egui::Pos2, align: egui::Align2, s: &str| {++ ui.painter().text(pos, align, s, egui::FontId::proportional(11.5), t.text_strong);+ };- 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,++ // The colour space view (a label, so screen readers hear which).++ ui.scope_builder(++ egui::UiBuilder::new()++ .max_rect(egui::Rect::from_min_size(area.min, egui::vec2(260.0, 24.0)))++ .layout(egui::Layout::left_to_right(egui::Align::Center)),++ |ui| {++ ui.label(++ egui::RichText::new(tr(if comp.lab() { "Lab Color Space View" } else { "RGB Color Space View" })).size(11.5).color(t.text_strong),++ );++ },++ );++ let fr = put(at::field());++ let fresp = ui.interact(fr, ui.id().with("cp_field"), egui::Sense::click_and_drag());++ let (tv, _, _) = p.coords(comp);++ let cells = if matches!(comp, PickComp::R | PickComp::G | PickComp::Bl | PickComp::H) { 2 } else { 24 };++ gradient_mesh(ui.painter(), fr, cells, cells, |x, y| p.at(comp, tv, x, y).rgb);++ fresp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Other, true, "Color field"));++ if let Some(pos) = fresp.interact_pointer_pos().filter(|_| fresp.is_pointer_button_down_on() || fresp.clicked()) {++ let u = ((pos.x - fr.left()) / fr.width()).clamp(0.0, 1.0);++ let v = ((fr.bottom() - pos.y) / fr.height()).clamp(0.0, 1.0);++ p = p.at(comp, tv, u, v);++ }++ // The marker: a cross with an open centre, white over black.++ let (_, u, v) = p.coords(comp);++ let m = egui::pos2(fr.left() + u * fr.width(), fr.bottom() - v * fr.height());++ let painter = ui.painter().with_clip_rect(fr);++ for (dx, dy) in [(1.0, 0.0), (-1.0, 0.0), (0.0, 1.0), (0.0, -1.0)] {++ let (a, b) = (m + egui::vec2(dx * 3.0, dy * 3.0), m + egui::vec2(dx * 10.0, dy * 10.0));++ let side = egui::vec2(dy, dx) * 1.2;++ painter.line_segment([a + side, b + side], egui::Stroke::new(1.0, egui::Color32::BLACK));++ painter.line_segment([a - side, b - side], egui::Stroke::new(1.0, egui::Color32::BLACK));++ painter.line_segment([a, b], egui::Stroke::new(1.5, egui::Color32::WHITE));++ }++ // The slider, with a marker on each side.++ let sr = put(at::slider());++ let sresp = ui.interact(sr.expand2(egui::vec2(6.0, 0.0)), ui.id().with("cp_slider"), egui::Sense::click_and_drag());++ gradient_mesh(ui.painter(), sr, 1, 48, |_, y| p.slider_at(comp, y));++ sresp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Slider, true, "Color slider"));++ if let Some(pos) = sresp.interact_pointer_pos().filter(|_| sresp.is_pointer_button_down_on() || sresp.clicked()) {++ let tn = ((sr.bottom() - pos.y) / sr.height()).clamp(0.0, 1.0);++ let (_, u, v) = p.coords(comp);++ p = p.at(comp, tn, u, v);++ }++ let (tn, _, _) = p.coords(comp);++ let y = sr.bottom() - tn * sr.height();++ for (x, dir) in [(sr.left(), 1.0), (sr.right(), -1.0)] {++ let pts = vec![++ egui::pos2(x - 5.0 * dir, y - 4.5),++ egui::pos2(x, y - 4.5),++ egui::pos2(x + 3.5 * dir, y),++ egui::pos2(x, y + 4.5),++ egui::pos2(x - 5.0 * dir, y + 4.5),++ ];++ ui.painter().add(egui::Shape::convex_polygon(pts, egui::Color32::WHITE, egui::Stroke::new(1.0, egui::Color32::from_gray(40))));++ }++ // The new colour over the one it replaces.++ let pr = put(at::swatch());++ let old = designcraft_color::Color::from_hex(&d.s("old")).map_or([0.0; 3], |c| c.to_rgb_uncalibrated());++ ui.painter().rect_filled(egui::Rect::from_min_max(pr.min, egui::pos2(pr.max.x, pr.center().y)), 0.0, color32(p.rgb));++ ui.painter().rect_filled(egui::Rect::from_min_max(egui::pos2(pr.min.x, pr.center().y), pr.max), 0.0, color32(old));++ ui.painter().rect_stroke(pr, 0.0, egui::Stroke::new(1.0, egui::Color32::from_gray(80)), egui::StrokeKind::Inside);++ // OK, Cancel, Add CMYK Swatch: rounded, OK filled.++ let pill = |ui: &mut egui::Ui, i: usize, label: &str, primary: bool| -> bool {++ let r = put(at::button(i));++ let resp = ui.interact(r, ui.id().with(("cp_button", i)), egui::Sense::click());++ let (fill, fg, stroke) = if primary {++ (t.accent_strong, egui::Color32::WHITE, egui::Stroke::NONE)++ } else {++ (if resp.hovered() { t.hover } else { egui::Color32::TRANSPARENT }, t.text_strong, egui::Stroke::new(1.0, t.text_dim))++ };++ ui.painter().rect(r, r.height() / 2.0, fill, stroke, egui::StrokeKind::Inside);++ ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, label, egui::FontId::proportional(12.0), fg);++ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label));++ resp.clicked()+ };- 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;++ if pill(ui, 0, &tr("OK"), true) || ui.input(|i| i.key_pressed(egui::Key::Enter)) {++ d.fields.insert("_close".into(), json!("ok"));++ }++ if pill(ui, 1, &tr("Cancel"), false) || ui.input(|i| i.key_pressed(egui::Key::Escape)) {++ d.fields.insert("_close".into(), json!("cancel"));++ }++ if pill(ui, 2, &tr("Add CMYK Swatch"), false) {++ let [c, m, y, k] = designcraft_color::Color::Rgb { r: p.rgb[0], g: p.rgb[1], b: p.rgb[2] }++ .to_cmyk_managed(designcraft_color::cms::active_settings().intent)++ .map(|v| (v * 100.0).round());++ match app.run("swatch.create", json!({"color": {"c": c, "m": m, "y": y, "k": k}})) {++ Ok(r) => app.status(format!("{} {}", tr("Added swatch"), r["name"].as_str().unwrap_or(""))),++ Err(e) => app.status(e),++ }++ }++ // The values: a radio button, a label, the field, a unit.++ let mut comp_now = comp;++ let mut edited: Option<Picked> = None;++ let cmyk = nums::<4>(d, "cmyk").map(|v| v.map(|x| x as f32)).unwrap_or_else(|| {++ designcraft_color::Color::Rgb { r: p.rgb[0], g: p.rgb[1], b: p.rgb[2] }++ .to_cmyk_managed(designcraft_color::cms::active_settings().intent)++ .map(|v| v * 100.0)++ });++ // (column x of the radio, row, component, label, key, value, range, unit)++ let rows: [(f32, usize, Option<PickComp>, &str, &str, f32, (f32, f32), &str); 13] = [++ (at::LEFT, 0, Some(PickComp::H), "H:", "h", p.hsb[0], (0.0, 360.0), "°"),++ (at::LEFT, 1, Some(PickComp::S), "S:", "s", p.hsb[1] * 100.0, (0.0, 100.0), "%"),++ (at::LEFT, 2, Some(PickComp::Br), "B:", "b", p.hsb[2] * 100.0, (0.0, 100.0), "%"),++ (at::RIGHT, 0, Some(PickComp::L), "L:", "l", p.lab[0], (0.0, 100.0), ""),++ (at::RIGHT, 1, Some(PickComp::A), "a:", "la", p.lab[1], (-128.0, 127.0), ""),++ (at::RIGHT, 2, Some(PickComp::Lb), "b:", "lb", p.lab[2], (-128.0, 127.0), ""),++ (at::LEFT, 3, Some(PickComp::R), "R:", "r", p.rgb[0] * 255.0, (0.0, 255.0), ""),++ (at::LEFT, 4, Some(PickComp::G), "G:", "g", p.rgb[1] * 255.0, (0.0, 255.0), ""),++ (at::LEFT, 5, Some(PickComp::Bl), "B:", "bl", p.rgb[2] * 255.0, (0.0, 255.0), ""),++ (at::RIGHT, 3, None, "C:", "c", cmyk[0], (0.0, 100.0), "%"),++ (at::RIGHT, 4, None, "M:", "m", cmyk[1], (0.0, 100.0), "%"),++ (at::RIGHT, 5, None, "Y:", "y", cmyk[2], (0.0, 100.0), "%"),++ (at::RIGHT, 6, None, "K:", "k", cmyk[3], (0.0, 100.0), "%"),++ ];++ for (x, row, c, label, key, value, range, unit) in rows {++ let cy = area.min.y + at::ROWS[row];++ let x = area.min.x + x;++ match c {++ Some(c) => {++ let rr = egui::Rect::from_center_size(egui::pos2(x, cy), egui::vec2(14.0, 14.0));++ let resp = ui.interact(rr, ui.id().with(("cp_radio", key)), egui::Sense::click());++ ui.painter().circle(rr.center(), 6.0, t.input, egui::Stroke::new(1.0, t.text_dim));++ if comp_now == c {++ ui.painter().circle_filled(rr.center(), 2.6, t.text_strong);+ }- 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);++ resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::RadioButton, true, comp_now == c, label));++ if resp.clicked() {++ comp_now = c;++ }++ text(ui, egui::pos2(x + 11.0, cy), egui::Align2::LEFT_CENTER, label);++ }++ // C/M/Y/K have no radio button: their labels end at the field.++ None => text(ui, egui::pos2(x + 28.0, cy), egui::Align2::RIGHT_CENTER, label),++ }++ let fr = egui::Rect::from_min_size(egui::pos2(x + 35.0, cy - 10.5), egui::vec2(44.0, 21.0));++ if let Some(v) = picker_field(ui, d, fr, key, value, range) {++ if matches!(key, "r" | "g" | "bl") {++ d.fields.insert("model".into(), json!("rgb"));++ }++ if matches!(key, "c" | "m" | "y" | "k") {++ d.fields.insert("model".into(), json!("cmyk"));++ }++ edited = Some(match key {++ "h" => Picked::from_hsb([v, p.hsb[1], p.hsb[2]]),++ "s" => Picked::from_hsb([p.hsb[0], v / 100.0, p.hsb[2]]),++ "b" => Picked::from_hsb([p.hsb[0], p.hsb[1], v / 100.0]),++ "l" => Picked::from_lab([v, p.lab[1], p.lab[2]], p.hsb[0]),++ "la" => Picked::from_lab([p.lab[0], v, p.lab[2]], p.hsb[0]),++ "lb" => Picked::from_lab([p.lab[0], p.lab[1], v], p.hsb[0]),++ "r" => Picked::from_rgb([v / 255.0, p.rgb[1], p.rgb[2]], p.hsb[0]),++ "g" => Picked::from_rgb([p.rgb[0], v / 255.0, p.rgb[2]], p.hsb[0]),++ "bl" => Picked::from_rgb([p.rgb[0], p.rgb[1], v / 255.0], p.hsb[0]),++ _ => {++ let mut c = cmyk;++ c[["c", "m", "y", "k"].iter().position(|k| *k == key).unwrap_or(0)] = v;++ exact_cmyk = Some(c);++ let [c, m, y, k] = c.map(|x| x / 100.0);++ Picked::from_rgb(designcraft_color::Color::Cmyk { c, m, y, k }.to_rgb(), p.hsb[0])}- d.fields.insert("hexEdit".into(), json!(h));});-- });- 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));- 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 !unit.is_empty() {++ text(ui, egui::pos2(fr.right() + 8.0, cy), egui::Align2::LEFT_CENTER, unit);+ }}- }-- /// `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);- if edit != ColorEdit::None {- d.fields.insert("edited".into(), json!(true));++ if let Some(e) = edited {++ p = e;++ }++ if comp_now != comp {++ d.fields.insert("component".into(), json!(comp_now.key()));++ }++ // The hex code, and the eyedropper's mark beside it.++ let cy = area.min.y + at::ROWS[7];++ text(ui, egui::pos2(area.min.x + 321.0, cy), egui::Align2::LEFT_CENTER, "#:");++ let hr = egui::Rect::from_min_size(egui::pos2(area.min.x + 341.0, cy - 10.5), egui::vec2(64.0, 21.0));++ let id = egui::Id::new("color_picker_hex");++ let editing = ui.memory(|m| m.has_focus(id));++ let mut h = if editing { d.s("hexEdit") } else { p.hex().trim_start_matches('#').to_string() };++ if ui++ .put(hr, egui::TextEdit::singleline(&mut h).id(id).font(font).vertical_align(egui::Align::Center).margin(egui::Margin::symmetric(4, 2)))++ .changed()++ && (h.len() == 6 || (h.len() == 7 && h.starts_with('#')))++ && let Some(c) = designcraft_color::Color::from_hex(&h)++ {++ p = Picked::from_rgb(c.to_rgb_uncalibrated(), p.hsb[0]);++ }++ d.fields.insert("hexEdit".into(), json!(h));++ crate::icons::paint(++ ui.painter(),++ egui::Rect::from_center_size(egui::pos2(hr.right() + 16.0, cy), egui::vec2(15.0, 15.0)),++ "tool-eyedropper",++ t.icon,++ );++ if p != before {++ store_picked(d, &p);++ if let Some(c) = exact_cmyk {++ d.fields.insert("cmyk".into(), json!(c));+ }- 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})- })+ }- 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]))));}- /// 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");+ /// 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 params = match step_and_repeat_params(app, d) {- Ok(p) => p,- Err(e) => {- d.fields.insert("status".into(), json!(e));- 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));+ }}- };- if shown.as_ref() == Some(¶ms) {- return;+ });+ }++ 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);}- if shown.is_none()- && let Err(e) = app.session.begin_interaction("Step and Repeat")+ 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("status".into(), json!(e.to_string()));- return;+ d.fields.insert("family".into(), font["family"].clone());+ d.fields.insert("style".into(), font["style"].clone());}- 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);+ 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),+ ));}- /// New Cross-Reference: link to a paragraph (paragraph styles on the left, their paragraphs on- /// the right) or a text anchor, with a cross-reference format.- fn insert_xref(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {- let Some(st) = app.session.active() else { return };- let doc = &st.doc;- let all = "[All Paragraphs]";- ui.horizontal(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Link To:"));- combo(ui, d, "linkTo", &[("paragraph", "Paragraph"), ("anchor", "Text Anchor")]);- });- ui.add_space(6.0);- let dim = crate::theme::Tokens::get(ui.ctx()).text_dim;- if d.s("linkTo") == "anchor" {- egui::ScrollArea::vertical().id_salt("xr_anchors").max_height(220.0).max_width(460.0).show(ui, |ui| {- let mut any = false;- for st in doc.stories.values() {- for a in &st.anchors {- any = true;- let key = format!("a:{}", a.id);- if ui.selectable_label(d.s("target") == key, &a.name).clicked() {- d.fields.insert("target".into(), json!(key));- }- }- }- if !any {- ui.label(crate::rtl::widget(- ui,- egui::RichText::new(crate::i18n::tr(&app.ui.language, "No text anchors in this document.")).color(dim),- ));- }- });- } else {- let mut styles: Vec<String> = vec![all.to_string()];- styles.extend(doc.styles.paragraph.iter().map(|s| s.name.clone()));- let cur_style = if d.s("style").is_empty() { all.to_string() } else { d.s("style") };- ui.horizontal_top(|ui| {- let col = |w: f32| (egui::vec2(w, 240.0), egui::Layout::top_down(egui::Align::Min));- let (sz, lay) = col(180.0);- ui.allocate_ui_with_layout(sz, lay, |ui| {- egui::ScrollArea::vertical().id_salt("xr_styles").auto_shrink([false, false]).show(ui, |ui| {- for name in &styles {- if ui.selectable_label(*name == cur_style, name).clicked() {- d.fields.insert("style".into(), json!(name));- }- }- })- });- ui.add_space(8.0);- let (sz, lay) = col(330.0);- ui.allocate_ui_with_layout(sz, lay, |ui| {- egui::ScrollArea::vertical().id_salt("xr_paras").auto_shrink([false, false]).show(ui, |ui| {- for st in doc.stories.values().filter(|s| !s.frames.is_empty()) {- for (pi, r) in st.para_ranges().into_iter().enumerate() {- if cur_style != all && st.paras[pi].style != cur_style {- continue;- }- let text = designcraft_doc::xref::clean(&st.text[r]);- if text.is_empty() {- continue;- }- let short: String = text.chars().take(52).collect();- let key = format!("{}:{pi}", st.id.0);- if ui.selectable_label(d.s("target") == key, short).clicked() {- d.fields.insert("target".into(), json!(key));- }- }- }- })- });- });+ #[cfg(test)]+ mod tests {+ use super::*;++ #[test]+ fn paragraph_style_settings_show_captured_color_and_pending_spacing_without_changing_the_document() {+ 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,200],"content":"text","text":"Heading"})).unwrap();+ app.run("text.select", json!({"story":f["story"],"anchor":0,"focus":7})).unwrap();+ app.run("type.char", json!({"fontFamily":"Source Sans 3","fontStyle":"Bold","size":16,"fill":"[Paper]"})).unwrap();+ app.run("style.paragraph.create", json!({"name":"Header","fromSelection":true})).unwrap();+ let doc = app.session.doc().unwrap().doc.clone();+ let style = doc.styles.para("Header").unwrap();+ let mut d = Dialog::new("paragraphStyleOptions", json!({"name":"Header"}));+ let summary = paragraph_style_summary("", &d, style, &doc.styles);+ for value in ["Source Sans 3", "Bold", "16 pt", "[Paper]"] {+ assert!(summary.contains(value), "{summary}");+ }+ assert!(summary.len() < 250, "default attributes do not swamp the captured settings: {summary}");+ d.fields.insert("c.fill".into(), json!("[Registration]"));+ d.fields.insert("p.spaceAfter".into(), json!(4.5));+ let summary = paragraph_style_summary("", &d, style, &doc.styles);+ assert!(summary.contains("[Registration]") && !summary.contains("[Paper]"), "{summary}");+ assert!(summary.contains("4.5 pt"), "{summary}");+ assert_eq!(app.session.doc().unwrap().doc, doc);+ }++ #[test]+ fn paragraph_style_settings_compare_with_the_chosen_parent() {+ let mut styles = designcraft_doc::Styles::default();+ styles.paragraph.push(designcraft_doc::ParagraphStyle {+ name: "Parent".into(),+ chars: designcraft_doc::CharAttrs { size: Some(20.0), ..Default::default() },+ based_on: None,+ next_style: None,+ para: Default::default(),+ shortcut: String::new(),+ });+ let style = designcraft_doc::ParagraphStyle {+ name: "Child".into(),+ based_on: Some("Parent".into()),+ next_style: None,+ para: Default::default(),+ chars: Default::default(),+ shortcut: String::new(),+ };+ let d = Dialog::new("paragraphStyleOptions", json!({"name":"Child"}));+ assert_eq!(paragraph_style_summary("", &d, &style, &styles), "Parent");+ }++ #[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}- 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()));++ 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());+ }}- 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));++ #[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");}- }- /// The Color Picker's components: the one picked runs along the slider, the other two of its- /// space across the field (InDesign's, as Photoshop's: R puts B across and G up).- #[derive(Clone, Copy, Debug, PartialEq, Eq)]- pub(crate) enum PickComp {- H,- S,- Br,- L,- A,- Lb,- R,- G,- Bl,- }+ #[test]+ fn document_setup_reads_a_bare_number_in_the_documents_units() {+ let mut app = document_setup_app("millimeters");+ setup_fields(&mut app, json!({"bleedTop": "5", "bleedBottom": "5", "bleedInside": "5", "bleedOutside": "5", "width": "210"}));+ confirm(&mut app).unwrap();+ let mm = designcraft_geom::units::PT_PER_MM;+ let settings = &app.session.active().unwrap().doc.settings;+ assert!(settings.bleed.iter().all(|b| (b - 5.0 * mm).abs() < 1e-6), "5 mm, not 5 picas: {:?}", settings.bleed);+ assert!((settings.page_width - 210.0 * mm).abs() < 1e-6, "{}", settings.page_width);+ }- impl PickComp {- const ALL: [PickComp; 9] =- [PickComp::H, PickComp::S, PickComp::Br, PickComp::L, PickComp::A, PickComp::Lb, PickComp::R, PickComp::G, PickComp::Bl];+ #[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]);+ }- fn key(self) -> &'static str {- match self {- PickComp::H => "h",- PickComp::S => "s",- PickComp::Br => "b",- PickComp::L => "l",- PickComp::A => "la",- PickComp::Lb => "lb",- PickComp::R => "r",- PickComp::G => "g",- PickComp::Bl => "bl",+ #[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");}}@@@ -4832,476 -7300,674 +7448,668 @@@}}- /// The slider's colour at `t`: the hue slider shows pure hues, the others this colour with- /// the component at `t`.- fn slider_at(&self, c: PickComp, t: f32) -> [f32; 3] {- if c == PickComp::H {- return designcraft_color::Color::from_hsb(t * 360.0, 1.0, 1.0).to_rgb_uncalibrated();+ 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() },}- let (_, u, v) = self.coords(c);- self.at(c, t, u, v).rgb}- pub fn hex(&self) -> String {- let q = |x: f32| (x.clamp(0.0, 1.0) * 255.0).round() as u8;- format!("#{:02x}{:02x}{:02x}", q(self.rgb[0]), q(self.rgb[1]), q(self.rgb[2]))+ /// 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)}- }-- fn color32(rgb: [f32; 3]) -> egui::Color32 {- let q = |x: f32| (x.clamp(0.0, 1.0) * 255.0).round() as u8;- egui::Color32::from_rgb(q(rgb[0]), q(rgb[1]), q(rgb[2]))- }- /// A `cols` × `rows` grid of quads over `r`, coloured at each vertex by `f(x, y)` (0..1, y up).- fn gradient_mesh(painter: &egui::Painter, r: egui::Rect, cols: usize, rows: usize, f: impl Fn(f32, f32) -> [f32; 3]) {- let mut mesh = egui::Mesh::default();- for j in 0..=rows {- for i in 0..=cols {- let (x, y) = (i as f32 / cols as f32, j as f32 / rows as f32);- mesh.colored_vertex(egui::pos2(r.left() + x * r.width(), r.bottom() - y * r.height()), color32(f(x, y)));- /// 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![]);}}- let w = (cols + 1) as u32;- for j in 0..rows as u32 {- for i in 0..cols as u32 {- let a = j * w + i;- mesh.add_triangle(a, a + 1, a + w);- mesh.add_triangle(a + 1, a + w + 1, a + w);- }++ 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()}- painter.add(egui::Shape::mesh(mesh));- }- /// `n` numbers from an array field.- fn nums<const N: usize>(d: &Dialog, key: &str) -> Option<[f64; N]> {- let a = d.fields.get(key)?.as_array()?;- let mut out = [0.0; N];- for (o, v) in out.iter_mut().zip(a) {- *o = v.as_f64().filter(|v| v.is_finite())?;+ #[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());++ 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");}- (a.len() == N).then_some(out)- }- /// The colour in the dialog's fields: `hex`, with the HSB hue and the Lab values kept while- /// they round-trip (`_hsb`, `_lab`).- fn picked_of(d: &Dialog) -> Picked {- let rgb = designcraft_color::Color::from_hex(&d.s("hex")).map_or([0.0; 3], |c| c.to_rgb_uncalibrated());- let hue = nums::<3>(d, "_hsb").map_or(0.0, |h| h[0] as f32);- let mut p = Picked::from_rgb(rgb, hue);- // The exact values the picker last set, while they still give this colour.- if let Some(h) = nums::<3>(d, "_hsb").map(|h| h.map(|v| v as f32))- && Picked::from_hsb(h).hex() == p.hex()- {- p.hsb = h;+ #[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"));++ let r = visible_label(&labels, screen, "R:");++ click_dialog(&mut app, &ctx, screen, egui::pos2(r.min.x + 46.0, r.center().y));+ 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");++ visible_label(&labels, screen, "12.5");++ assert_eq!(app.ui.dialog.as_ref().unwrap().fields["rgb"][1], json!(2.0));+ 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}");}- if let Some(l) = nums::<3>(d, "_lab").map(|l| l.map(|v| v as f32))- && Picked::from_lab(l, p.hsb[0]).hex() == p.hex()- {- p.lab = l;++ #[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"));++ let r = visible_label(&labels, screen, "M:");++ click_dialog(&mut app, &ctx, screen, egui::pos2(r.max.x + 29.0, r.center().y));+ 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()));++ let _ = r;++ let r = visible_label(&labels, screen, "R:");++ click_dialog(&mut app, &ctx, screen, egui::pos2(r.min.x + 46.0, r.center().y));+ 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));}- p- }- fn store_picked(d: &mut Dialog, p: &Picked) {- d.fields.insert("hex".into(), json!(p.hex()));- d.fields.insert("_hsb".into(), json!(p.hsb));- d.fields.insert("_lab".into(), json!(p.lab));- }+ #[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);+ }- /// The Color Picker's place in the dialog, as InDesign's (points from the body's top-left).- mod picker_layout {- use egui::{Rect, pos2, vec2};- // InDesign's proportions at this app's density (its 30 px fields are 21 pt here).- pub const SIZE: egui::Vec2 = vec2(566.0, 334.0);- pub fn field() -> Rect {- Rect::from_min_size(pos2(2.0, 31.0), vec2(265.0, 287.0))+ #[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");}- pub fn slider() -> Rect {- Rect::from_min_size(pos2(285.0, 32.0), vec2(19.0, 282.0))++ 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();}- pub fn swatch() -> Rect {- Rect::from_min_size(pos2(319.0, 0.0), vec2(71.0, 90.0))++ /// 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)}- /// OK, Cancel, Add … Swatch.- pub fn button(i: usize) -> Rect {- Rect::from_min_size(pos2(433.0, [0.0, 39.0, 78.0][i.min(2)]), vec2(132.0, 25.0))++ fn undo_steps(app: &DesignApp) -> usize {+ app.session.doc().map_or(0, |st| st.history.undo.len())}- /// Row centres: H/L, S/a, B/b, (gap), R/C, G/M, B/Y, K, #.- pub const ROWS: [f32; 8] = [129.0, 157.0, 185.0, 224.0, 252.0, 280.0, 308.0, 320.0];- /// The radio buttons' columns.- pub const LEFT: f32 = 326.0;- pub const RIGHT: f32 = 457.0;- }- /// A value field: the text typed stays while it has the focus; a number that parses applies.- fn picker_field(ui: &mut egui::Ui, d: &mut Dialog, r: egui::Rect, key: &str, value: f32, range: (f32, f32)) -> Option<f32> {- let id = egui::Id::new(("color_picker_field", key));- let editing = ui.memory(|m| m.has_focus(id));- let shown = format!("{}", value.round() as i64);- let edit_key = format!("_edit_{key}");- let mut text = if editing { d.fields.get(&edit_key).and_then(Value::as_str).map(str::to_string).unwrap_or(shown) } else { shown };- let resp = ui.put(- r,- egui::TextEdit::singleline(&mut text)- .id(id)- .font(egui::FontId::proportional(11.5))- .vertical_align(egui::Align::Center)- .margin(egui::Margin::symmetric(4, 2)),- );- let mut out = None;- if resp.changed()- && let Ok(v) = text.trim().parse::<f32>()- && v.is_finite()- {- out = Some(v.clamp(range.0, range.1));+ #[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);}- d.fields.insert(edit_key, json!(text));- out- }- /// The Color Picker, laid out as InDesign's: the colour space view (a field of two components,- /// a slider for the third: the one whose radio button is on, R at first), the new colour over the- /// one it replaces, OK / Cancel / Add CMYK Swatch at the top right, H/S/B beside L/a/b, R/G/B- /// beside C/M/Y/K, and the hex code. Its buttons replace the dialog's own.- fn color_picker(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {- use picker_layout as at;- let lang = app.ui.language.clone();- let tr = |s: &str| crate::i18n::tr(&lang, s).to_string();- if !d.fields.contains_key("old") {- let old = d.s("hex");- d.fields.insert("old".into(), json!(old));+ #[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);}- let comp = PickComp::from_key(&d.s("component"));- let mut p = picked_of(d);- let before = p;- let t = crate::theme::Tokens::get(ui.ctx());- let (area, _) = ui.allocate_exact_size(at::SIZE, egui::Sense::hover());- let o = area.min.to_vec2();- let put = |r: egui::Rect| r.translate(o);- let font = egui::FontId::proportional(11.5);- let text = |ui: &egui::Ui, pos: egui::Pos2, align: egui::Align2, s: &str| {- ui.painter().text(pos, align, s, egui::FontId::proportional(11.5), t.text_strong);- };- // The colour space view (a label, so screen readers hear which).- ui.scope_builder(- egui::UiBuilder::new()- .max_rect(egui::Rect::from_min_size(area.min, egui::vec2(260.0, 24.0)))- .layout(egui::Layout::left_to_right(egui::Align::Center)),- |ui| {- ui.label(- egui::RichText::new(tr(if comp.lab() { "Lab Color Space View" } else { "RGB Color Space View" })).size(11.5).color(t.text_strong),- );- },- );- let fr = put(at::field());- let fresp = ui.interact(fr, ui.id().with("cp_field"), egui::Sense::click_and_drag());- let (tv, _, _) = p.coords(comp);- let cells = if matches!(comp, PickComp::R | PickComp::G | PickComp::Bl | PickComp::H) { 2 } else { 24 };- gradient_mesh(ui.painter(), fr, cells, cells, |x, y| p.at(comp, tv, x, y).rgb);- fresp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Other, true, "Color field"));- if let Some(pos) = fresp.interact_pointer_pos().filter(|_| fresp.is_pointer_button_down_on() || fresp.clicked()) {- let u = ((pos.x - fr.left()) / fr.width()).clamp(0.0, 1.0);- let v = ((fr.bottom() - pos.y) / fr.height()).clamp(0.0, 1.0);- p = p.at(comp, tv, u, v);++ /// 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()}- // The marker: a cross with an open centre, white over black.- let (_, u, v) = p.coords(comp);- let m = egui::pos2(fr.left() + u * fr.width(), fr.bottom() - v * fr.height());- let painter = ui.painter().with_clip_rect(fr);- for (dx, dy) in [(1.0, 0.0), (-1.0, 0.0), (0.0, 1.0), (0.0, -1.0)] {- let (a, b) = (m + egui::vec2(dx * 3.0, dy * 3.0), m + egui::vec2(dx * 10.0, dy * 10.0));- let side = egui::vec2(dy, dx) * 1.2;- painter.line_segment([a + side, b + side], egui::Stroke::new(1.0, egui::Color32::BLACK));- painter.line_segment([a - side, b - side], egui::Stroke::new(1.0, egui::Color32::BLACK));- painter.line_segment([a, b], egui::Stroke::new(1.5, egui::Color32::WHITE));++ #[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);}- // The slider, with a marker on each side.- let sr = put(at::slider());- let sresp = ui.interact(sr.expand2(egui::vec2(6.0, 0.0)), ui.id().with("cp_slider"), egui::Sense::click_and_drag());- gradient_mesh(ui.painter(), sr, 1, 48, |_, y| p.slider_at(comp, y));- sresp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Slider, true, "Color slider"));- if let Some(pos) = sresp.interact_pointer_pos().filter(|_| sresp.is_pointer_button_down_on() || sresp.clicked()) {- let tn = ((sr.bottom() - pos.y) / sr.height()).clamp(0.0, 1.0);- let (_, u, v) = p.coords(comp);- p = p.at(comp, tn, u, v);++ #[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");}- let (tn, _, _) = p.coords(comp);- let y = sr.bottom() - tn * sr.height();- for (x, dir) in [(sr.left(), 1.0), (sr.right(), -1.0)] {- let pts = vec![- egui::pos2(x - 5.0 * dir, y - 4.5),- egui::pos2(x, y - 4.5),- egui::pos2(x + 3.5 * dir, y),- egui::pos2(x, y + 4.5),- egui::pos2(x - 5.0 * dir, y + 4.5),- ];- ui.painter().add(egui::Shape::convex_polygon(pts, egui::Color32::WHITE, egui::Stroke::new(1.0, egui::Color32::from_gray(40))));++ #[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);}- // The new colour over the one it replaces.- let pr = put(at::swatch());- let old = designcraft_color::Color::from_hex(&d.s("old")).map_or([0.0; 3], |c| c.to_rgb_uncalibrated());- ui.painter().rect_filled(egui::Rect::from_min_max(pr.min, egui::pos2(pr.max.x, pr.center().y)), 0.0, color32(p.rgb));- ui.painter().rect_filled(egui::Rect::from_min_max(egui::pos2(pr.min.x, pr.center().y), pr.max), 0.0, color32(old));- ui.painter().rect_stroke(pr, 0.0, egui::Stroke::new(1.0, egui::Color32::from_gray(80)), egui::StrokeKind::Inside);- // OK, Cancel, Add CMYK Swatch: rounded, OK filled.- let pill = |ui: &mut egui::Ui, i: usize, label: &str, primary: bool| -> bool {- let r = put(at::button(i));- let resp = ui.interact(r, ui.id().with(("cp_button", i)), egui::Sense::click());- let (fill, fg, stroke) = if primary {- (t.accent_strong, egui::Color32::WHITE, egui::Stroke::NONE)- } else {- (if resp.hovered() { t.hover } else { egui::Color32::TRANSPARENT }, t.text_strong, egui::Stroke::new(1.0, t.text_dim))- };- ui.painter().rect(r, r.height() / 2.0, fill, stroke, egui::StrokeKind::Inside);- ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, label, egui::FontId::proportional(12.0), fg);- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label));- resp.clicked()- };- if pill(ui, 0, &tr("OK"), true) || ui.input(|i| i.key_pressed(egui::Key::Enter)) {- d.fields.insert("_close".into(), json!("ok"));++ /// 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())}- if pill(ui, 1, &tr("Cancel"), false) || ui.input(|i| i.key_pressed(egui::Key::Escape)) {- d.fields.insert("_close".into(), json!("cancel"));++ /// 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()}- if pill(ui, 2, &tr("Add CMYK Swatch"), false) {- let [c, m, y, k] = designcraft_color::Color::Rgb { r: p.rgb[0], g: p.rgb[1], b: p.rgb[2] }- .to_cmyk_managed(designcraft_color::cms::active_settings().intent)- .map(|v| (v * 100.0).round());- match app.run("swatch.create", json!({"color": {"c": c, "m": m, "y": y, "k": k}})) {- Ok(r) => app.status(format!("{} {}", tr("Added swatch"), r["name"].as_str().unwrap_or(""))),- Err(e) => app.status(e),++ #[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());+ }++ #[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");}}- // The values: a radio button, a label, the field, a unit.- let mut comp_now = comp;- let mut edited: Option<Picked> = None;- let cmyk = designcraft_color::Color::Rgb { r: p.rgb[0], g: p.rgb[1], b: p.rgb[2] }- .to_cmyk_managed(designcraft_color::cms::active_settings().intent)- .map(|v| v * 100.0);- // (column x of the radio, row, component, label, key, value, range, unit)- let rows: [(f32, usize, Option<PickComp>, &str, &str, f32, (f32, f32), &str); 13] = [- (at::LEFT, 0, Some(PickComp::H), "H:", "h", p.hsb[0], (0.0, 360.0), "°"),- (at::LEFT, 1, Some(PickComp::S), "S:", "s", p.hsb[1] * 100.0, (0.0, 100.0), "%"),- (at::LEFT, 2, Some(PickComp::Br), "B:", "b", p.hsb[2] * 100.0, (0.0, 100.0), "%"),- (at::RIGHT, 0, Some(PickComp::L), "L:", "l", p.lab[0], (0.0, 100.0), ""),- (at::RIGHT, 1, Some(PickComp::A), "a:", "la", p.lab[1], (-128.0, 127.0), ""),- (at::RIGHT, 2, Some(PickComp::Lb), "b:", "lb", p.lab[2], (-128.0, 127.0), ""),- (at::LEFT, 3, Some(PickComp::R), "R:", "r", p.rgb[0] * 255.0, (0.0, 255.0), ""),- (at::LEFT, 4, Some(PickComp::G), "G:", "g", p.rgb[1] * 255.0, (0.0, 255.0), ""),- (at::LEFT, 5, Some(PickComp::Bl), "B:", "bl", p.rgb[2] * 255.0, (0.0, 255.0), ""),- (at::RIGHT, 3, None, "C:", "c", cmyk[0], (0.0, 100.0), "%"),- (at::RIGHT, 4, None, "M:", "m", cmyk[1], (0.0, 100.0), "%"),- (at::RIGHT, 5, None, "Y:", "y", cmyk[2], (0.0, 100.0), "%"),- (at::RIGHT, 6, None, "K:", "k", cmyk[3], (0.0, 100.0), "%"),- ];- for (x, row, c, label, key, value, range, unit) in rows {- let cy = area.min.y + at::ROWS[row];- let x = area.min.x + x;- match c {- Some(c) => {- let rr = egui::Rect::from_center_size(egui::pos2(x, cy), egui::vec2(14.0, 14.0));- let resp = ui.interact(rr, ui.id().with(("cp_radio", key)), egui::Sense::click());- ui.painter().circle(rr.center(), 6.0, t.input, egui::Stroke::new(1.0, t.text_dim));- if comp_now == c {- ui.painter().circle_filled(rr.center(), 2.6, t.text_strong);- }- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::RadioButton, true, comp_now == c, label));- if resp.clicked() {- comp_now = c;- }- text(ui, egui::pos2(x + 11.0, cy), egui::Align2::LEFT_CENTER, label);++ 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);}- // C/M/Y/K have no radio button: their labels end at the field.- None => text(ui, egui::pos2(x + 28.0, cy), egui::Align2::RIGHT_CENTER, label),- }- let fr = egui::Rect::from_min_size(egui::pos2(x + 35.0, cy - 10.5), egui::vec2(44.0, 21.0));- if let Some(v) = picker_field(ui, d, fr, key, value, range) {- edited = Some(match key {- "h" => Picked::from_hsb([v, p.hsb[1], p.hsb[2]]),- "s" => Picked::from_hsb([p.hsb[0], v / 100.0, p.hsb[2]]),- "b" => Picked::from_hsb([p.hsb[0], p.hsb[1], v / 100.0]),- "l" => Picked::from_lab([v, p.lab[1], p.lab[2]], p.hsb[0]),- "la" => Picked::from_lab([p.lab[0], v, p.lab[2]], p.hsb[0]),- "lb" => Picked::from_lab([p.lab[0], p.lab[1], v], p.hsb[0]),- "r" => Picked::from_rgb([v / 255.0, p.rgb[1], p.rgb[2]], p.hsb[0]),- "g" => Picked::from_rgb([p.rgb[0], v / 255.0, p.rgb[2]], p.hsb[0]),- "bl" => Picked::from_rgb([p.rgb[0], p.rgb[1], v / 255.0], p.hsb[0]),- _ => {- let mut c = cmyk;- c[["c", "m", "y", "k"].iter().position(|k| *k == key).unwrap_or(0)] = v;- let [c, m, y, k] = c.map(|x| x / 100.0);- Picked::from_rgb(designcraft_color::Color::Cmyk { c, m, y, k }.to_rgb(), p.hsb[0])- }- });- }- if !unit.is_empty() {- text(ui, egui::pos2(fr.right() + 8.0, cy), egui::Align2::LEFT_CENTER, unit);+ // `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());}}- if let Some(e) = edited {- p = e;++ #[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"]);}- if comp_now != comp {- d.fields.insert("component".into(), json!(comp_now.key()));++ #[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));}- // The hex code, and the eyedropper's mark beside it.- let cy = area.min.y + at::ROWS[7];- text(ui, egui::pos2(area.min.x + 321.0, cy), egui::Align2::LEFT_CENTER, "#:");- let hr = egui::Rect::from_min_size(egui::pos2(area.min.x + 341.0, cy - 10.5), egui::vec2(64.0, 21.0));- let id = egui::Id::new("color_picker_hex");- let editing = ui.memory(|m| m.has_focus(id));- let mut h = if editing { d.s("_hexEdit") } else { p.hex().trim_start_matches('#').to_string() };- if ui- .put(hr, egui::TextEdit::singleline(&mut h).id(id).font(font).vertical_align(egui::Align::Center).margin(egui::Margin::symmetric(4, 2)))- .changed()- && let Some(c) = designcraft_color::Color::from_hex(&h)- {- p = Picked::from_rgb(c.to_rgb_uncalibrated(), p.hsb[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);+ }}- d.fields.insert("_hexEdit".into(), json!(h));- crate::icons::paint(- ui.painter(),- egui::Rect::from_center_size(egui::pos2(hr.right() + 16.0, cy), egui::vec2(15.0, 15.0)),- "tool-eyedropper",- t.icon,- );- if p != before {- store_picked(d, &p);++ #[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"));}- }- /// Find/Replace Font: the document's fonts (missing ones first, flagged) and a replacement.- fn find_font(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {- // Listed once when the dialog opens (it scans every story).- if !d.fields.contains_key("_fonts") {- let list = app.session.execute("font.list", &json!({})).unwrap_or_default();- d.fields.insert("_fonts".into(), list);- }- let fonts = d.fields.get("_fonts").and_then(Value::as_array).cloned().unwrap_or_default();- let missing = fonts.iter().filter(|f| f["missing"] == true || f["styleMissing"] == true).count();- crate::rtl::label(- ui,- crate::i18n::tr(&app.ui.language, "Fonts in Document: {count} Missing: {missing}")- .replace("{count}", &fonts.len().to_string())- .replace("{missing}", &missing.to_string()),- );- egui::ScrollArea::vertical().id_salt("ff_list").max_height(180.0).show(ui, |ui| {- for f in &fonts {- let (fam, st) = (f["family"].as_str().unwrap_or(""), f["style"].as_str().unwrap_or(""));- let warn = f["missing"] == true || f["styleMissing"] == true;- let label = format!("{}{fam} {st}", if warn { "\u{26A0} " } else { "" });- let on = d.s("family") == fam && d.s("style") == st;- let mut text = egui::RichText::new(label);- if warn {- text = text.color(egui::Color32::from_rgb(0xe5, 0x4b, 0x4b));- }- if ui.selectable_label(on, text).clicked() {- d.fields.insert("family".into(), json!(fam));- d.fields.insert("style".into(), json!(st));+ #[test]+ fn 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);}- });- 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));- }- 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 style_preview_refuses_justification_spacing_ok_would_refuse() {+ 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 d =+ Dialog::new("paragraphStyleOptions", json!({"name": designcraft_doc::BASIC_PARAGRAPH, "preview": true, "p.wordSpaceDesired": 1.1}));+ style_options_preview(&mut app, &mut d);+ assert_ne!(app.session.doc().unwrap().doc, before, "a valid value previews");+ // Minimum above Desired: the page goes back and the dialog says why.+ d.fields.insert("p.wordSpaceMin".into(), json!(1.5));+ style_options_preview(&mut app, &mut d);+ assert_eq!(app.session.doc().unwrap().doc, before);+ assert!(d.s("status").contains("Word Spacing"), "{:?}", d.fields.get("status"));+ assert!(app.session.doc().unwrap().interaction.is_none());+ }#[test]- fn step_and_repeat_dialog_previews_and_makes_the_copies_as_one_undo_step() {+ 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();- 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);+ 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 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();+ // 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]@@@ -5487,7 -8153,7 +8295,7 @@@fn visible_label(labels: &[(String, egui::Rect, egui::Rect)], screen: egui::Rect, expected: &str) -> egui::Rect {let (_, rect, clip) = labels.iter().find(|(text, _, _)| text.trim() == expected).unwrap_or_else(|| panic!("{expected} is painted"));assert!(screen.contains_rect(*rect), "{expected} must stay on screen: {rect:?}");-- assert!(clip.contains_rect(*rect), "{expected} must not be clipped: {rect:?}, {clip:?}");++ assert!(clip.expand(0.5).contains_rect(*rect), "{expected} must not be clipped: {rect:?}, {clip:?}");*rect}@@@ -7214,65 -9874,7 +10016,116 @@@(0..doc.page_count()).map(|abs| doc.page(abs).unwrap().guides.len()).collect()}+ /// The Color Picker laid out as InDesign's: a field and a slider for the component whose radio+ /// is on, the new colour over the old one, and the values in every space.#[test]+++ fn the_color_picker_picks_on_its_field_and_slider_and_adds_a_cmyk_swatch() {+ use egui_kittest::kittest::Queryable;+++ 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, 200, 200], "shape": "rectangle"})).unwrap();++++ app.run("object.color", json!({"color":designcraft_color::Color::from_hex("#7c1315").unwrap(),"target":"fill"})).unwrap();+ app.ui.dialog = Some(Dialog::new("colorPicker", json!({"target": "fill", "hex": "#7c1315", "text": false})));+++ let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0));+++ h.run_steps(3);+++ // R at first: R up the slider, B across and G up the field.+++ let _ = h.get_by_label("RGB Color Space View");+++ let field = h.get_by_label("Color field").rect();+++ crate::test_window::click_at(&mut h, egui::pos2(field.right() - 1.0, field.top() + 1.0));+++ h.run_steps(2);+++ let p = picked_of(h.state().app.ui.dialog.as_ref().unwrap());+++ assert!((p.rgb[0] - 124.0 / 255.0).abs() < 0.01 && p.rgb[1] > 0.97 && p.rgb[2] > 0.97, "{p:?}: R kept, G and B full");+++ // The slider sets R alone.+++ let slider = h.get_by_label("Color slider").rect();+++ crate::test_window::click_at(&mut h, egui::pos2(slider.center().x, slider.bottom() - 1.0));+++ h.run_steps(2);+++ let p = picked_of(h.state().app.ui.dialog.as_ref().unwrap());+++ assert!(p.rgb[0] < 0.02 && p.rgb[1] > 0.97, "{p:?}");+++ // Hue on the slider: the field is saturation across, brightness up.- h.state_mut().app.ui.dialog.as_mut().unwrap().fields.insert("hex".into(), json!("#7c1315"));++++ store_picked(h.state_mut().app.ui.dialog.as_mut().unwrap(), &Picked::from_rgb([124.0 / 255.0, 19.0 / 255.0, 21.0 / 255.0], 0.0));+++ h.state_mut().app.ui.dialog.as_mut().unwrap().fields.insert("component".into(), json!("h"));+++ h.run_steps(2);+++ crate::test_window::click_at(&mut h, egui::pos2(field.left() + 1.0, field.top() + 1.0));+++ h.run_steps(2);+++ let p = picked_of(h.state().app.ui.dialog.as_ref().unwrap());+++ assert!(p.hsb[1] < 0.02 && p.hsb[2] > 0.98 && (p.hsb[0] - 359.0).abs() < 2.0, "{p:?}: no saturation, full brightness, the hue kept");+++ // Lab shows its own view.+++ h.state_mut().app.ui.dialog.as_mut().unwrap().fields.insert("component".into(), json!("l"));+++ h.run_steps(2);+++ let _ = h.get_by_label("Lab Color Space View");+++ // Add CMYK Swatch adds the colour as a CMYK swatch; OK applies it.- h.state_mut().app.ui.dialog.as_mut().unwrap().fields.insert("hex".into(), json!("#7c1315"));++++ store_picked(h.state_mut().app.ui.dialog.as_mut().unwrap(), &Picked::from_rgb([124.0 / 255.0, 19.0 / 255.0, 21.0 / 255.0], 0.0));+++ h.run_steps(2);+++ let before = h.state().app.session.active().unwrap().doc.swatches.len();+++ h.get_by_label("Add CMYK Swatch").click();+++ h.run_steps(3);+++ let doc = &h.state().app.session.active().unwrap().doc;+++ assert_eq!(doc.swatches.len(), before + 1);+++ assert!(matches!(+ doc.swatches.last().unwrap().value,+ designcraft_color::swatch::SwatchValue::Color { color: designcraft_color::Color::Cmyk { .. }, .. }+ ));+++ // Its own OK, at the top right, applies it.+++ h.get_by_label("OK").click();+++ h.run_steps(3);+++ assert!(h.state().app.ui.dialog.is_none(), "OK closes it");+++ let st = h.state().app.session.active().unwrap();+++ let id = st.selection.items[0];+++ let fill = st.doc.item(id).unwrap().fill.swatch.clone();+++ assert_eq!(st.doc.resolve_color(&fill, 1.0).unwrap().to_hex(), "#7c1315");+ }++ #[test]++fn create_guides_dialog_targets_the_page_in_view() {let mut app = facing_app(6);crate::canvas::go_to_page(&mut app, 4);@@@ -7317,4 -9919,12 +10170,258 @@@app.ui.dialog = Some(Dialog::new("newDocument", json!({"width": "15"})));assert_eq!(app.ui.dialog.as_ref().unwrap().m("width"), Some(180.0));}+ #[test]+ fn character_style_options_set_the_digits() {+ let mut app = styled_app();+ ctl(&mut app, "ui.dialog.open", json!({"id": "characterStyleOptions", "fields": {"name": "Emphasis"}}));+ ctl(&mut app, "ui.dialog.set", json!({"field": "c.digits", "value": "farsi"}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ assert_eq!(char_style(&app, "Emphasis").unwrap().chars.digits, Some(designcraft_doc::Digits::Farsi));+ }+ }++++/// The Color Picker's components: the one picked runs along the slider, the other two of its++/// space across the field (InDesign's, as Photoshop's: R puts B across and G up).++#[derive(Clone, Copy, Debug, PartialEq, Eq)]++pub(crate) enum PickComp {++ H,++ S,++ Br,++ L,++ A,++ Lb,++ R,++ G,++ Bl,++}++++impl PickComp {++ const ALL: [PickComp; 9] =++ [PickComp::H, PickComp::S, PickComp::Br, PickComp::L, PickComp::A, PickComp::Lb, PickComp::R, PickComp::G, PickComp::Bl];++++ fn key(self) -> &'static str {++ match self {++ PickComp::H => "h",++ PickComp::S => "s",++ PickComp::Br => "b",++ PickComp::L => "l",++ PickComp::A => "la",++ PickComp::Lb => "lb",++ PickComp::R => "r",++ PickComp::G => "g",++ PickComp::Bl => "bl",++ }++ }++++ fn from_key(k: &str) -> PickComp {++ PickComp::ALL.into_iter().find(|c| c.key() == k).unwrap_or(PickComp::R)++ }++++ fn lab(self) -> bool {++ matches!(self, PickComp::L | PickComp::A | PickComp::Lb)++ }++}++++/// The colour the picker shows, in each of its spaces (HSB keeps its hue through greys).++#[derive(Clone, Copy, Debug, PartialEq)]++pub(crate) struct Picked {++ pub rgb: [f32; 3],++ pub hsb: [f32; 3],++ pub lab: [f32; 3],++}++++impl Picked {++ pub fn from_rgb(rgb: [f32; 3], hue: f32) -> Picked {++ let rgb = rgb.map(|v| v.clamp(0.0, 1.0));++ let c = designcraft_color::Color::Rgb { r: rgb[0], g: rgb[1], b: rgb[2] };++ let mut hsb = c.to_hsb();++ if hsb[1] <= 1e-4 || hsb[2] <= 1e-4 {++ hsb[0] = hue;++ }++ let l = designcraft_color::cms::lab::srgb_to_lab(rgb);++ Picked { rgb, hsb, lab: [l.l, l.a, l.b] }++ }++++ fn from_hsb(hsb: [f32; 3]) -> Picked {++ let hsb = [hsb[0].rem_euclid(360.0), hsb[1].clamp(0.0, 1.0), hsb[2].clamp(0.0, 1.0)];++ let mut p = Picked::from_rgb(designcraft_color::Color::from_hsb(hsb[0], hsb[1], hsb[2]).to_rgb_uncalibrated(), hsb[0]);++ p.hsb = hsb;++ p++ }++++ fn from_lab(lab: [f32; 3], hue: f32) -> Picked {++ let lab = [lab[0].clamp(0.0, 100.0), lab[1].clamp(-128.0, 127.0), lab[2].clamp(-128.0, 127.0)];++ let mut p = Picked::from_rgb(designcraft_color::cms::lab::lab_to_srgb(designcraft_color::cms::Lab::new(lab[0], lab[1], lab[2])), hue);++ p.lab = lab;++ p++ }++++ /// (slider, across, up), each 0..1, for component `c`.++ pub fn coords(&self, c: PickComp) -> (f32, f32, f32) {++ let [r, g, b] = self.rgb;++ let [h, s, v] = self.hsb;++ let [l, la, lb] = self.lab;++ let (a, bb) = ((la + 128.0) / 255.0, (lb + 128.0) / 255.0);++ match c {++ PickComp::R => (r, b, g),++ PickComp::G => (g, b, r),++ PickComp::Bl => (b, r, g),++ PickComp::H => (h / 360.0, s, v),++ PickComp::S => (s, h / 360.0, v),++ PickComp::Br => (v, h / 360.0, s),++ PickComp::L => (l / 100.0, a, bb),++ PickComp::A => (a, bb, l / 100.0),++ PickComp::Lb => (bb, a, l / 100.0),++ }++ }++++ /// The colour at (slider `t`, across `u`, up `v`) for component `c`.++ pub fn at(&self, c: PickComp, t: f32, u: f32, v: f32) -> Picked {++ let hue = self.hsb[0];++ let ab = |x: f32| x * 255.0 - 128.0;++ match c {++ PickComp::R => Picked::from_rgb([t, v, u], hue),++ PickComp::G => Picked::from_rgb([v, t, u], hue),++ PickComp::Bl => Picked::from_rgb([u, v, t], hue),++ PickComp::H => Picked::from_hsb([t * 360.0, u, v]),++ PickComp::S => Picked::from_hsb([u * 360.0, t, v]),++ PickComp::Br => Picked::from_hsb([u * 360.0, v, t]),++ PickComp::L => Picked::from_lab([t * 100.0, ab(u), ab(v)], hue),++ PickComp::A => Picked::from_lab([v * 100.0, ab(t), ab(u)], hue),++ PickComp::Lb => Picked::from_lab([v * 100.0, ab(u), ab(t)], hue),++ }++ }++++ /// The slider's colour at `t`: the hue slider shows pure hues, the others this colour with++ /// the component at `t`.++ fn slider_at(&self, c: PickComp, t: f32) -> [f32; 3] {++ if c == PickComp::H {++ return designcraft_color::Color::from_hsb(t * 360.0, 1.0, 1.0).to_rgb_uncalibrated();++ }++ let (_, u, v) = self.coords(c);++ self.at(c, t, u, v).rgb++ }++++ pub fn hex(&self) -> String {++ let q = |x: f32| (x.clamp(0.0, 1.0) * 255.0).round() as u8;++ format!("#{:02x}{:02x}{:02x}", q(self.rgb[0]), q(self.rgb[1]), q(self.rgb[2]))++ }++}++++fn color32(rgb: [f32; 3]) -> egui::Color32 {++ let q = |x: f32| (x.clamp(0.0, 1.0) * 255.0).round() as u8;++ egui::Color32::from_rgb(q(rgb[0]), q(rgb[1]), q(rgb[2]))++}++++/// A `cols` × `rows` grid of quads over `r`, coloured at each vertex by `f(x, y)` (0..1, y up).++fn gradient_mesh(painter: &egui::Painter, r: egui::Rect, cols: usize, rows: usize, f: impl Fn(f32, f32) -> [f32; 3]) {++ let mut mesh = egui::Mesh::default();++ for j in 0..=rows {++ for i in 0..=cols {++ let (x, y) = (i as f32 / cols as f32, j as f32 / rows as f32);++ mesh.colored_vertex(egui::pos2(r.left() + x * r.width(), r.bottom() - y * r.height()), color32(f(x, y)));++ }++ }++ let w = (cols + 1) as u32;++ for j in 0..rows as u32 {++ for i in 0..cols as u32 {++ let a = j * w + i;++ mesh.add_triangle(a, a + 1, a + w);++ mesh.add_triangle(a + 1, a + w + 1, a + w);++ }++ }++ painter.add(egui::Shape::mesh(mesh));++}++++/// The colour in the dialog's fields: `hex`, with the HSB hue and the Lab values kept while++/// they round-trip (`_hsb`, `_lab`).++fn picked_of(d: &Dialog) -> Picked {++ let mut rgb = designcraft_color::Color::from_hex(&d.s("hex")).map_or([0.0; 3], |c| c.to_rgb_uncalibrated());++ if let Some(raw) = nums::<3>(d, "rgb") {++ let raw = raw.map(|x| (x / 255.0) as f32);++ if Picked::from_rgb(raw, 0.0).hex() == Picked::from_rgb(rgb, 0.0).hex() {++ rgb = raw;++ }++ }++ let hue = nums::<3>(d, "_hsb").map_or(0.0, |h| h[0] as f32);++ let mut p = Picked::from_rgb(rgb, hue);++ // The exact values the picker last set, while they still give this colour.++ if let Some(h) = nums::<3>(d, "_hsb").map(|h| h.map(|v| v as f32))++ && Picked::from_hsb(h).hex() == p.hex()++ {++ p.hsb = h;++ }++ if let Some(l) = nums::<3>(d, "_lab").map(|l| l.map(|v| v as f32))++ && Picked::from_lab(l, p.hsb[0]).hex() == p.hex()++ {++ p.lab = l;++ }++ p++}++++fn store_picked(d: &mut Dialog, p: &Picked) {++ d.fields.insert("edited".into(), json!(true));++ d.fields.insert("rgb".into(), json!(p.rgb.map(|x| x * 255.0)));++ d.fields.insert(++ "cmyk".into(),++ json!(++ designcraft_color::Color::Rgb { r: p.rgb[0], g: p.rgb[1], b: p.rgb[2] }++ .to_cmyk_managed(designcraft_color::cms::active_settings().intent)++ .map(|x| x * 100.0)++ ),++ );++ d.fields.insert("hex".into(), json!(p.hex()));++ d.fields.insert("_hsb".into(), json!(p.hsb));++ d.fields.insert("_lab".into(), json!(p.lab));++}++++/// The Color Picker's place in the dialog, as InDesign's (points from the body's top-left).++mod picker_layout {++ use egui::{Rect, pos2, vec2};++ // InDesign's proportions at this app's density (its 30 px fields are 21 pt here).++ pub const SIZE: egui::Vec2 = vec2(566.0, 334.0);++ pub fn field() -> Rect {++ Rect::from_min_size(pos2(2.0, 31.0), vec2(265.0, 287.0))++ }++ pub fn slider() -> Rect {++ Rect::from_min_size(pos2(285.0, 32.0), vec2(19.0, 282.0))++ }++ pub fn swatch() -> Rect {++ Rect::from_min_size(pos2(319.0, 0.0), vec2(71.0, 90.0))++ }++ /// OK, Cancel, Add … Swatch.++ pub fn button(i: usize) -> Rect {++ Rect::from_min_size(pos2(433.0, [0.0, 39.0, 78.0][i.min(2)]), vec2(132.0, 25.0))++ }++ /// Row centres: H/L, S/a, B/b, (gap), R/C, G/M, B/Y, K, #.++ pub const ROWS: [f32; 8] = [129.0, 157.0, 185.0, 224.0, 252.0, 280.0, 308.0, 320.0];++ /// The radio buttons' columns.++ pub const LEFT: f32 = 326.0;++ pub const RIGHT: f32 = 457.0;++}++++/// A value field: the text typed stays while it has the focus; a number that parses applies.++fn picker_field(ui: &mut egui::Ui, d: &mut Dialog, r: egui::Rect, key: &str, value: f32, range: (f32, f32)) -> Option<f32> {++ let id = egui::Id::new(("color_picker_field", key));++ let editing = ui.memory(|m| m.has_focus(id));++ let shown = format!("{}", value.round() as i64);++ let edit_key = format!("_edit_{key}");++ let mut text = if editing { d.fields.get(&edit_key).and_then(Value::as_str).map(str::to_string).unwrap_or(shown) } else { shown };++ let resp = ui.put(++ r,++ egui::TextEdit::singleline(&mut text)++ .id(id)++ .font(egui::FontId::proportional(11.5))++ .vertical_align(egui::Align::Center)++ .margin(egui::Margin::symmetric(4, 2)),++ );++ let mut out = None;++ if resp.changed()++ && let Ok(v) = text.trim().parse::<f32>()++ && v.is_finite()++ {++ out = Some(v.clamp(range.0, range.1));++ }++ d.fields.insert(edit_key, json!(text));++ out+}diff --cc crates/ui-egui/src/i18n.rsindex 87a3eda7b,efe089ef9..6e9a0b40b--- a/crates/ui-egui/src/i18n.rs+++ b/crates/ui-egui/src/i18n.rs@@@ -58,28 -89,69 +89,91 @@@ const TABLE: &[(&str, [&str; 5])] = &("Cut", ["Ausschneiden", "Couper", "Cortar", "カット", "剪切"]),("Copy", ["Kopieren", "Copier", "Copiar", "コピー", "复制"]),("Paste", ["Einfügen", "Coller", "Pegar", "ペースト", "粘贴"]),+ ("Hide Rulers", ["Lineale ausblenden", "Masquer les règles", "Ocultar reglas", "定規を隠す", "隐藏标尺"]),+ ("Inches Decimal", ["Zoll dezimal", "Pouces décimaux", "Pulgadas decimales", "インチ(10 進)", "十进制英寸"]),+ (+ "Paste Vector Art",+ ["Vektorgrafik einfügen", "Coller l’illustration vectorielle", "Pegar ilustración vectorial", "ベクトルアートをペースト", "粘贴矢量图稿"],+ ),+ ("Back", ["Zurück", "Retour", "Atrás", "戻る", "返回"]),+ ("Margins and Columns", ["Ränder und Spalten", "Marges et colonnes", "Márgenes y columnas", "マージン・段組", "边距和分栏"]),+ ("Warning", ["Warnung", "Avertissement", "Advertencia", "警告", "警告"]),+ ("Don't show again", ["Nicht mehr anzeigen", "Ne plus afficher", "No volver a mostrar", "今後表示しない", "不再显示"]),+ (+ "The affected page contains objects. Delete the page anyway?",+ [+ "Die betroffene Seite enthält Objekte. Seite trotzdem löschen?",+ "La page concernée contient des objets. Supprimer quand même la page ?",+ "La página afectada contiene objetos. ¿Desea eliminarla de todos modos?",+ "対象のページにはオブジェクトが含まれています。ページを削除しますか?",+ "受影响的页面包含对象。仍要删除该页面吗?",+ ],+ ),+ (+ "The affected pages contain objects. Delete the pages anyway?",+ [+ "Die betroffenen Seiten enthalten Objekte. Seiten trotzdem löschen?",+ "Les pages concernées contiennent des objets. Supprimer quand même les pages ?",+ "Las páginas afectadas contienen objetos. ¿Desea eliminarlas de todos modos?",+ "対象のページにはオブジェクトが含まれています。ページを削除しますか?",+ "受影响的页面包含对象。仍要删除这些页面吗?",+ ],+ ),+ ("Capture", ["Erfassen", "Capturer", "Capturar", "取り込み", "捕捉"]),+ ("Panel Locations", ["Bedienfeldpositionen", "Emplacements des panneaux", "Ubicaciones de paneles", "パネルの位置", "面板位置"]),+ ("First Page", ["Erste Seite", "Première page", "Primera página", "最初のページ", "第一页"]),+ ("Previous Page", ["Vorherige Seite", "Page précédente", "Página anterior", "前のページ", "上一页"]),+ ("Next Page", ["Nächste Seite", "Page suivante", "Página siguiente", "次のページ", "下一页"]),+ ("Last Page", ["Letzte Seite", "Dernière page", "Última página", "最後のページ", "最后一页"]),+ (+ "Close Tab Group",+ ["Registerkartengruppe schließen", "Fermer le groupe d'onglets", "Cerrar grupo de fichas", "タブグループを閉じる", "关闭选项卡组"],+ ),+ ("Minimize", ["Minimieren", "Réduire", "Minimizar", "最小化", "最小化"]),+ ("Collapse to Icons", ["Auf Symbole minimieren", "Réduire en icônes", "Contraer a iconos", "アイコンパネルに折りたたむ", "折叠为图标"]),+ ("Panel Options", ["Bedienfeldoptionen", "Options du panneau", "Opciones de panel", "パネルオプション", "面板选项"]),+ ("Panel Options…", ["Bedienfeldoptionen…", "Options du panneau…", "Opciones de panel…", "パネルオプション…", "面板选项…"]),+ ("Show Thumbnails", ["Miniaturen anzeigen", "Afficher les vignettes", "Mostrar miniaturas", "サムネールを表示", "显示缩览图"]),+ ("Show Vertically", ["Vertikal anzeigen", "Afficher verticalement", "Mostrar verticalmente", "縦に表示", "垂直显示"]),+ ("Panel Layout", ["Bedienfeldlayout", "Disposition du panneau", "Diseño del panel", "パネルレイアウト", "面板版面"]),+ ("Pages on Top", ["Seiten oben", "Pages en haut", "Páginas en la parte superior", "ページを上に表示", "页面在上"]),+ (+ "Parents on Top",+ ["Übergeordnete Seiten oben", "Parents en haut", "Páginas principales en la parte superior", "親ページを上に表示", "父页面在上"],+ ),+ ("Resize:", ["Größe ändern:", "Redimensionner :", "Cambiar tamaño:", "サイズ変更:", "调整大小:"]),+ ("Extra Small", ["Sehr klein", "Très petite", "Extra pequeño", "極小", "特小"]),+ ("Small", ["Klein", "Petite", "Pequeño", "小", "小"]),+ ("Medium", ["Mittel", "Moyenne", "Mediano", "中", "中"]),+ ("Large", ["Groß", "Grande", "Grande", "大", "大"]),+ ("Extra Large", ["Sehr groß", "Très grande", "Extra grande", "特大", "特大"]),+ ("Jumbo", ["Riesig", "Géante", "Gigante", "最大", "巨大"]),+ ("Proportional", ["Proportional", "Proportionnel", "Proporcional", "比例", "按比例"]),+ ("Pages Fixed", ["Seiten fixiert", "Pages fixes", "Páginas fijas", "ページを固定", "页面固定"]),+ ("Parents Fixed", ["Übergeordnete fixiert", "Parents fixes", "Páginas principales fijas", "親ページを固定", "父页面固定"]),+ ("Parents", ["Übergeordnete Seiten", "Parents", "Páginas principales", "親ページ", "父页面"]),+ (+ "RGB Color Space View",+ [+ "RGB-Farbraumansicht",+ "Affichage de l’espace colorimétrique RVB",+ "Vista de espacio de color RGB",+ "RGB カラースペース表示",+ "RGB 色彩空间视图",+ ],+ ),+ (+ "Lab Color Space View",+ [+ "Lab-Farbraumansicht",+ "Affichage de l’espace colorimétrique Lab",+ "Vista de espacio de color Lab",+ "Lab カラースペース表示",+ "Lab 色彩空间视图",+ ],+ ),+ ("Add CMYK Swatch", ["CMYK-Farbfeld hinzufügen", "Ajouter une nuance CMJN", "Añadir muestra CMYK", "CMYK スウォッチを追加", "添加 CMYK 色板"]),+ ("Added swatch", ["Farbfeld hinzugefügt", "Nuance ajoutée", "Muestra añadida", "スウォッチを追加しました", "已添加色板"]),("Bulleted & Numbered Lists",[