Merge branch 'pdf-port/sync' into pdf-port/sync-look

This commit is contained in:
Dylan M. Taylor
2026-11-23 11:09:46 -05:00
26 changed files with 644 additions and 48 deletions
@@ -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)
+34 -12
View File
@@ -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<std::path::PathBuf>,
}
/// What a write puts on the clipboard: the first flavour of each kind among the caller's.
struct Plan<'a> {
text: Option<Part<'a>>,
@@ -62,13 +68,16 @@ struct Plan<'a> {
rtf: Option<Part<'a>>,
mathml: Option<Part<'a>>,
picture: Option<Picture<'a>>,
files: Option<FileList>,
}
/// 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<Primary> {
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))
}
}
}
@@ -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));
}
@@ -127,6 +127,8 @@ fn wayland_write(plan: &Plan<'_>, owner: &[u8]) -> Result<Option<usize>, 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(),
};
@@ -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)
+14
View File
@@ -733,6 +733,9 @@ pub struct PrintDialog<'a> {
/// The pager under the sheet preview in the `Document` layout.
#[prop]
preview_pager: Option<PanePager>,
/// 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<PanePager>,
printer_search: bool,
/// The destination the user picked, or automation set, not taken yet.
printer_chosen: Option<Destination>,
/// 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<PagerStep> {
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() {
+26 -4
View File
@@ -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<String>,
/// 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::<PrintWords>();
let mut queues: Vec<Entry<Destination>> = 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());
+100
View File
@@ -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<RefCell<Settings>>) {
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<Printer> =
(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");
}
+12 -2
View File
@@ -183,6 +183,12 @@ pub struct FormatText<'a> {
/// The range of the character spacing field, in points.
#[prop]
char_spacing_range: RangeInclusive<f32>,
/// 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<f32>,
/// 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: &paragraph_spacing_presets,
disabled: None,
};
let spacing = match reason(FormatControl::ParagraphSpacing) {
+25 -4
View File
@@ -26,6 +26,9 @@ pub(super) struct Session {
pub dragging: Option<u32>,
/// The chars the press selected, which a drag by word, line or paragraph keeps selected.
pub drag_origin: Range<usize>,
/// 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<Range<usize>>,
/// 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);
+50
View File
@@ -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");
}
+56
View File
@@ -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, &paragraph, &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<String> {
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()
}
+7
View File
@@ -125,6 +125,10 @@ pub struct Overrides {
pub motion: Option<MotionMode>,
/// Also the child `Ui`'s direction and layout.
pub direction: Option<Direction>,
/// 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<Direction>,
/// The words of the scope and everything inside it.
pub words: Option<WordsOverride>,
/// 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)) => {
+12 -6
View File
@@ -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::<Record>::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
@@ -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::<Record>::with(ctx, viewport, |record| {
@@ -495,6 +495,8 @@ pub(crate) struct RowOptions {
max_chars: Option<usize>,
/// 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<u16>,
units: Option<UnitChoices>,
@@ -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<u16> {
self.field_chars
@@ -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);
}
@@ -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:?}");
}
}
}
+30 -2
View File
@@ -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<R>(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),
)
}
@@ -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();
@@ -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"));
}
+17 -2
View File
@@ -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<C: Component>(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<C: Component>(
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::<PickerWords>();
let opening = Popup::opening(popup, cx);
let typed = body.memory::<Query>();
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::<Query>().focused;
if field.response.has_focus() {
+54 -4
View File
@@ -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<dyn Fn(&T) -> 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<HeaderRows<'a>>);
@@ -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<Label>,
/// Shown above the list while the query matches none of the searched options; the list's "No matches" without it.
#[prop(into)]
no_matches: Option<Label>,
/// Options the search never hides, shown after the matches.
#[prop(func = "Fn(&T) -> bool")]
search_kept: Option<SearchKept<'a, T>>,
/// The open list is at least this wide, in points, within the screen; the field's width without it.
#[prop(quantity = "width of the open list, in points")]
list_width: Option<f32>,
/// Shown, muted, while the value is none of the entries.
#[prop(into)]
placeholder: Option<Label>,
@@ -123,6 +148,10 @@ impl<'a, T: Value + 'static> Select<'a, T> {
value,
entries,
searchable: false,
search_label: None,
no_matches: None,
search_kept: None,
list_width: None,
placeholder: None,
decorate: None,
picture: None,
@@ -314,14 +343,24 @@ impl<T: Value + 'static> Component for Select<'_, T> {
let words = cx.words::<PickerWords>();
let held = self.position(cx.value());
let (searchable, dress, picture) = (self.searchable, self.decorate.as_ref(), self.picture.as_ref());
let kept =
|at: usize| self.search_kept.as_ref().is_some_and(|kept| entries.get(at).and_then(Entry::value).is_some_and(|value| (kept.0)(value)));
let (search_label, no_matches, wide) = (self.search_label.clone(), self.no_matches.clone(), self.list_width.is_some());
let folder = cx.env.folder();
let mut header_menu = self.header_menu.as_mut();
let list = cx.id.with("options");
let events = ui.show(popup, Overlay::dropdown().list(list), |ui, body| {
let overlay = Overlay::dropdown().list(list);
let overlay = match self.list_width {
Some(width) if width.is_finite() && width > 0.0 => overlay.min_width(MinWidth::Points(width)),
_ => overlay,
};
let events = ui.show(popup, overlay, |ui, body| {
let mut query = String::new();
if searchable || header_menu.is_some() {
let _ = Row::new().show(ui, |ui, _| {
let row = if wide { Row::new().fill_width() } else { Row::new() };
let _ = row.show(ui, |ui, _| {
if searchable {
query = search::show(ui, body, popup, cx, &name, list);
query = search::show_named(ui, body, popup, cx, &name, (search_label.as_ref(), wide), list);
}
if let Some(rows) = header_menu.as_mut() {
let more = IconButton::new(IconId::new(HEADER_MENU_ICON)).popup(PopupKind::Menu).label(words.header_menu.clone()).show(ui);
@@ -334,6 +373,13 @@ impl<T: Value + 'static> Component for Select<'_, T> {
});
}
let rows = EntryRows::new(entries, &labels);
// A query that matches none of the searched options says so above the kept ones.
let matcher = craft_i18n::matcher::Matcher::new(&folder, query.trim());
let none_match = !matcher.is_empty()
&& !(0..entries.len()).filter(|&at| entries[at].is_item() && !kept(at)).any(|at| matcher.score(labels[at].as_str()).is_some());
if let (true, Some(text)) = (none_match, no_matches.as_ref()) {
Text::new(text.clone()).shade(Shade::Muted).show(ui);
}
let selection = held.filter(|_| query.trim().is_empty()).map_or_else(Selection::default, Selection::single);
// While a query narrows the list the lead starts nowhere, so Down lands on the first match and Enter picks it.
let lead = if query.trim().is_empty() { LeadOnOpen::First } else { LeadOnOpen::Selected };
@@ -342,7 +388,11 @@ impl<T: Value + 'static> Component for Select<'_, T> {
.empty(words.no_matches.clone())
.selection(Bind::given(selection))
.lead_on_open(lead)
.filter(&query, |at| vec![labels[*at].clone()])
// A kept option matches any query by carrying the query among its texts.
.filter(
&query,
|at| if kept(*at) { vec![labels[*at].clone(), Label::from(query.trim().to_owned())] } else { vec![labels[*at].clone()] },
)
.show_items(ui, &rows, &mut |at, _| rows.row(*at, held, dress, picture))
.events
});
+1 -1
View File
@@ -34,7 +34,7 @@ wayland-client = "0.31"
[target.'cfg(target_os = "macos")'.dependencies]
muda = { version = "0.21.2", default-features = false, optional = true }
objc2 = { version = "0.6.4", default-features = false, features = ["std"], optional = true }
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSApplication", "NSButton", "NSControl", "NSEvent", "NSMenu", "NSMenuItem", "NSResponder", "NSScreen", "NSView", "NSWindow"], optional = true }
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSApplication", "NSButton", "NSControl", "NSEvent", "NSMenu", "NSMenuItem", "NSResponder", "NSScreen", "NSUserInterfaceLayout", "NSView", "NSWindow"], optional = true }
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSArray", "NSBundle", "NSEnumerator", "NSGeometry", "NSLocale", "NSProcessInfo", "NSString"], optional = true }
# `caps_lock`: the toggle bit of the Caps Lock key, through winsafe's safe wrapper (the workspace forbids `unsafe`).
+18 -6
View File
@@ -45,7 +45,8 @@ pub fn in_resize_area(size: [f32; 2], at: [f32; 2]) -> bool {
/// The three buttons as AppKit laid them out, in points.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Lights {
/// The zoom (rightmost) button's right edge from the window's left edge.
/// The far edge of the zoom button (the last of the three) from the window edge the lights start at: its right edge
/// from the left edge, or, with the lights at the right ([`MacInset::lights_right`]), its left edge from the right.
pub right: f32,
/// The lights' vertical centre below the window's top.
pub centre_from_top: f32,
@@ -69,7 +70,7 @@ pub fn inset_from_lights(lights: Lights) -> Option<MacInset> {
&& size <= 2.0 * centre_from_top
&& centre_from_top <= MAX_CENTRE_FROM_TOP
&& right <= MAX_RIGHT;
sane.then(|| MacInset { leading: right + (centre_from_top - size / 2.0), centre_from_top })
sane.then(|| MacInset { leading: right + (centre_from_top - size / 2.0), centre_from_top, lights_right: false })
}
/// The inset for macOS `major` (26 for Tahoe) before a window exists to measure.
@@ -120,6 +121,12 @@ impl Cache {
}
Some(self.measured.unwrap_or_else(default))
}
/// Whether the last measurement found the lights at the window's right end ([`MacInset::lights_right`]); false
/// before a window was measured.
pub fn lights_right(&self) -> bool {
self.measured.is_some_and(|inset| inset.lights_right)
}
}
/// The inset for the running macOS version before a window exists to measure; [`MacInset::default`] elsewhere.
@@ -141,7 +148,7 @@ pub fn os_default() -> MacInset {
#[cfg(all(feature = "appkit", target_os = "macos"))]
pub fn measure() -> Option<MacInset> {
use objc2::MainThreadMarker;
use objc2_app_kit::{NSApplication, NSWindowButton, NSWindowStyleMask};
use objc2_app_kit::{NSApplication, NSUserInterfaceLayoutDirection, NSWindowButton, NSWindowStyleMask};
// eframe runs the app on the main thread; anywhere else AppKit is out of reach.
let mtm = MainThreadMarker::new()?;
@@ -159,12 +166,17 @@ pub fn measure() -> Option<MacInset> {
let zoom = window.standardWindowButton(NSWindowButton::ZoomButton)?;
// Window coordinates count up from the bottom.
let frame = zoom.convertRect_toView(zoom.bounds(), None);
let window_height = window.frame().size.height;
let window_size = window.frame().size;
// A right-to-left titlebar (a right-to-left system language) lays the lights out from the right edge, the zoom
// button leftmost: the reserved room is measured from that edge.
let lights_right = window.windowTitlebarLayoutDirection() == NSUserInterfaceLayoutDirection::RightToLeft;
let far = if lights_right { window_size.width - frame.origin.x } else { frame.origin.x + frame.size.width };
inset_from_lights(Lights {
right: (frame.origin.x + frame.size.width) as f32,
centre_from_top: (window_height - (frame.origin.y + frame.size.height / 2.0)) as f32,
right: far as f32,
centre_from_top: (window_size.height - (frame.origin.y + frame.size.height / 2.0)) as f32,
size: frame.size.height as f32,
})
.map(|inset| inset.with_lights_right(lights_right))
}
/// One measurement of the first titled full-size-content window, without the cache. `None` when no such window
+12 -1
View File
@@ -96,13 +96,24 @@ pub struct MacInset {
pub leading: f32,
/// Distance from the window's top to the lights' vertical centre.
pub centre_from_top: f32,
/// AppKit lays the lights out from the window's right edge (`windowTitlebarLayoutDirection` is right to left: a
/// right-to-left system language, whatever the app's own language). `leading` is then reserved at the right end.
pub lights_right: bool,
}
impl MacInset {
/// The inset with the lights at the right end when `right`.
pub fn with_lights_right(mut self, right: bool) -> Self {
self.lights_right = right;
self
}
}
impl Default for MacInset {
/// The standard lights' geometry, for a window that does not exist yet and a macOS version
/// that is not known; [`crate::mac::default_inset`] knows the versions.
fn default() -> Self {
Self { leading: 78.0, centre_from_top: 14.0 }
Self { leading: 78.0, centre_from_top: 14.0, lights_right: false }
}
}