diff --git a/ROADMAP.md b/ROADMAP.md index f223e06cce..45e01b2860 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -191,6 +191,7 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target | 2026-10-17 | File › Print's Scale to paper size (#2108): pick Letter, Legal, A4 or any Layout › Size paper and every page is scaled to it and centred, the paper turned to each page's orientation, in the preview, the print job (with the spooler's media) and Save these pages as PDF; the document keeps its page size. `paper` param on `ui.print`/`file.printPdf` | | 2026-10-17 | Non-overlapping body floating tables clear header tables. Original native controls distinguish never-overlap from allowed overlap. | |---|---| +| 2026-10-18 | Picture Format › Size (#2573): width and height in the interface unit, and a size typed in any unit works, pixels too (`300 px` keeps the picture's proportions, #1901), applied once typed (Enter, Tab or a click elsewhere; Esc cancels) in one undo step. The group's launcher opens a Size dialog: height and width, scale of the original size (or of the size it opened with), Lock aspect ratio, the original size with its pixels, and Reset. `picture.size {"original": true, "scale"?}` sizes from the original; sizes past 4000 pt that keep the proportions shrink as a whole. | | 2026-10-16 | Save Changes gives assistive technology a named alert dialog with the loss warning and any save failure; visual layout and save policy unchanged (#1015). Native screen-reader verification remains pending. | | 2026-10-15 | The font family caches are bounded (4096 families for text, 1024 for math, names over 256 bytes aren't remembered), so a document naming thousands of missing fonts can't grow memory; equation fonts are looked up again after a font is added or removed instead of keeping the old choice (#1354) | | 2026-10-15 | AutoCorrect recognizes `-->` as `→` (#2223), respecting replacement settings and undo without changing paragraph-start arrow bullets. | @@ -500,6 +501,7 @@ Footer page-table height and body wrapping are corrected. Other pagination gaps | 2026-10-17 | trivial | Progress log: recipient list search and merged-only view (#1576) | | 2026-10-18 | trivial | Progress log: symbols keep their font when the text font changes (#2036) | | 2026-10-17 | trivial | Progress log: Restrict Editing guards tables, Paste Formatting and merge fields (#1327) | +| 2026-10-18 | trivial | Progress log: Picture Format › Size, sizes typed in any unit and the Size dialog (#2573); readiness estimates unchanged | | 2026-10-14 | trivial | Progress log: a list item's first word is not flagged for a missing capital (#1741) | | 2026-10-18 | trivial | #2445: pending Save As answers keep their originating document identity, so a replacement document is never written to an old picker destination; real Save-button and focused-editor shortcut controls verified | | 2026-10-16 | trivial | #2445: interactive Save on import-only .doc/.dot paths uses the existing DOCX Save As flow; cancel and failed writes keep the draft, and Close waits for a successful save. Explicit/script saves still report unsupported legacy output | diff --git a/contributors/people.toml b/contributors/people.toml index 82cfc86ea3..f46de495e9 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -154,3 +154,6 @@ sync_github_name = true [people.C00kieMonsta] real_name = "Antoine Boxho" sync_github_name = true + +[people.matteo-andreuzza] +sync_github_name = true diff --git a/crates/engine/src/cmd/objects.rs b/crates/engine/src/cmd/objects.rs index 64eb6486d3..a750f67d22 100644 --- a/crates/engine/src/cmd/objects.rs +++ b/crates/engine/src/cmd/objects.rs @@ -91,7 +91,11 @@ fn has_shape(s: &Session) -> Option<&'static str> { pub fn specs() -> Vec { vec![ - CommandSpec::new("picture.size", "Size", "Picture Format › Size", size).params(r#"{"width"?: pt, "height"?: pt, "lockAspect"?: bool, "scale"?: percent}"#).when(has_sizable), + CommandSpec::new("picture.size", "Size", "Picture Format › Size", size) + .params( + r#"{"width"?: pt, "height"?: pt, "lockAspect"?: bool, "scale"?: percent, "original"?: bool} (scale: of the current size, or with original of the picture's original size, its pixels at 96 ppi less what is cropped; original alone restores that size; one side alone keeps the proportions unless lockAspect is false; 1–4000 pt: when the proportions are kept, a side past 4000 pt shrinks the other with it)"#, + ) + .when(has_sizable), CommandSpec::new("picture.crop", "Crop", "Picture Format › Size", crop) .params( r#"{"left"?, "top"?, "right"?, "bottom"? (fractions of the source 0–0.45; a side left out is uncropped), "width"?: pt, "height"?: pt (the new display size, in the same undo step; a floating picture also moves by what a left/top crop trims, so the visible part stays put)}"#, @@ -1002,35 +1006,83 @@ fn crop(s: &mut Session, v: &Value) -> CmdResult { }) } +/// A picture's original size: its image's pixels at 96 ppi (the size Insert › Pictures gives it) +/// or a metafile's own frame, before any crop. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct OriginalSize { + /// Points. + pub w: f32, + pub h: f32, + /// A bitmap's pixels (None for a metafile). + pub pixels: Option<(u32, u32)>, +} + +/// The original size of the picture showing `media`, read from the image its Picture Format +/// adjustments started from (Compress Pictures may have resampled the current one); None when the +/// image can't be read. +pub fn original_size(s: &Session, media: &str) -> Option { + let key = s.originals.get(media).map_or(media, String::as_str); + let bytes = s.doc.media.get(key).or_else(|| s.doc.media.get(media))?; + if let Some((pw, ph)) = wordcraft_render::image_size(bytes) { + return Some(OriginalSize { w: pw as f32 * 0.75, h: ph as f32 * 0.75, pixels: Some((pw, ph)) }); + } + let (w, h, _) = wordcraft_render::metafile_size(bytes)?; + Some(OriginalSize { w, h, pixels: None }) +} + +/// What a picture's crop leaves of its original size: the size Reset gives back and what a scale +/// of the original counts from. None for anything but a picture whose image can be read. +pub fn cropped_original_size(s: &Session, o: &InlineObject) -> Option<(f32, f32)> { + let InlineObject::Image { media, crop, .. } = o else { return None }; + let orig = original_size(s, media)?; + let part = |lo: f32, hi: f32| (1.0 - lo - hi).max(0.1); + Some((orig.w * part(crop[0], crop[2]), orig.h * part(crop[1], crop[3]))) +} + +/// Size: `scale` is a percentage of the current size, or with `original` of what the crop leaves +/// of the original size (`original` alone gives that back: the Size dialog's Reset); then `width` +/// and `height`, where one alone keeps the proportions unless `lockAspect` is false. fn size(s: &mut Session, v: &Value) -> CmdResult { let (_, o) = selected(s).ok_or_else(|| CmdError::Disabled("no object".into()))?; - let (w0, h0) = obj_size(&o); let lock = p::bool(v, "lockAspect").unwrap_or(true); - let (mut w, mut h) = (w0, h0); - if let Some(sc) = p::f32(v, "scale") { + let (mut w, mut h) = obj_size(&o); + let scale = p::f32(v, "scale"); + if p::bool(v, "original").unwrap_or(false) { + let (ow, oh) = + cropped_original_size(s, &o).ok_or_else(|| CmdError::Disabled("only a picture whose image can be read has an original size".into()))?; + let k = scale.unwrap_or(100.0) / 100.0; + (w, h) = (ow * k, oh * k); + } else if let Some(sc) = scale { w *= sc / 100.0; h *= sc / 100.0; } - match (p::f32(v, "width"), p::f32(v, "height")) { + let (nw, nh) = (p::f32(v, "width"), p::f32(v, "height")); + match (nw, nh) { (Some(nw), Some(nh)) => { w = nw; h = nh; } (Some(nw), None) => { - if lock && w0 > 0.0 { - h = h0 * nw / w0; + if lock && w > 0.0 { + h *= nw / w; } w = nw; } (None, Some(nh)) => { - if lock && h0 > 0.0 { - w = w0 * nh / h0; + if lock && h > 0.0 { + w *= nh / h; } h = nh; } _ => {} } - let (w, h) = (w.clamp(1.0, 4000.0), h.clamp(1.0, 4000.0)); + // A size that keeps the proportions shrinks on both sides to fit, rather than flattening. + let keep = match (nw, nh) { + (Some(_), Some(_)) => false, + (None, None) => true, + _ => lock, + }; + let (w, h) = fit_size(w, h, keep); // Any drawing: a group's members scale with its frame (its child space is kept); a chart or // SmartArt graphic lays itself out again at the new size. let theme = s.doc.settings.theme_colors.clone(); @@ -1041,6 +1093,27 @@ fn size(s: &mut Session, v: &Value) -> CmdResult { }) } +/// An object size within 1–4000 pt. With `keep`, both sides scale by one factor, the one nearest +/// 1 that brings them within the limits, so the proportions hold; a shape too long and thin for any +/// such factor is clamped side by side. +pub fn fit_size(w: f32, h: f32, keep: bool) -> (f32, f32) { + let side = |x: f32| if x.is_nan() { 1.0 } else { x.clamp(1.0, 4000.0) }; + if keep && w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0 { + let (lo, hi) = ((1.0 / w).max(1.0 / h), (4000.0 / w).min(4000.0 / h)); + if lo <= hi { + let k = if lo > 1.0 { + lo + } else if hi < 1.0 { + hi + } else { + 1.0 + }; + return (side(w * k), side(h * k)); + } + } + (side(w), side(h)) +} + /// Apply an image operation to the selected picture's bitmap (stored as a new PNG). fn adjust(s: &mut Session, f: impl Fn(image::DynamicImage) -> image::DynamicImage) -> CmdResult { let (_, o) = selected(s).ok_or_else(|| CmdError::Disabled("no picture".into()))?; @@ -2124,6 +2197,67 @@ mod tests { assert_eq!(crop, [0.1, 0.2, 0.05, 0.0]); } + /// #2573: Size from the original. `original` alone gives the picture back its original size + /// (its pixels at 96 ppi, less what is cropped) and `scale` is a percentage of it; Compress + /// Pictures doesn't change what the original is. Only a picture has one. + #[test] + fn picture_size_counts_from_the_original() { + let mut s = Session::new(wordcraft_doc::Document::new()); + let data = super::super::insert::base64_encode(&png(40, 20)); + s.run("insert.picture", &json!({"data": data})).unwrap(); + let size = |s: &Session| obj_size(&selected(s).unwrap().1); + assert_eq!(size(&s), (30.0, 15.0), "40×20 px at 96 ppi"); + s.run("picture.size", &json!({"width": 300.0, "height": 100.0, "lockAspect": false})).unwrap(); + s.run("picture.compress", &json!({"maxPixels": 32})).unwrap(); + let Some((_, InlineObject::Image { media, .. })) = selected(&s) else { panic!("a picture") }; + assert_eq!(wordcraft_render::image_size(&s.doc.media[&media]), Some((32, 16)), "compressed"); + assert_eq!(original_size(&s, &media), Some(OriginalSize { w: 30.0, h: 15.0, pixels: Some((40, 20)) })); + s.run("picture.size", &json!({"original": true})).unwrap(); + assert_eq!(size(&s), (30.0, 15.0)); + s.run("picture.size", &json!({"original": true, "scale": 250})).unwrap(); + assert_eq!(size(&s), (75.0, 37.5)); + // Half the width cropped away: half the original width is left. + s.run("picture.crop", &json!({"left": 0.25, "right": 0.25})).unwrap(); + s.run("picture.size", &json!({"original": true})).unwrap(); + assert_eq!(size(&s), (15.0, 15.0)); + s.run("edit.undo", &json!({})).unwrap(); + assert_eq!(size(&s), (75.0, 37.5), "one undo step"); + s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap(); + assert!(s.run("picture.size", &json!({"original": true})).is_err(), "a shape has no original size"); + } + + /// #2573: a size past 4000 pt (or under 1 pt) that keeps the proportions scales as a whole + /// instead of flattening against the limit; both sides given are clamped each on its own. + #[test] + fn picture_size_past_the_limit_keeps_the_proportions() { + let mut s = Session::new(wordcraft_doc::Document::new()); + let data = super::super::insert::base64_encode(&png(40, 20)); + s.run("insert.picture", &json!({"data": data})).unwrap(); + let size = |s: &Session| obj_size(&selected(s).unwrap().1); + s.run("picture.size", &json!({"width": 9000.0})).unwrap(); + assert_eq!(size(&s), (4000.0, 2000.0)); + s.run("picture.size", &json!({"scale": 1000})).unwrap(); + assert_eq!(size(&s), (4000.0, 2000.0)); + s.run("picture.size", &json!({"width": 9000.0, "height": 10.0})).unwrap(); + assert_eq!(size(&s), (4000.0, 10.0)); + s.run("picture.size", &json!({"height": 30.0, "lockAspect": false})).unwrap(); + assert_eq!(size(&s), (4000.0, 30.0)); + // Below 1 pt as well: a 1% scale of 50×200 pt is 1×4 pt, not 1×2. + s.run("picture.size", &json!({"width": 50.0, "height": 200.0})).unwrap(); + s.run("picture.size", &json!({"scale": 1})).unwrap(); + assert_eq!(size(&s), (1.0, 4.0)); + // Too long and thin for one factor: side by side. NaN and infinity stay in range. + assert_eq!(fit_size(0.5, 5000.0, true), (1.0, 4000.0)); + assert_eq!(fit_size(f32::NAN, 10.0, true), (1.0, 10.0)); + assert_eq!(fit_size(f32::INFINITY, 10.0, true), (4000.0, 10.0)); + // Hostile values never leave the 1–4000 pt range. + for v in [json!({"scale": -50}), json!({"width": -1.0}), json!({"original": "yes", "scale": 1e30}), json!({"height": 1e30})] { + s.run("picture.size", &v).unwrap(); + let (w, h) = size(&s); + assert!((1.0..=4000.0).contains(&w) && (1.0..=4000.0).contains(&h), "{v}: {w}×{h}"); + } + } + /// A crop handle drop: `picture.crop` with the new size is one edit, one undo step. #[test] fn picture_crop_with_size_is_one_undo_step() { diff --git a/crates/ui-egui/src/dialogs_layout.rs b/crates/ui-egui/src/dialogs_layout.rs index 365fde41b9..7b4049badb 100644 --- a/crates/ui-egui/src/dialogs_layout.rs +++ b/crates/ui-egui/src/dialogs_layout.rs @@ -1,12 +1,12 @@ //! Layout, Review and Mailings dialogs (#407): Line Numbers (Layout › Line Numbers › Line //! Numbering Options…), Hyphenation (Hyphenation Options… and Manual…), Language (Review › //! Language), Envelopes and Labels (Mailings › Create), Formula (Table Layout › Data, #1201) -//! Sort (Table Layout › Data, #1200), Split Cells (Table Layout › Merge) and Convert Text to Table -//! (Insert › Table, #2592). Each ends by running a command (`layout.lineNumbers`, -//! `layout.hyphenation`, `layout.manualHyphenation` with `caret.set` and `text.optionalHyphen`, -//! `review.language`, `mailings.envelopes`, `mailings.labels`, `table.formula`, `table.sort`, -//! `table.split`, `table.fromText`), so -//! scripts and agents get the same result without the dialog. Shown through +//! Sort (Table Layout › Data, #1200), Split Cells (Table Layout › Merge), Convert Text to Table +//! (Insert › Table, #2592) and Size (Picture Format › Size, #2573). Each ends by running a +//! command (`layout.lineNumbers`, `layout.hyphenation`, `layout.manualHyphenation` with +//! `caret.set` and `text.optionalHyphen`, `review.language`, `mailings.envelopes`, +//! `mailings.labels`, `table.formula`, `table.sort`, `table.split`, `table.fromText`, +//! `picture.size`), so scripts and agents get the same result without the dialog. Shown through //! [`crate::dialogs::Dialog::Layout`]. use egui::{Ui, vec2}; @@ -15,6 +15,7 @@ use serde_json::{Value, json}; use wordcraft_doc::section::LineNumberRestart; use wordcraft_engine::cmd::mailings::{ENVELOPE_SIZES, LABEL_PRODUCTS}; +use wordcraft_engine::cmd::objects::fit_size; use crate::WordApp; use crate::options::MeasureExt; @@ -33,6 +34,7 @@ pub enum LayoutDialog { Sort(SortForm), SplitCells(SplitCellsForm), TextToTable(TextToTableForm), + Size(SizeForm), } impl LayoutDialog { @@ -48,6 +50,7 @@ impl LayoutDialog { LayoutDialog::Sort(_) => "tableSort", LayoutDialog::SplitCells(_) => "splitCells", LayoutDialog::TextToTable(_) => "textToTable", + LayoutDialog::Size(_) => "pictureSize", } } @@ -64,6 +67,7 @@ impl LayoutDialog { LayoutDialog::Sort(_) => "Sort", LayoutDialog::SplitCells(_) => "Split Cells", LayoutDialog::TextToTable(_) => "Convert Text to Table", + LayoutDialog::Size(_) => "Size", } } } @@ -81,6 +85,7 @@ pub fn open(name: &str, app: &mut WordApp) -> Option { "tableSort" => LayoutDialog::Sort(SortForm::read(app)?), "splitCells" => LayoutDialog::SplitCells(SplitCellsForm::read(app)?), "textToTable" => LayoutDialog::TextToTable(TextToTableForm::read(app)?), + "pictureSize" => LayoutDialog::Size(SizeForm::read(app)?), _ => return None, }) } @@ -98,6 +103,7 @@ pub fn body(app: &mut WordApp, ui: &mut Ui, d: &mut LayoutDialog) -> bool { LayoutDialog::Sort(f) => sort_ui(app, ui, f), LayoutDialog::SplitCells(f) => split_cells_ui(app, ui, f), LayoutDialog::TextToTable(f) => text_to_table_ui(app, ui, f), + LayoutDialog::Size(f) => size_ui(app, ui, f), } } @@ -1095,6 +1101,216 @@ fn text_to_table_ui(app: &mut WordApp, ui: &mut Ui, f: &mut TextToTableForm) -> cancel } +// --------------------------------------------------------------------------------------------- +// Size + +/// The Size dialog's fields (Picture Format › Size launcher, #2573) for the selected picture or +/// shape. Lengths are in points; the fields show them in the interface unit. +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SizeForm { + /// Where the object sized is (the selected one when the dialog opened). + pub at: wordcraft_doc::Pos, + pub width: f32, + pub height: f32, + /// Changing one side changes the other in proportion (on for pictures, as in Word). + pub lock: bool, + /// The scale counts from the original size; otherwise from the size the dialog opened with. + pub relative: bool, + /// The size the dialog opened with. + pub start: (f32, f32), + /// What the crop leaves of the picture's original size: Reset's size. None for a shape, or a + /// picture whose image can't be read. + pub original: Option<(f32, f32)>, + /// The original size before the crop, and a bitmap's pixels, as shown. + pub uncropped: Option<(f32, f32)>, + pub pixels: Option<(u32, u32)>, + /// What the form was read from (see [`seen`]). + #[serde(skip)] + seen: Seen, +} + +/// An object's picture, crop and size, bit for bit: what [`SizeForm::follow`] compares. +type Seen = (String, [u32; 4], [u32; 2]); + +fn seen(o: &wordcraft_doc::para::InlineObject) -> Seen { + let (w, h) = o.frame().map_or((0.0, 0.0), |(w, h, _)| (w, h)); + match o { + wordcraft_doc::para::InlineObject::Image { media, crop, .. } => (media.clone(), crop.map(f32::to_bits), [w.to_bits(), h.to_bits()]), + _ => (String::new(), [0; 4], [w.to_bits(), h.to_bits()]), + } +} + +impl SizeForm { + /// The selected picture's or shape's size; None when nothing that has one is selected. + pub fn read(app: &WordApp) -> Option { + use wordcraft_doc::para::InlineObject; + let (at, o) = wordcraft_engine::cmd::objects::selected(&app.session)?; + let (w, h, _) = o.frame()?; + let full = match &o { + InlineObject::Image { media, .. } => wordcraft_engine::cmd::objects::original_size(&app.session, media), + _ => None, + }; + let original = wordcraft_engine::cmd::objects::cropped_original_size(&app.session, &o); + Some(SizeForm { + at, + width: w, + height: h, + lock: matches!(o, InlineObject::Image { .. }), + relative: original.is_some(), + start: (w, h), + original, + uncropped: full.map(|f| (f.w, f.h)), + pixels: full.and_then(|f| f.pixels), + seen: seen(&o), + }) + } + + /// Follow the selection: dialogs aren't modal, so a click on the page may pick another object, + /// and the ribbon or the handles may crop, change or resize this one. The form then starts over + /// on what is selected, or there is nothing to size (false: close the dialog). OK and Reset + /// never work from numbers read from another object or an older state of this one. + pub fn follow(&mut self, app: &WordApp) -> bool { + match wordcraft_engine::cmd::objects::selected(&app.session) { + Some((at, o)) if at == self.at && seen(&o) == self.seen => true, + Some(_) => SizeForm::read(app).map(|f| *self = f).is_some(), + None => false, + } + } + + /// What the scale counts from. + fn base(&self) -> (f32, f32) { + match self.original { + Some(o) if self.relative => o, + _ => self.start, + } + } + + /// The width and height as percentages of [`Self::base`]. + pub fn scale(&self) -> (f32, f32) { + let (bw, bh) = self.base(); + (self.width / bw.max(0.01) * 100.0, self.height / bh.max(0.01) * 100.0) + } + + /// A new width; locked, the height follows in proportion, both kept within 1–4000 pt by one + /// factor (as `picture.size` does), so the limit never changes the shape. + pub fn set_width(&mut self, w: f32) { + if self.lock && self.width > 0.0 { + (self.width, self.height) = fit_size(w, self.height * w / self.width, true); + } else { + self.width = fit_size(w, self.height, false).0; + } + } + + /// A new height; locked, the width follows (see [`Self::set_width`]). + pub fn set_height(&mut self, h: f32) { + if self.lock && self.height > 0.0 { + (self.width, self.height) = fit_size(self.width * h / self.height, h, true); + } else { + self.height = fit_size(self.width, h, false).1; + } + } + + /// The width as a percentage of [`Self::base`]. + pub fn set_scale_width(&mut self, percent: f32) { + self.set_width(self.base().0 * percent / 100.0); + } + + /// The height as a percentage of [`Self::base`]. + pub fn set_scale_height(&mut self, percent: f32) { + self.set_height(self.base().1 * percent / 100.0); + } + + /// Reset: the picture's original size, less what is cropped; one past 4000 pt (a large photo) + /// shrinks as a whole. + pub fn reset(&mut self) { + if let Some((w, h)) = self.original { + (self.width, self.height) = fit_size(w, h, true); + } + } + + /// `picture.size` parameters: both sides, as set here. + pub fn params(&self) -> Value { + json!({"width": self.width, "height": self.height, "lockAspect": false}) + } +} + +/// The Size dialog; returns true to close it. +fn size_ui(app: &mut WordApp, ui: &mut Ui, f: &mut SizeForm) -> bool { + if !f.follow(app) { + return true; + } + let unit = unit(); + let k = unit.pt_per_unit(); + // A length in the interface unit that takes any typed unit (`300 px` too), applied once typed + // (Enter, Tab or a click elsewhere, OK included) so a half-typed number never resizes the other + // side; `None` until its value changes (while + // typing, the field reports each keystroke as a change). The range bounds what is typed or + // dragged only: a value already outside it (a 1 px picture is 0.75 pt) is shown as it is, not + // clamped, which egui would report as a change and so apply unasked. + let length = |ui: &mut Ui, label: &str, pt: f32| { + let name = ui.label(tl!(label)); + let was = pt / k; + let mut v = was; + let field = + egui::DragValue::new(&mut v).speed(1.0 / k).range(1.0 / k..=4000.0 / k).clamp_existing_to_range(false).measure(unit).max_decimals(2); + let changed = ui.add(field.update_while_editing(false)).labelled_by(name.id).changed(); + (changed && v != was).then_some(v * k) + }; + let percent = |ui: &mut Ui, label: &str, was: f32| { + let name = ui.label(tl!(label)); + let mut v = was; + let field = egui::DragValue::new(&mut v).speed(1.0).range(1.0..=10_000.0).clamp_existing_to_range(false).suffix(" %").max_decimals(1); + let changed = ui.add(field.update_while_editing(false)).labelled_by(name.id).changed(); + (changed && v != was).then_some(v) + }; + heading(ui, "Size"); + egui::Grid::new("size_lengths").num_columns(4).spacing(vec2(10.0, 6.0)).show(ui, |ui| { + if let Some(h) = length(ui, "Height:", f.height) { + f.set_height(h); + } + if let Some(w) = length(ui, "Width:", f.width) { + f.set_width(w); + } + ui.end_row(); + }); + heading(ui, "Scale"); + let (sw, sh) = f.scale(); + egui::Grid::new("size_scale").num_columns(4).spacing(vec2(10.0, 6.0)).show(ui, |ui| { + if let Some(p) = percent(ui, "Height:", sh) { + f.set_scale_height(p); + } + if let Some(p) = percent(ui, "Width:", sw) { + f.set_scale_width(p); + } + ui.end_row(); + }); + ui.checkbox(&mut f.lock, tl!("Lock aspect ratio")); + ui.add_enabled(f.original.is_some(), egui::Checkbox::new(&mut f.relative, tl!("Relative to original picture size"))); + if let Some((w, h)) = f.uncropped { + heading(ui, "Original size"); + ui.horizontal(|ui| { + ui.label(format!("{} {}", tl!("Height:"), crate::options::length(h))); + ui.add_space(12.0); + ui.label(format!("{} {}", tl!("Width:"), crate::options::length(w))); + if let Some((pw, ph)) = f.pixels { + ui.add_space(12.0); + let (pw, ph) = (pw.to_string(), ph.to_string()); + ui.weak(crate::i18n::fmt(tl!("{width} × {height} pixels"), &[("width", &pw), ("height", &ph)])); + } + ui.add_space(12.0); + if ui.button(tl!("Reset")).clicked() { + f.reset(); + } + }); + } + let (ok, cancel) = buttons(ui, "OK", true); + if ok { + return run(app, "picture.size", f.params()); + } + cancel +} + #[cfg(test)] mod tests { use serde_json::json; @@ -1534,4 +1750,233 @@ mod tests { assert_eq!(a.session.run("mailings.labels", &f.params()).unwrap()["filled"], 1); assert!(product_label(f.product).contains("63.5 × 33.9 mm (A4)")); } + + /// A `w`×`h` pixel PNG, base64 for `insert.picture`. + fn png_data(w: u32, h: u32) -> String { + let img = image::RgbaImage::from_pixel(w, h, image::Rgba([200, 30, 30, 255])); + let mut png = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + wordcraft_engine::cmd::insert::base64_encode(&png) + } + + /// An app with a `w`×`h` pixel picture, inserted and selected as by Insert › Pictures. + fn picture_app(w: u32, h: u32) -> WordApp { + let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default()); + a.run("insert.picture", json!({"data": png_data(w, h)})).unwrap(); + a + } + + fn selected_size(a: &WordApp) -> (f32, f32) { + let (_, o) = wordcraft_engine::cmd::objects::selected(&a.session).unwrap(); + o.frame().map(|(w, h, _)| (w, h)).unwrap() + } + + /// #2573: Picture Format › Size's launcher (`picture.size` without a size) opens the Size + /// dialog on the selected picture: its size, the scale of its original size, Lock aspect ratio + /// and Reset; OK resizes it in one undo step. + #[test] + fn size_dialog_scales_locks_and_resets_the_picture() { + let mut a = picture_app(40, 20); + assert_eq!(selected_size(&a), (30.0, 15.0), "40×20 px at 96 ppi"); + a.run("picture.size", json!({"width": 60.0, "height": 15.0, "lockAspect": false})).unwrap(); + assert_eq!(a.run("picture.size", json!({})).unwrap(), json!({"pending": "pictureSize"})); + assert_eq!(selected_size(&a), (60.0, 15.0), "opening the dialog changes nothing"); + let LayoutDialog::Size(mut f) = form(&mut a) else { panic!("size") }; + assert!(f.lock && f.relative, "a picture opens locked, scaled from its original size"); + assert_eq!((f.original, f.uncropped, f.pixels), (Some((30.0, 15.0)), Some((30.0, 15.0)), Some((40, 20)))); + assert_eq!(f.scale(), (200.0, 100.0)); + // Locked, the other side follows in proportion, in size and in scale. + f.set_scale_height(200.0); + assert_eq!((f.width, f.height, f.scale()), (120.0, 30.0, (400.0, 200.0))); + f.set_width(60.0); + assert_eq!((f.width, f.height), (60.0, 15.0)); + f.lock = false; + f.set_height(45.0); + assert_eq!((f.width, f.height), (60.0, 45.0), "unlocked, one side alone"); + f.reset(); + assert_eq!((f.width, f.height, f.scale()), (30.0, 15.0, (100.0, 100.0)), "Reset: the original size"); + f.relative = false; + assert_eq!(f.scale(), (50.0, 100.0), "from the size the dialog opened with"); + f.set_scale_width(150.0); + assert_eq!((f.width, f.height), (90.0, 15.0)); + a.run("picture.size", f.params()).unwrap(); + assert_eq!(selected_size(&a), (90.0, 15.0)); + a.run("edit.undo", json!({})).unwrap(); + assert_eq!(selected_size(&a), (60.0, 15.0), "one undo step"); + } + + /// #2573: a cropped picture's Reset is what the crop leaves of the original; a shape opens the + /// dialog unlocked with no original size; with nothing selected nothing opens. + #[test] + fn size_dialog_follows_the_crop_and_shapes_have_no_original() { + let mut a = picture_app(40, 20); + a.run("picture.crop", json!({"left": 0.25, "right": 0.25})).unwrap(); + a.run("picture.size", json!({})).unwrap(); + let LayoutDialog::Size(mut f) = form(&mut a) else { panic!("size") }; + assert_eq!((f.original, f.uncropped), (Some((15.0, 15.0)), Some((30.0, 15.0)))); + f.reset(); + assert_eq!((f.width, f.height), (15.0, 15.0)); + + let mut a = app(); + assert!(!crate::widgets::enabled(&a, "picture.size"), "nothing to size"); + let _ = a.run("ui.dialog", json!({"name": "pictureSize"})); + assert!(a.dialog.is_none()); + a.run("insert.shape", json!({"kind": "rectangle"})).unwrap(); + a.run("picture.size", json!({})).unwrap(); + let LayoutDialog::Size(f) = form(&mut a) else { panic!("size") }; + assert!(!f.lock && !f.relative && f.original.is_none() && f.uncropped.is_none()); + assert_eq!(f.scale(), (100.0, 100.0)); + } + + /// #2573 review: locked, a side past 4000 pt shrinks the other with it instead of flattening + /// the picture, and so does Reset for a photo larger than 4000 pt; under 1 pt likewise. + #[test] + fn size_dialog_keeps_the_proportions_at_the_limits() { + let close = |(w, h): (f32, f32), (ew, eh): (f32, f32)| (w - ew).abs() < 0.01 && (h - eh).abs() < 0.01; + let mut a = picture_app(6000, 30); + a.run("picture.size", json!({})).unwrap(); + let LayoutDialog::Size(mut f) = form(&mut a) else { panic!("size") }; + assert_eq!(f.original, Some((4500.0, 22.5)), "6000×30 px at 96 ppi"); + f.reset(); + assert!(close((f.width, f.height), (4000.0, 20.0)), "Reset: {}×{}", f.width, f.height); + a.run("picture.size", f.params()).unwrap(); + assert!(close(selected_size(&a), (4000.0, 20.0)), "applied: {:?}", selected_size(&a)); + (f.width, f.height) = (15.0, 30.0); + f.set_width(4000.0); + assert_eq!((f.width, f.height), (2000.0, 4000.0)); + f.set_height(0.5); + assert_eq!((f.width, f.height), (1.0, 2.0)); + f.lock = false; + f.set_width(9000.0); + assert_eq!((f.width, f.height), (4000.0, 2.0), "unlocked, one side alone"); + } + + /// #2573 review: dialogs aren't modal. Cropping the picture or picking another one while the + /// Size dialog is open starts the form over, so OK never sizes a picture with stale numbers; + /// with nothing left to size the dialog closes. + #[test] + fn size_dialog_follows_the_selection() { + let mut a = picture_app(40, 20); + a.run("picture.size", json!({})).unwrap(); + let LayoutDialog::Size(mut f) = form(&mut a) else { panic!("size") }; + f.set_width(300.0); + assert!(f.follow(&a) && f.width == 300.0, "the same picture keeps the edits"); + // Cropped from the ribbon meanwhile: read again, Reset is what the new crop leaves. + a.run("picture.crop", json!({"left": 0.25, "right": 0.25})).unwrap(); + assert!(f.follow(&a)); + assert_eq!((f.width, f.original), (30.0, Some((15.0, 15.0)))); + a.run("select.collapse", json!({"end": true})).unwrap(); + a.run("insert.picture", json!({"data": png_data(20, 40)})).unwrap(); + assert!(f.follow(&a), "another picture selected"); + assert_eq!((f.width, f.height, f.original), (15.0, 30.0, Some((15.0, 30.0)))); + a.run("select.collapse", json!({"end": true})).unwrap(); + a.run("text.insert", json!({"text": " caption"})).unwrap(); + assert!(!f.follow(&a), "nothing to size"); + } + + /// #2573 review: the Size dialog end to end. Its launcher (`picture.size` without a size) + /// opens it; a height typed in pixels changes nothing until OK, which sizes the picture in + /// proportion as one undo step and closes the dialog. + #[test] + fn size_dialog_typed_height_applies_on_ok_in_proportion() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let mut a = picture_app(40, 20); + a.run("picture.size", json!({})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state( + |ui, app: &mut WordApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + a, + ); + h.run_steps(4); + // The Size section's Height (the Scale section has one too, after it). + h.get_all_by_role_and_label(Role::SpinButton, "Height:").next().expect("the height field").click(); + h.run_steps(2); + h.get_all_by_role_and_label(Role::SpinButton, "Height:").next().expect("editing").type_text("60 px"); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert!(h.state().dialog.is_some()); + assert_eq!(selected_size(h.state()), (30.0, 15.0), "nothing applies before OK"); + h.get_by_role_and_label(Role::Button, "OK").click(); + h.run_steps(2); + assert!(h.state().dialog.is_none(), "OK closes the dialog"); + assert_eq!(selected_size(h.state()), (90.0, 45.0), "60 px = 45 pt high, the width follows"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(selected_size(h.state()), (30.0, 15.0), "one undo step"); + } + + /// #2573 review: a value outside a field's range (a 1 px picture enlarged past 10000%) is shown + /// as it is. egui would otherwise clamp it on the first frame and report a change, which the + /// form would take as an edit and OK would apply unasked. + #[test] + fn size_dialog_leaves_out_of_range_values_alone() { + let mut a = picture_app(1, 1); + a.run("picture.size", json!({"width": 100.0, "height": 100.0, "lockAspect": false})).unwrap(); + a.run("picture.size", json!({})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state( + |ui, app: &mut WordApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + a, + ); + h.run_steps(4); + let Some(Dialog::Layout(d)) = &h.state().dialog else { panic!("the Size dialog is open") }; + let LayoutDialog::Size(f) = d.as_ref() else { panic!("size") }; + assert!((f.scale().0 - 100.0 / 0.75 * 100.0).abs() < 1.0, "13333%: {:?}", f.scale()); + assert_eq!((f.width, f.height), (100.0, 100.0), "the form keeps the size"); + assert_eq!(selected_size(h.state()), (100.0, 100.0)); + } + + /// #2573 review: a typed size is kept when the field loses focus, as text fields do: typing a + /// height and going straight for OK (a real click: press, then release frames later) applies + /// it. Taking it only on Enter would throw the typed size away. Esc cancels, applying nothing. + #[test] + fn size_dialog_typed_height_then_ok_without_enter_applies_it() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let harness = |a: WordApp| { + egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state( + |ui, app: &mut WordApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + a, + ) + }; + let mut a = picture_app(40, 20); + a.run("picture.size", json!({})).unwrap(); + let mut h = harness(a); + h.run_steps(4); + h.get_all_by_role_and_label(Role::SpinButton, "Height:").next().expect("the height field").click(); + h.run_steps(2); + h.get_all_by_role_and_label(Role::SpinButton, "Height:").next().expect("editing").type_text("60 px"); + h.run_steps(2); + let ok = h.get_by_role_and_label(Role::Button, "OK").rect().center(); + h.event(egui::Event::PointerMoved(ok)); + h.event(egui::Event::PointerButton { pos: ok, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.run_steps(2); + h.event(egui::Event::PointerButton { pos: ok, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); + assert!(h.state().dialog.is_none(), "OK closes the dialog"); + assert_eq!(selected_size(h.state()), (90.0, 45.0), "the typed height, in proportion"); + + // Esc throws the typing away and, as Cancel, closes the dialog: nothing applied. + let mut a = picture_app(40, 20); + a.run("picture.size", json!({})).unwrap(); + let mut h = harness(a); + h.run_steps(4); + h.get_all_by_role_and_label(Role::SpinButton, "Height:").next().expect("the height field").click(); + h.run_steps(2); + h.get_all_by_role_and_label(Role::SpinButton, "Height:").next().expect("editing").type_text("60 px"); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(h.state().dialog.is_none(), "Esc cancels the dialog"); + assert_eq!(selected_size(h.state()), (30.0, 15.0), "nothing applied"); + } } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 57abefaee6..bd49444f82 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2678,3 +2678,10 @@ # Drop Cap disabled reasons (#2601) the paragraph is empty абзацът е празен the paragraph starts with a space абзацът започва с интервал + +# Picture Format › Size: the Size dialog, sizes typed in any unit (#2573) + Lock aspect ratio Заключване на пропорциите + Relative to original picture size Спрямо оригиналния размер на картината + Original size Оригинален размер + {width} × {height} pixels {width} × {height} пиксела + Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions. Въведете размер в произволна единица, например 5 cm или 300 px. Другата страна се променя съответно, така че картината запазва пропорциите си. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 0c6ccb2e69..e2ab393f9c 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2681,3 +2681,10 @@ preview Title Ukázka # Drop Cap disabled reasons (#2601) the paragraph is empty odstavec je prázdný the paragraph starts with a space odstavec začíná mezerou + +# Picture Format › Size: the Size dialog, sizes typed in any unit (#2573) + Lock aspect ratio Zamknout poměr stran + Relative to original picture size Vzhledem k původní velikosti obrázku + Original size Původní velikost + {width} × {height} pixels {width} × {height} pixelů + Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions. Zadejte velikost v libovolné jednotce, například 5 cm nebo 300 px. Druhá strana se přizpůsobí, takže obrázek zachová své proporce. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index f2b52b7a4f..e5fc1fa341 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2278,3 +2278,10 @@ Lines to drop: Initialhöhe (Zeilen): Distance from text: Abstand zum Text: Distance from text Abstand zum Text + +# Picture Format › Size: the Size dialog, sizes typed in any unit (#2573) + Lock aspect ratio Seitenverhältnis sperren + Relative to original picture size Relativ zur ursprünglichen Bildgröße + Original size Originalgröße + {width} × {height} pixels {width} × {height} Pixel + Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions. Geben Sie eine Größe in einer beliebigen Einheit ein, z. B. 5 cm oder 300 px. Die andere Seite passt sich an, sodass das Bild seine Proportionen behält. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 89076be0e2..5899799551 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2645,3 +2645,10 @@ preview Title Título Lines to drop: Líneas que ocupa: Distance from text: Distancia del texto: Distance from text Distancia del texto + +# Picture Format › Size: the Size dialog, sizes typed in any unit (#2573) + Lock aspect ratio Bloquear relación de aspecto + Relative to original picture size Relativo al tamaño original de la imagen + Original size Tamaño original + {width} × {height} pixels {width} × {height} píxeles + Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions. Escribe un tamaño en cualquier unidad, como 5 cm o 300 px. El otro lado se ajusta, así que la imagen conserva sus proporciones. diff --git a/crates/ui-egui/src/i18n/et.tsv b/crates/ui-egui/src/i18n/et.tsv index 113493366e..f6e1dd4a30 100644 --- a/crates/ui-egui/src/i18n/et.tsv +++ b/crates/ui-egui/src/i18n/et.tsv @@ -2313,3 +2313,10 @@ Lines to drop: Ridade arv: Distance from text: Kaugus tekstist: Distance from text Kaugus tekstist + +# Picture Format › Size: the Size dialog, sizes typed in any unit (#2573) + Lock aspect ratio Lukusta kuvasuhe + Relative to original picture size Pildi algsuuruse suhtes + Original size Algne suurus + {width} × {height} pixels {width} × {height} pikslit + Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions. Sisesta suurus mis tahes ühikus, näiteks 5 cm või 300 px. Teine külg muutub kaasa, nii et pilt säilitab oma proportsioonid. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index e189851cf3..9a9ebabb7e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2691,3 +2691,10 @@ template Letter Lettre Lines to drop: Hauteur (lignes) : Distance from text: Distance du texte : Distance from text Distance du texte + +# Picture Format › Size: the Size dialog, sizes typed in any unit (#2573) + Lock aspect ratio Verrouiller les proportions + Relative to original picture size Proportionnellement à la taille d'origine de l'image + Original size Taille d'origine + {width} × {height} pixels {width} × {height} pixels + Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions. Tapez une taille dans n'importe quelle unité, par exemple 5 cm ou 300 px. L'autre côté suit, et l'image garde ses proportions. diff --git a/crates/ui-egui/src/i18n/hr.tsv b/crates/ui-egui/src/i18n/hr.tsv index 79219d9c2b..6f5653d500 100644 --- a/crates/ui-egui/src/i18n/hr.tsv +++ b/crates/ui-egui/src/i18n/hr.tsv @@ -2689,3 +2689,10 @@ preview Title Naslov # Drop Cap disabled reasons (#2601) the paragraph is empty odlomak je prazan the paragraph starts with a space odlomak počinje razmakom + +# Picture Format › Size: the Size dialog, sizes typed in any unit (#2573) + Lock aspect ratio Zaključaj omjer širine i visine + Relative to original picture size U odnosu na izvornu veličinu slike + Original size Izvorna veličina + {width} × {height} pixels {width} × {height} piksela + Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions. Upišite veličinu u bilo kojoj jedinici, npr. 5 cm ili 300 px. Druga se strana prilagođava pa slika zadržava svoje proporcije. diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index eb661bb5de..5264868175 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2685,3 +2685,10 @@ # Drop Cap disabled reasons (#2601) the paragraph is empty a bekezdés üres the paragraph starts with a space a bekezdés szóközzel kezdődik + +# Picture Format › Size: the Size dialog, sizes typed in any unit (#2573) + Lock aspect ratio Méretarány zárolása + Relative to original picture size Az eredeti képmérethez viszonyítva + Original size Eredeti méret + {width} × {height} pixels {width} × {height} képpont + Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions. Írj be egy méretet bármilyen mértékegységben, például 5 cm vagy 300 px. A másik oldal követi, így a kép megtartja az arányait. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 419f476bb1..2aa48750b4 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2698,3 +2698,10 @@ preview Title Esempio # Drop Cap disabled reasons (#2601) the paragraph is empty il paragrafo è vuoto the paragraph starts with a space il paragrafo inizia con uno spazio + +# Picture Format › Size: the Size dialog, sizes typed in any unit (#2573) + Lock aspect ratio Blocca proporzioni + Relative to original picture size Rispetto alle dimensioni originali dell'immagine + Original size Dimensioni originali + {width} × {height} pixels {width} × {height} pixel + Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions. Scrivi una dimensione in qualsiasi unità, ad esempio 5 cm o 300 px. L'altro lato si adegua, così l'immagine mantiene le proporzioni. diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 69ed5e8474..5df1f3df8a 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -2279,3 +2279,10 @@ Lines to drop: ドロップする行数: Distance from text: 本文からの距離: Distance from text 本文からの距離 + +# Picture Format › Size: the Size dialog, sizes typed in any unit (#2573) + Lock aspect ratio 縦横比を固定する + Relative to original picture size 元の図のサイズを基準にする + Original size 元のサイズ + {width} × {height} pixels {width} × {height} ピクセル + Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions. 5 cm や 300 px など、任意の単位でサイズを入力します。もう一方の辺も合わせて変わるため、図の縦横比は保たれます。 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index d6d81f7198..4c410563ec 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -2533,3 +2533,10 @@ preview Title 제목 Lines to drop: 장식할 줄 수: Distance from text: 본문과의 간격: Distance from text 본문과의 간격 + +# Picture Format › Size: the Size dialog, sizes typed in any unit (#2573) + Lock aspect ratio 가로 세로 비율 고정 + Relative to original picture size 원래 그림 크기 기준 + Original size 원래 크기 + {width} × {height} pixels {width} × {height} 픽셀 + Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions. 5 cm 또는 300 px처럼 원하는 단위로 크기를 입력하세요. 다른 쪽도 함께 바뀌어 그림의 비율이 유지됩니다. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 9fa7378e78..0c4469dd1b 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2694,3 +2694,10 @@ preview Title Tytuł # Drop Cap disabled reasons (#2601) the paragraph is empty akapit jest pusty the paragraph starts with a space akapit zaczyna się od spacji + +# Picture Format › Size: the Size dialog, sizes typed in any unit (#2573) + Lock aspect ratio Zablokuj proporcje + Relative to original picture size Względem oryginalnego rozmiaru obrazu + Original size Rozmiar oryginalny + {width} × {height} pixels {width} × {height} pikseli + Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions. Wpisz rozmiar w dowolnej jednostce, np. 5 cm lub 300 px. Druga strona dopasuje się, więc obraz zachowa proporcje. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 5bbb3ad8ef..3b61a23aa3 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2291,3 +2291,10 @@ Lines to drop: Linhas ocupadas: Distance from text: Distância do texto: Distance from text Distância do texto + +# Picture Format › Size: the Size dialog, sizes typed in any unit (#2573) + Lock aspect ratio Bloquear proporção + Relative to original picture size Em relação ao tamanho original da imagem + Original size Tamanho original + {width} × {height} pixels {width} × {height} pixels + Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions. Digite um tamanho em qualquer unidade, como 5 cm ou 300 px. O outro lado acompanha, e a imagem mantém as proporções. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 92e02e8e08..f72af8f0a8 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2687,3 +2687,10 @@ preview Title Пример # Drop Cap disabled reasons (#2601) the paragraph is empty абзац пуст the paragraph starts with a space абзац начинается с пробела + +# Picture Format › Size: the Size dialog, sizes typed in any unit (#2573) + Lock aspect ratio Сохранять пропорции + Relative to original picture size Относительно исходного размера рисунка + Original size Исходный размер + {width} × {height} pixels {width} × {height} пикс. + Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions. Введите размер в любых единицах, например 5 cm или 300 px. Другая сторона изменится вместе с ней, и рисунок сохранит пропорции. diff --git a/crates/ui-egui/src/i18n/sr-latn.tsv b/crates/ui-egui/src/i18n/sr-latn.tsv index 47c2592d14..ee5fcb93a8 100644 --- a/crates/ui-egui/src/i18n/sr-latn.tsv +++ b/crates/ui-egui/src/i18n/sr-latn.tsv @@ -2289,3 +2289,10 @@ Lines to drop: Broj redova: Distance from text: Rastojanje od teksta: Distance from text Rastojanje od teksta + +# Picture Format › Size: the Size dialog, sizes typed in any unit (#2573) + Lock aspect ratio Zaključaj odnos širine i visine + Relative to original picture size U odnosu na originalnu veličinu slike + Original size Originalna veličina + {width} × {height} pixels {width} × {height} piksela + Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions. Unesite veličinu u bilo kojoj jedinici, na primer 5 cm ili 300 px. Druga strana se prilagođava, pa slika zadržava svoje proporcije. diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 86d36aac76..b0f3e78a3e 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -2293,3 +2293,10 @@ Lines to drop: Број редова: Distance from text: Растојање од текста: Distance from text Растојање од текста + +# Picture Format › Size: the Size dialog, sizes typed in any unit (#2573) + Lock aspect ratio Закључај однос ширине и висине + Relative to original picture size У односу на оригиналну величину слике + Original size Оригинална величина + {width} × {height} pixels {width} × {height} пиксела + Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions. Унесите величину у било којој јединици, на пример 5 cm или 300 px. Друга страна се прилагођава, па слика задржава своје пропорције. diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 4fe9cc5914..0fcd86e75c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2704,3 +2704,10 @@ preview Title Titel # Drop Cap disabled reasons (#2601) the paragraph is empty stycket är tomt the paragraph starts with a space stycket börjar med ett blanksteg + +# Picture Format › Size: the Size dialog, sizes typed in any unit (#2573) + Lock aspect ratio Lås proportioner + Relative to original picture size I förhållande till bildens ursprungliga storlek + Original size Ursprunglig storlek + {width} × {height} pixels {width} × {height} pixlar + Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions. Skriv en storlek i valfri enhet, till exempel 5 cm eller 300 px. Den andra sidan följer med, så att bilden behåller sina proportioner. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index e8786eb18e..95160afd0e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2686,3 +2686,10 @@ preview Title Örnek # Drop Cap disabled reasons (#2601) the paragraph is empty paragraf boş the paragraph starts with a space paragraf boşlukla başlıyor + +# Picture Format › Size: the Size dialog, sizes typed in any unit (#2573) + Lock aspect ratio En boy oranını kilitle + Relative to original picture size Özgün resim boyutuna göre + Original size Özgün boyut + {width} × {height} pixels {width} × {height} piksel + Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions. Herhangi bir birimde bir boyut yazın, örneğin 5 cm veya 300 px. Diğer kenar da buna uyar, böylece resim oranlarını korur. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 6c587aa28f..7d7f61e141 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2291,3 +2291,10 @@ Lines to drop: Висота в рядках: Distance from text: Відстань від тексту: Distance from text Відстань від тексту + +# Picture Format › Size: the Size dialog, sizes typed in any unit (#2573) + Lock aspect ratio Зберігати пропорції + Relative to original picture size Відносно початкового розміру зображення + Original size Початковий розмір + {width} × {height} pixels {width} × {height} пікс. + Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions. Введіть розмір у будь-яких одиницях, наприклад 5 cm або 300 px. Інша сторона зміниться разом із нею, тож зображення збереже пропорції. diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4cc15d7b7a..6ad412aa17 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2729,3 +2729,10 @@ template Letter Thư # Drop Cap disabled reasons (#2601) the paragraph is empty đoạn văn trống the paragraph starts with a space đoạn văn bắt đầu bằng dấu cách + +# Picture Format › Size: the Size dialog, sizes typed in any unit (#2573) + Lock aspect ratio Khóa tỷ lệ khung hình + Relative to original picture size So với kích thước gốc của ảnh + Original size Kích thước gốc + {width} × {height} pixels {width} × {height} điểm ảnh + Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions. Nhập kích thước theo đơn vị bất kỳ, ví dụ 5 cm hoặc 300 px. Cạnh còn lại thay đổi theo, nên ảnh giữ nguyên tỷ lệ. diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 305beef454..bc0178f73e 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2291,3 +2291,10 @@ Lines to drop: 下沉行数: Distance from text: 距正文: Distance from text 距正文 + +# Picture Format › Size: the Size dialog, sizes typed in any unit (#2573) + Lock aspect ratio 锁定纵横比 + Relative to original picture size 相对于原始图片大小 + Original size 原始大小 + {width} × {height} pixels {width} × {height} 像素 + Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions. 可用任意单位输入大小,例如 5 cm 或 300 px。另一边随之调整,图片保持原有比例。 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 43ad8f283d..6ded3d9bfa 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2280,3 +2280,10 @@ Lines to drop: 放大行數: Distance from text: 與本文距離: Distance from text 與本文距離 + +# Picture Format › Size: the Size dialog, sizes typed in any unit (#2573) + Lock aspect ratio 鎖定長寬比 + Relative to original picture size 相對於原始圖片大小 + Original size 原始大小 + {width} × {height} pixels {width} × {height} 像素 + Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions. 可用任何單位輸入大小,例如 5 cm 或 300 px。另一邊隨之調整,圖片保持原有比例。 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c1452c5830..7c2f160bf3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2496,6 +2496,8 @@ fn input_dialog(id: &str, params: &Value) -> Option<&'static str> { "table.properties" if params.as_object().is_none_or(|m| m.is_empty()) => Some("tableProperties"), // Cell Margins without settings shows the dialog; values continue through the same command. "table.cellMargins" if params.as_object().is_none_or(|m| m.is_empty()) => Some("tableCellMargins"), + // Size without a size (Picture Format › Size's launcher) shows the Size dialog (#2573). + "picture.size" if params.as_object().is_none_or(|m| m.is_empty()) => Some("pictureSize"), // Formula without one asks for it, suggested from the numbers next to the cell (#1201). "table.formula" if !has("formula") => Some("tableFormula"), // Sort without settings asks for the column, order and header row (#1200). diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index bf8fd2066e..ea1728ce2c 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -598,6 +598,23 @@ fn edge_cue(ui: &mut Ui, rect: Rect, glyph: &str, hint: &str, t: &Tokens) -> boo resp.clicked() } +/// Whether Esc just ended typing in a field (`r`, remembered under `id`). egui 0.36 keeps a +/// `DragValue`'s typed text after Esc and applies it a frame later, when the field still counts as +/// having just lost focus but Esc is no longer pressed: a change reported within two frames of the +/// Esc is that late value, to be dropped so that Esc cancels as in Word. +fn esc_cancelled(ui: &Ui, r: &egui::Response, id: egui::Id) -> bool { + let now = ui.ctx().cumulative_pass_nr(); + let (focus_key, esc_key) = (id.with("focused"), id.with("esc")); + // Read outside `data_mut`: both lock the context. + let focused = r.has_focus(); + let had_focus = ui.data(|d| d.get_temp::(focus_key)).unwrap_or(false); + ui.data_mut(|d| d.insert_temp(focus_key, focused)); + if had_focus && !focused && ui.input(|i| i.key_pressed(egui::Key::Escape)) { + ui.data_mut(|d| d.insert_temp(esc_key, now)); + } + ui.data(|d| d.get_temp::(esc_key)).is_some_and(|at| now.saturating_sub(at) <= 2) +} + fn stack(ui: &mut Ui, add: impl FnOnce(&mut Ui)) { ui.vertical(|ui| { ui.spacing_mut().item_spacing = vec2(1.0, 0.0); @@ -2317,8 +2334,10 @@ fn chart_design(app: &mut WordApp, ui: &mut Ui) { crate::widgets::row(ui, |ui| { ui.label(egui::RichText::new(tl!(label)).small()); let mut v = v0; - let r = ui.add(egui::DragValue::new(&mut v).speed(1.0).range(36.0..=2000.0).suffix(" pt")); - if r.changed() { + // The range bounds what is typed or dragged; a size outside it is shown as it + // is (clamped, egui would report a change and resize the chart unasked). + let r = ui.add(egui::DragValue::new(&mut v).speed(1.0).range(36.0..=2000.0).clamp_existing_to_range(false).suffix(" pt")); + if r.changed() && v != v0 { if r.dragged() && !r.drag_started() { app.session.join_next_undo(); } @@ -2405,8 +2424,10 @@ fn shape_format(app: &mut WordApp, ui: &mut Ui) { for (label, key, v0) in [("W:", "width", w0), ("H:", "height", h0)] { ui.label(egui::RichText::new(tl!(label)).small()); let mut v = v0; - let r = ui.add(egui::DragValue::new(&mut v).speed(1.0).range(4.0..=2000.0).suffix(" pt")); - if r.changed() { + // `picture.size`'s own range; a size outside it (a thin line) is shown as it + // is (clamped, egui would report a change and resize the shape unasked). + let r = ui.add(egui::DragValue::new(&mut v).speed(1.0).range(1.0..=4000.0).clamp_existing_to_range(false).suffix(" pt")); + if r.changed() && v != v0 { if r.dragged() && !r.drag_started() { app.session.join_next_undo(); } @@ -2572,31 +2593,44 @@ fn picture_format(app: &mut WordApp, ui: &mut Ui) { group_menu(ui, app, Some("Group")); }); }); - group(ui, "Size", None, app, |ui, app| { + // The launcher opens the Size dialog: scale, Lock aspect ratio, the original size (#2573). + group(ui, "Size", Some("picture.size"), app, |ui, app| { let (media, off, w0, h0, crop0, alt0) = match wordcraft_engine::cmd::objects::selected(&app.session) { Some((pos, wordcraft_doc::para::InlineObject::Image { media, w, h, alt, crop, .. })) => (media, pos.off, w, h, crop, alt), _ => (String::new(), 0, 0.0, 0.0, [0.0; 4], String::new()), }; // `picture.size` locks the aspect ratio unless told otherwise, so one dimension suffices. + // The fields show the interface unit and take a size typed in any unit, pixels too + // (`300 px`, #1901), applied once typed (Enter, Tab or a click elsewhere; Esc cancels), + // never per keystroke; a drag applies as it goes, one undo step. + let unit = crate::options::unit(); + let k = unit.pt_per_unit(); stack(ui, |ui| { crate::widgets::row(ui, |ui| { - ui.label(egui::RichText::new(tl!("W:")).small()); - let mut w = w0; - let r = ui.add(egui::DragValue::new(&mut w).speed(1.0).range(4.0..=2000.0).suffix(format!(" {}", tl!("pt")))); - if r.changed() { - if r.dragged() && !r.drag_started() { - app.session.join_next_undo(); + for (label, key, pt) in [("W:", "width", w0), ("H:", "height", h0)] { + let name = ui.label(egui::RichText::new(tl!(label)).small()); + let was = pt / k; + let mut v = was; + // Not `clamp_existing_to_range`: egui would clamp a size outside the range (a 1 px + // picture is 0.75 pt) and report it as a change, resizing the picture unasked. + let field = egui::DragValue::new(&mut v) + .speed(1.0 / k) + .range(1.0 / k..=4000.0 / k) + .clamp_existing_to_range(false) + .measure(unit) + .max_decimals(2); + let r = ui.add(field.update_while_editing(false)).labelled_by(name.id).on_hover_text(tl!( + "Type a size in any unit, such as 5 cm or 300 px. The other side follows, so the picture keeps its proportions." + )); + // While typing, the field reports each keystroke as a change; only a new + // value (Enter, Tab, a click elsewhere, a drag) resizes, and Esc cancels. + let cancelled = esc_cancelled(ui, &r, egui::Id::new(("picture_size_field", key))); + if r.changed() && v != was && !cancelled { + if r.dragged() && !r.drag_started() { + app.session.join_next_undo(); + } + let _ = app.run("picture.size", json!({key: v * k})); } - let _ = app.run("picture.size", json!({"width": w})); - } - ui.label(egui::RichText::new(tl!("H:")).small()); - let mut h = h0; - let r = ui.add(egui::DragValue::new(&mut h).speed(1.0).range(4.0..=2000.0).suffix(format!(" {}", tl!("pt")))); - if r.changed() { - if r.dragged() && !r.drag_started() { - app.session.join_next_undo(); - } - let _ = app.run("picture.size", json!({"height": h})); } rotation_field(ui, app); }); @@ -3287,4 +3321,114 @@ mod tests { assert_eq!(resolve_tab("Table Design", &["Home"]), "Home"); assert_eq!(resolve_tab("Home", &["Home"]), "Home"); } + + /// #2573, #1901: Picture Format › Size's width shows the interface unit and takes a size typed + /// in pixels. It applies once typed (Enter), not while typing, keeping the picture's proportions, as one + /// undo step. + #[test] + fn picture_width_typed_in_pixels_keeps_the_proportions() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let mut a = crate::WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default()); + a.run("file.options", json!({"units": "centimeters"})).unwrap(); + a.run("insert.picture", json!({"data": png_data()})).unwrap(); + a.run("ui.tab", json!({"tab": "Picture Format"})).unwrap(); + let size = |a: &crate::WordApp| wordcraft_engine::cmd::objects::selected(&a.session).and_then(|(_, o)| o.frame().map(|(w, h, _)| (w, h))); + assert_eq!(size(&a), Some((15.0, 7.5)), "20×10 px at 96 ppi"); + // Wide enough for the whole tab: the Size group is its last. + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(2560.0, 900.0)).build_ui_state( + |ui, app: &mut crate::WordApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + a, + ); + h.run_steps(4); + let shown = h.get_by_role_and_label(Role::SpinButton, "W:").value().unwrap_or_default(); + assert!(shown.ends_with(" cm"), "the interface unit: {shown:?}"); + h.get_by_role_and_label(Role::SpinButton, "W:").click(); + h.run_steps(2); + // Editing, the field is still a spin button, now showing the bare number to type over. + let editing = h.get_by_role_and_label(Role::SpinButton, "W:"); + assert!(editing.is_focused() && editing.value().is_some_and(|v| !v.ends_with(" cm")), "a click starts typing"); + editing.type_text("300 px"); + h.run_steps(2); + assert_eq!(size(h.state()), Some((15.0, 7.5)), "nothing applies while typing"); + h.key_press(egui::Key::Enter); + h.run_steps(2); + let (w, ht) = size(h.state()).unwrap(); + assert!((w - 225.0).abs() < 0.01 && (ht - 112.5).abs() < 0.01, "300 px = 225 pt, the height follows: {w}×{ht}"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(size(h.state()), Some((15.0, 7.5)), "one undo step"); + // Esc throws a typed size away. + h.get_by_role_and_label(Role::SpinButton, "W:").click(); + h.run_steps(2); + h.get_by_role_and_label(Role::SpinButton, "W:").type_text("500 px"); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert_eq!(size(h.state()), Some((15.0, 7.5)), "Esc cancels the typing"); + } + + /// #2573 review: showing Picture Format never resizes a picture whose size is outside the + /// fields' range (a 1×1 px spacer is 0.75 pt): egui clamps such a value by default and reports + /// it as a change. + #[test] + fn picture_format_leaves_a_tiny_picture_alone() { + let mut a = crate::WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default()); + let img = image::RgbaImage::from_pixel(1, 1, image::Rgba([0, 0, 0, 255])); + let mut png = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + a.run("insert.picture", json!({"data": wordcraft_engine::cmd::insert::base64_encode(&png)})).unwrap(); + a.run("ui.tab", json!({"tab": "Picture Format"})).unwrap(); + let size = |a: &crate::WordApp| wordcraft_engine::cmd::objects::selected(&a.session).and_then(|(_, o)| o.frame().map(|(w, h, _)| (w, h))); + assert_eq!(size(&a), Some((0.75, 0.75))); + let undo = a.session.undo_depth(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(2560.0, 900.0)).build_ui_state( + |ui, app: &mut crate::WordApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + a, + ); + h.run_steps(6); + assert_eq!(size(h.state()), Some((0.75, 0.75)), "shown, not resized"); + assert_eq!(h.state().session.undo_depth(), undo, "no undo step"); + } + + /// #2573 review: Shape Format and Chart Design leave sizes outside their fields' ranges alone + /// too (a 0.5 pt high line; a chart narrower than 36 pt), as Picture Format does. + #[test] + fn shape_and_chart_formats_leave_out_of_range_sizes_alone() { + let size = |a: &crate::WordApp| wordcraft_engine::cmd::objects::selected(&a.session).and_then(|(_, o)| o.frame().map(|(w, h, _)| (w, h))); + let shown = |a: crate::WordApp| { + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(2560.0, 900.0)).build_ui_state( + |ui, app: &mut crate::WordApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + a, + ); + h.run_steps(6); + let a = h.state(); + (size(a), a.session.undo_depth()) + }; + let mut a = crate::WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default()); + a.run("insert.shape", json!({"kind": "rectangle"})).unwrap(); + a.run("picture.size", json!({"width": 3000.0, "height": 1.0, "lockAspect": false})).unwrap(); + a.run("ui.tab", json!({"tab": "Shape Format"})).unwrap(); + let before = (size(&a), a.session.undo_depth()); + assert_eq!(before.0, Some((3000.0, 1.0))); + assert_eq!(shown(a), before, "Shape Format shown, the shape untouched"); + + let mut a = crate::WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default()); + a.run("insert.chart", json!({"type": "doughnut"})).unwrap(); + a.run("picture.size", json!({"width": 20.0, "height": 2500.0, "lockAspect": false})).unwrap(); + a.run("ui.tab", json!({"tab": "Chart Design"})).unwrap(); + let before = (size(&a), a.session.undo_depth()); + assert_eq!(before.0, Some((20.0, 2500.0))); + assert_eq!(shown(a), before, "Chart Design shown, the chart untouched"); + } } diff --git a/docs/ui-parity.md b/docs/ui-parity.md index eaf8c6110c..e138d6bdb4 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -29,7 +29,7 @@ Document title opens Rename Document; the account badge opens Options › Genera | Modal dialogs | **56** (`Dialog` enum: Discard Recovery, Font, Enclose Characters, Paragraph, Tabs, Borders and Shading, Find, Go To, Insert Table, Table Properties, Page Setup, Link, Bookmark, Word Count, Zoom, Watermark, New Style, Modify Style, Manage Styles, Table Style, Commands, Icons, Templates and Add-ins, Organizer, Compare and Combine, AutoCorrect Options, Paste Special, About, Save Changes, Password, Encrypt with Password, Define New Multilevel List, Track Changes Options; Columns, Symbol with Special Characters, Field (#321); Field code (#339); mail merge Recipients (Filter and Sort, #778; Find in list and a merged-only view, #1576), Insert Merge Field, Find Recipient, Rules, Match Fields, Check for Errors; Caption with New Label and Numbering, Index, Mark Index Entry, Custom Table of Contents with Options and TOC styles, Source Manager, Create/Edit Source (#402); Cross-reference (#916); Line Numbers, Hyphenation with Manual Hyphenation, Language, Envelopes, Labels (#407); Page Setup has a Paper size list and custom width and height, opened from Layout › Size › More Paper Sizes… (#1433)) plus panes and menus for the rest | ~100 (Options panes…) | ~45% | 11–19 | | Task panes (Navigation, Styles, Comments, Reviewing, Format Picture/Shape, Thesaurus, Accessibility, Clipboard, Selection) | Navigation (long headings truncate with an ellipsis instead of expanding the pane, #759), Styles, Comments, Thesaurus, Restrict Editing, Accessibility (grouped findings, jump-to, fixes) and Alt Text (#386), Read Aloud, Zotero; Style Inspector (#236); Clipboard pane (#264) open | all | 70% | 4–6 | | Keyboard shortcuts | **152** commands bound in `CommandSpec::key`, 172 key combinations (counted from the registry on Linux, 2026-10-13); styles, spacing, symbols, fields, views, mail merge (#330); field keys Alt+F9, Shift+F9, Ctrl+Shift+F9, Ctrl+F11, Ctrl+Shift+F11, Shift+F11 (#339), Next Field on Alt+F1 and Alt+Shift+F1 (Word's other keys for it) since F11 went to full screen (#980; GNOME and KDE may keep Alt+F1 for their own overview or application menu, and then Next Field has no key there; Previous Field keeps Shift+F11); Alt+Shift+arrows (move paragraphs, promote/demote), Shift+F5 Go Back and Alt+X (#343); Outline view: Alt+Shift+Plus/Minus expand/collapse, Alt+Shift+1–9 and Alt+Shift+A Show Level (#493); Alt+Q to "Tell me" command search (#819, not on macOS); on macOS, Word for Mac's own keys: ⌘⇧S Save As, ⌘⌥E Insert Endnote, ⌘⌥A New Comment, ⌃H Replace, ⌘⌥R collapse the ribbon. The Spike: Ctrl+F3 cuts to it, Ctrl+Shift+F3 inserts it and empties it (⌘F3, ⌘⇧F3 on macOS). Missing: en dash on the numeric keypad Insert Hyperlink has Word's Link to: Existing File or Web Page / Place in This Document (top of the document, headings, bookmarks) (#1234). | ~250 default shortcuts | ~70% | 2–4 | -| Modal dialogs | **59** (`Dialog` enum: Discard Recovery, Font, Enclose Characters, Paragraph, Tabs, Borders and Shading, Find, Go To, Insert Table, Table Properties, Page Setup, Link, Bookmark, Word Count, Zoom, Watermark, New Style, Modify Style, Manage Styles, Table Style, Commands, Icons, Templates and Add-ins, Organizer, Compare and Combine, AutoCorrect Options, Paste Special, About, Save Changes, Password, Encrypt with Password, Define New Multilevel List, Track Changes Options; Columns, Symbol with Special Characters, Field (#321); Field code (#339); mail merge Recipients, Insert Merge Field, Find Recipient, Rules, Match Fields, Check for Errors; Caption with New Label and Numbering, Index, Mark Index Entry, Custom Table of Contents with Options and TOC styles, Source Manager, Create/Edit Source (#402); Cross-reference (#916); Drop Cap with Position, Font, Lines to drop and Distance from text, opened from Insert › Drop Cap › Drop Cap Options… (#2601); Line Numbers, Hyphenation with Manual Hyphenation, Language, Envelopes, Labels (#407); Page Setup has a Paper size list and custom width and height, opened from Layout › Size › More Paper Sizes… (#1433); every dialog's close control is a box at the title bar's right end, the full title-bar height and 1.6× as wide, all of it clickable, red with a white ✕ on hover as a Windows caption button (#1885); Split Cells (columns, rows, merge before split; defaults follow the selection as in Word: twice its columns, its rows, Merge offered for several cells or one merged across columns; a merged cell splits into 1 to its height rows, its height or 1 × 1 cutting it back into rows, more refused with Word's message; parts split across columns are equal and other rows keep their grid lines) and Convert Text to Table (live column count, read-only rows; Initial column width Auto or 0 to 22 in, AutoFit to contents/window; Paragraphs/Commas/Tabs/Other "-" separators) (#2592)) plus panes and menus for the rest | ~100 (Options panes…) | ~45% | 11–19 | +| Modal dialogs | **60** (`Dialog` enum: Discard Recovery, Font, Enclose Characters, Paragraph, Tabs, Borders and Shading, Find, Go To, Insert Table, Table Properties, Page Setup, Link, Bookmark, Word Count, Zoom, Watermark, New Style, Modify Style, Manage Styles, Table Style, Commands, Icons, Templates and Add-ins, Organizer, Compare and Combine, AutoCorrect Options, Paste Special, About, Save Changes, Password, Encrypt with Password, Define New Multilevel List, Track Changes Options; Columns, Symbol with Special Characters, Field (#321); Field code (#339); mail merge Recipients, Insert Merge Field, Find Recipient, Rules, Match Fields, Check for Errors; Caption with New Label and Numbering, Index, Mark Index Entry, Custom Table of Contents with Options and TOC styles, Source Manager, Create/Edit Source (#402); Cross-reference (#916); Drop Cap with Position, Font, Lines to drop and Distance from text, opened from Insert › Drop Cap › Drop Cap Options… (#2601); Line Numbers, Hyphenation with Manual Hyphenation, Language, Envelopes, Labels (#407); Page Setup has a Paper size list and custom width and height, opened from Layout › Size › More Paper Sizes… (#1433); every dialog's close control is a box at the title bar's right end, the full title-bar height and 1.6× as wide, all of it clickable, red with a white ✕ on hover as a Windows caption button (#1885); Split Cells (columns, rows, merge before split; defaults follow the selection as in Word: twice its columns, its rows, Merge offered for several cells or one merged across columns; a merged cell splits into 1 to its height rows, its height or 1 × 1 cutting it back into rows, more refused with Word's message; parts split across columns are equal and other rows keep their grid lines) and Convert Text to Table (live column count, read-only rows; Initial column width Auto or 0 to 22 in, AutoFit to contents/window; Paragraphs/Commas/Tabs/Other "-" separators) (#2592); Size, from Picture Format › Size's launcher: height and width in the interface unit (a size typed in any unit, `300 px` too), scale of the original or the opening size, Lock aspect ratio, the original size with its pixels and Reset (#2573)) plus panes and menus for the rest | ~100 (Options panes…) | ~45% | 11–19 | | Task panes (Navigation, Styles, Comments, Reviewing, Format Picture/Shape, Thesaurus, Accessibility, Clipboard, Selection) | Navigation (long headings truncate with an ellipsis instead of expanding the pane, #759), Styles, Comments (balloons and cards read in both themes, #2045), Thesaurus, Restrict Editing, Accessibility (grouped findings, jump-to, fixes) and Alt Text (#386), Read Aloud, Zotero; Style Inspector (#236); Clipboard pane (#264) open | all | 70% | 4–6 | | Context menus (right-click) | text, spelling suggestions, fields (Update Field, Edit Field…, Toggle Field Codes, #339; Update Field on a table of contents entry updates the table, #1197, and after a save and reopen, #2182); right-click selects a picture, shape or text box and offers Insert Caption… (#1230) and Wrap Text (styles, Move with Text / Fix Position on Page, #513); tables, the items following the selection as in Word (Insert, Delete › Cells, Columns, Rows or Table whatever is selected (#1198), Merge and Split Cells, Distribute, AutoFit, Text Direction, Insert Caption…, Table Properties…; no Border Styles yet) | rich per context | 65% | 2–4 | | Backstage (Home, New, Open, Info, Save As, Print, Share, Export, Options) | Home and New separate (#254), Info properties kept (#268), Options in Word's panes with working settings (#485), Print page with preview, page range and copies (#641); launched with nothing to open, the app starts on Home (the Start screen: Blank document, templates, Recent; no document is open until one is picked or opened, so Esc or Back shows an empty window with the ribbon greyed out but for Help, #1129), with File › Options › General › Start-up to turn it off (#766); Info › Inspect Document finds and removes hidden text by its effective formatting (direct, character or paragraph style) in every story: body, headers, footers, notes, comments and text boxes, and lists what it couldn't reach (#1344); File › Close (Mod+W, Mod+F4) closes the document and keeps the window, showing no page, as Word does; the window's close button quits (#1712) | | 68% | 4–6 | @@ -75,6 +75,7 @@ Footnote and endnote editing keeps body and note text at normal opacity, on ligh |---|---|---| | 2026-10-16 | trivial | Dragging the vertical scrollbar shows a tip beside the pointer with the page at the top of the window ("Page 7 of 10"); nothing said where the drag would land (#2551) | | 2026-10-17 | trivial | Recipient List dialog: Find in list box with a match count, "Show only records that will be merged", striped rows; hidden rows keep their record for edit and remove (#1576) | +| 2026-10-18 | trivial | Picture Format › Size (#2573): the width and height show the interface unit and take a size typed in any unit, pixels too (`300 px`), applied once typed (Enter, Tab or a click elsewhere; Esc cancels) with the proportions kept; the group's launcher opens a Size dialog (height and width, scale, Lock aspect ratio, Relative to original picture size, original size with its pixels, Reset); `picture.size` takes `original`; readiness estimates unchanged | | 2026-10-15 | trivial | File › Close (Mod+W, Mod+F4) closes the document and keeps the window, showing no page, as Word does (it quit the whole app); the window's close button still asks to save and quits (#1712) | | 2026-10-16 | trivial | Save Changes exposes an alert-dialog role, the document-specific question and loss/failure context to accessibility; full-app focus/ancestry regression. Native screen-reader verification remains pending. | | 2026-10-16 | trivial | Dragging the vertical scrollbar shows a tip beside the pointer with the page at the top of the window ("Page 7 of 10"); nothing said where the drag would land (#2551) |