diff --git a/crates/platform/src/clipboard/offer/macos.rs b/crates/platform/src/clipboard/offer/macos.rs index 7faa00a61..ed4153b98 100644 --- a/crates/platform/src/clipboard/offer/macos.rs +++ b/crates/platform/src/clipboard/offer/macos.rs @@ -68,6 +68,8 @@ pub(super) fn write(handle: &mut arboard::Clipboard, state: &mut State, plan: &P string("public.html", &html.text); } } + // arboard's file list is the whole copy. + Primary::Files => {} } state.change = Some(board.changeCount()); Ok(index) diff --git a/crates/platform/src/clipboard/offer/mod.rs b/crates/platform/src/clipboard/offer/mod.rs index cb7fe0736..085469882 100644 --- a/crates/platform/src/clipboard/offer/mod.rs +++ b/crates/platform/src/clipboard/offer/mod.rs @@ -26,8 +26,8 @@ use self::windows as platform; use std::borrow::Cow; use super::backend::{Decode, system_error}; -use super::convert::rgba8_image; -use super::types::{ClipboardError, ClipboardImage, Flavor, HTML, MATHML, PNG, RGBA8, RTF, TEXT}; +use super::convert::{parse_uri_list, rgba8_image}; +use super::types::{ClipboardError, ClipboardImage, Flavor, HTML, MATHML, PNG, RGBA8, RTF, TEXT, URI_LIST}; /// The platform's offer state: the cached X11 `TARGETS` connection and the macOS change count recorded at a write. pub(super) struct Offer { @@ -55,6 +55,12 @@ struct Picture<'a> { png: Option<&'a [u8]>, } +/// The copied files a write offers: the local paths of the first file list that names any. +struct FileList { + index: usize, + paths: Vec, +} + /// What a write puts on the clipboard: the first flavour of each kind among the caller's. struct Plan<'a> { text: Option>, @@ -62,13 +68,16 @@ struct Plan<'a> { rtf: Option>, mathml: Option>, picture: Option>, + files: Option, } -/// Which of a plan's two shapes a write takes: arboard holds a bitmap or rich text, not both. -#[derive(Clone, Copy, PartialEq, Eq)] +/// Which of a plan's shapes a write takes: arboard holds a bitmap, rich text or a file list, one of them. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] enum Primary { Picture, Rich, + /// Copied files, the way a file manager's Copy puts them. + Files, } impl<'a> Plan<'a> { @@ -89,18 +98,26 @@ impl<'a> Plan<'a> { }?; pixels.is_whole().then_some(Picture { index, pixels, png }) }); - Self { text: part(TEXT), html: part(HTML), rtf: part(RTF), mathml: part(MATHML), picture } + // Only `file:` URIs become files; a list that names none leaves the write to the other flavours. + let files = flavors.iter().enumerate().find_map(|(index, flavor)| { + let paths = (flavor.mime == URI_LIST).then(|| parse_uri_list(&String::from_utf8_lossy(&flavor.data)))?; + (!paths.is_empty()).then_some(FileList { index, paths }) + }); + Self { text: part(TEXT), html: part(HTML), rtf: part(RTF), mathml: part(MATHML), picture, files } } - /// The shape of the write: whichever of the bitmap and the HTML or text the caller put first. + /// The shape of the write: whichever of the bitmap, the HTML or text and the file list the caller put first. fn primary(&self) -> Option { let rich = [&self.html, &self.text].into_iter().flatten().map(|part| part.index).min(); - match (self.picture.as_ref().map(|picture| picture.index), rich) { - (Some(picture), Some(rich)) if rich < picture => Some(Primary::Rich), - (Some(_), _) => Some(Primary::Picture), - (None, Some(_)) => Some(Primary::Rich), - (None, None) => None, - } + [ + self.picture.as_ref().map(|picture| (picture.index, Primary::Picture)), + rich.map(|index| (index, Primary::Rich)), + self.files.as_ref().map(|files| (files.index, Primary::Files)), + ] + .into_iter() + .flatten() + .min_by_key(|&(index, _)| index) + .map(|(_, primary)| primary) } } @@ -127,6 +144,11 @@ fn arboard_write(handle: &mut arboard::Clipboard, plan: &Plan<'_>) -> Result<(us } (None, None) => Err(ClipboardError::NoFormat), }, + Primary::Files => { + let files = plan.files.as_ref().ok_or(ClipboardError::NoFormat)?; + handle.set().file_list(&files.paths).map_err(system_error)?; + Ok((files.index, Primary::Files)) + } } } diff --git a/crates/platform/src/clipboard/offer/tests.rs b/crates/platform/src/clipboard/offer/tests.rs index cd667d8f6..d102c6e45 100644 --- a/crates/platform/src/clipboard/offer/tests.rs +++ b/crates/platform/src/clipboard/offer/tests.rs @@ -26,3 +26,35 @@ fn cf_html_offsets_delimit_the_fragment_bytes() { assert_eq!(&data[end_html..], b"\0", "EndHTML excludes the trailing NUL"); assert_eq!(end_html, data.len() - 1); } + +// Copied files reach the system clipboard as a file list holding the same paths, spaces and +// non-ASCII names included; a URI that names no local file is never written as one, and a list +// with no file in it leaves the write to the next flavour. +#[test] +fn a_file_list_is_written_as_files() { + use super::{Plan, Primary}; + use crate::clipboard::types::{Flavor, URI_LIST}; + + let paths = vec![std::env::temp_dir().join("a b#1.pdf"), std::env::temp_dir().join("café 100%.png")]; + let flavors = [Flavor::files(&paths), Flavor::text("names")]; + let plan = Plan::new(&flavors, None); + assert_eq!(plan.primary(), Some(Primary::Files)); + assert_eq!(plan.files.as_ref().map(|files| (files.index, files.paths.clone())), Some((0, paths.clone()))); + + let mut mixed = b"# copied\r\nhttps://example.com/a.pdf\r\n".to_vec(); + mixed.extend(Flavor::files(&paths[..1]).data); + let flavors = [Flavor::new(URI_LIST, mixed)]; + let plan = Plan::new(&flavors, None); + assert_eq!(plan.primary(), Some(Primary::Files)); + assert_eq!(plan.files.as_ref().map(|files| files.paths.clone()), Some(paths[..1].to_vec())); + + let flavors = [Flavor::new(URI_LIST, b"https://example.com/a.pdf\r\n".to_vec()), Flavor::text("names")]; + let plan = Plan::new(&flavors, None); + assert!(plan.files.is_none()); + assert_eq!(plan.primary(), Some(Primary::Rich)); + assert_eq!(plan.text.as_ref().map(|text| text.index), Some(1)); + + // Text put first stays the write's shape even with files beside it. + let flavors = [Flavor::text("names"), Flavor::files(&paths)]; + assert_eq!(Plan::new(&flavors, None).primary(), Some(Primary::Rich)); +} diff --git a/crates/platform/src/clipboard/offer/unix.rs b/crates/platform/src/clipboard/offer/unix.rs index 9539d4200..ab8eef8a5 100644 --- a/crates/platform/src/clipboard/offer/unix.rs +++ b/crates/platform/src/clipboard/offer/unix.rs @@ -127,6 +127,8 @@ fn wayland_write(plan: &Plan<'_>, owner: &[u8]) -> Result, Clipboa let Some((index, png)) = plan.picture.as_ref().and_then(|picture| Some((picture.index, picture.png?))) else { return Ok(None) }; [Some((index, PNG, png.to_vec())), text(&plan.html, HTML), text(&plan.text, UTF8_TEXT)].into_iter().flatten().collect() } + // arboard offers a file list with the names file managers read (`text/uri-list` and GNOME's own). + Some(Primary::Files) => return Ok(None), // The text first: the plain-text aliases serve the first text type offered. _ => [text(&plan.text, UTF8_TEXT), text(&plan.html, HTML), text(&plan.rtf, RTF), text(&plan.mathml, MATHML)].into_iter().flatten().collect(), }; diff --git a/crates/platform/src/clipboard/offer/windows.rs b/crates/platform/src/clipboard/offer/windows.rs index 643974906..770a7847d 100644 --- a/crates/platform/src/clipboard/offer/windows.rs +++ b/crates/platform/src/clipboard/offer/windows.rs @@ -94,6 +94,8 @@ pub(super) fn write(handle: &mut arboard::Clipboard, state: &mut State, plan: &P add(HTML_FORMAT, &wrap_cf_html(&html.text)); } } + // arboard's file list is the whole copy. + Primary::Files => {} } state.unmarked = !add(OWNER_FORMAT, owner); Ok(index) diff --git a/crates/print/src/ui/dialog.rs b/crates/print/src/ui/dialog.rs index 1e3aa2613..ed20fad3a 100644 --- a/crates/print/src/ui/dialog.rs +++ b/crates/print/src/ui/dialog.rs @@ -733,6 +733,9 @@ pub struct PrintDialog<'a> { /// The pager under the sheet preview in the `Document` layout. #[prop] preview_pager: Option, + /// The printer list searches a long fleet ([`PrintPanel::printer_search`]). + #[prop] + printer_search: bool, /// Makes Print keep the dialog open and report its press in `PrintDialogOutput::held`. #[prop(vis = "pub(crate)")] hold_ok: bool, @@ -801,6 +804,7 @@ impl<'a> PrintDialog<'a> { driver: DriverControls::None, duplex_by_layout: false, preview_pager: None, + printer_search: false, hold_ok: false, finish_held: false, refusal: None, @@ -826,6 +830,7 @@ impl<'a> PrintDialog<'a> { driver, duplex_by_layout, preview_pager, + printer_search, hold_ok, finish_held, refusal, @@ -883,6 +888,7 @@ impl<'a> PrintDialog<'a> { .destinations(destinations) .duplex_by_layout(duplex_by_layout) .inline(document) + .printer_search(printer_search) .show(ui); refresh |= panel.refresh; settings_clicked |= panel.settings_clicked; @@ -1005,6 +1011,7 @@ pub struct HostedPrint { driver: DriverControls, duplex_by_layout: bool, preview_pager: Option, + printer_search: bool, /// The destination the user picked, or automation set, not taken yet. printer_chosen: Option, /// Whether Print files its answer for the app instead of closing. @@ -1038,6 +1045,7 @@ impl HostedPrint { driver: DriverControls::None, duplex_by_layout: false, preview_pager: None, + printer_search: false, printer_chosen: None, hold: false, held: HeldAnswer::new(), @@ -1146,6 +1154,11 @@ impl HostedPrint { self.preview_pager = pager; } + /// Whether the printer list searches a long fleet ([`PrintPanel::printer_search`]). + pub fn set_printer_search(&mut self, on: bool) { + self.printer_search = on; + } + /// The pager press since the last call. pub fn take_preview_step(&mut self) -> Option { self.requests.take_preview_step() @@ -1248,6 +1261,7 @@ impl StackDialog for HostedPrint { .layout(self.layout) .driver(self.driver) .duplex_by_layout(self.duplex_by_layout) + .printer_search(self.printer_search) .hold_ok(self.hold) .finish_held(finish_held); if let Some(pager) = self.preview_pager.clone() { diff --git a/crates/print/src/ui/panel.rs b/crates/print/src/ui/panel.rs index d6bfb7c68..092080fc8 100644 --- a/crates/print/src/ui/panel.rs +++ b/crates/print/src/ui/panel.rs @@ -42,6 +42,8 @@ craft_ui::words! { save_as_pdf: "printPanel.saveAsPdf" = "Save as PDF"; default_mark: "printPanel.defaultMark" = "(default)"; finding: "printPanel.finding" = "Finding printers…"; + search_printers: "printPanel.searchPrinters" = "Search printers"; + no_printers_match: "printPanel.noPrintersMatch" = "No printers match."; } } @@ -138,8 +140,16 @@ pub struct PrintPanel<'a> { /// Why the driver gave no page. #[prop] page_error: Option, + /// The printer list is for a long fleet: a "Search printers" field heads it, focused as it opens, and narrows the + /// printers by their names (case and accents ignored) while Save as PDF stays at the end; typing changes no choice, + /// only a pick does, and the open list is wide enough for long names (PRINTER_LIST_WIDTH, within the screen). + #[prop] + printer_search: bool, } +/// How wide a searchable printer list opens, in points: room for a long network queue's name. +pub const PRINTER_LIST_WIDTH: f32 = 430.0; + impl<'a> PrintPanel<'a> { /// The panel over `settings`, offering `printers`. pub fn new(settings: Bind<'a, Settings>, printers: &'a [Printer]) -> Self { @@ -154,12 +164,14 @@ impl<'a> PrintPanel<'a> { inline: false, page: None, page_error: None, + printer_search: false, } } /// Shows the panel. pub fn show(self, ui: &mut Ui) -> PrintPanelOutput { - let PrintPanel { settings, printers, discovering, busy, driver, destinations, duplex_by_layout, inline, page, page_error } = self; + let PrintPanel { settings, printers, discovering, busy, driver, destinations, duplex_by_layout, inline, page, page_error, printer_search } = + self; let env = Env::of(ui); let words = env.words::(); let mut queues: Vec> = printers @@ -193,10 +205,20 @@ impl<'a> PrintPanel<'a> { let mut now = before.clone(); Field::new(words.printer.clone()).id_salt("printer").show(ui, |ui, _| { Row::new().show(ui, |ui, _| { - let picked = Select::new(words.printer.clone(), Bind::given(now.destination.clone()), &queues) + let select = Select::new(words.printer.clone(), Bind::given(now.destination.clone()), &queues) .placeholder(placeholder.clone()) - .id_salt("queue") - .show(ui); + .id_salt("queue"); + let select = if printer_search { + select + .searchable() + .search_label(words.search_printers.clone()) + .no_matches(words.no_printers_match.clone()) + .search_kept(|destination: &Destination| *destination == Destination::File) + .list_width(PRINTER_LIST_WIDTH) + } else { + select + }; + let picked = select.show(ui); if let Some(destination) = picked.value() { if *destination != now.destination { printer_chosen = Some(destination.clone()); diff --git a/crates/print/tests/it/panel.rs b/crates/print/tests/it/panel.rs index 9965f7eb5..cfdd874ef 100644 --- a/crates/print/tests/it/panel.rs +++ b/crates/print/tests/it/panel.rs @@ -53,3 +53,103 @@ fn a_printer_with_its_own_dialog_disables_the_job_controls() { pick(&mut fixture, "Browser", "Office"); assert_eq!(disabled(&fixture), [false; 4], "a printer without its own dialog enables them again"); } + +/// The long last queue of the trial fleet. +const LAST: &str = "München Satellite 119 - Engineering floor 4 (network queue) - colour duplex device, Building North"; + +/// A searchable panel over a fleet of 120 queues, Save as PDF after them, the first queue the default and chosen; the +/// settings it edits. +fn fleet(room: Vec2) -> (Fixture, Rc>) { + use craft_print::ui::Destinations; + let settings = Rc::new(RefCell::new(Settings::default())); + let first = "Office 000 - Engineering floor 4 (network queue)"; + settings.borrow_mut().destination = Destination::Printer(first.into()); + let shown = Rc::clone(&settings); + let mut printers: Vec = + (0..119).map(|i| Printer::new(format!("Office {i:03} - Engineering floor 4 (network queue)")).is_default(i == 0)).collect(); + printers.push(Printer::new(LAST)); + let mut fixture = Fixture::new(move |ui| { + let _ = PrintPanel::new(Bind::bound(&mut *shown.borrow_mut()), &printers) + .destinations(Destinations::PrintersAndFile) + .printer_search(true) + .show(ui); + }); + fixture.room(room); + fixture.settle(); + (fixture, settings) +} + +/// Opens the printer list, which shows `value`. +fn open_list(fixture: &mut Fixture, value: &str) { + let list = + fixture.by_role(Role::COMBO_BOX).into_iter().find(|list| fixture.tree().value_of(list.node).is_some_and(|shown| shown.starts_with(value))); + let list = list.unwrap_or_else(|| panic!("the printer list shows {value}")); + fixture.click(&list).idle(3); +} + +/// Searching folds the names and changes no choice; a pick chooses and closes the list, and the list opens again on +/// the whole fleet (upstream PdfCraft printer_picker_filters_a_large_fleet_without_changing_the_selection). +#[trial] +fn printer_picker_filters_a_large_fleet_without_changing_the_selection() { + let (mut fixture, settings) = fleet(Vec2::new(1400.0, 900.0)); + let initial = settings.borrow().destination.clone(); + open_list(&mut fixture, "Office 000"); + let search = fixture.by_label("Search printers").expect("the search field heads the list"); + assert!(search.rect.width() > 350.0, "room for long device names: {:?}", search.rect); + fixture.type_text(" MÜNCHEN satellite ").idle(3); + assert_eq!(settings.borrow().destination, initial, "typing is not a printer choice"); + assert!(fixture.by_label("Office 001 - Engineering floor 4 (network queue)").is_none(), "the search hides the other queues"); + let last = fixture.by_label(LAST).expect("the search finds the queue"); + fixture.click(&last).idle(3); + assert_eq!(settings.borrow().destination, Destination::Printer(LAST.into()), "the pick chooses the queue"); + assert!(fixture.by_label("Search printers").is_none(), "choosing closes the list"); + + open_list(&mut fixture, "München"); + let search = fixture.by_label("Search printers").expect("the list opens again"); + assert!(fixture.tree().value_of(search.node).is_none_or(str::is_empty), "the search starts empty: the whole fleet shows again"); + assert!(fixture.by_label("No printers match.").is_none()); +} + +/// Save as PDF stays a destination when no queue matches the search, and choosing it does not print +/// (upstream printer_picker_keeps_save_as_pdf_available_when_the_filter_matches_nothing). +#[trial] +fn printer_picker_keeps_save_as_pdf_available_when_the_filter_matches_nothing() { + let (mut fixture, settings) = fleet(Vec2::new(1400.0, 900.0)); + let initial = settings.borrow().destination.clone(); + open_list(&mut fixture, "Office 000"); + let search = fixture.by_label("Search printers").expect("the search field heads the list"); + fixture.click(&search).idle(2); + assert!(fixture.by_label("Search printers").is_some(), "a click in the search keeps the list open"); + fixture.type_text("no-such-printer").idle(3); + assert!(fixture.by_label("No printers match.").is_some(), "the list says no queue matches"); + assert_eq!(settings.borrow().destination, initial); + let pdf = fixture.by_label("Save as PDF").expect("Save as PDF stays in the list"); + fixture.click(&pdf).idle(3); + assert_eq!(settings.borrow().destination, Destination::File, "the pick chooses Save as PDF"); + assert!(fixture.by_label("Search printers").is_none(), "choosing closes the list"); +} + +/// In a smaller window the list keeps long names within the screen, the search and Save as PDF on it, and reopens +/// with the chosen queue in sight (upstream printer_picker_scrolls_long_names_without_losing_the_search_or_pdf_choice). +#[trial] +fn printer_picker_scrolls_long_names_without_losing_the_search_or_pdf_choice() { + let size = Vec2::new(1024.0, 768.0); + let (mut fixture, settings) = fleet(size); + open_list(&mut fixture, "Office 000"); + fixture.type_text("münchen").idle(3); + let last = fixture.by_label(LAST).expect("the search finds the queue"); + assert!(last.rect.left() >= 0.0 && last.rect.right() <= size.x, "the long name stays within the screen: {:?}", last.rect); + fixture.click(&last).idle(3); + assert_eq!(settings.borrow().destination, Destination::Printer(LAST.into())); + + open_list(&mut fixture, "München"); + let search = fixture.by_label("Search printers").expect("the search field heads the list").rect; + let row = fixture.by_label(LAST).expect("the chosen queue shows").rect; + assert!(search.top() >= 0.0 && row.top() >= search.bottom() && row.bottom() <= size.y, "the chosen queue {row:?} is in sight on reopening"); + fixture.key(egui::Key::End, egui::Modifiers::NONE).idle(3); + let pdf = fixture.by_label("Save as PDF").expect("Save as PDF ends the list").rect; + assert!(pdf.bottom() <= size.y, "Save as PDF is on screen: {pdf:?}"); + let pdf = fixture.by_label("Save as PDF").expect("Save as PDF ends the list"); + fixture.click(&pdf).idle(3); + assert_eq!(settings.borrow().destination, Destination::File, "the PDF row is clickable with the whole fleet shown"); +} diff --git a/crates/text/src/ui/character/format_text.rs b/crates/text/src/ui/character/format_text.rs index 6b1a0ee04..5f697ac1a 100644 --- a/crates/text/src/ui/character/format_text.rs +++ b/crates/text/src/ui/character/format_text.rs @@ -183,6 +183,12 @@ pub struct FormatText<'a> { /// The range of the character spacing field, in points. #[prop] char_spacing_range: RangeInclusive, + /// The paragraph spacings the paragraph spacing menu offers, in points; none by default. + #[prop] + paragraph_spacing_presets: &'a [f32], + /// The range of the paragraph spacing field, in points; the Paragraph dialog's by default. + #[prop] + paragraph_spacing_range: RangeInclusive, /// Controls the host cannot apply, each disabled with its reason. #[prop] unsupported: &'a [(FormatControl, Label)], @@ -206,6 +212,8 @@ impl<'a> FormatText<'a> { scale_range: 0.0..=1000.0, char_spacing_presets: &[], char_spacing_range: -1000.0..=10000.0, + paragraph_spacing_presets: &[], + paragraph_spacing_range: *SPACE_RANGE.start() as f32..=*SPACE_RANGE.end() as f32, unsupported: &[], } } @@ -228,6 +236,8 @@ impl<'a> FormatText<'a> { let size_presets = length_menu(&units, unit, self.size_presets); let char_spacing_presets = length_menu(&units, unit, self.char_spacing_presets); + let paragraph_spacing_presets = length_menu(&units, unit, self.paragraph_spacing_presets); + let paragraph_spacing_range = wide(&self.paragraph_spacing_range); let scale_presets = number_presets(&units, std::iter::once(self.scale_presets)); let (size_range, scale_range, char_spacing_range) = (wide(&self.size_range), wide(&self.scale_range), wide(&self.char_spacing_range)); @@ -400,8 +410,8 @@ impl<'a> FormatText<'a> { label: words.paragraph_spacing.clone(), side: mark(GlyphLabel::text("¶↓"), None, FieldLayout::Inside), value: paragraph.space_after, - range: SPACE_RANGE, - presets: &[], + range: paragraph_spacing_range.clone(), + presets: ¶graph_spacing_presets, disabled: None, }; let spacing = match reason(FormatControl::ParagraphSpacing) { diff --git a/crates/text/src/ui/editor/edits.rs b/crates/text/src/ui/editor/edits.rs index bd1826fd1..e1b319a36 100644 --- a/crates/text/src/ui/editor/edits.rs +++ b/crates/text/src/ui/editor/edits.rs @@ -26,6 +26,9 @@ pub(super) struct Session { pub dragging: Option, /// The chars the press selected, which a drag by word, line or paragraph keeps selected. pub drag_origin: Range, + /// The word a double press selected: the Shift-clicks after it extend from the whole word, in either direction, + /// while the selection holds it. A key move, Select All or a plain press ends it. + pub word: Option>, /// The pass time of the last edit, move or press: the caret blink restarts from it. pub blink_start: f64, /// Length and hash of the host's text as the last pass left it. @@ -347,6 +350,7 @@ impl Edits<'_> { NavMove::PageDown => chars, _ => caret, }; + self.session.word = None; self.move_caret(to, mods.extend); } @@ -377,6 +381,7 @@ impl Edits<'_> { /// Select everything. pub fn select_all(&mut self) { + self.session.word = None; self.selection = TextSelection { anchor: 0, caret: self.chars() }; } @@ -388,15 +393,31 @@ impl Edits<'_> { let chars = self.chars(); let offset = offset.min(chars); let count = click_count(clicks); - self.selection.caret = offset; - if !shift { - self.selection.anchor = offset; - } + let selected = self.selection.range(); + // A Shift-click after a double press extends from the whole word: the far end of the word stays, whichever + // side the click is on, and a click inside the word keeps just the word. + let word = self.session.word.take().filter(|word| shift && count == 1 && selected.start <= word.start && word.end <= selected.end); self.session.drag_origin = offset..offset; + if let Some(word) = word { + self.selection = if offset < word.start { + TextSelection { anchor: word.end, caret: offset } + } else if offset > word.end { + TextSelection { anchor: word.start, caret: offset } + } else { + TextSelection { anchor: word.start, caret: word.end } + }; + self.session.word = Some(word); + } else { + self.selection.caret = offset; + if !shift { + self.selection.anchor = offset; + } + } if count >= 2 { let line = (count == 3).then(|| self.host.line_range(line)); let range = click_selection(self.host.text(), offset, line, count); self.selection = TextSelection { anchor: range.start, caret: range.end }; + self.session.word = (count == 2 && !range.is_empty()).then(|| range.clone()); self.session.drag_origin = range; } self.session.dragging = Some(count); diff --git a/crates/text/tests/it/editor.rs b/crates/text/tests/it/editor.rs index 0797b7bdb..f085a4ac9 100644 --- a/crates/text/tests/it/editor.rs +++ b/crates/text/tests/it/editor.rs @@ -700,3 +700,53 @@ fn an_editor_that_does_not_return_focus_leaves_its_opener_alone() { assert_eq!(focused(&fixture).as_deref() == Some("Opener"), returns, "returns {returns}: the focus went back to the opener only when asked"); } } + +/// The screen point of document x `x` on the trial host's line: one char per document unit at 100 %. +fn at_char(session: &Session, x: f32) -> egui::Pos2 { + let origin = session.fixture.by_label("Document").map_or(pos2(0.0, 0.0), |canvas| canvas.rect.min); + origin + vec2(x, 10.0) +} + +/// A double press on a one-letter word selects only that word, from either half of its letter (production 439401188, +/// #7413: "Take a calm" selected "Take a"). +#[trial] +fn a_double_press_on_a_one_letter_word_selects_only_that_word() { + for x in [5.2, 5.8] { + let mut editor = session("Take a calm walk.", None); + let at = at_char(&editor, x); + editor.fixture.click_at(at).click_at(at).settle(); + assert_eq!(editor.selection.borrow().range(), 5..6, "a double press at {x} selects the a"); + } +} + +/// After a double press selects a word, Shift-clicks extend from the whole word in either direction and keep it: before +/// it, after it, and back before it again; a click inside it keeps just the word (production 439401188). +#[trial] +fn shift_clicks_after_a_word_selection_extend_from_the_whole_word() { + let mut editor = session("Take a calm walk.", None); + let calm = at_char(&editor, 9.0); + editor.fixture.click_at(calm).click_at(calm).settle(); + assert_eq!(editor.selection.borrow().range(), 7..11, "the double press selects calm"); + editor.fixture.advance(1.0).hold(Modifiers::SHIFT); + for (x, expected) in [(2.0, 2..11), (15.0, 7..15), (1.0, 1..11), (9.0, 7..11)] { + editor.fixture.click_at(at_char(&editor, x)).advance(1.0).settle(); + assert_eq!(editor.selection.borrow().range(), expected, "a Shift-click at {x} extends from calm"); + } + editor.fixture.hold(Modifiers::NONE); +} + +/// A key that moves the selection ends the word anchor: a Shift-click after it extends from the selection's own anchor +/// (production 439401188). +#[trial] +fn a_key_move_ends_the_word_anchor() { + let mut editor = session("Take a calm walk.", None); + let a = at_char(&editor, 5.2); + editor.fixture.click_at(a).click_at(a).settle(); + assert_eq!(editor.selection.borrow().range(), 5..6, "the double press selects the a"); + editor.fixture.key(Key::ArrowRight, Modifiers::SHIFT).settle(); + assert_eq!(editor.selection.borrow().range(), 5..7, "Shift+Right extends by a char"); + editor.fixture.advance(1.0).hold(Modifiers::SHIFT); + editor.fixture.click_at(at_char(&editor, 2.0)).settle(); + editor.fixture.hold(Modifiers::NONE); + assert_eq!(editor.selection.borrow().range(), 2..5, "the Shift-click extends from the selection's anchor, not the word"); +} diff --git a/crates/text/tests/it/format_text.rs b/crates/text/tests/it/format_text.rs index 0d9d72145..dd7a32949 100644 --- a/crates/text/tests/it/format_text.rs +++ b/crates/text/tests/it/format_text.rs @@ -151,3 +151,59 @@ fn the_size_field_reads_mixed_in_a_272_point_pane() { let align = fixture.by_label("Alignment").expect("the alignment menu is shown"); assert!(align.rect.right() <= 218.5, "the alignment menu stays in the panel: {:?}", align.rect); } + +/// The paragraph spacing a host gives: its presets in the field's menu and its range, which a typed value is held to. +/// The field sits on the line spacing row, centred on it, inside the panel (PdfCraft: 0, 6, 12, 18 and 24 pt, at most +/// 72 pt). +#[trial] +fn paragraph_spacing_takes_the_hosts_presets_and_range_on_the_line_spacing_row() { + use craft_text::ui::character::ParagraphChange; + let character = CharacterValues { family: Some("Helvetica".to_owned()), size: Some(12.0), ..CharacterValues::default() }; + let paragraph = ParagraphValues { space_after: Some(6.0), ..ParagraphValues::default() }; + let families = vec!["Helvetica".to_owned()]; + let edits = Rc::new(RefCell::new(Vec::new())); + let panel = Rc::new(RefCell::new(egui::Rect::NOTHING)); + let (sink, panel_out) = (edits.clone(), panel.clone()); + let mut fixture = Fixture::new(move |ui| { + let out = FormatText::new("Format text", &character, ¶graph, &families) + .line_spacing(LineSpacing::Multiple(1.0)) + .paragraph_spacing_presets(&[0.0, 6.0, 12.0, 18.0, 24.0]) + .paragraph_spacing_range(0.0..=72.0) + .show(ui); + *panel_out.borrow_mut() = out.response.rect; + sink.borrow_mut().extend(out.edits); + }); + fixture.idle(10); + let line = fixture.by_label("Line spacing").expect("the line spacing select is shown").rect; + let spacing = fixture.by_label("Paragraph spacing").expect("the paragraph spacing field is shown").rect; + let panel = *panel.borrow(); + assert!((spacing.center().y - line.center().y).abs() <= 1.0, "the field {spacing:?} is centred on the line spacing row {line:?}"); + assert!( + spacing.left() >= line.right() && spacing.right() <= panel.right() + 0.5, + "the field {spacing:?} is beside it, inside the panel {panel:?}" + ); + + let field = fixture.by_label("Paragraph spacing").expect("the paragraph spacing field is shown"); + fixture.click(&field).idle(2); + fixture.key(Key::A, Modifiers::COMMAND).type_text("100"); + fixture.key(Key::Enter, Modifiers::NONE).idle(2); + let last = changes(&edits).into_iter().rev().find_map(|change| match change { + FormatTextChange::Paragraph(ParagraphChange::SpaceAfter(points)) => Some(points), + _ => None, + }); + assert_eq!(last, Some(72.0), "a typed spacing is held to the host's range"); + + let texts = texts_after_opening(&mut fixture, "Paragraph spacing"); + for preset in ["0", "12", "18", "24"] { + assert!(texts.iter().any(|text| text.split_whitespace().next() == Some(preset)), "the menu offers {preset} pt: {texts:?}"); + } +} + +/// The texts painted once the menu of the field named `label` is open. +fn texts_after_opening(fixture: &mut Fixture, label: &str) -> Vec { + let field = fixture.by_label(label).unwrap_or_else(|| panic!("{label} is shown")); + fixture.click(&field).idle(2); + // Alt+Down opens a number field's presets list. + fixture.key(Key::ArrowDown, Modifiers::ALT).idle(3); + fixture.texts().iter().map(|run| run.text.clone()).collect() +} diff --git a/crates/ui-contract/src/runtime/env/overrides.rs b/crates/ui-contract/src/runtime/env/overrides.rs index a98942392..2d43b3aec 100644 --- a/crates/ui-contract/src/runtime/env/overrides.rs +++ b/crates/ui-contract/src/runtime/env/overrides.rs @@ -125,6 +125,10 @@ pub struct Overrides { pub motion: Option, /// Also the child `Ui`'s direction and layout. pub direction: Option, + /// The flow direction alone (layout order, arrow keys and roving, and the child `Ui`'s layout): the paragraph + /// direction of text stays the inherited one. A strip mirrored to follow something physical (the macOS traffic + /// lights at the right end) keeps its labels reading as the interface does. Wins over `direction`'s flow. + pub flow: Option, /// The words of the scope and everything inside it. pub words: Option, /// App values set for the scope. @@ -167,6 +171,9 @@ impl Overrides { scoped.direction = direction; scoped.text_direction = direction; } + if let Some(flow) = self.flow { + scoped.direction = flow; + } match self.words { Some(WordsOverride::Replace(words)) => scoped.inherited_mut().words = words, Some(WordsOverride::Overlay(rows)) => { diff --git a/crates/ui-contract/src/runtime/windows/host.rs b/crates/ui-contract/src/runtime/windows/host.rs index 76df21013..109221e17 100644 --- a/crates/ui-contract/src/runtime/windows/host.rs +++ b/crates/ui-contract/src/runtime/windows/host.rs @@ -428,15 +428,21 @@ impl WindowHost { under.into_iter().map(|(viewport, _)| viewport).collect() } - /// Who draws the running viewport's frame, and the caption buttons it shows. + /// Who draws the running viewport's frame, and the caption buttons it shows. An inset frame whose window was + /// measured with the traffic lights at the right end says so ([`MacInset::lights_right`](craft_window::policy::MacInset)). pub fn frame(&self) -> Frame { let viewport = pass::current_viewport(&self.ctx); - if viewport == ViewportId::ROOT - && let Some(frame) = shared(&self.ctx, |shared| shared.root_frame.clone()) - { - return frame; + let frame = match shared(&self.ctx, |shared| shared.root_frame.clone()) { + Some(frame) if viewport == ViewportId::ROOT => frame, + _ => frame_in(&self.ctx, viewport), + }; + match frame { + Frame::Inset(inset) if !inset.lights_right => { + let right = PerViewport::::with_existing(&self.ctx, viewport, |record| record.lights.lights_right()).unwrap_or(false); + Frame::Inset(inset.with_lights_right(right)) + } + frame => frame, } - frame_in(&self.ctx, viewport) } /// The desktop the app's windows open on, as the installed frame decision detected it; `None` when the app diff --git a/crates/ui-contract/src/runtime/windows/shell.rs b/crates/ui-contract/src/runtime/windows/shell.rs index 014869182..e6da0eef4 100644 --- a/crates/ui-contract/src/runtime/windows/shell.rs +++ b/crates/ui-contract/src/runtime/windows/shell.rs @@ -118,7 +118,12 @@ pub(super) fn refresh(ctx: &Context, viewport: ViewportId, facts: viewports::Fac }) .map(|inset| { let mut insets = EdgeInsets::all(0.0); - insets.left = inset.map_or(0.0, |inset| inset.leading); + // The lights' room is at the end AppKit lays them out from: the right one under a right-to-left titlebar. + match inset { + Some(inset) if inset.lights_right => insets.right = inset.leading, + Some(inset) => insets.left = inset.leading, + None => {} + } insets }); PerViewport::::with(ctx, viewport, |record| { diff --git a/crates/ui-patterns/src/patterns/form_dialogs/param.rs b/crates/ui-patterns/src/patterns/form_dialogs/param.rs index 4aca47e64..ab868511f 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/param.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/param.rs @@ -495,6 +495,8 @@ pub(crate) struct RowOptions { max_chars: Option, /// Whether a text row shows its text in the monospace face ([`Param::mono`]). mono: bool, + /// Whether a text row selects its text when it takes the focus ([`Param::select_on_focus`]). + select_on_focus: bool, /// The width a text row's field asks for, in characters ([`Param::field_chars`]). field_chars: Option, units: Option, @@ -889,6 +891,14 @@ impl Param { self } + /// A [`ParamKind::Text`] row selects its whole text when it takes the focus, so typing replaces it (a Rename + /// dialog opening on the name); by default the caret goes to the end. Other kinds are unchanged. + #[must_use] + pub fn select_on_focus(mut self) -> Self { + self.options.get_or_insert_default().select_on_focus = true; + self + } + /// The width of a [`ParamKind::Text`] row's field, in characters (`TextField::width_chars`): the field asks for /// `chars` times the width of a `0` in its face instead of the field length, so one row of a form can be wider or /// narrower than the others (a watermark's text against a short name). A row that lacks room still narrows it. @@ -1203,6 +1213,11 @@ impl RowOptions { self.mono } + /// Whether a text row selects its text when it takes the focus. + pub(crate) fn select_on_focus(&self) -> bool { + self.select_on_focus + } + /// The width a text row's field asks for, in characters; `None` for the field length. pub(crate) fn field_chars(&self) -> Option { self.field_chars diff --git a/crates/ui-patterns/src/patterns/form_dialogs/rows.rs b/crates/ui-patterns/src/patterns/form_dialogs/rows.rs index a23157406..8b6cba420 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/rows.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/rows.rs @@ -1120,6 +1120,9 @@ impl<'p> Pass<'p> { if options.mono() { field = field.mono(); } + if options.select_on_focus() { + field = field.select_on_focus(); + } if let Some(chars) = options.field_chars() { field = field.width_chars(chars); } diff --git a/crates/ui-patterns/tests/it/form_dialogs/params.rs b/crates/ui-patterns/tests/it/form_dialogs/params.rs index 55fdac136..ec345db28 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/params.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/params.rs @@ -699,3 +699,25 @@ fn a_group_row_under_a_heading_of_its_name_shows_the_name_once() { assert_eq!(names, 1, "the heading alone names the group: {texts:?}"); assert!(text_at(&texts, "The options").is_some(), "the group shows: {texts:?}"); } + +/// A text row with `select_on_focus` selects its whole text when it takes the focus, so typing replaces it (PdfCraft's +/// Rename opens on the name selected); a row without it keeps the text and types at the caret. +#[trial] +fn a_text_row_that_selects_on_focus_is_replaced_by_typing() { + for (select, expected) in [(true, "Draft"), (false, "")] { + let param = Param::new("name", "Name", ParamKind::text("Report")); + let params = vec![if select { param.select_on_focus() } else { param }]; + let values = Rc::new(RefCell::new(DialogFields::new())); + values.borrow_mut().set("name", FieldValue::Text("Report".into())); + let mut fixture = rows(params, &values); + let field = fixture.by_label("Name").expect("the name row has a field"); + fixture.click(&field).settle(); + fixture.type_text("Draft").settle(); + let typed = values.borrow().text("name").map(str::to_owned); + if select { + assert_eq!(typed.as_deref(), Some(expected), "typing replaced the selected name"); + } else { + assert!(typed.as_deref().is_some_and(|text| text.contains("Report") && text.contains("Draft")), "typing kept the name: {typed:?}"); + } + } +} diff --git a/crates/ui-shell/src/shell/app_shell.rs b/crates/ui-shell/src/shell/app_shell.rs index 6d46c2f09..4523c163e 100644 --- a/crates/ui-shell/src/shell/app_shell.rs +++ b/crates/ui-shell/src/shell/app_shell.rs @@ -378,6 +378,13 @@ pub struct AppShell<'a, S> { /// The host's flag for the document tabs, read back through `ShellCx::tabs_visible`. #[prop] document_tabs: bool, + /// Whether the title slot mirrors with the window's macOS traffic lights when AppKit lays them out from the right + /// end (`MacInset::lights_right`: a right-to-left system language, whatever the app's language): the slot's flow + /// runs from the right, so what starts the title bar sits beside the lights and its document tabs read from the + /// right, their overflow at the other end. Text keeps the interface's direction. Off, the bar keeps its order and + /// only the lights' room moves to the right end. + #[prop] + title_follows_lights: bool, /// The window's title: the shell sends `WindowAction::SetTitle` every pass and the window host drops a title equal /// to the last one it set. Not in an embedded shell. #[prop(into)] @@ -409,6 +416,7 @@ impl<'a, S> AppShell<'a, S> { allow_reveal: true, edge_reveal: true, document_tabs: true, + title_follows_lights: false, window_title: None, body_label: None, title: None, @@ -524,6 +532,7 @@ impl<'a, S> AppShell<'a, S> { allow_reveal, edge_reveal, document_tabs, + title_follows_lights, window_title, body_label, title, @@ -635,6 +644,9 @@ impl<'a, S> AppShell<'a, S> { } let tabs = mode.tabs_visible() && document_tabs; + // The title slot reads from the right while the lights sit there; a right-to-left window already does. + let mirror_title = + title_follows_lights && !embedded && !rtl && matches!(WindowHost::of(&ctx).frame(), super::Frame::Inset(inset) if inset.lights_right); let mut shell = ShellCx::new(window.clone(), if only { BodyMode::Only } else { BodyMode::Normal }, regions.clone()) .with_tabs(tabs) .with_tab_reveal(kept.reveal.tab()) @@ -700,6 +712,7 @@ impl<'a, S> AppShell<'a, S> { if !*shown || covers(&placed.slot, only) != covering { continue; } + let mirrored = placed.title && mirror_title; let by_content = placed.sized_by_content(); let along_x = placed.along_x(); // A slot sized by its content is as large as its content from its outer edge, in the room it @@ -725,7 +738,7 @@ impl<'a, S> AppShell<'a, S> { let key = slot.key(); // The slot runs every pass; the app memoizes inside it. if !by_content { - region.show(ui, |ui, bcx| add(ui, bcx, app)); + region.show(ui, |ui, bcx| in_lights_flow(ui, mirrored, |ui| add(ui, bcx, app))); continue; } // The slot's extent along its edge is the pane's: its content's, with what the pane keeps @@ -735,7 +748,7 @@ impl<'a, S> AppShell<'a, S> { // what shows. let shown = region.show(ui, |ui, bcx| { let stack = if along_x { Stack::new() } else { Stack::new().fill_width() }; - stack.show(ui, |ui, _| add(ui, bcx, app)); + stack.show(ui, |ui, _| in_lights_flow(ui, mirrored, |ui| add(ui, bcx, app))); !ui.is_sizing_pass() }); let pane = shown.output.response.rect; @@ -834,3 +847,18 @@ impl<'a, S> AppShell<'a, S> { } } } + +/// Runs `body` with its flow from the right when `mirrored` (the title slot following traffic lights at the right end), +/// else as it is. Only the flow turns: text keeps the interface's direction. +fn in_lights_flow(ui: &mut Ui, mirrored: bool, body: impl FnOnce(&mut Ui) -> R) -> R { + if !mirrored { + return body(ui); + } + // The slot's room is the bar's own: a bar that fills takes it all, whatever the flow of the body around it. + let room = ui.max_rect(); + crate::runtime::env::with_env( + ui, + |overrides| overrides.flow = Some(craft_i18n::Direction::Rtl), + |ui| crate::runtime::env::in_room(ui, room, body), + ) +} diff --git a/crates/ui-shell/src/shell/title_bar/measure.rs b/crates/ui-shell/src/shell/title_bar/measure.rs index c23bec511..a4c13811a 100644 --- a/crates/ui-shell/src/shell/title_bar/measure.rs +++ b/crates/ui-shell/src/shell/title_bar/measure.rs @@ -34,15 +34,18 @@ impl Ends { } /// The ends of a bar in `frame`. A window in full screen (`shown` false) has none. The macOS lights and the - /// Windows captions stay where the platform puts them: the lights on the physical left, the Windows captions + /// Windows captions stay where the platform puts them: the lights on the physical left (the right under a + /// right-to-left titlebar, [`MacInset::lights_right`](crate::shell::MacInset)), the Windows captions /// mirrored, the Linux layouts as the user set them (see [`CaptionPlan::new`]). pub(super) fn of(frame: &Frame, shown: bool, rtl: bool) -> Ends { if !shown { return Ends::bare(); } match frame { - Frame::Inset(inset) if rtl => Ends { end: End::inset(inset.leading), ..Ends::bare() }, - Frame::Inset(inset) => Ends { start: End::inset(inset.leading), ..Ends::bare() }, + // The lights' room is at the physical end AppKit lays them out from: the start end when the bar reads from + // that side. + Frame::Inset(inset) if inset.lights_right == rtl => Ends { start: End::inset(inset.leading), ..Ends::bare() }, + Frame::Inset(inset) => Ends { end: End::inset(inset.leading), ..Ends::bare() }, Frame::Integrated(captions) => { let plan = CaptionPlan::new(captions, rtl); let total = plan.left_width() + plan.right_width(); diff --git a/crates/ui-shell/tests/it/shell/title_bar.rs b/crates/ui-shell/tests/it/shell/title_bar.rs index 6fa6e12d9..fdbadce91 100644 --- a/crates/ui-shell/tests/it/shell/title_bar.rs +++ b/crates/ui-shell/tests/it/shell/title_bar.rs @@ -267,3 +267,89 @@ fn an_action_title_is_a_button_and_reports_its_activation() { title.rect ); } + +/// What the mirrored-title trial saw, by label: the buttons' and the tabs' rects in the settled pass. +fn lights_right_bar(follows: bool, lights_right: bool) -> impl Fn(&str) -> Rect { + use craft_ui::buttons::Button; + use craft_ui::contract::{Show as _, ShowContainer as _}; + use craft_ui::shell::MacInset; + use craft_ui::tabs::{DocumentTab, DocumentTabs}; + let frame = Frame::Inset(MacInset::default().with_lights_right(lights_right)); + let desktop = Desktop { kind: DesktopKind::Other, ssd: None, gtk_theme: None, icon_theme: None }; + let windows = Windows::with(InstallSpec::new(ShellInfo::default(), Arc::new(NoWindows)).frame(Decision { frame, overridden: None, desktop })); + let tabs = [DocumentTab::new(0_usize, "first.pdf"), DocumentTab::new(1, "last.pdf")]; + let frame = || { + windows.frame(vec![], vec![], |ui| { + let _ = AppShell::new(WindowKey::main()) + .title_follows_lights(follows) + .title_bar(|ui, _, _: &mut ()| { + let _ = TitleBar::new() + .trailing(|ui, _| { + Button::new("Discord").show(ui); + Button::new("Preferences").show(ui); + }) + .show(ui, |ui, _| { + Button::new("Home").show(ui); + let _ = DocumentTabs::new("Documents", &tabs) + .selected(0) + .trailing(|ui| { + Button::new("Open").show(ui); + }) + .show(ui); + }); + }) + .body(|_, _, _| {}) + .show(ui, &mut ()); + }) + }; + for _ in 0..3 { + frame(); + } + let settled = frame(); + let tree = settled.trees.into_iter().rev().find(|(viewport, _)| *viewport == ViewportId::ROOT).expect("the root pass ran").1; + move |label: &str| { + tree.with_role(Role::BUTTON) + .into_iter() + .chain(tree.with_role(Role::TAB)) + .find(|key| tree.name_of(*key) == Some(label)) + .and_then(|key| tree.bounds_of(key)) + .unwrap_or_else(|| panic!("{label} is in the tree")) + } +} + +/// macOS with a right-to-left system language lays the traffic lights out from the right end. A shell whose title +/// follows the lights mirrors the bar's flow: the lights' room is at the right, Home sits beside it, the tabs read from +/// the right, then Open; the trailing controls are at the far left, in mirrored order. Labels keep reading left to +/// right (production 4448ee940). +#[trial] +fn a_title_that_follows_the_lights_mirrors_when_they_are_at_the_right() { + let (width, lights) = (800.0, craft_ui::shell::MacInset::default().leading); + let rect = lights_right_bar(true, true); + let home = rect("Home"); + for label in ["Home", "first.pdf", "last.pdf", "Open", "Discord", "Preferences"] { + assert!(rect(label).right() <= width - lights + 0.5, "{label} {:?} clears the lights at the right", rect(label)); + } + assert!(home.right() >= width - lights - 16.0, "Home {home:?} sits beside the lights"); + assert!(rect("first.pdf").right() <= home.left() + 0.5, "the first tab follows Home"); + assert!(rect("last.pdf").right() <= rect("first.pdf").left() + 0.5, "the tabs read from the right"); + assert!(rect("Open").right() <= rect("last.pdf").left() + 0.5, "Open follows the tabs"); + let (discord, preferences) = (rect("Discord"), rect("Preferences")); + assert!(preferences.left() < 20.0, "Preferences {preferences:?} at the far end"); + assert!(preferences.right() <= discord.left() + 0.5, "Preferences, then Discord, mirroring their order"); + assert!(discord.right() < rect("Open").left(), "Discord stays clear of Open"); +} + +/// Without the opt-in the bar keeps its order and only the lights' room moves to the right end, so nothing sits under +/// them; with the lights at the left the bar is as it always was. +#[trial] +fn the_lights_room_follows_the_lights_without_mirroring_the_bar() { + let (width, lights) = (800.0, craft_ui::shell::MacInset::default().leading); + let rect = lights_right_bar(false, true); + assert!(rect("Home").left() < 20.0, "Home {:?} keeps the start", rect("Home")); + assert!(rect("first.pdf").left() >= rect("Home").right() - 0.5, "the tabs read from the left"); + let preferences = rect("Preferences"); + assert!(preferences.right() <= width - lights + 0.5, "Preferences {preferences:?} clears the lights at the right"); + let rect = lights_right_bar(true, false); + assert!(rect("Home").left() >= lights - 0.5, "Home {:?} after the lights at the left", rect("Home")); + assert!(rect("Preferences").right() >= width - 20.0, "Preferences {:?} at the right end", rect("Preferences")); +} diff --git a/crates/ui-widgets/src/pickers/search.rs b/crates/ui-widgets/src/pickers/search.rs index 9a808e3c6..70e9b9926 100644 --- a/crates/ui-widgets/src/pickers/search.rs +++ b/crates/ui-widgets/src/pickers/search.rs @@ -3,7 +3,7 @@ use super::words::PickerWords; use crate::contract::overlay::Popup; -use crate::contract::{Bind, BodyCx, Component, Cx, PopupHandle, Remember as _, Show as _, WordSetCx as _}; +use crate::contract::{Bind, BodyCx, Component, Cx, PopupHandle, Props as _, Remember as _, Show as _, Sizing, WordSetCx as _}; use crate::runtime::env::Label; use crate::runtime::focus::{self, FocusTarget}; use crate::text::TextField; @@ -21,13 +21,28 @@ struct Query { /// the query. The dropdown leaves the key focus on the picker; the field takes it once the layer has recorded the /// picker as its opener, so typing reaches the field. pub(super) fn show(ui: &mut Ui, body: &mut BodyCx<'_>, popup: PopupHandle, cx: &Cx<'_, C>, owner: &Label, list: Id) -> String { + show_named(ui, body, popup, cx, owner, (None, false), list) +} + +/// [`show`] with the field named `named` when given, filling the popup's width with `fill`. +pub(super) fn show_named( + ui: &mut Ui, + body: &mut BodyCx<'_>, + popup: PopupHandle, + cx: &Cx<'_, C>, + owner: &Label, + (named, fill): (Option<&Label>, bool), + list: Id, +) -> String { let words = cx.words::(); let opening = Popup::opening(popup, cx); let typed = body.memory::(); if opening { *typed = Query::default(); } - let field = TextField::search(name(&words, owner), Bind::bound(&mut typed.text)).drives(list).show(ui); + let label = named.cloned().unwrap_or_else(|| name(&words, owner)); + let field = TextField::search(label, Bind::bound(&mut typed.text)).drives(list); + let field = if fill { field.sizing(Sizing::FillWidth) } else { field }.show(ui); let query = typed.text.clone(); let taken = &mut body.memory::().focused; if field.response.has_focus() { diff --git a/crates/ui-widgets/src/pickers/select.rs b/crates/ui-widgets/src/pickers/select.rs index 3a434196f..d59d0e544 100644 --- a/crates/ui-widgets/src/pickers/select.rs +++ b/crates/ui-widgets/src/pickers/select.rs @@ -16,6 +16,7 @@ use crate::contract::{ MeasureCx, Numeric, Overlay, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, PopupHandle, PopupKind, Props as _, Role, Show as _, ShowCollection as _, ShowContainer as _, Sizing, WordSetCx as _, step_stop, step_stops, }; +use crate::display::{Shade, Text}; use crate::layout_components::Row; use crate::list::{List, ListRow, ThumbAspect}; use crate::menu::Menu; @@ -25,6 +26,7 @@ use crate::runtime::focus::FocusMove; use crate::runtime::overlay::CloseReason; use crate::style::{ComponentStyle, Ink, StyleCx, SurfaceLook, TextLook, TypeRole}; use craft_behavior::nav::{StepResult, ValueAxes, ValueSteps}; +use craft_behavior::overlay::MinWidth; use craft_behavior::{ CancelReason, GesturePhase, HitLevel, HitPriority, IconId, Metrics, NavMove, PartKey, Selection, Sense, TypeAhead, Value, WheelPhase, wheel_step, }; @@ -59,6 +61,17 @@ pub struct SelectStyle { /// The icon of the button in the popup header that opens the header menu. const HEADER_MENU_ICON: &str = "more"; +/// The options a searchable select keeps whatever the query: a destination of its own beside the searched ones (Save +/// as PDF among the printers). +struct SearchKept<'a, T>(Box bool + 'a>); + +impl<'a, T> SearchKept<'a, T> { + /// Keeps the options `kept` answers true for. + fn new(kept: impl Fn(&T) -> bool + 'a) -> Self { + SearchKept(Box::new(kept)) + } +} + /// The rows of the menu a select's popup header opens: the host's menu body. struct HeaderMenu<'a>(Box>); @@ -94,6 +107,18 @@ pub struct Select<'a, T: Value + 'static> { /// A filter field above the entries narrows them as the user types. #[prop(flag)] searchable: bool, + /// The search field's name; "{label} Search" without it. + #[prop(into)] + search_label: Option