diff --git a/crates/engine/src/cmd/lists.rs b/crates/engine/src/cmd/lists.rs index 987e9fd537..3a68a4003f 100644 --- a/crates/engine/src/cmd/lists.rs +++ b/crates/engine/src/cmd/lists.rs @@ -157,6 +157,104 @@ fn default_level(i: usize) -> Level { levels_for(ListKind::Numbered).into_iter().nth(i).unwrap_or_default() } +/// Define New Bullet (#2786): the selected paragraphs go into a list of their own whose bullet is +/// `char`, drawn in `font` (with `size`, `bold`, `italic` and `color` when given) and aligned by +/// `align` at every level they use. A list of its own, so +/// no other list using the same character changes, and it never toggles a bullet off the way +/// `para.bullets` does. Each paragraph keeps its level (level 1 when it wasn't in a list). +pub fn define_bullet(s: &mut Session, v: &Value) -> CmdResult { + let ch = match v.get("char") { + None => '★', + Some(c) => { + let c = c.as_str().ok_or_else(|| CmdError::Params("char must be one character".into()))?; + let mut it = c.chars(); + match (it.next(), it.next()) { + (Some(c), None) if !c.is_control() => c, + _ => return Err(CmdError::Params("char must be one character".into())), + } + } + }; + let font = match v.get("font") { + None => None, + Some(f) => { + let f = f.as_str().map(str::trim).ok_or_else(|| CmdError::Params("font must be a family name".into()))?; + if f.len() > 128 { + return Err(CmdError::Params("font name too long".into())); + } + (!f.is_empty()).then(|| f.to_string()) + } + }; + let size = match v.get("size") { + None => None, + Some(n) => match n.as_f64() { + Some(pt) if (1.0..=1638.0).contains(&pt) => Some(pt as f32), + _ => return Err(CmdError::Params("size must be 1 to 1638 points".into())), + }, + }; + let flag = |k: &str| -> Result, CmdError> { + match v.get(k) { + None => Ok(None), + Some(b) => b.as_bool().map(Some).ok_or_else(|| CmdError::Params(format!("{k} must be true or false"))), + } + }; + let (bold, italic) = (flag("bold")?, flag("italic")?); + let color = match v.get("color") { + None => None, + Some(c) => { + let c = c.as_str().ok_or_else(|| CmdError::Params("color must be RRGGBB or auto".into()))?; + Some(TextColor::parse(c).ok_or_else(|| CmdError::Params("color must be RRGGBB or auto".into()))?) + } + }; + let align = match p::str(v, "align") { + None if v.get("align").is_none() => None, + Some("left") => Some(Align::Left), + Some("center") => Some(Align::Center), + Some("right") => Some(Align::Right), + _ => return Err(CmdError::Params("align must be left, center or right".into())), + }; + // A paragraph's level, from its own numbering or its style's (List Bullet 2 numbers its + // paragraphs at level 2 without any of their own). + let styles = s.doc.styles.clone(); + let level_of = |pp: &wordcraft_doc::props::ParaProps| styles.resolve_para(pp).numbering.filter(|n| n.num != 0).map_or(0, |n| n.level); + let story = s.sel.focus.story; + let used: std::collections::BTreeSet = + super::selected_paths(s).iter().filter_map(|p| s.doc.para(story, p)).map(|x| level_of(&x.props)).collect(); + let mut levels = levels_for(ListKind::BulletChar(ch)); + for l in used { + if let Some(lv) = levels.get_mut(usize::from(l)) { + lv.text = ch.to_string(); + lv.chr.font = font.clone(); + if size.is_some() { + lv.chr.size = size; + } + if bold.is_some() { + lv.chr.bold = bold; + } + if italic.is_some() { + lv.chr.italic = italic; + } + if color.is_some() { + lv.chr.color = color; + } + if let Some(a) = align { + lv.align = a; + } + } + } + let num = Arc::make_mut(&mut s.doc.numbering).try_add_levels(None, levels)?; + super::para::fmt(s, &|pp| { + let level = level_of(pp); + pp.numbering = Some(NumRef { num, level }); + pp.indent_left = None; + pp.indent_first = None; + pp.indent_left_chars = None; + pp.indent_first_chars = None; + if pp.style.is_none() || pp.style.as_deref() == Some("Normal") { + pp.style = Some("ListParagraph".into()); + } + }) +} + fn get(s: &mut Session, v: &Value) -> CmdResult { let num = p::u64(v, "num").map(|n| n.min(u32::MAX as u64) as u32).or_else(|| caret_list(s)).ok_or_else(|| CmdError::Failed("not in a list".into()))?; diff --git a/crates/engine/src/cmd/tools/specs.rs b/crates/engine/src/cmd/tools/specs.rs index 2eee21614d..e622e2064e 100644 --- a/crates/engine/src/cmd/tools/specs.rs +++ b/crates/engine/src/cmd/tools/specs.rs @@ -316,10 +316,9 @@ pub fn specs() -> Vec { sel_result(s) }) .params(r#"{"value": n}"#), - CommandSpec::new("para.defineBullet", "Define New Bullet", "Home › Paragraph › Bullets", |s, v| { - s.run("para.bullets", &json!({"kind": p::str(v, "char").unwrap_or("★")})) - }) - .params(r#"{"char": string}"#), + CommandSpec::new("para.defineBullet", "Define New Bullet", "Home › Paragraph › Bullets", crate::cmd::lists::define_bullet).params( + r#"{"char"?: one character (default ★), "font"?: family (the bullet's own font; "" = the text's), "size"?: pt, "bold"?: bool, "italic"?: bool, "color"?: "RRGGBB" | "auto", "align"?: "left|center|right"} (the selected paragraphs get a list of their own; each keeps its level)"#, + ), CommandSpec::new("para.defineNumber", "Define New Number Format", "Home › Paragraph › Numbering", |s, v| { let fmt = wordcraft_doc::section::NumFormat::from_ooxml(p::str(v, "format").unwrap_or("decimal")); let text = p::str(v, "text").unwrap_or("%1.").to_string(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 42922bf7dc..6ea3c4f71a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -8548,6 +8548,83 @@ fn colour_commands_take_any_custom_hex() { assert_eq!(s.doc.settings.page_color, wordcraft_doc::Rgb::parse("123ABC")); } +/// #2786: Define New Bullet puts the selection in a list of its own: the character, its font and +/// its alignment at the levels the paragraphs use, each paragraph keeping its level. A list that +/// already uses the same character is left alone, defining again never toggles the bullet off, +/// it survives a DOCX round trip, and bad params are errors that change nothing. +#[test] +fn define_bullet_gives_the_selection_a_bullet_of_its_own() { + use wordcraft_doc::props::Align; + let mut s = Session::new(wordcraft_doc::Document::from_text("One\nTwo\nThree")); + let num_at = |s: &Session, i: usize| s.doc.para_at(&Pos::body(i, 0)).unwrap().props.numbering.unwrap(); + // "Three" already has a ♦ list, defined the ordinary way. + s.sel = crate::Selection::caret(Pos::body(2, 0)); + run(&mut s, "para.bullets", json!({"kind": "♦"})); + let other = num_at(&s, 2).num; + let other_level = s.doc.numbering.level(other, 0).unwrap().clone(); + // "Two" sits at level 2 of a bulleted list before the definition. + s.sel = crate::Selection::caret(Pos::body(1, 0)); + run(&mut s, "para.bullets", json!({})); + run(&mut s, "para.listLevel", json!({"level": 1})); + s.sel = crate::Selection { anchor: Pos::body(0, 0), focus: Pos::body(1, 3) }; + run(&mut s, "para.defineBullet", json!({"char": "♦", "font": "Segoe UI Symbol", "align": "center"})); + let (one, two) = (num_at(&s, 0), num_at(&s, 1)); + assert_eq!(one.num, two.num, "one list for the selection"); + assert_ne!(one.num, other, "not the existing ♦ list"); + assert_eq!((one.level, two.level), (0, 1), "each paragraph keeps its level"); + for lvl in [0, 1] { + let l = s.doc.numbering.level(one.num, lvl).unwrap(); + assert_eq!((l.text.as_str(), l.chr.font.as_deref(), l.align), ("♦", Some("Segoe UI Symbol"), Align::Center), "level {lvl}"); + } + assert_eq!(s.doc.numbering.level(other, 0).unwrap(), &other_level, "the other ♦ list is unchanged"); + // Defining the same bullet again keeps it (para.bullets would toggle it off). + run(&mut s, "para.defineBullet", json!({"char": "♦"})); + assert_eq!(s.doc.numbering.level(num_at(&s, 0).num, 0).unwrap().text, "♦"); + // DOCX keeps the character, its font and the alignment. + run(&mut s, "para.defineBullet", json!({"char": "✓", "font": "Segoe UI Symbol", "align": "right", "size": 14, "bold": true, "color": "C00000"})); + let back = wordcraft_docx::read(&wordcraft_docx::write(&s.doc).unwrap()).unwrap(); + let n = back.para_at(&Pos::body(0, 0)).unwrap().props.numbering.unwrap(); + let l = back.numbering.level(n.num, 0).unwrap(); + assert_eq!((l.text.as_str(), l.chr.font.as_deref(), l.align), ("✓", Some("Segoe UI Symbol"), Align::Right)); + // The Font dialog's size, bold and colour reach the bullet too. + assert_eq!((l.chr.size, l.chr.bold), (Some(14.0), Some(true))); + assert_eq!(l.chr.color, wordcraft_doc::props::TextColor::parse("C00000")); + // A paragraph numbered only by its style keeps the style's level (review of #2860). + let mut s2 = Session::new(wordcraft_doc::Document::from_text("Styled")); + let styled = Arc::make_mut(&mut s2.doc.numbering).try_add_list(wordcraft_doc::ListKind::Bullet).unwrap(); + Arc::make_mut(&mut s2.doc.styles).get_mut("ListParagraph").unwrap().para.numbering = Some(wordcraft_doc::props::NumRef { num: styled, level: 1 }); + s2.doc.para_mut(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().props.style = Some("ListParagraph".into()); + assert!(s2.doc.para_at(&Pos::body(0, 0)).unwrap().props.numbering.is_none(), "no numbering of its own"); + s2.sel = crate::Selection::caret(Pos::body(0, 0)); + run(&mut s2, "para.defineBullet", json!({"char": "♦"})); + let n = s2.doc.para_at(&Pos::body(0, 0)).unwrap().props.numbering.unwrap(); + assert_eq!(n.level, 1, "the style's level is kept"); + assert_eq!(s2.doc.numbering.level(n.num, 1).unwrap().text, "♦"); + // No params: ★, as before. + s.sel = crate::Selection::caret(Pos::body(2, 0)); + run(&mut s, "para.defineBullet", json!({})); + assert_eq!(s.doc.numbering.level(num_at(&s, 2).num, 0).unwrap().text, "★"); + let doc = s.doc.clone(); + let long = "x".repeat(200); + for junk in [ + json!({"char": ""}), + json!({"char": "ab"}), + json!({"char": 5}), + json!({"char": "\u{7}"}), + json!({"char": "•", "align": "middle"}), + json!({"char": "•", "align": 1}), + json!({"char": "•", "font": 3}), + json!({"char": "•", "font": long}), + json!({"char": "•", "size": 0}), + json!({"char": "•", "size": "big"}), + json!({"char": "•", "bold": "yes"}), + json!({"char": "•", "color": "purple"}), + ] { + assert!(s.run("para.defineBullet", &junk).is_err(), "{junk}"); + } + assert_eq!(s.doc, doc); +} + /// #4685: Home › Paragraph › Shading on text selected inside a paragraph shades that text, as in /// Word, so No Color takes off a text shading a file gave it (an orange "highlight" from a .docx is /// `w:shd`, which Text Highlight Color › No Color leaves, in Word too). A caret or a whole diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index c9872347a9..178f6f5c7a 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -42,6 +42,7 @@ pub(crate) use find::swallow_shortcut_text; pub use find::{FindExtra, FindTab, GoToWhat}; #[cfg(test)] use find::{command_matches, goto_page}; +pub use font::font_for_bullet; #[cfg(test)] use font::{apply_font, preview_size}; use font::{east_asian_char, font_props}; @@ -97,6 +98,11 @@ pub enum Dialog { /// alone stays as it is. #[serde(skip)] start: serde_json::Map, + /// Formatting a bullet for Define New Bullet (#2786): OK hands the font, size, bold, + /// italic and colour back to that dialog instead of formatting the text, and Cancel goes + /// back to it unchanged. + #[serde(skip)] + bullet: Option>, }, Paragraph { /// Right-to-left reading order (Direction in Word's Paragraph dialog). @@ -488,14 +494,27 @@ pub enum Dialog { } impl Dialog { + /// The Define New Bullet form a Font or Symbol dialog opened from it carries (#2786). + fn bullet_form(&mut self) -> Option { + match self { + Dialog::Font { bullet, .. } => bullet.take().map(|b| *b), + Dialog::Insert(i) => match i.as_mut() { + crate::dialogs_insert::InsertDialog::Symbol(f) => f.bullet.take().map(|b| *b), + _ => None, + }, + _ => None, + } + } + /// Whether the dialog blocks the rest of the window while it is open. As in Word for Mac - /// (16.114.1, #3859), all are but those you keep working beside. + /// (16.114.1, #3859), all are but those you keep working beside. Symbol opened from Define + /// New Bullet picks the bullet for it, so it blocks the window as that dialog does (#2786). pub fn is_modal(&self) -> bool { use crate::dialogs_insert::InsertDialog; use crate::dialogs_refs::RefsDialog; match self { Dialog::Find { .. } | Dialog::InsertMergeField { .. } => false, - Dialog::Insert(d) => !matches!(**d, InsertDialog::Symbol(_)), + Dialog::Insert(d) => !matches!(&**d, InsertDialog::Symbol(f) if f.bullet.is_none()), Dialog::Refs(d) => !matches!(**d, RefsDialog::MarkEntry(_) | RefsDialog::CrossRef(_)), _ => true, } @@ -634,6 +653,7 @@ impl Dialog { kern: kern.map(|k| k > 0.0), kern_at: kern.filter(|k| *k > 0.0).unwrap_or(12.0) as f32, start: serde_json::Map::new(), + bullet: None, }; let props = font_props(&d); if let Dialog::Font { start, .. } = &mut d { @@ -905,6 +925,7 @@ impl Dialog { } } +pub mod dialogs_bullet; pub mod dialogs_chart; pub mod dialogs_controls; pub mod dialogs_insert; diff --git a/crates/ui-egui/src/dialogs/chrome.rs b/crates/ui-egui/src/dialogs/chrome.rs index bb708daaae..90b09f33ec 100644 --- a/crates/ui-egui/src/dialogs/chrome.rs +++ b/crates/ui-egui/src/dialogs/chrome.rs @@ -261,7 +261,14 @@ pub fn show(app: &mut WordApp, ctx: &egui::Context) { }); } count_dialog_frame(ctx, id); - close |= crate::window_close::show(ctx, &shown.response, &Tokens::get(ctx)); + if crate::window_close::show(ctx, &shown.response, &Tokens::get(ctx)) && !close { + close = true; + // The title bar's close box is Cancel: a dialog opened from Define New Bullet goes + // back to it, as its Cancel button does (#2786). + if back_to_bullet(app, &mut d) { + return; + } + } // A file browser it opened (Attach…, Browse…) stays above it. if d.is_modal() && !close && !app.file_browser_open() { block_behind(app, ctx, &shown.response); @@ -278,6 +285,13 @@ pub fn show(app: &mut WordApp, ctx: &egui::Context) { } } +/// Back to Define New Bullet from a Font or Symbol dialog it opened, when `d` is one (#2786). +fn back_to_bullet(app: &mut WordApp, d: &mut Dialog) -> bool { + let Some(form) = d.bullet_form() else { return false }; + app.dialog = Some(Dialog::Insert(Box::new(crate::dialogs_insert::InsertDialog::DefineBullet(form)))); + true +} + /// Cancel key for dialogs: Escape everywhere, plus ⌘. (Command+Period) on macOS. pub(crate) fn cancel_key_pressed(ui: &Ui) -> bool { ui.input(|i| i.key_pressed(egui::Key::Escape) || (cfg!(target_os = "macos") && i.modifiers.command && i.key_pressed(egui::Key::Period))) diff --git a/crates/ui-egui/src/dialogs/dialogs_bullet.rs b/crates/ui-egui/src/dialogs/dialogs_bullet.rs new file mode 100644 index 0000000000..3a26957136 --- /dev/null +++ b/crates/ui-egui/src/dialogs/dialogs_bullet.rs @@ -0,0 +1,370 @@ +//! Define New Bullet (Home › Paragraph › Bullets, #2786): the bullet character (picked in the +//! Symbol dialog), its font (in the app's Font dialog) and its alignment, with a preview. It +//! ends in one command, `para.defineBullet`, so agents get the same result without the dialog. + +use egui::{Ui, vec2}; +use serde::Serialize; +use serde_json::json; +use wordcraft_doc::props::Align; + +use crate::WordApp; +use crate::dialogs::Dialog; +use crate::dialogs_insert::{InsertDialog, SymbolForm}; +use crate::theme::{Tokens, regular, semibold}; + +/// The alignments the dialog offers: `para.defineBullet`'s `align` and their names. +pub const ALIGNMENTS: [(&str, &str); 3] = [("left", "Left"), ("center", "Center"), ("right", "Right")]; + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DefineBulletForm { + /// The bullet character. + pub ch: String, + /// The bullet's own font; empty = the text's. + pub font: String, + /// The bullet's size in points; empty = the text's. + pub size: String, + pub bold: bool, + pub italic: bool, + /// `RRGGBB`; empty or `auto` = the text's colour. + pub color: String, + /// `left`, `center` or `right`. + pub align: String, +} + +impl DefineBulletForm { + /// Starts from the bullet the caret's paragraph has (its level's character, font and + /// alignment), or a plain • when it has none. + pub fn new(app: &WordApp) -> DefineBulletForm { + let doc = &app.session.doc; + let level = doc + .para_at(&app.session.sel.focus) + .and_then(|p| doc.styles.resolve_para(&p.props).numbering) + .filter(|n| n.num != 0) + .and_then(|n| doc.numbering.level(n.num, n.level)) + .filter(|l| l.format == wordcraft_doc::section::NumFormat::Bullet && l.text.chars().count() == 1); + match level { + Some(l) => DefineBulletForm { + ch: l.text.clone(), + font: l.chr.font.clone().unwrap_or_default(), + size: l.chr.size.map(|s| s.to_string()).unwrap_or_default(), + bold: l.chr.bold.unwrap_or(false), + italic: l.chr.italic.unwrap_or(false), + color: match l.chr.color { + Some(wordcraft_doc::props::TextColor::Rgb(c)) => c.hex(), + _ => String::new(), + }, + align: match l.align { + Align::Center => "center", + Align::Right => "right", + _ => "left", + } + .into(), + }, + None => DefineBulletForm::plain("•"), + } + } + + /// A bullet `ch` in the text's own formatting, left aligned. + pub fn plain(ch: &str) -> DefineBulletForm { + DefineBulletForm { + ch: ch.into(), + font: String::new(), + size: String::new(), + bold: false, + italic: false, + color: String::new(), + align: "left".into(), + } + } + + /// The bullet's formatting as the preview draws it, at [`Self::preview_pt`]. + pub fn chr(&self) -> wordcraft_doc::props::CharProps { + wordcraft_doc::props::CharProps { + size: Some(self.preview_pt()), + font: (!self.font.is_empty()).then(|| self.font.clone()), + bold: self.bold.then_some(true), + italic: self.italic.then_some(true), + color: wordcraft_doc::Rgb::parse(&self.color).map(wordcraft_doc::props::TextColor::Rgb), + ..Default::default() + } + } + + /// The bullet's size in the preview, in points: its own size, or the text's (11 pt) when it + /// has none, kept to what the preview's rows can show (4–20 pt). + pub fn preview_pt(&self) -> f32 { + let pt = self.size.trim().parse::().ok().filter(|pt| pt.is_finite() && (1.0..=1638.0).contains(pt)).unwrap_or(11.0); + pt.clamp(4.0, 20.0) + } + + /// The `para.defineBullet` params this form stands for. + pub fn params(&self) -> serde_json::Value { + let mut v = json!({"char": self.ch, "font": self.font, "align": self.align, "bold": self.bold, "italic": self.italic}); + // No size is the text's size; anything else goes to the command, which rejects a bad one. + let size = self.size.trim(); + if !size.is_empty() { + v["size"] = match size.parse::() { + Ok(pt) if pt.is_finite() => json!(pt), + _ => json!(size), + }; + } + v["color"] = json!(if wordcraft_doc::Rgb::parse(&self.color).is_some() { self.color.as_str() } else { "auto" }); + v + } +} + +/// Draws the dialog; returns true to close it (OK, Cancel, or Symbol… / Font…, which hand the +/// dialog over to the Symbol or Font dialog and get it back when it closes). +pub fn body(app: &mut WordApp, ui: &mut Ui, f: &mut DefineBulletForm) -> bool { + let t = Tokens::get(ui.ctx()); + ui.set_width(340.0); + ui.label(egui::RichText::new(tl!("Bullet character")).font(semibold(12.0))); + ui.add_space(4.0); + let (mut to_symbol, mut to_font) = (false, false); + ui.horizontal(|ui| { + to_symbol = ui.button(tl!("Symbol…")).clicked(); + to_font = ui.button(tl!("Font…")).clicked(); + }); + if to_symbol { + let form = f.clone(); + app.dialog = Some(Dialog::Insert(Box::new(InsertDialog::Symbol(SymbolForm::for_bullet(app, form))))); + return true; + } + if to_font { + // The app's own Font dialog, formatting the bullet and handing it back. + if let Some(d) = crate::dialogs::font_for_bullet(app, f.clone()) { + app.dialog = Some(d); + return true; + } + } + ui.add_space(6.0); + ui.horizontal(|ui| { + ui.label(tl!("Alignment:")); + ui.add_space(6.0); + for (k, n) in ALIGNMENTS { + ui.radio_value(&mut f.align, k.to_string(), tl!(n)); + } + }); + ui.add_space(8.0); + ui.label(egui::RichText::new(tl!("Preview")).font(regular(12.0)).color(t.text_dim)); + preview(app, ui, f); + ui.add_space(6.0); + let (ok, cancel) = crate::dialogs_insert::buttons(ui, "OK", "Cancel", f.ch.chars().count() == 1); + if ok && let Err(e) = app.run("para.defineBullet", f.params()) { + // A bad setting (a size out of range…) keeps the dialog open to correct it. + app.status(e); + return false; + } + ok || cancel +} + +/// The preview, drawn like Define New Multilevel List's: two plain lines of text, three bulleted +/// ones and two plain lines again, as grey bars on a white page. The bullet sits at the first +/// level's aligned-at position (18 pt), aligned there as chosen, and its text starts at the text +/// indent (36 pt); the bullet itself is laid out by the layout engine, so a symbol font shows the +/// character the page will. +fn preview(app: &mut WordApp, ui: &mut Ui, f: &DefineBulletForm) { + let t = Tokens::get(ui.ctx()); + let row = 17.0; + let (rect, _) = ui.allocate_exact_size(vec2(340.0, row * 7.0 + 10.0), egui::Sense::hover()); + let p = ui.painter_at(rect); + p.rect_filled(rect, 2.0, egui::Color32::WHITE); + p.rect_stroke(rect, 2.0, egui::Stroke::new(1.0, t.border_strong), egui::StrokeKind::Inside); + // Positions in points, scaled so 4.5 inches fit, as in Define New Multilevel List. + let scale = (rect.width() - 16.0) / 324.0; + let left = rect.left() + 8.0; + let (aligned_at, text_at) = (left + 18.0 * scale, left + 36.0 * scale); + let bar = |y: f32, from: f32, gray: u8| { + let r = egui::Rect::from_min_max(egui::pos2(from, y - 2.0), egui::pos2(rect.right() - 8.0, y + 2.0)); + p.rect_filled(r, 1.0, egui::Color32::from_gray(gray)); + }; + // Room for the character at its size (`previews::glyph` draws it at `chr`'s size). + let chr = wordcraft_doc::props::CharProps { size: Some(f.preview_pt() * scale), ..f.chr() }; + let glyph = f.preview_pt() * scale / 0.7; + for i in 0..7 { + let y = rect.top() + 5.0 + row * i as f32 + row / 2.0; + if !(2..5).contains(&i) { + bar(y, left, 205); + continue; + } + let x = match f.align.as_str() { + "center" => aligned_at - glyph / 2.0, + "right" => aligned_at - glyph, + _ => aligned_at, + }; + let r = egui::Rect::from_min_size(egui::pos2(x, y - glyph / 2.0), vec2(glyph, glyph)); + crate::previews::glyph(app, ui, r, &f.ch, &chr, egui::Color32::WHITE); + bar(y, text_at.max(r.right() + 2.0), 120); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use egui_kittest::kittest::Queryable; + use wordcraft_engine::Session; + + /// The interface fonts take effect from the frame after they're installed: the first frame + /// installs them and draws nothing. + fn fonts_ready(ui: &Ui) -> bool { + let id = egui::Id::unique("define_bullet_test_fonts"); + let ready = ui.ctx().data(|d| d.get_temp::(id)).unwrap_or(false); + if !ready { + crate::theme::install_fonts(ui.ctx()); + ui.ctx().data_mut(|d| d.insert_temp(id, true)); + } + ready + } + + fn app_with_bullet() -> WordApp { + let mut a = WordApp::new(Session::new(wordcraft_doc::Document::from_text("One\nTwo")), crate::Services::default()); + a.run("para.bullets", json!({"kind": "▪"})).unwrap(); + a + } + + fn level_at(app: &WordApp, i: usize) -> wordcraft_doc::numbering::Level { + let doc = &app.session.doc; + let n = doc.para_at(&wordcraft_doc::Pos::body(i, 0)).unwrap().props.numbering.unwrap(); + doc.numbering.level(n.num, n.level).unwrap().clone() + } + + /// The form starts from the caret's bullet; OK ends in `para.defineBullet` with the + /// character, its font and the alignment. + #[test] + fn ok_defines_the_bullet_the_form_shows() { + let app = app_with_bullet(); + let f = DefineBulletForm::new(&app); + let font = level_at(&app, 0).chr.font.unwrap_or_default(); + assert_eq!((f.ch.as_str(), f.font.as_str(), f.align.as_str()), ("▪", font.as_str(), "left")); + let mut h = egui_kittest::Harness::builder().with_size(vec2(500.0, 500.0)).build_ui_state( + |ui, (app, f): &mut (WordApp, DefineBulletForm)| { + if fonts_ready(ui) { + body(app, ui, f); + } + }, + (app, DefineBulletForm { font: "Segoe UI Symbol".into(), align: "right".into(), ..DefineBulletForm::plain("†") }), + ); + h.run_steps(2); + h.get_by_label("OK").click(); + h.run_steps(2); + let l = level_at(&h.state().0, 0); + assert_eq!((l.text.as_str(), l.chr.font.as_deref(), l.align), ("†", Some("Segoe UI Symbol"), Align::Right)); + } + + /// #2786 review: a size the command rejects (not a number, out of range) is an error OK + /// reports, keeping the dialog open and the list as it was; no size is the text's size. + #[test] + fn ok_with_a_bad_size_keeps_the_dialog_open() { + assert!(DefineBulletForm::plain("†").params().get("size").is_none(), "no size: the text's size"); + for bad in ["abc", "5000", "0"] { + let app = app_with_bullet(); + let before = level_at(&app, 0); + let form = DefineBulletForm { size: bad.into(), ..DefineBulletForm::plain("†") }; + let mut h = egui_kittest::Harness::builder().with_size(vec2(500.0, 500.0)).build_ui_state( + |ui, (app, f, closed): &mut (WordApp, DefineBulletForm, bool)| { + if fonts_ready(ui) && body(app, ui, f) { + *closed = true; + } + }, + (app, form, false), + ); + h.run_steps(2); + h.get_by_label("OK").click(); + h.run_steps(2); + assert!(!h.state().2, "{bad}: the dialog stays open"); + assert_eq!(level_at(&h.state().0, 0).text, before.text, "{bad}: the list is unchanged"); + } + } + + /// #2786 review: the preview draws the bullet at its own size, the text's when it has none, + /// within what the rows can show. + #[test] + fn the_preview_draws_the_bullets_size() { + let at = |size: &str| DefineBulletForm { size: size.into(), ..DefineBulletForm::plain("•") }.preview_pt(); + assert_eq!(at(""), 11.0); + assert_eq!(at("16"), 16.0); + assert!(at("8") < at("11") && at("11") < at("18")); + assert_eq!(at("72"), 20.0, "kept to the rows"); + assert_eq!(at("abc"), 11.0); + // The preview draws the character with these props: `previews::glyph` keeps their size. + let f = DefineBulletForm { size: "16".into(), ..DefineBulletForm::plain("•") }; + assert_eq!(f.chr().size, Some(16.0)); + } + + /// Symbol… hands the form to the Symbol dialog, whose OK brings it back with the character + /// picked there; Cancel brings it back unchanged. + #[test] + fn symbol_picks_the_character_and_returns() { + let form = DefineBulletForm { align: "center".into(), ..DefineBulletForm::plain("▪") }; + let mut h = egui_kittest::Harness::builder().with_size(vec2(500.0, 500.0)).build_ui_state( + |ui, (app, f): &mut (WordApp, DefineBulletForm)| { + if fonts_ready(ui) { + body(app, ui, f); + } + }, + (app_with_bullet(), form.clone()), + ); + h.run_steps(2); + h.get_by_label("Symbol…").click(); + h.run_steps(2); + let mut app = std::mem::replace(&mut h.state_mut().0, app_with_bullet()); + drop(h); + let Some(dialog) = app.dialog.take() else { panic!("the Symbol dialog is open") }; + // Picking the bullet, it blocks the window as Define New Bullet does (#3859). + assert!(dialog.is_modal(), "the bullet's Symbol dialog is modal"); + let Dialog::Insert(d) = dialog else { panic!("the Symbol dialog is open") }; + let InsertDialog::Symbol(mut sym) = *d else { panic!("the Symbol dialog is open") }; + assert_eq!(sym.bullet.as_deref().map(|b| b.align.as_str()), Some("center"), "it carries the form"); + sym.selected = Some('†'); + let mut h = egui_kittest::Harness::builder().with_size(vec2(700.0, 700.0)).build_ui_state( + |ui, (app, d): &mut (WordApp, InsertDialog)| { + if fonts_ready(ui) { + crate::dialogs_insert::body(app, ui, d); + } + }, + (app, InsertDialog::Symbol(sym)), + ); + h.run_steps(2); + h.get_by_label("OK").click(); + h.run_steps(2); + let back = match h.state_mut().0.dialog.take() { + Some(Dialog::Insert(d)) => match *d { + InsertDialog::DefineBullet(f) => f, + _ => panic!("back to Define New Bullet"), + }, + _ => panic!("back to Define New Bullet"), + }; + assert_eq!((back.ch.as_str(), back.align.as_str()), ("†", "center")); + // Nothing was inserted into the text. + assert_eq!(h.state().0.session.doc.para_at(&wordcraft_doc::Pos::body(0, 0)).unwrap().text, "One"); + } + + /// The Symbol dialog's title-bar close box goes back to Define New Bullet, as Cancel does. + #[test] + fn closing_the_symbol_dialog_returns_to_the_bullet() { + let mut app = app_with_bullet(); + let form = DefineBulletForm { align: "center".into(), ..DefineBulletForm::plain("▪") }; + let sym = SymbolForm::for_bullet(&app, form); + app.dialog = Some(Dialog::Insert(Box::new(InsertDialog::Symbol(sym)))); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1000.0, 800.0)).build_ui_state( + |ui, app: &mut WordApp| { + if fonts_ready(ui) { + let ctx = ui.ctx().clone(); + crate::dialogs::show(app, &ctx); + } + }, + app, + ); + h.run_steps(3); + h.get_by_label("Close").click(); + h.run_steps(3); + let back = match h.state_mut().dialog.take() { + Some(Dialog::Insert(d)) => match *d { + InsertDialog::DefineBullet(f) => f, + _ => panic!("back to Define New Bullet"), + }, + _ => panic!("back to Define New Bullet"), + }; + assert_eq!((back.ch.as_str(), back.align.as_str()), ("▪", "center")); + } +} diff --git a/crates/ui-egui/src/dialogs/dialogs_insert.rs b/crates/ui-egui/src/dialogs/dialogs_insert.rs index a175138238..aa574c9e23 100644 --- a/crates/ui-egui/src/dialogs/dialogs_insert.rs +++ b/crates/ui-egui/src/dialogs/dialogs_insert.rs @@ -38,6 +38,7 @@ pub enum InsertDialog { SmartArt(crate::dialogs_smart_art::SmartArtForm), ChartType(crate::dialogs_chart::ChartTypeForm), ChartData(crate::dialogs_chart::ChartDataForm), + DefineBullet(crate::dialogs_bullet::DefineBulletForm), DropCap(DropCapForm), } @@ -53,6 +54,7 @@ impl InsertDialog { InsertDialog::ChartType(f) if f.change => "changeChartType", InsertDialog::ChartType(_) => "insertChart", InsertDialog::ChartData(_) => "chartData", + InsertDialog::DefineBullet(_) => "defineBullet", InsertDialog::DropCap(_) => "dropCap", } } @@ -68,14 +70,16 @@ impl InsertDialog { InsertDialog::ChartType(f) if f.change => "Change Chart Type", InsertDialog::ChartType(_) => "Insert Chart", InsertDialog::ChartData(_) => "Edit Data", + InsertDialog::DefineBullet(_) => "Define New Bullet", InsertDialog::DropCap(_) => "Drop Cap", } } } /// The dialog `ui.dialog` opens by `name`: `columns`, `symbol`, `specialCharacters`, `field`, -/// `insertChart`, `changeChartType` or `chartData` (the last two for the selected chart), or -/// `insertSmartArt`, or `dropCap` (Drop Cap Options…, where the paragraph can take one). +/// `insertChart`, `changeChartType` or `chartData` (the last two for the selected chart), +/// `insertSmartArt`, `defineBullet` (Home › Bullets › Define New Bullet…), or `dropCap` (Drop Cap +/// Options…, where the paragraph can take one). pub fn open(name: &str, app: &WordApp) -> Option { Some(match name { "dateTime" => InsertDialog::DateTime(DateTimeForm::new(app)), @@ -87,6 +91,7 @@ pub fn open(name: &str, app: &WordApp) -> Option { "insertChart" => InsertDialog::ChartType(crate::dialogs_chart::ChartTypeForm::new(app, false)?), "changeChartType" => InsertDialog::ChartType(crate::dialogs_chart::ChartTypeForm::new(app, true)?), "chartData" => InsertDialog::ChartData(crate::dialogs_chart::ChartDataForm::new(app)?), + "defineBullet" => InsertDialog::DefineBullet(crate::dialogs_bullet::DefineBulletForm::new(app)), "dropCap" => InsertDialog::DropCap(DropCapForm::read(app)?), _ => return None, }) @@ -102,6 +107,7 @@ pub fn body(app: &mut WordApp, ui: &mut Ui, d: &mut InsertDialog) -> bool { InsertDialog::SmartArt(f) => crate::dialogs_smart_art::picker_ui(app, ui, f), InsertDialog::ChartType(f) => crate::dialogs_chart::type_ui(app, ui, f), InsertDialog::ChartData(f) => crate::dialogs_chart::data_ui(app, ui, f), + InsertDialog::DefineBullet(f) => crate::dialogs_bullet::body(app, ui, f), InsertDialog::DropCap(f) => drop_cap_ui(app, ui, f), } } diff --git a/crates/ui-egui/src/dialogs/dialogs_insert/symbol.rs b/crates/ui-egui/src/dialogs/dialogs_insert/symbol.rs index 797d6aef72..0905cd85c6 100644 --- a/crates/ui-egui/src/dialogs/dialogs_insert/symbol.rs +++ b/crates/ui-egui/src/dialogs/dialogs_insert/symbol.rs @@ -131,6 +131,10 @@ pub struct SymbolForm { /// Scroll the grid to this row on the next frame. #[serde(skip)] scroll_to: Option, + /// Picking a bullet for Define New Bullet (#2786): OK hands the character and its font back + /// to that dialog instead of inserting it, and Cancel goes back to it unchanged. + #[serde(skip)] + pub bullet: Option>, } /// Grid geometry. @@ -151,12 +155,45 @@ impl SymbolForm { let recent = app.ui.recent_symbols.first().cloned(); let font = recent.as_ref().map(|r| r.font.clone()).unwrap_or_default(); let selected = recent.and_then(|r| r.ch.chars().next()); - let mut f = - SymbolForm { tab, font, selected, code: String::new(), special: 0, text_font, chars: Vec::new(), chars_of: None, scroll_to: None }; + let mut f = SymbolForm { + tab, + font, + selected, + code: String::new(), + special: 0, + text_font, + chars: Vec::new(), + chars_of: None, + scroll_to: None, + bullet: None, + }; f.sync_code(); f } + /// The Symbol dialog picking `form`'s bullet: it opens on the bullet's font and character. + pub fn for_bullet(app: &WordApp, form: crate::dialogs_bullet::DefineBulletForm) -> SymbolForm { + let mut f = SymbolForm::new(app, 0); + f.font = form.font.clone(); + f.selected = form.ch.chars().next(); + f.load(); + f.sync_code(); + f.scroll_to = f.selected.and_then(|c| f.row_of(c)); + f.bullet = Some(Box::new(form)); + f + } + + /// Back to Define New Bullet, with `picked` (a character and its font) when one was chosen. + fn back_to_bullet(&mut self, app: &mut WordApp, picked: Option<(String, String)>) -> bool { + let Some(mut form) = self.bullet.take() else { return false }; + if let Some((ch, font)) = picked { + form.ch = ch; + form.font = font; + } + app.dialog = Some(crate::dialogs::Dialog::Insert(Box::new(super::InsertDialog::DefineBullet(*form)))); + true + } + /// The font the grid shows: the chosen one, or the text's. pub fn shown_font(&self) -> &str { if self.font.is_empty() { &self.text_font } else { &self.font } @@ -269,11 +306,16 @@ fn symbol_cell(app: &mut WordApp, ui: &mut Ui, font: &str, c: char, selected: bo pub(super) fn symbol_ui(app: &mut WordApp, ui: &mut Ui, f: &mut SymbolForm) -> bool { let t = Tokens::get(ui.ctx()); ui.set_width(GRID_COLS as f32 * CELL + 24.0); - let names = [tl!("Symbols").to_string(), tl!("Special Characters").to_string()]; - if let Some(k) = crate::widgets::dialog_tabs(ui, &names, f.tab as usize) { - f.tab = k as u8; + if f.bullet.is_some() { + // A bullet is one character in a font: the Special Characters tab has nothing for it. + f.tab = 0; + } else { + let names = [tl!("Symbols").to_string(), tl!("Special Characters").to_string()]; + if let Some(k) = crate::widgets::dialog_tabs(ui, &names, f.tab as usize) { + f.tab = k as u8; + } + ui.add_space(6.0); } - ui.add_space(6.0); let mut insert: Option<(Value, String, String)> = None; if f.tab == 1 { if special_ui(app, ui, f, &mut insert, &t) { @@ -326,8 +368,10 @@ pub(super) fn symbol_ui(app: &mut WordApp, ui: &mut Ui, f: &mut SymbolForm) -> b let rows = f.chars.len().div_ceil(GRID_COLS); let mut area = egui::ScrollArea::vertical().id_salt("symbol_grid").max_height(CELL * GRID_ROWS as f32).auto_shrink([false, false]); if let Some(row) = f.scroll_to.take() { - // Keep the row in view: it lands on the grid's second row when there is room. - area = area.vertical_scroll_offset(row.saturating_sub(1) as f32 * CELL); + // Keep the row in view: it lands on the grid's second row when there is room. Rows + // are `CELL` plus the item spacing apart (`show_rows` adds it between rows). + let pitch = CELL + ui.spacing().item_spacing.y; + area = area.vertical_scroll_offset(row.saturating_sub(1) as f32 * pitch); } let font = f.shown_font().to_string(); let chars = f.chars.clone(); @@ -398,15 +442,23 @@ pub(super) fn symbol_ui(app: &mut WordApp, ui: &mut Ui, f: &mut SymbolForm) -> b if double && let Some(p) = f.params() { insert = Some((p, f.selected.map(String::from).unwrap_or_default(), f.font.clone())); } - // The Insert button. - let (ok, close) = buttons(ui, "Insert", "Close", f.selected.is_some()); + // The Insert button (OK while picking a bullet). + let (ok_label, close_label) = if f.bullet.is_some() { ("OK", "Cancel") } else { ("Insert", "Close") }; + let (ok, close) = buttons(ui, ok_label, close_label, f.selected.is_some()); if ok && let Some(p) = f.params() { insert = Some((p, f.selected.map(String::from).unwrap_or_default(), f.font.clone())); } if close { + f.back_to_bullet(app, None); return true; } } + if f.bullet.is_some() + && let Some((_, ch, font)) = insert + { + remember_symbol(app, &ch, &font); + return f.back_to_bullet(app, Some((ch, font))); + } if let Some((params, ch, font)) = insert { // Special characters with their own command insert through it (non-breaking hyphen…). let r = match params.get("command").and_then(Value::as_str) { diff --git a/crates/ui-egui/src/dialogs/dispatch.rs b/crates/ui-egui/src/dialogs/dispatch.rs index 4d682cc315..18693522de 100644 --- a/crates/ui-egui/src/dialogs/dispatch.rs +++ b/crates/ui-egui/src/dialogs/dispatch.rs @@ -247,6 +247,9 @@ fn font_dialog(app: &mut WordApp, ui: &mut Ui, d: &mut Dialog) -> bool { font_sample_box(app, ui, sample_paper(app), &sample_props, (*sup, *sub), *hidden); }); let (ok, cancel) = buttons(ui, tl!("OK")); + if (ok || cancel) && super::font::hand_back_bullet(app, d, ok) { + return true; + } if ok { apply_font(app, d); } diff --git a/crates/ui-egui/src/dialogs/font.rs b/crates/ui-egui/src/dialogs/font.rs index 672829ab8b..eec09022ab 100644 --- a/crates/ui-egui/src/dialogs/font.rs +++ b/crates/ui-egui/src/dialogs/font.rs @@ -167,6 +167,48 @@ pub(super) fn east_asian_char(c: char) -> bool { matches!(u32::from(c), 0x1100..=0x11FF | 0x2E80..=0x9FFF | 0xA960..=0xA97F | 0xAC00..=0xD7FF | 0xF900..=0xFAFF | 0xFE30..=0xFE4F | 0xFF00..=0xFFEF | 0x20000..=0x3FFFF) } +/// The Font dialog formatting Define New Bullet's bullet (#2786): it opens on the bullet's font, +/// size, bold, italic and colour, and carries the form back (see `Dialog::Font::bullet`). +pub fn font_for_bullet(app: &mut WordApp, form: crate::dialogs_bullet::DefineBulletForm) -> Option { + let mut d = Dialog::open("font", app)?; + if let Dialog::Font { font, font_was, size, bold, italic, color, .. } = &mut d { + if !form.font.is_empty() { + *font = app.previews.font_shown(&form.font); + *font_was = font.clone(); + } + *size = form.size.clone(); + *bold = form.bold; + *italic = form.italic; + *color = form.color.clone(); + } + let props = font_props(&d); + if let Dialog::Font { start, bullet, .. } = &mut d { + *start = props; + *bullet = Some(Box::new(form)); + } + Some(d) +} + +/// The Font dialog's OK or Cancel while it formats Define New Bullet's bullet (#2786): back to +/// that dialog, with the font (its stored English name, and only when the user changed it, so a +/// bullet in the text's font keeps following the text), size, bold, italic and colour on OK. +/// False when the dialog isn't formatting a bullet. +pub(super) fn hand_back_bullet(app: &mut WordApp, d: &mut Dialog, ok: bool) -> bool { + let Dialog::Font { bullet, font, font_was, size, bold, italic, color, .. } = d else { return false }; + let Some(mut form) = bullet.take() else { return false }; + if ok { + if font.trim() != font_was.trim() { + form.font = app.previews.font_stored(font.trim()); + } + form.size = size.trim().to_string(); + form.bold = *bold; + form.italic = *italic; + form.color = color.clone(); + } + app.dialog = Some(Dialog::Insert(Box::new(crate::dialogs_insert::InsertDialog::DefineBullet(*form)))); + true +} + /// The Font dialog's OK: one formatting step that sets only the properties the user changed, so /// formatting the dialog can't show or left alone stays as it is. Fonts are set by their stored /// (English) names, the Latin font for Persian/Arabic text too (as `format.font`). diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index c3e9d99258..a1ea146d36 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -895,6 +895,88 @@ fn modify_style_font_box_finds_the_family() { assert_eq!(rc.font, wordcraft_doc::styles::HEADING_FONT); } +/// #2786: Define New Bullet's Font… is this Font dialog, opened on the bullet's formatting. OK +/// hands the font, size and bold back to Define New Bullet without formatting the text; +/// Cancel, and the title bar's close box, go back with the form as it was. +#[test] +fn font_dialog_formats_a_bullet_and_hands_it_back() { + use crate::dialogs_bullet::DefineBulletForm; + use crate::dialogs_insert::InsertDialog; + use egui_kittest::kittest::Queryable; + let back = |button: &str| -> (DefineBulletForm, wordcraft_doc::props::CharProps) { + let mut app = app_with("Example"); + let _ = app.run("para.bullets", json!({"kind": "▪"})); + let form = DefineBulletForm { font: "Arial".into(), ..DefineBulletForm::plain("▪") }; + app.dialog = font_for_bullet(&mut app, form); + let Some(Dialog::Font { size, bold, bullet, .. }) = &mut app.dialog else { panic!("the Font dialog is open") }; + assert!(bullet.is_some(), "it carries the form"); + assert!(!*bold && size.is_empty(), "it shows the bullet's formatting, not the text's"); + *size = "16".into(); + *bold = true; + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state( + move |ui, app: &mut WordApp| { + let ctx = ui.ctx().clone(); + if fonts { + show(app, &ctx); + } else { + crate::theme::install_fonts_for(&ctx, false); + fonts = true; + } + }, + app, + ); + h.run_steps(3); + h.get_by_label(button).click(); + h.run_steps(3); + let app = h.state_mut(); + let Some(Dialog::Insert(d)) = app.dialog.take() else { panic!("back to Define New Bullet") }; + let InsertDialog::DefineBullet(f) = *d else { panic!("back to Define New Bullet") }; + let text = app.session.doc.para_at(&wordcraft_doc::Pos::body(0, 0)).map(|p| p.props_of_char(0).clone()).unwrap_or_default(); + (f, text) + }; + let (f, text) = back("OK"); + assert_eq!((f.ch.as_str(), f.font.as_str(), f.size.as_str(), f.bold), ("▪", "Arial", "16", true)); + assert_ne!(text.bold, Some(true), "the text isn't formatted"); + assert_ne!(text.size, Some(16.0), "the text isn't formatted"); + for button in ["Cancel", "Close"] { + let (f, _) = back(button); + assert_eq!((f.font.as_str(), f.size.as_str(), f.bold), ("Arial", "", false), "{button} keeps the form"); + } + // A bullet in the text's font (no font of its own) keeps it when OK doesn't change the + // font box, though the box shows the text's font (review of #2860). + let mut app = app_with("Example"); + let _ = app.run("para.bullets", json!({"kind": "▪"})); + let Some(mut d) = font_for_bullet(&mut app, DefineBulletForm::plain("▪")) else { panic!("the Font dialog opens") }; + if let Dialog::Font { font, .. } = &d { + assert!(!font.is_empty(), "the box shows the text's font"); + } + if let Dialog::Font { bullet: Some(b), font, font_was, .. } = &mut d { + assert_eq!(font, font_was); + assert!(b.font.is_empty()); + } + app.dialog = Some(d); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state( + move |ui, app: &mut WordApp| { + let ctx = ui.ctx().clone(); + if fonts { + show(app, &ctx); + } else { + crate::theme::install_fonts_for(&ctx, false); + fonts = true; + } + }, + app, + ); + h.run_steps(3); + h.get_by_label("OK").click(); + h.run_steps(3); + let Some(Dialog::Insert(d)) = h.state_mut().dialog.take() else { panic!("back to Define New Bullet") }; + let InsertDialog::DefineBullet(f) = *d else { panic!("back to Define New Bullet") }; + assert_eq!(f.font, "", "still the text's font"); +} + /// A dialog was pinned by its anchor, so dragging its title bar did nothing (#732). #[test] fn dragging_a_dialog_title_bar_moves_it() { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 357f141b9f..09dc4d7c13 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -91,6 +91,7 @@ use serde_json::{Value, json}; use wordcraft_engine::Session; pub use control::ControlRequest; +pub use dialogs::dialogs_bullet; pub use dialogs::dialogs_chart; pub use dialogs::dialogs_controls; pub use dialogs::dialogs_insert; diff --git a/crates/ui-egui/src/previews.rs b/crates/ui-egui/src/previews.rs index e618034cf8..6af6d6a212 100644 --- a/crates/ui-egui/src/previews.rs +++ b/crates/ui-egui/src/previews.rs @@ -556,6 +556,32 @@ fn snippet_blocks(base: &Document, blocks: Vec, options: SnippetOptions) Some(egui::ColorImage::from_rgba_unmultiplied([img.width as usize, img.height as usize], &px)) } +/// One character formatted by `chr` (at its size, or fitted to `r` without one), centred in `r` +/// and drawn with `tint`: +/// laid out like document text, so symbol fonts show what the page will (Define New Bullet, #2786). +pub fn glyph(app: &mut WordApp, ui: &mut Ui, r: Rect, ch: &str, chr: &CharProps, tint: egui::Color32) { + let ppp = ui.ctx().pixels_per_point(); + let key = format!("glyph:{ch}:{chr:?}:{ppp}:{}x{}", r.width(), r.height()); + let tex = app.previews.get_or(ui.ctx(), &key, || { + let chr = CharProps { size: Some(chr.size.unwrap_or(r.height() * 0.7)), ..chr.clone() }; + let mut p = Paragraph::with_text(ch, chr); + p.props.align = Some(wordcraft_doc::props::Align::Center); + p.props.space_before = Some(0.0); + p.props.space_after = Some(0.0); + snippet_blocks( + &Document::new(), + vec![Block::Para(p)], + SnippetOptions { width: r.width(), height: r.height(), pixels_per_point: ppp, margin: 0.0, paper: None, dark: false }, + ) + }); + if let Some(hd) = tex { + let sz = hd.size_vec2() / ppp; + let ir = Rect::from_min_size(r.min, sz.min(r.size())); + let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2((ir.width() / sz.x).min(1.0), (ir.height() / sz.y).min(1.0))); + ui.painter().with_clip_rect(r).image(hd.id(), ir, uv, tint); + } +} + /// Manage Styles' preview of one style (`ty`: the `styles.manage` type), `size` points wide and /// tall: a line of sample text, or a small table for a table style. pub fn style_preview(app: &mut WordApp, ui: &mut Ui, id: &str, ty: &str, size: egui::Vec2) { diff --git a/crates/ui-egui/src/ribbon/home.rs b/crates/ui-egui/src/ribbon/home.rs index 54581154d5..5cb359457e 100644 --- a/crates/ui-egui/src/ribbon/home.rs +++ b/crates/ui-egui/src/ribbon/home.rs @@ -26,6 +26,23 @@ pub(super) fn painter_double_click(app: &mut WordApp) { let _ = app.run("edit.formatPainter", json!({"sticky": true})); } +/// Change List Level › and Define New Bullet… at the foot of the Bullets drop-down (#2786). +/// Change List Level is for a paragraph in a list of its own numbering, the one `para.listLevel` +/// changes (a style's numbering it leaves alone). +fn bullet_list_items(ui: &mut Ui, app: &mut WordApp) { + ui.separator(); + let in_list = app.session.doc.para_at(&app.session.sel.focus).and_then(|p| p.props.numbering).is_some_and(|n| n.num != 0); + ui.add_enabled_ui(in_list, |ui| { + ui.menu_button(tl!("Change List Level"), |ui| { + for level in 0..9u8 { + let label = format!("{} {}", tl!("Level"), level + 1); + mi_text(ui, app, &label, "para.listLevel", json!({"level": level})); + } + }); + }); + mi(ui, app, "Define New Bullet…", "ui.dialog", json!({"name": "defineBullet"})); +} + pub(super) fn home(app: &mut WordApp, ui: &mut Ui) { let st = app.session.run("format.state", &json!({})).unwrap_or_default(); let flag = |k: &str| st.get(k).and_then(Value::as_bool).unwrap_or(false); @@ -196,6 +213,7 @@ pub(super) fn home(app: &mut WordApp, ui: &mut Ui) { } }); mi(ui, app, "None", "para.bullets", json!({"off": true})); + bullet_list_items(ui, app); }); split( ui,