From 460b5438c0a6262135ab5759eafa81dffe8b3a27 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 10:18:30 -0800 Subject: [PATCH 01/91] Dialogs: a Save As goes ahead when the portal answers with a file type of another shape answer() in crates/dialogs/src/portal.rs read the portal's current_filter with zvariant's tuple conversion, which panics on a structure with fewer fields than the tuple (zvariant 5.15.1, structure.rs:382). The Save dialog's thread then ended after a file was picked, and nothing was saved. filter_label reads the label only from a structure of a string and an array of (us), the (sa(us)) type the FileChooser portal documents. A current_filter of any other shape names no file type, and the answer keeps the path. A structure with more fields than (sa(us)) used to name its file type and now names none. This carries the fix from storytold/photocraft#13490 to the code that moved here from apps/photocraft/src/portal_save.rs. --- crates/dialogs/src/portal.rs | 17 +++++++++--- crates/dialogs/src/portal/tests.rs | 42 ++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/crates/dialogs/src/portal.rs b/crates/dialogs/src/portal.rs index 1c6e75b04f..f75f2223bd 100644 --- a/crates/dialogs/src/portal.rs +++ b/crates/dialogs/src/portal.rs @@ -158,13 +158,22 @@ fn answer(code: u32, results: &HashMap) -> Result) = v.try_clone().ok()?.try_into().ok()?; - Some(label) - }); + let filter = results.get("current_filter").and_then(|v| filter_label(v)); Ok(Some(Saved { path, filter })) } +/// The label of a file type as the portal sends it, a `(sa(us))` structure; `None` for a value of +/// another shape. +fn filter_label(value: &Value<'_>) -> Option { + match value { + Value::Structure(s) => match s.fields() { + [Value::Str(label), Value::Array(globs)] if globs.element_signature() == "(us)" => Some(label.to_string()), + _ => None, + }, + _ => None, + } +} + /// `file:///home/me/A%20b.psd` → `/home/me/A b.psd`; `None` for other schemes. // pc: apps/photocraft/src/portal_save.rs:134 file_uri_path fn file_uri_path(uri: &str) -> Option { diff --git a/crates/dialogs/src/portal/tests.rs b/crates/dialogs/src/portal/tests.rs index 18cbc07e8b..26cf0b788d 100644 --- a/crates/dialogs/src/portal/tests.rs +++ b/crates/dialogs/src/portal/tests.rs @@ -10,6 +10,48 @@ fn file_uris_become_local_paths() { assert_eq!(file_uri_path("file://host/x.png"), None); } +/// A `current_filter` of another shape than `(sa(us))` (a structure with fewer, other or more fields, a string) +/// gives the path alone; `uris` of another shape is an error. +#[trial] +fn an_answer_of_another_shape_is_not_read() { + let answer_with = |uris: Value<'_>, filter: Option>| { + let mut r = HashMap::new(); + r.insert("uris".to_string(), OwnedValue::try_from(uris).unwrap()); + if let Some(filter) = filter { + r.insert("current_filter".to_string(), OwnedValue::try_from(filter).unwrap()); + } + answer(0, &r) + }; + let card = || Value::from(vec!["file:///tmp/card".to_string()]); + let malformed = [ + Value::from(("PNG".to_string(),)), + Value::from(("PNG".to_string(), vec![(0u32,)])), + Value::from(("PNG".to_string(), vec![("*.png".to_string(), 0u32)])), + Value::from((1u32, vec![(0u32, "*.png".to_string())])), + Value::from(("PNG".to_string(), vec![(0u32, "*.png".to_string())], 1u32)), + Value::from("PNG"), + ]; + for filter in malformed { + let shape = filter.value_signature().to_string(); + assert_eq!(answer_with(card(), Some(filter)), Ok(Some(Saved { path: "/tmp/card".into(), filter: None })), "{shape}"); + } + // The shape the portal defines is still read, and so is the one `options` sends. + let png = Value::from(("PNG".to_string(), vec![(0u32, "*.png".to_string())])); + assert_eq!(answer_with(card(), Some(png)), Ok(Some(Saved { path: "/tmp/card".into(), filter: Some("PNG".into()) }))); + let sent = Value::from(wire(&Filter::new("Photoshop", &["psd", "psb"]))); + assert_eq!(filter_label(&sent), Some("Photoshop".into())); + let malformed = [ + Value::from(vec![1u32]), + Value::from(vec![("file:///tmp/card".to_string(),)]), + Value::from(Vec::::new()), + Value::from("file:///tmp/card"), + ]; + for uris in malformed { + let shape = uris.value_signature().to_string(); + assert!(answer_with(uris, None).is_err(), "{shape}"); + } +} + /// The name the Save dialog's answer ends up with: the picked type (`picked`, an index into `filters`) decides the /// extension a bare name takes, and an extension the user typed wins unless it is the one the dialog opened with. #[trial] From 5926d7ead3f1e6079b029fbc5fe388947b7f0ae4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 10:32:21 -0800 Subject: [PATCH 02/91] Screen: the color picker portal's answer of another shape fails the pick without a panic On Wayland the screen color picker reads the Screenshot portal's PickColor answer, whose color is a (ddd) structure. It read it with zvariant's tuple conversion, which panics inside zvariant 5.15.1 (structure.rs:382) on a structure with fewer fields than the tuple. portal_color now reads the channels only from a structure of three doubles; any other shape fails the pick with "the desktop color picker returned no color". --- crates/platform/src/screen.rs | 43 ++++++++++++++++++++++++++++++++--- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/crates/platform/src/screen.rs b/crates/platform/src/screen.rs index 0fc52b6787..8a247ab446 100644 --- a/crates/platform/src/screen.rs +++ b/crates/platform/src/screen.rs @@ -155,6 +155,19 @@ fn picked_color(rgb: [f64; 3]) -> Result { Ok(Capture::Color(rgb.map(|v| v as f32))) } +/// The colour in the portal's `PickColor` answer, a `(ddd)` structure; `None` for a value of another shape. +#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] +fn portal_color(value: &zbus::zvariant::Value<'_>) -> Option<[f64; 3]> { + use zbus::zvariant::Value; + match value { + Value::Structure(s) => match s.fields() { + [Value::F64(r), Value::F64(g), Value::F64(b)] => Some([*r, *g, *b]), + _ => None, + }, + _ => None, + } +} + /// The most pixels one monitor image may hold (64 M); larger captures fail with `Failed`. pub const MAX_PIXELS: usize = 64 * 1024 * 1024; @@ -231,7 +244,10 @@ fn unpack_rgba( #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] mod backend { - use super::{Arc, AtomicBool, Capture, MAX_MONITORS, Ordering, ScreenError, ScreenImage, add_to_budget, picked_color, pixel_count, usable_scale}; + use super::{ + Arc, AtomicBool, Capture, MAX_MONITORS, Ordering, ScreenError, ScreenImage, add_to_budget, picked_color, pixel_count, portal_color, + usable_scale, + }; const MAX_ICC_PROFILE_BYTES: usize = 1024 * 1024; /// Length limit of the property reads, in 32-bit units. @@ -437,8 +453,7 @@ mod backend { _ => return Err(failed("the desktop color picker could not sample this screen")), } let value = values.get("color").ok_or_else(|| failed("the desktop color picker returned no color"))?; - let (r, g, b): (f64, f64, f64) = value.try_clone().map_err(failed)?.try_into().map_err(|e: zbus::zvariant::Error| failed(e))?; - picked_color([r, g, b]) + picked_color(portal_color(value).ok_or_else(|| failed("the desktop color picker returned no color"))?) } } @@ -724,4 +739,26 @@ mod tests { assert!(unpack_rgba(&[0; 3], 1, 1, 4, [0, 1, 2, 3], false, true).is_err()); assert!(checked_stride(1, 1, usize::MAX).is_err()); } + + /// A `color` of another shape than `(ddd)` (a structure with fewer, other or more fields, a string, an array) + /// gives no colour; a `(ddd)` value gives its channels. + #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] + #[test] + fn a_color_of_another_shape_is_not_read() { + use zbus::zvariant::Value; + let malformed = [ + Value::from((0.5f64,)), + Value::from((0.5f64, 0.25f64)), + Value::from((0.5f64, 0.25f64, 1u32)), + Value::from(("red".to_string(), 0.25f64, 0.75f64)), + Value::from((0.5f64, 0.25f64, 0.75f64, 1.0f64)), + Value::from("red"), + Value::from(vec![0.5f64, 0.25, 0.75]), + ]; + for color in malformed { + let shape = color.value_signature().to_string(); + assert_eq!(portal_color(&color), None, "{shape}"); + } + assert_eq!(portal_color(&Value::from((0.5f64, 0.25f64, 0.75f64))), Some([0.5, 0.25, 0.75])); + } } From ed647a5d49c88c3ade7486267a329ab5d5ffb485 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:18:35 -0800 Subject: [PATCH 03/91] Canvas: the body's tool pass carries the text the editor part pastes The framework takes a paste event out of egui's input and keeps its text for the focused component, so a canvas body that applies its editor's Edit(Paste) could only read the installed clipboard, which fails where the system clipboard can't be opened (a Wayland session where arboard finds no data-control protocol). ToolPass::pasted now holds the text the platform's paste event carried in the pass of that paste: Ctrl+V's, or the one a Paste command asks the platform for. --- crates/ui-canvas/src/canvas/mod.rs | 13 ++++++++ crates/ui-canvas/tests/it/canvas/editor.rs | 36 +++++++++++++++++++++- 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index f8c7da9cab..ad3724c1bd 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -240,6 +240,8 @@ pub struct Canvas<'a> { settled: Option, /// The Menu key or Shift+F10 reached the focused canvas this pass. context_key: bool, + /// The text of the paste the editor part takes this pass, taken in `update` with its inputs. + pasted: Option>, /// The ease the app asked for from the view it drew ([`ease_from`](Self::ease_from)). ease: Option, /// The app's tool moves the view with the pointer this pass (an image-moving crop slides the view by fractional @@ -316,6 +318,7 @@ impl<'a> Canvas<'a> { snap: None, settled: None, context_key: false, + pasted: None, ease: None, follows_pointer: false, tool_regions: Vec::new(), @@ -689,6 +692,7 @@ impl<'a> Canvas<'a> { navigation: self.navigation, editor_input: self.editor_input.clone(), editor: cx.editor_handle(), + pasted: self.pasted.clone(), } } @@ -758,6 +762,11 @@ pub struct ToolPass { pub editor_input: Arc<[EditorInput]>, /// The editor part of this pass, through which the body reports its editor state; `None` without an editor. pub editor: Option, + /// The text of the paste the editor part takes this pass (its [`EditorInput::Edit`] of + /// [`EditCommand::Paste`](craft_behavior::EditCommand::Paste)), as the platform's paste event carried it: Ctrl+V's, + /// or the one a Paste command asks the platform for. The framework takes that event out of egui's input, and the + /// platform's read can succeed where the installed clipboard can't be opened. `None` in a pass without one. + pub pasted: Option>, } impl ToolPass { @@ -863,6 +872,10 @@ impl Component for Canvas<'_> { fn update(&mut self, cx: &mut Cx<'_, Self>) { // Taken once: `Cx::editor_input` empties the pass's inputs, and the body reads them from the `ToolPass`. self.editor_input = cx.editor_input().collect::>().into(); + self.pasted = match cx.clipboard().paste() { + crate::runtime::pending::Pending::Ready(content) => content.text.clone(), + _ => None, + }; // Left untaken: the canvas's generic context request is recorded as for a secondary click. self.context_key = cx.intents().untaken(&Intent::ContextMenu); // The canvas is no value component: it reads and writes its view's binding itself, as a container does. diff --git a/crates/ui-canvas/tests/it/canvas/editor.rs b/crates/ui-canvas/tests/it/canvas/editor.rs index 48153ff5f3..4cf2f9cd83 100644 --- a/crates/ui-canvas/tests/it/canvas/editor.rs +++ b/crates/ui-canvas/tests/it/canvas/editor.rs @@ -2,7 +2,7 @@ //! body through its `ToolPass`. use craft_behavior::kurbo::{Point, Size}; -use craft_behavior::{CanvasView, EditorInput, Proposal, TextPos}; +use craft_behavior::{CanvasView, EditCommand, EditorInput, Proposal, TextPos}; use craft_ui::canvas::{Canvas, tool_pass}; use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; use craft_ui::primitives::{EditorPurpose, EditorState}; @@ -88,6 +88,40 @@ fn a_canvas_editor_takes_focus_on_a_background_press_and_hands_its_inputs_to_the ); } +/// One pass's editor inputs and pasted text, as the body read them from its `ToolPass`. +type PassPaste = (Vec, Option); + +/// A paste event's text reaches the body with the editor part's paste in that pass's `ToolPass`, and in no later pass: +/// the framework takes the event out of egui's input, and the body can't read the installed clipboard where it can't +/// be opened. +#[trial] +fn a_paste_events_text_reaches_the_body_with_the_editors_paste() { + let seen: Rc>> = Rc::default(); + let shown = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let room = ui.available_rect_before_wrap(); + let view = CanvasView::new(room, Point::new(PAGE.width / 2.0, PAGE.height / 2.0), 1.0); + let _ = canvas(view).show_at(ui, room, |_, body| { + let Some(pass) = tool_pass(&body.env) else { return }; + shown.borrow_mut().push((pass.editor_input.to_vec(), pass.pasted.as_deref().map(str::to_owned))); + }); + }); + fixture.room(ROOM); + fixture.settle(); + fixture.click_at((ROOM / 2.0).to_pos2()); + seen.borrow_mut().clear(); + fixture.frame(vec![Event::Paste("from the platform".into())]); + fixture.frame(vec![]); + let passes = seen.take(); + let pasted: Vec<&PassPaste> = passes.iter().filter(|(_, text)| text.is_some()).collect(); + assert!(!pasted.is_empty(), "a pass carries the paste's text: {passes:?}"); + for (inputs, text) in &pasted { + assert_eq!(text.as_deref(), Some("from the platform")); + assert!(inputs.iter().any(|input| matches!(input, EditorInput::Edit(EditCommand::Paste))), "with the editor's paste: {inputs:?}"); + } + assert!(passes.last().is_some_and(|(_, text)| text.is_none()), "a later pass carries none: {passes:?}"); +} + /// Guards `EditorHandle::report` for an editor whose view describes its text (a page editor): its report has no lines, /// so its caret reaches the input method and no empty text is announced on the canvas's node. #[trial] From 2cde919852d239ac996621d8037a5e8645c6fdde Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 21:44:12 -0800 Subject: [PATCH 04/91] craft-docx: read and write the hide spelling and grammar errors settings Settings gains hide_spelling_errors and hide_grammar_errors, the per-document Hide spelling errors and Hide grammar errors options. craft-docx reads w:hideSpellingErrors and w:hideGrammaticalErrors from settings.xml, writes them after w:mirrorMargins and before w:proofState, and lists them as owned in the settings merge, so a saved file carries each one once and drops it when it is turned off. --- crates/docx/src/read/meta.rs | 2 ++ crates/docx/src/write/settings.rs | 7 ++++ crates/docx/src/write/settings_merge.rs | 2 ++ crates/docx/tests/it/settings_merge.rs | 47 +++++++++++++++++++++++++ crates/wordmodel/src/settings.rs | 9 +++++ 5 files changed, 67 insertions(+) diff --git a/crates/docx/src/read/meta.rs b/crates/docx/src/read/meta.rs index b9debe1fa0..a6e3c51bcb 100644 --- a/crates/docx/src/read/meta.rs +++ b/crates/docx/src/read/meta.rs @@ -24,6 +24,8 @@ impl Reader<'_> { "w:linkStyles" => s.link_styles = on_off(k), "w:removePersonalInformation" => s.remove_personal_info = on_off(k), "w:removeDateAndTime" => s.remove_date_time = on_off(k), + "w:hideSpellingErrors" => s.hide_spelling_errors = on_off(k), + "w:hideGrammaticalErrors" => s.hide_grammar_errors = on_off(k), "w:compat" => { s.allow_space_of_same_style_in_table = k.child("w:allowSpaceOfSameStyleInTable").is_some_and(on_off); // Only Word's own setting: another `w:uri` names a different application's. diff --git a/crates/docx/src/write/settings.rs b/crates/docx/src/write/settings.rs index a098174056..afd7d6a389 100644 --- a/crates/docx/src/write/settings.rs +++ b/crates/docx/src/write/settings.rs @@ -54,6 +54,13 @@ pub(super) fn settings_xml(doc: &Document, footnotes: bool, endnotes: bool, temp if s.gutter_at_top { w.empty("w:gutterAtTop", &[]); } + // After `w:gutterAtTop` and before `w:proofState` in CT_Settings. + if s.hide_spelling_errors { + w.empty("w:hideSpellingErrors", &[]); + } + if s.hide_grammar_errors { + w.empty("w:hideGrammaticalErrors", &[]); + } if let Some(id) = template_rel { w.empty("w:attachedTemplate", &[("r:id", id)]); } diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index a72046e831..2e064f05ac 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -19,6 +19,8 @@ const OWNED: &[&str] = &[ "w:displayBackgroundShape", "w:mirrorMargins", "w:gutterAtTop", + "w:hideSpellingErrors", + "w:hideGrammaticalErrors", "w:attachedTemplate", "w:linkStyles", "w:trackRevisions", diff --git a/crates/docx/tests/it/settings_merge.rs b/crates/docx/tests/it/settings_merge.rs index c07986795e..312564626c 100644 --- a/crates/docx/tests/it/settings_merge.rs +++ b/crates/docx/tests/it/settings_merge.rs @@ -163,3 +163,50 @@ fn do_not_track_moves_round_trips() { assert!(s.contains(""), "{s}"); assert!(!craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap().settings.track_moves); } + +/// Hide spelling errors and Hide grammar errors in this document only (`w:hideSpellingErrors`, +/// `w:hideGrammaticalErrors`) are read, written once each (before `w:proofState` in a merged +/// part), written in a generated part, and left out when they are turned off. +#[test] +fn hidden_proofing_errors_round_trip() { + let original = SETTINGS.replace("") < pos(&s, "")); + assert!(pos(&s, "") < pos(&s, ""), "{s}"); + assert!(pos(&s, "") < pos(&s, "") && !s.contains("hideSpellingErrors"), "{s}"); + let back = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); + assert!(back.settings.hide_grammar_errors && !back.settings.hide_spelling_errors); +} diff --git a/crates/wordmodel/src/settings.rs b/crates/wordmodel/src/settings.rs index 46faf16c36..d7689fa66d 100644 --- a/crates/wordmodel/src/settings.rs +++ b/crates/wordmodel/src/settings.rs @@ -170,6 +170,13 @@ pub struct Settings { /// comments and tracked changes are saved without `w:date`. #[serde(skip_serializing_if = "std::ops::Not::not")] pub remove_date_time: bool, + /// Hide spelling errors in this document only (`w:hideSpellingErrors`): no squiggles under + /// misspelled words. Spelling & Grammar (F7) still finds them. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub hide_spelling_errors: bool, + /// Hide grammar errors in this document only (`w:hideGrammaticalErrors`). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub hide_grammar_errors: bool, /// The document was opened from ODF: the standard's rules that differ from Word's apply as /// it is laid out. #[serde(skip_serializing_if = "Option::is_none")] @@ -333,6 +340,8 @@ impl Default for Settings { zoom: None, remove_personal_info: false, remove_date_time: false, + hide_spelling_errors: false, + hide_grammar_errors: false, odf: None, } } From 97b202c281875d53a4dee080a394c125cbaa3aaf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:22:43 -0800 Subject: [PATCH 05/91] Fit: items rank their short forms, and late ones shorten after the free items leave fit_items took every short form, last item first, before any free item left the strip. A host could not choose which items shorten first, or keep a label until the other items had gone to the overflow menu. FitItem gains two builder options: - short_order(order: u16) ranks the item's short form. Lower ranks shorten first; items of one rank shorten last item first. Every item ranks 0 by default. - short_late() keeps the item's full form until no more free items can leave. Late items then shorten in the same rank order. Items that left do not come back. Items that set neither option fit exactly as before. --- crates/behavior/src/fit.rs | 58 ++++++++++++++++++++++++++---------- crates/behavior/tests/fit.rs | 31 +++++++++++++++++++ 2 files changed, 74 insertions(+), 15 deletions(-) diff --git a/crates/behavior/src/fit.rs b/crates/behavior/src/fit.rs index 4814a0078d..ee52c7e4a7 100644 --- a/crates/behavior/src/fit.rs +++ b/crates/behavior/src/fit.rs @@ -1,6 +1,6 @@ //! The fit rules: which tabs, bar items or titles stay in a strip and which go to an overflow menu. [`fit`] and //! [`fit_whole`] assign tab widths (tabs shrink before they overflow, or keep their width); [`fit_items`] shortens -//! items that have a short form, then drops command items and titles from the end. All of them read no egui types. +//! items that have a short form, in the order their host ranks, and drops command items and titles from the end. All of them read no egui types. /// Tabs visible on a strip and tabs that need an overflow menu, all in original order. #[derive(Clone, Debug, Default, PartialEq)] @@ -230,12 +230,16 @@ pub struct FitItem { pub keep: FitKeep, /// The extent of the item's shorter form, if it has one. pub short: Option, + /// The rank of the item's short form: lower ranks shorten first, and equal ranks shorten the last item first. + pub short_order: u16, + /// Whether the item keeps its full form until no more free items can leave. + pub short_late: bool, } impl FitItem { /// An item `extent` long in `section`. pub const fn new(extent: f32, section: u16, keep: FitKeep) -> Self { - FitItem { extent, section, keep, short: None } + FitItem { extent, section, keep, short: None, short_order: 0, short_late: false } } /// The item with a shorter form `extent` long, which it takes before any free item leaves. @@ -243,6 +247,20 @@ impl FitItem { self.short = Some(extent); self } + + /// The item with its short form ranked `order`: short forms of a lower rank are taken first, and items of + /// one rank take theirs last item first. Every item ranks 0 by default. + pub const fn short_order(mut self, order: u16) -> Self { + self.short_order = order; + self + } + + /// The item takes its short form only after every free item that can leave has left, so the other items go to + /// the overflow menu before this one shortens. A free item with a late short form leaves in its turn instead. + pub const fn short_late(mut self) -> Self { + self.short_late = true; + self + } } /// Which items the strip shows and which go to the overflow menu, as indexes into the input, in input order. @@ -277,11 +295,13 @@ pub fn run_extent(items: &[FitItem], shown: &[bool], gap: f64, section_gap: f64) } /// Decides which items stay in a strip `available` long. Everything fits and no item is `Menu`: all items show. -/// Otherwise the `Menu` items are in the menu, and the items with a [`FitItem::short`] form take it first, the last -/// one first, until the run fits (listed in [`Fit::short`]); a `Pinned` item shortens as a `Free` one does. Only then -/// does the last `Free` item leave, one at a time, until the rest and an overflow control `overflow_extent` long, -/// set off by `gap`, fit; `Pinned` items stay even when they alone are longer than `available`. Items that leave are -/// never listed as short. Negative and non-finite lengths count as zero. +/// Otherwise the `Menu` items are in the menu, and the items with a [`FitItem::short`] form take it first, lowest +/// [`FitItem::short_order`] first and the last item of a rank first, until the run fits (listed in [`Fit::short`]); a +/// `Pinned` item shortens as a `Free` one does. Only then does the last `Free` item leave, one at a time, until the +/// rest and an overflow control `overflow_extent` long, set off by `gap`, fit. When no `Free` item is left to go, the +/// items marked [`FitItem::short_late`] take their short forms in the same order; items that left do not come back. +/// `Pinned` items stay even when they alone are longer than `available`. Items that leave are never listed as short. +/// Negative and non-finite lengths count as zero. pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, overflow_extent: f32) -> Fit { let (available, gap, section_gap, overflow_extent) = (item_extent(available), item_extent(gap), item_extent(section_gap), item_extent(overflow_extent)); @@ -302,19 +322,27 @@ pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, // The shadow run holds each item at the extent it takes: shortened items at their `short` extent. let mut run: Vec = items.to_vec(); let mut short = vec![false; items.len()]; - while !fits(&run, &shown) { - let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && !short[at] && items[at].short.is_some()) else { - break; - }; - short[last] = true; - if let (Some(item), Some(extent)) = (run.get_mut(last), items[last].short) { - item.extent = extent; + // Takes the short forms of the shown items with this `late` mark, lowest rank first and the last item of a rank + // first (`min_by_key` keeps the first minimum, which is the last index in a reversed scan), until the run fits. + let shorten = |late: bool, run: &mut [FitItem], short: &mut [bool], shown: &[bool]| { + while !fits(run, shown) { + let next = (0..items.len()) + .rev() + .filter(|&at| shown[at] && !short[at] && items[at].short.is_some() && items[at].short_late == late) + .min_by_key(|&at| items[at].short_order); + let Some(next) = next else { break }; + short[next] = true; + if let (Some(item), Some(extent)) = (run.get_mut(next), items[next].short) { + item.extent = extent; + } } - } + }; + shorten(false, &mut run, &mut short, &shown); while !fits(&run, &shown) { let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && items[at].keep == FitKeep::Free) else { break }; shown[last] = false; } + shorten(true, &mut run, &mut short, &shown); let (kept, left): (Vec, Vec) = (0..items.len()).partition(|&at| shown[at]); let short = kept.iter().copied().filter(|&at| short[at]).collect(); Fit { shown: kept, overflow: left, short } diff --git a/crates/behavior/tests/fit.rs b/crates/behavior/tests/fit.rs index 08cd377125..d1110a4a8a 100644 --- a/crates/behavior/tests/fit.rs +++ b/crates/behavior/tests/fit.rs @@ -64,6 +64,37 @@ fn short_items_shorten_from_the_end_before_any_item_leaves() { assert_eq!(squeezed.short.len(), 2, "pinned items shorten as free ones do: {squeezed:?}"); } +/// Guards the host's order of short forms: a lower `short_order` shortens first wherever its item sits, and a +/// `short_late` item keeps its full form until every free item has gone to the menu, then shortens in rank order. +#[test] +fn short_forms_follow_their_rank_and_late_ones_wait_for_the_free_items() { + let item = |extent| FitItem::new(extent, 0, FitKeep::Free); + let ranked = [item(50.0).short(20.0), item(50.0), item(50.0).short(20.0).short_order(1)]; + let fit = fit_items(&ranked, 120.0, 0.0, 0.0, 10.0); + assert_eq!(fit.short, [0], "the lower rank shortens before the later item: {fit:?}"); + assert!(fit.overflow.is_empty(), "{fit:?}"); + + // Two free items in one section, then two pinned ones that shorten only late, the first ranked before the second. + let pinned = |extent| FitItem::new(extent, 1, FitKeep::Pinned).short(20.0).short_late(); + let bar = [item(40.0), item(40.0), pinned(60.0), pinned(60.0).short_order(1)]; + let at = |available| fit_items(&bar, available, 0.0, 0.0, 10.0); + + let roomy = at(180.0); + assert_eq!(roomy.overflow, [1], "a free item leaves before any late item shortens: {roomy:?}"); + assert!(roomy.short.is_empty(), "{roomy:?}"); + + let tight = at(130.0); + assert_eq!(tight.overflow, [0, 1], "every free item leaves first: {tight:?}"); + assert!(tight.short.is_empty(), "{tight:?}"); + + let narrow = at(100.0); + assert_eq!(narrow.short, [2], "then the lower-ranked late item shortens: {narrow:?}"); + assert_eq!(narrow.overflow, [0, 1], "items that left stay in the menu: {narrow:?}"); + + let narrowest = at(50.0); + assert_eq!(narrowest.short, [2, 3], "then the next rank: {narrowest:?}"); +} + #[test] fn kept_selection_keeps_its_width_and_overflow_starts_at_the_end() { let natural = [80.0, 90.0, 85.0, 95.0, 70.0]; From 45515d18b536184b357ffdd1cce3eb84bf97525d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:29:19 -0800 Subject: [PATCH 06/91] craft-automation: ui.drag presses, moves in even steps and releases as one request A host app that serves the control channel can now run a whole drag from one request instead of composing ui.click with hold, ui.move steps and ui.release itself. - synthetic::Drag reads {from, to, button?, steps?, modifiers}. from and to are point objects {x?, y?, coordinates?, page?}, each in its own space; errors inside one name it (from.x ...). steps runs from 1 to MAX_DRAG_STEPS (200), default DRAG_STEPS (12). - Drag::inject resolves both points before it queues anything, then queues the press at from, the moves to to in even steps (the last one lands on to) and the release at to. The modifiers stay held through the release and are let go afterwards unless other input stays held, as after ui.click. - input_method dispatches ui.drag, so its reply waits for the release. - The crate README, docs/craft-framework.md and docs/porting.md list it. Tests: a drag with a document-point end presses at from, makes one move per step towards to, releases at to and leaves nothing held; a drag keeps its modifiers while a held key stays down; a drag whose end cannot be placed queues no press; bad drag params join the refused-input table. --- crates/automation/README.md | 2 +- crates/automation/src/synthetic.rs | 79 ++++++++++++++++++++++++- crates/automation/tests/it/synthetic.rs | 70 +++++++++++++++++++++- docs/craft-framework.md | 2 +- docs/porting.md | 2 +- 5 files changed, 147 insertions(+), 8 deletions(-) diff --git a/crates/automation/README.md b/crates/automation/README.md index d82a01e5b5..be6496ceb0 100644 --- a/crates/automation/README.md +++ b/crates/automation/README.md @@ -14,7 +14,7 @@ Features: `ui` (the egui parts), `agents` (agents in the open window: the launch | `security` | Tokens (`generate_token`, `validate_token`, `server_token`, `client_token`), the authentication handshake (`ServerHandshake`: the challenge handshake, which never sends the token, or the one-frame `auth {token}`), bounded line reads, connection and request limits. | | `protocol` | The JSON-lines wire format: one `{"id", "method", "params"}` request per line, one `{"id", "ok", "result" | "error"}` reply per line; `Params` validators that name the bad parameter. | | `control` | `ControlRequest`, `Reply`, `Dispatch` and `ControlChannel`: the UI-thread side that drains requests between frames, replies after injected input or a background job settles, and admits screenshots. The app supplies the method table. | -| `synthetic` | `Click`, `KeyPress` and `move_from_params`: the validated parameters of `ui.click`, `ui.move` and `ui.key`, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. | +| `synthetic` | `Click`, `KeyPress`, `move_from_params` and `Drag`: the validated parameters of `ui.click`, `ui.move`, `ui.key` and `ui.drag` (a press, moves in even steps and the release, from one request), and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. | | `server` | `listen` (bind a port) and `serve` (a listener bound earlier): the loopback TCP server that authenticates each connection and forwards requests to the channel, until its `Listening` is dropped. | | `client` | `ControlClient`: connect, authenticate, call (a screenshot is `call("ui.screenshot", ..)`); for integration tests and CLIs. | | `screenshot` | `Captures`: the bounded, cancellable screenshot queue over `WindowHost::screenshot`, with settling, geometry epochs, retries and the PNG reply. | diff --git a/crates/automation/src/synthetic.rs b/crates/automation/src/synthetic.rs index 96024d958c..8a2bdb184b 100644 --- a/crates/automation/src/synthetic.rs +++ b/crates/automation/src/synthetic.rs @@ -1,5 +1,5 @@ -//! Synthetic pointer, keyboard and input-method input: `ui.click`, `ui.move`, `ui.wheel`, `ui.key`, `ui.release`, -//! `ui.type`, `ui.ime` and `ui.capsLock`. +//! Synthetic pointer, keyboard and input-method input: `ui.click`, `ui.move`, `ui.drag`, `ui.wheel`, `ui.key`, +//! `ui.release`, `ui.type`, `ui.ime` and `ui.capsLock`. //! //! This module reads and validates the protocol's parameters; the window host queues the input //! ([`WindowHost::inject_move`], [`WindowHost::inject_click`], [`WindowHost::inject_wheel`], @@ -11,7 +11,8 @@ //! withdraws a step queued for a document or focus that changed before the pass consumed it. //! //! Held input: `hold: true` on `ui.click` leaves its last press down and on `ui.key` its key, until `ui.release`; a -//! `ui.move` while a button is held drags. Each request names the modifiers held during it; a move or wheel leaves +//! `ui.move` while a button is held drags. `ui.drag` is the whole gesture in one request: a press, moves in even steps +//! and the release, queued together, so its reply waits for the release. Each request names the modifiers held during it; a move or wheel leaves //! them held (a hover with modifiers across a screenshot), a click or key that holds nothing lets them go. //! //! Points are screen points (egui points), or document points with `coordinates: "document"`, which the application @@ -33,6 +34,12 @@ pub const MAX_CLICKS: u64 = 256; /// display, yet small enough that egui's pointer delta between two such points stays finite. pub const MAX_SCREEN_POINT: f64 = 1e6; +/// Most moves one `ui.drag` may ask for (`steps`). +pub const MAX_DRAG_STEPS: u64 = 200; + +/// The moves a `ui.drag` makes when its request names no `steps`. +pub const DRAG_STEPS: u64 = 12; + /// The longest hover rest one `ui.move` may ask for (`rest`, seconds). pub const MAX_REST: f64 = 10.0; @@ -192,6 +199,71 @@ impl Move { } } +/// A validated `ui.drag`: a press at one point, moves in even steps to another with the button down, and the release +/// there. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct Drag { + /// Where the button goes down. + pub from: At, + /// Where the button comes up. + pub to: At, + /// The button pressed. + pub button: PointerButton, + /// Moves from `from` to `to`; the last one lands on `to`. + pub steps: u64, + /// Modifiers held from the press to the release. + pub mods: Mods, +} + +impl Drag { + /// `{from, to, button?, steps?, modifiers…}`, no other fields. `from` and `to` are each a point object + /// `{x?, y?, coordinates?, page?}` in its own space, as `ui.click` reads its point; a missing one is + /// ``"missing `from`"``, and the errors inside one name it (``"from.x must be a finite number"``). `button` + /// defaults to `left`. `steps` is an unsigned integer from 1 to [`MAX_DRAG_STEPS`], default [`DRAG_STEPS`]; + /// outside that range is ``"`steps` must be between 1 and 200 (got {steps})"``. + pub fn from_params(params: &Value) -> Result { + let p = Params(params).only(None, &["from", "to", "button", "steps", "modifiers", "shift", "alt", "command", "ctrl"])?; + let p = Params(&p); + let point = |name: &str| -> Result { + let Some(point) = p.0.get(name) else { return Err(format!("missing `{name}`")) }; + let point = Params(point).only(Some(name), &POINT)?; + At::from_params(&Params(&point)).map_err(|error| format!("{name}.{error}")) + }; + let steps = p.uint_field("steps")?.unwrap_or(DRAG_STEPS); + if !(1..=MAX_DRAG_STEPS).contains(&steps) { + return Err(format!("`steps` must be between 1 and {MAX_DRAG_STEPS} (got {steps})")); + } + Ok(Self { + from: point("from")?, + to: point("to")?, + button: button(&p)?.unwrap_or(PointerButton::Primary), + steps, + mods: p.modifiers(&KEY_MODIFIERS)?, + }) + } + + /// Queues a move to `from` and a press there, `steps` moves in even steps to `to` with the button held, and the + /// release at `to`, in `viewport`; the modifiers are then let go unless other input stays held, as after a click. + /// Both points are resolved before anything is queued, so a point that cannot be placed leaves no press down. + /// When the host withdraws the rest of the gesture after its press ran, the button stays down until `ui.release`, + /// as any held input does. + pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> { + let (from, to) = (self.from.resolve(map)?, self.to.resolve(map)?); + let steps = u16::try_from(self.steps).unwrap_or(u16::MAX); + host.inject_click(viewport, from, self.button, 1, self.mods, true); + for step in 1..=steps { + let at = if step == steps { to } else { from.lerp(to, f32::from(step) / f32::from(steps)) }; + host.inject_move(viewport, at, self.mods, 0.0); + } + host.inject_release(viewport, Some(to), Released::Button(self.button)); + // A click of no presses at the pointer's place queues no event: it only lets the modifiers go when nothing + // stays held. + host.inject_click(viewport, to, self.button, 0, self.mods, false); + Ok(()) + } +} + /// A validated `ui.wheel`. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] @@ -304,6 +376,7 @@ pub fn input_method(method: &str, params: &Value, host: &WindowHost, viewport: V Some(match method { "ui.click" => Click::from_params(params).and_then(|click| click.inject(host, viewport, map)), "ui.move" => Move::from_params(params).and_then(|step| step.inject(host, viewport, map)), + "ui.drag" => Drag::from_params(params).and_then(|drag| drag.inject(host, viewport, map)), "ui.wheel" => Wheel::from_params(params).and_then(|wheel| wheel.inject(host, viewport, map)), "ui.key" => KeyPress::from_params(params).map(|key| key.inject(host, viewport)), "ui.release" => Release::from_params(params).and_then(|release| release.inject(host, viewport, map)), diff --git a/crates/automation/tests/it/synthetic.rs b/crates/automation/tests/it/synthetic.rs index 494cc848dd..aa70cb1439 100644 --- a/crates/automation/tests/it/synthetic.rs +++ b/crates/automation/tests/it/synthetic.rs @@ -1,11 +1,11 @@ -//! Synthetic input through the window host: held presses and keys, modifiers, the wheel, Caps Lock, hover rest, +//! Synthetic input through the window host: held presses and keys, drags, modifiers, the wheel, Caps Lock, hover rest, //! document coordinates and input-method compositions, as the passes see them, and the params refused before //! anything is queued. use std::cell::{Cell, RefCell}; use std::rc::Rc; -use craft_automation::synthetic::{At, MAX_CLICKS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method}; +use craft_automation::synthetic::{At, MAX_CLICKS, MAX_DRAG_STEPS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method}; use craft_ui::contract::{Bind, Show as _}; use craft_ui::runtime::egui::injected::hook_without_pass; use craft_ui::runtime::windows::WindowHost; @@ -122,6 +122,52 @@ fn a_held_press_stays_down_until_its_release() { assert!(!rig.now().primary_down, "a click without hold releases"); } +/// `ui.drag` presses at `from`, moves to `to` in `steps` even steps with the button down, releases at `to` with its +/// modifiers held throughout, then lets them go. Each point is in its own space: `to` here is a document point. +#[trial] +fn a_drag_presses_moves_in_steps_and_releases_at_its_end() { + let mut rig = Rig::new(); + rig.fx.settle(); + rig.take(); + let to = map(0, pos2(220.0, 40.0)).expect("the test map places every point"); + rig.send("ui.drag", json!({"from": {"x": 10, "y": 20}, "to": {"x": 220, "y": 40, "coordinates": "document"}, "steps": 4, "shift": true})); + let after = rig.now(); + let events: Vec = rig.take().into_iter().flat_map(|pass| pass.events).collect(); + let buttons: Vec<(Pos2, bool, bool)> = events + .iter() + .filter_map(|event| match event { + Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers } => Some((*pos, *pressed, modifiers.shift)), + _ => None, + }) + .collect(); + assert_eq!(buttons, vec![(pos2(10.0, 20.0), true, true), (to, false, true)], "one press at `from`, one release at `to`, both with Shift"); + let held = events.iter().skip_while(|event| !matches!(event, Event::PointerButton { pressed: true, .. })); + let moves: Vec = held + .take_while(|event| !matches!(event, Event::PointerButton { pressed: false, .. })) + .filter_map(|event| match event { + Event::PointerMoved(at) => Some(*at), + _ => None, + }) + .collect(); + assert_eq!(moves.len(), 4, "one move per step while the button is down: {moves:?}"); + assert!(moves.windows(2).all(|pair| pair[1].x > pair[0].x), "each step goes further towards `to`: {moves:?}"); + assert_eq!(moves.last(), Some(&to), "the last step lands on `to`"); + assert!(!after.primary_down && !after.shift, "the drag leaves no button or modifier held"); +} + +/// A drag keeps its modifiers held after its release while other input stays down, as a click does. +#[trial] +fn a_drag_keeps_its_modifiers_while_a_held_key_stays_down() { + let mut rig = Rig::new(); + rig.send("ui.key", json!({"key": "Space", "hold": true})); + rig.send("ui.drag", json!({"from": {"x": 10, "y": 10}, "to": {"x": 60, "y": 10}, "steps": 2, "shift": true})); + let after = rig.now(); + assert!(after.space_down && !after.primary_down, "the key stays down and the drag's button is up"); + assert!(after.shift, "the modifiers stay with the held key"); + rig.send("ui.release", json!({})); + assert!(!rig.now().space_down && !rig.now().shift, "the release lets everything go"); +} + /// A move's modifiers stay held after it (a hover with modifiers); a click that holds nothing lets its own go. #[trial] fn a_move_keeps_its_modifiers_and_a_click_lets_them_go() { @@ -291,6 +337,19 @@ fn document_points_need_a_canvas() { assert_eq!(screen, Some(Ok(()))); } +/// A drag whose end cannot be placed is refused whole: its press at a screen point is not queued either. +#[trial] +fn a_drag_with_an_end_it_cannot_place_queues_no_press() { + let mut rig = Rig::new(); + rig.fx.settle(); + let (host, ctx) = (rig.host(), rig.fx.ctx().clone()); + let none = |_: usize, _: Pos2| None; + let params = json!({"from": {"x": 1, "y": 1}, "to": {"x": 5, "y": 5, "coordinates": "document"}}); + assert_eq!(input_method("ui.drag", ¶ms, &host, ViewportId::ROOT, &none), Some(Err(NO_DOCUMENT.to_owned()))); + assert!(host.injected_idle()); + assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "the refused drag queued nothing"); +} + /// A step handed to the input whose pass has not run is withdrawn when the focus moved, and when the application /// withdraws the input because its document changed: the integration's preserved copy leaves the input, no key /// stays down, and the waiters fail with `TARGET_CHANGED`. @@ -356,6 +415,13 @@ fn bad_input_params_are_refused_before_anything_is_queued() { ("ui.move", json!({"x": 10, "rest": "long"})), ("ui.move", json!({"x": 10, "coordinates": "page"})), ("ui.move", json!({"y": -far})), + ("ui.drag", json!({"from": {"x": 10}})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20, "nudge": 1}})), + ("ui.drag", json!({"from": {"x": 10}, "to": [20, 20]})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": far}})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "steps": 0})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "steps": MAX_DRAG_STEPS + 1})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "x": 5})), ("ui.key", json!({"key": "A", "hold": true, "nudge": 1})), ("ui.key", json!({"key": 5})), ("ui.key", json!({"key": "NoSuchKey", "hold": true})), diff --git a/docs/craft-framework.md b/docs/craft-framework.md index 5e24eaacdc..0c87b65c8a 100644 --- a/docs/craft-framework.md +++ b/docs/craft-framework.md @@ -1124,7 +1124,7 @@ Control channel, screenshot queue, profiler and recorded actions for tests and s | `server` | Loopback JSON-lines TCP transport (native): `listen`, `serve`, stopped by dropping its `Listening` | exists | | `agents`, `ui::agents` | AI agents in the open window: the agent settings, the ArtCraft Launcher's switch, the connection file and the CLI's live client (re-exported from `craft-control`), the link host and the Agents page of Preferences | exists | | `client` | JSON-lines client for tests and command-line tools (native) | exists | -| `synthetic` | Synthetic pointer and keyboard input: `ui.click`, `ui.move`, `ui.key`, `ui.type` | exists | +| `synthetic` | Synthetic pointer and keyboard input: `ui.click`, `ui.move`, `ui.drag`, `ui.key`, `ui.type` | exists | | `dialogs` | `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` over a `DialogHost` | exists | | `profiler` | Frame profiler | exists | | `screenshot` | Screenshot request queue | exists | diff --git a/docs/porting.md b/docs/porting.md index f7a03e41bd..fdd9301051 100644 --- a/docs/porting.md +++ b/docs/porting.md @@ -130,7 +130,7 @@ The old app is the visual reference, but not automatically right: judge each dif | Command-line values | `args::ControlOptions`, `EnvNames` | Parses its own flags and calls `ControlOptions::resolve` | | Transport | `server::listen`, `server::serve`, `ControlClient` | Calls `listen` (or `serve` on a listener it bound earlier), keeps the `Listening` and owns the `ControlChannel` | | Request queue, replies | `ControlChannel`, `Reply`, `result_reply` | Runs each request and returns a `Reply` | -| Input methods | `synthetic::Click`, `KeyPress`, `move_from_params`: the checked parameters of `ui.click`, `ui.key`, `ui.move` | Dispatches the method names to them | +| Input methods | `synthetic::Click`, `KeyPress`, `move_from_params`, `Drag`: the checked parameters of `ui.click`, `ui.key`, `ui.move`, `ui.drag` | Dispatches the method names to them | | Dialog methods | `dialogs`: `ui.dialog.set`, `ui.dialog.confirm`, `ui.dialog.cancel` and the dialog list | Dispatches them; may add `ui.dialog.open` for its own dialog kinds | | Screenshots | `Captures` (the bounded queue), `screenshot_reply`, PNG encoding | Allocates a token for `ui.screenshot`, drives the queue each frame, supplies the file writer | | View and window state | nothing | Methods such as `ui.set` (tool, panels, theme), `ui.resize`, `engine.execute` | From 6c33621a06715619e8a82d1bc6e01ccfdbaa32fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:30:38 -0800 Subject: [PATCH 07/91] Menu bar: the output reports the width every title takes side by side craft_ui::menu::MenuBarOutput and craft_menu::MenuBarOutput gain a `natural: f32` field: the width of every title side by side with none in the "..." menu, whatever room the bar had. `titles` stays the rect of the titles drawn. A host that puts controls after the titles on the same row compares `natural` with the room it leaves the bar, and can narrow its own controls before titles fold. The field is zero while the bar shows nothing (ScreenTop), and a memoized replay keeps it. Trials: a bar in a wide and a narrow rect (craft-ui-widgets) and MenuBarUi in a wide and a narrow Stack (craft-menu) report the same natural width, equal to the titles' width when all fit and larger than the drawn titles when some fold. --- crates/menu/README.md | 4 ++- crates/menu/src/bar.rs | 12 ++++++--- crates/menu/tests/it/title_bar.rs | 30 ++++++++++++++++++++- crates/ui-widgets/src/menu/bar.rs | 14 +++++++--- crates/ui-widgets/tests/it/menu/bar.rs | 36 +++++++++++++++++++++++++- 5 files changed, 86 insertions(+), 10 deletions(-) diff --git a/crates/menu/README.md b/crates/menu/README.md index cb82dc8f9e..307cd092ad 100644 --- a/crates/menu/README.md +++ b/crates/menu/README.md @@ -132,7 +132,9 @@ app translates. The dialog never opens a file dialog or touches the file system. ## Windows, Linux and web: the in-window bar -`MenuBarUi` draws a laid-out bar and returns the titles' rect (`MenuBarOutput`). Show it inside a +`MenuBarUi` draws a laid-out bar and returns the titles' rect and the width every title takes side by +side (`MenuBarOutput`). A host that puts controls after the titles on the same row compares that +width with the room it leaves the bar. Show it inside a `Stack` (a top panel's body) or the title bar's row: there the titles that don't fit its room fold into "…". Each item is a command row: its enabled state, check mark and chord follow the command in the diff --git a/crates/menu/src/bar.rs b/crates/menu/src/bar.rs index 4b2c81e742..9ea75cec33 100644 --- a/crates/menu/src/bar.rs +++ b/crates/menu/src/bar.rs @@ -48,11 +48,11 @@ pub(crate) fn keymap_platform(target: Target, os: Platform) -> Platform { /// A replay at another place moves the titles' rect with the bar. impl craft_ui::runtime::Shift for MenuBarOutput { fn shifted(&self, by: &egui::RecordShift) -> Self { - MenuBarOutput { titles: by.rect(self.titles) } + MenuBarOutput { titles: by.rect(self.titles), natural: self.natural } } fn snapped(&self, to: &Self, within: f32) -> Self { - MenuBarOutput { titles: craft_ui::runtime::Shift::snapped(&self.titles, &to.titles, within) } + MenuBarOutput { titles: craft_ui::runtime::Shift::snapped(&self.titles, &to.titles, within), natural: self.natural } } } @@ -63,6 +63,9 @@ pub struct MenuBarOutput { /// The menu titles alone, without the room the bar leaves after them /// ([`craft_ui::menu::MenuBarOutput::titles`]). pub titles: Rect, + /// The width every title takes side by side with none in "…", whatever room the bar had + /// ([`craft_ui::menu::MenuBarOutput::natural`]). Zero when the bar shows nothing. + pub natural: f32, } /// The bar for one frame: `MenuBarUi::new(&bar).show(ui)`. Draw it at the top of the window, inside a `Stack` (a top @@ -145,7 +148,7 @@ impl<'a> MenuBarUi<'a> { help, label: env.words::().label.clone(), }; - MemoView::new("menu-bar", props, show_bar).show(ui).unwrap_or(MenuBarOutput { titles: Rect::NOTHING }) + MemoView::new("menu-bar", props, show_bar).show(ui).unwrap_or(MenuBarOutput { titles: Rect::NOTHING, natural: 0.0 }) } } @@ -182,7 +185,8 @@ fn show_bar(props: &mut BarProps<'_>, ui: &mut Ui) -> MenuBarOutput { if let Some(menu) = props.help { bar = bar.help(MenuHelp::new(menu, &entries)); } - MenuBarOutput { titles: bar.show(ui).titles } + let shown = bar.show(ui); + MenuBarOutput { titles: shown.titles, natural: shown.natural } } /// What the kept text of a bar is made of: the model, the platform that names its shortcuts, the preferred mnemonics, diff --git a/crates/menu/tests/it/title_bar.rs b/crates/menu/tests/it/title_bar.rs index 1e79bf5c18..15543e8d97 100644 --- a/crates/menu/tests/it/title_bar.rs +++ b/crates/menu/tests/it/title_bar.rs @@ -1,6 +1,7 @@ //! The in-window menu bar in an app's title bar: every title shows while the bar has room for them, the document title //! takes the rest of the bar, and only a bar too narrow for every title folds the last into "…". In a `Stack` -//! narrower than its titles the bar folds the same way and draws nothing past the stack's edge. +//! narrower than its titles the bar folds the same way and draws nothing past the stack's edge. In any room the bar +//! reports the width its titles take side by side. use std::cell::Cell; use std::rc::Rc; @@ -131,3 +132,30 @@ fn a_bar_in_a_stack_narrower_than_its_titles_folds_them_and_draws_nothing_past_i fixture.click(&more).settle(); assert!(fixture.by_label("Help").is_some(), "Help is a row of the \"…\" menu"); } + +/// The bar reports the width every title takes side by side: in a stack that holds them all it is the titles' width, +/// and in a stack too narrow for them it is the same width while the drawn titles are narrower. +#[trial] +fn the_bar_reports_the_width_every_title_takes_in_a_wide_and_a_narrow_stack() { + let mut reports = Vec::new(); + for width in [1520.0, 240.0] { + let bar = Rc::new(model()); + let seen = Rc::new(Cell::new((0.0, 0.0))); + let out = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let bar = Rc::clone(&bar); + let out = Rc::clone(&out); + Stack::new().show(ui, move |ui, _| { + let shown = MenuBarUi::new(&bar).target(Target::Windows).show(ui); + out.set((shown.natural, shown.titles.width())); + }); + }); + fixture.os(Os::Windows).room(vec2(width, 600.0)).settle(); + reports.push(seen.get()); + } + let [(wide, wide_titles), (narrow, narrow_titles)] = [reports[0], reports[1]]; + assert!(wide > 0.0, "the bar reports a width"); + assert!((wide - wide_titles).abs() < 0.5, "with room for every title the natural width {wide} is the titles' width {wide_titles}"); + assert!((narrow - wide).abs() < 0.5, "a narrow bar reports the same natural width {narrow} as a wide one {wide}"); + assert!(narrow_titles < narrow, "a narrow bar draws titles {narrow_titles} narrower than its natural width {narrow}"); +} diff --git a/crates/ui-widgets/src/menu/bar.rs b/crates/ui-widgets/src/menu/bar.rs index c74ef97b5c..dced87415a 100644 --- a/crates/ui-widgets/src/menu/bar.rs +++ b/crates/ui-widgets/src/menu/bar.rs @@ -209,6 +209,10 @@ pub struct MenuBarOutput { pub open: bool, /// The titles alone (with "…" when it shows), from the first title's reading start to the last title's end. pub titles: Rect, + /// The width every title takes side by side with none in "…", whatever room the bar had: a host that places + /// controls after the titles on the same row compares it with the room it leaves the bar. Zero when the bar + /// shows nothing (`MenuPlacement::ScreenTop`). + pub natural: f32, } impl Outcome for MenuBarOutput { @@ -304,12 +308,14 @@ pub struct MenuBar<'a> { #[prop] keyboard: bool, open: bool, + /// The width of every title side by side, from this pass's measure or parts step. + natural: f32, } impl<'a> MenuBar<'a> { /// A bar named `label` with one title per menu, in reading order. pub fn new(label: impl Into