fw sync: clippy clean over the merged sync (all targets, all features)

Real fixes, no allows: split long functions (portal first reads, canvas wheel read, text editor input pass, list row toggle parts, notice action rows, thumbnails grid aspect and edit rules, comments row entries), boxed the large Entry item row, type aliases for complex types, a StatusMeasure for the status cell's measures, double #[must_use] removed where the type is #[must_use], Copy clones and useless conversions dropped, struct-update syntax in place of field reassignment, a split press-pass test.
This commit is contained in:
Dylan M. Taylor committed 2026-11-23 03:42:16 -05:00
1 parent 173d63d915
commit 5abaa7360e
35 files changed
+411 -309

No files matched your search

+10 -3
View File
@@ -1004,9 +1004,13 @@ mod tests {
assert_eq!(end.target, Some(2));
assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{:?}", end.phase);
assert_eq!(end.activated, None, "a passed press is no click");
}
// The move past slop came in the press's own pass: the shape below gets the Down, its DragStart next pass,
// and a release in between waits for it.
/// The move past slop came in the press's own pass: the shape below gets the Down, its DragStart next pass, and a
/// release in between waits for it.
#[test]
fn a_drag_past_slop_in_the_press_pass_hands_the_down_over() {
let origin = pos2(0.0, 0.0);
let mut machine = PressMachine::new();
let first = passing_pass(&mut machine, &[press(0.0, 1.0), moved(40.0)]);
assert!(matches!(first.phase, Some(PressPhase::Down { .. })) && first.passes.is_some(), "{first:?}");
@@ -1020,8 +1024,11 @@ mod tests {
let end = passing_pass(&mut machine, &[]);
assert_eq!(end.target, Some(2));
assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{:?}", end.phase);
}
// No shape took the passed press: it is abandoned, and its release is no click.
/// No shape took the passed press: it is abandoned, and its release is no click.
#[test]
fn a_passed_press_no_shape_takes_is_abandoned() {
let mut machine = PressMachine::new();
let _ = passing_pass(&mut machine, &[press(0.0, 1.0)]);
assert!(passing_pass(&mut machine, &[moved(40.0)]).passes.is_some());
-2
View File
@@ -129,14 +129,12 @@ impl<'a> SwatchPalette<'a> {
/// An Other… cell after the swatches, named `label`: activating it files a `ColorRequest` keyed `key` at the bound
/// colour as `pick_color`, for the host's own picker, and sets nothing.
#[must_use]
pub fn other(mut self, key: impl Into<String>, label: impl Into<Label>) -> Self {
self.other = Some((key.into(), label.into()));
self
}
/// A row of recent `colors` under `caption`, below the grid, each named by its hex; an empty slice shows no row.
#[must_use]
pub fn recent(mut self, caption: impl Into<Label>, colors: &'a [Srgba]) -> Self {
self.recent = Some((caption.into(), colors));
self
+38 -21
View File
@@ -454,15 +454,7 @@ impl<'a> PageThumbnails<'a> {
// The New Slide row's key comes after the pages' and the section headers'.
let new_page = count + groups.len();
let tail: Vec<TailRow<usize>> = if new_page_row { vec![TailRow::new(new_page, words.new_page.clone())] } else { Vec::new() };
// Organize uses a portrait page frame for every page, so landscape pages fit inside it
// instead of collapsing the room reserved for the controls around the picture.
let aspect = if organize {
0.85
} else if count == 0 {
1.0
} else {
aspect_of(source, 0)
};
let aspect = grid_aspect(source, organize);
let mut grid = TileGrid::<usize>::new(label)
.id_source(id)
.selection(Bind::bound(&mut *picked))
@@ -490,18 +482,7 @@ impl<'a> PageThumbnails<'a> {
grid = grid.checks(true).action_place(TileActionPlace::Band);
}
if editable {
// Pages copy as files do in a file manager: Ctrl off macOS, Option on macOS.
let rule = if organize { ReorderRule::new().copy_with(CopyKeys::Platform) } else { ReorderRule::new() };
grid = grid
.reorder(rule)
.accepts(move |_, _, insert| insert <= new_page)
.drag_count(words.count.counted())
.takes_drop(DropKind::new(DropPlace::Between, |_: &OsFiles, _| true))
.deletable(true)
.delete_target(craft_ui::contract::DeleteTarget::FocusOrHover);
if organize && let Some(insert_label) = insert_label {
grid = grid.insert_gaps(insert_label);
}
grid = editing(grid, &words, organize, new_page, insert_label);
}
let ctx = ui.ctx().clone();
let thumbnails = Thumbnails::<usize>::in_context(&ctx, "page-thumbnails", ThumbnailOptions::new().max_side(texture_side(&ctx)));
@@ -586,6 +567,42 @@ impl<'a> PageThumbnails<'a> {
}
}
/// The grid's tile aspect: Organize's portrait frame for every page, else the first page's.
fn grid_aspect(source: &dyn PageSource, organize: bool) -> f32 {
// Organize uses a portrait page frame for every page, so landscape pages fit inside it instead of collapsing the
// room reserved for the controls around the picture.
if organize {
0.85
} else if source.page_count() == 0 {
1.0
} else {
aspect_of(source, 0)
}
}
/// An editable grid's rules: reordering and copying, file drops between pages, deleting, and Organize's insert gaps.
fn editing<'g>(
grid: TileGrid<'g, usize>,
words: &ThumbnailWords,
organize: bool,
new_page: usize,
insert_label: Option<&'g dyn Fn(usize) -> Label>,
) -> TileGrid<'g, usize> {
// Pages copy as files do in a file manager: Ctrl off macOS, Option on macOS.
let rule = if organize { ReorderRule::new().copy_with(CopyKeys::Platform) } else { ReorderRule::new() };
let grid = grid
.reorder(rule)
.accepts(move |_, _, insert| insert <= new_page)
.drag_count(words.count.counted())
.takes_drop(DropKind::new(DropPlace::Between, |_: &OsFiles, _| true))
.deletable(true)
.delete_target(craft_ui::contract::DeleteTarget::FocusOrHover);
match insert_label {
Some(insert_label) if organize => grid.insert_gaps(insert_label),
_ => grid,
}
}
/// Page `at`'s width over its height; 1 for a page without a size.
fn aspect_of(source: &dyn PageSource, at: usize) -> f32 {
let size = source.page_size(at);
+8 -11
View File
@@ -1562,18 +1562,15 @@ impl KeyMoves {
if let Some(forward) = to_end {
(moves.to_end, moves.go_to) = end(forward);
}
match keys.page.filter(|(_, mods)| !mods.extend && !mods.fine) {
Some((step @ (NavMove::PageUp | NavMove::PageDown), mods)) => {
let forward = step == NavMove::PageDown;
if state.continuous && !mods.lead {
// A key line of the last screen stays in view, so the reader keeps their place.
let screen = (f64::from(rect.height()) - line).max(line);
moves.pan.1 += if forward { screen } else { -screen };
} else {
moves.turn = Some(forward);
}
if let Some((step @ (NavMove::PageUp | NavMove::PageDown), mods)) = keys.page.filter(|(_, mods)| !mods.extend && !mods.fine) {
let forward = step == NavMove::PageDown;
if state.continuous && !mods.lead {
// A key line of the last screen stays in view, so the reader keeps their place.
let screen = (f64::from(rect.height()) - line).max(line);
moves.pan.1 += if forward { screen } else { -screen };
} else {
moves.turn = Some(forward);
}
_ => {}
}
if let Some((direction, mods)) = nudge
&& direction.y != 0.0
+4 -1
View File
@@ -129,8 +129,11 @@ fn a_moved_page_keeps_its_identity_across_a_move() {
assert_eq!(moved, vec![1, 2, 3, 0, 4]);
}
/// A value the rig and its trial share.
type Shared<T> = Rc<RefCell<T>>;
/// An Organize grid of `count` pages with id `id` and current page `current`; the events it reports and the picked set.
fn organize_rig(count: usize, id: egui::Id, current: usize) -> (Fixture, Rc<RefCell<Vec<ThumbnailEvent>>>, Rc<RefCell<Selection<usize>>>) {
fn organize_rig(count: usize, id: egui::Id, current: usize) -> (Fixture, Shared<Vec<ThumbnailEvent>>, Shared<Selection<usize>>) {
let events: Rc<RefCell<Vec<ThumbnailEvent>>> = Rc::default();
let seen = Rc::clone(&events);
let picked: Rc<RefCell<Selection<usize>>> = Rc::default();
+6 -5
View File
@@ -1166,11 +1166,11 @@ fn a_fit_holds_the_page_at_the_top_still_while_pages_of_other_sizes_scroll_past(
let source = Recording::new(DemoPages::new(sizes.len()), sizes, &Rc::default());
let Rig { mut fixture, state, out, .. } = rig_over(source, state_with(|s| s.fit = Fit::Width), NavigationOptions::default(), true);
let (zoom, rects) = (state.borrow().zoom, out.borrow().rects.clone());
for page in 1..rects.len() {
state.borrow_mut().offset.1 = rects[page].y0;
for (page, rect) in rects.iter().enumerate().skip(1) {
state.borrow_mut().offset.1 = rect.y0;
fixture.idle(2);
assert_eq!(state.borrow().zoom, zoom, "page {page} at the top leaves the fitted zoom alone");
assert_eq!(out.borrow().rects[page], rects[page], "page {page} at the top keeps its place and size");
assert_eq!(out.borrow().rects[page], *rect, "page {page} at the top keeps its place and size");
}
}
@@ -1408,7 +1408,8 @@ fn reselecting_the_display_moves_nothing_and_a_change_keeps_the_current_page() {
view.fixture.idle(2);
assert_eq!(view.state.borrow().offset, offset, "writing the display it has moves nothing");
let changes: [(&str, fn(&mut PageViewState)); 2] = [("display", |s| s.display = PageDisplay::TwoUp), ("fit", |s| s.fit = Fit::Page)];
type Change = (&'static str, fn(&mut PageViewState));
let changes: [Change; 2] = [("display", |s| s.display = PageDisplay::TwoUp), ("fit", |s| s.fit = Fit::Page)];
for (what, change) in changes {
// Where a go-to to the current page puts the view, from the same state.
let mut reference = rig(6, view.state.borrow().clone());
@@ -1719,7 +1720,7 @@ fn command_page_down_turns_a_page_and_right_a_spread_in_a_scrolling_view() {
fixture.idle(2);
assert_eq!(state.borrow().current, 1, "Cmd+Page Down turns one page");
let top = out.borrow().rects[1].y0 - out.borrow().offset.1;
assert!(top >= 0.0 && top < 40.0, "the page's top comes to the view's top: {top}");
assert!((0.0..40.0).contains(&top), "the page's top comes to the view's top: {top}");
fixture.key(Key::PageUp, Modifiers::COMMAND);
fixture.idle(2);
assert_eq!(state.borrow().current, 0, "Cmd+Page Up turns back");
+20 -12
View File
@@ -385,6 +385,24 @@ async fn next_event(settings: &mut [zbus::MessageStream], owners: &mut zbus::Mes
});
futures_lite::future::race(setting, async { owners.next().await.map(Event::Owner) }).await
}
/// GNOME's text scale, read on GNOME-like sessions only (`TEXT_SCALE_KEY`).
async fn read_text_scale(connection: &zbus::Connection, gnome: bool) -> Option<Option<f32>> {
if gnome { read_with(connection, GNOME, TEXT_SCALE_KEY, text_scale_reply).await } else { None }
}
/// Publishes the contrast, motion and text scale of the first concurrent read.
fn publish_first_reads(shared: &Shared, fallbacks: &mut Fallbacks, contrast: Option<Contrast>, answers: &Answers, text_scale: Option<Option<f32>>) {
if let Some(contrast) = contrast {
shared.publish_contrast(contrast);
}
match answers.reduced_motion() {
Some(reduced) => shared.publish_motion(reduced),
// A portal that knows none of the keys (a bare window manager's) leaves the files to answer.
None => fallbacks.motion(shared),
}
if let Some(scale) = text_scale {
shared.publish_text_scale(scale);
}
}
async fn watch_connection(shared: &Shared, fallbacks: &mut Fallbacks, connected: &mut bool, connection: zbus::Connection) -> Option<()> {
// MatchRule installs before activation: unlike a proxy subscription it needs no current owner.
let mut settings = [
@@ -405,21 +423,11 @@ async fn watch_connection(shared: &Shared, fallbacks: &mut Fallbacks, connected:
zip(read(&connection, STANDARD, shared.gnome), read(&connection, GNOME, shared.gnome)),
zip(read_with(&connection, STANDARD, CONTRAST_KEY, contrast_reply), read_motion(&connection)),
),
async { if shared.gnome { read_with(&connection, GNOME, TEXT_SCALE_KEY, text_scale_reply).await } else { None } },
read_text_scale(&connection, shared.gnome),
)
.await;
let mut answers = Answers { standard, gnome, motion, gnome_motion, kde_motion };
if let Some(contrast) = contrast {
shared.publish_contrast(contrast);
}
match answers.reduced_motion() {
Some(reduced) => shared.publish_motion(reduced),
// A portal that knows none of the keys (a bare window manager's) leaves the files to answer.
None => fallbacks.motion(shared),
}
if let Some(scale) = text_scale {
shared.publish_text_scale(scale);
}
publish_first_reads(shared, fallbacks, contrast, &answers, text_scale);
match combined(standard, gnome) {
Some(answer) => {
*connected = true;
+1 -1
View File
@@ -513,7 +513,7 @@ fn a_document_print_dialog_has_compact_inline_rows() {
let texts = fixture.texts();
let count = |text: &str| texts.iter().filter(|run| run.text == text).count();
assert_eq!(count("Printer Setup"), 0, "the printer rows carry no heading");
assert_eq!(fixture.by_label("Refresh").is_none(), true, "the printers are found as the dialog opens: no Refresh");
assert!(fixture.by_label("Refresh").is_none(), "the printers are found as the dialog opens: no Refresh");
// The heading is an overline, in capitals (production's "PAGES TO PRINT"); the radio's caption is not repeated.
assert_eq!(count("PAGES TO PRINT") + count("Pages to Print"), 1, "the heading is shown once, not again as the radio's caption");
assert_eq!(count("PAGES TO PRINT"), 1, "the heading is an overline in capitals");
+1 -1
View File
@@ -168,7 +168,7 @@ impl SignatureImage {
let high = f32::from(cutoff);
let span = f32::from(feather.max(1));
let mut rgba = self.rgba.clone();
for pixel in rgba.chunks_exact_mut(4) {
for pixel in rgba.as_chunks_mut::<4>().0 {
let whiteness = f32::from(pixel[0].min(pixel[1]).min(pixel[2]));
let keep = ((high - whiteness) / span).clamp(0.0, 1.0);
pixel[3] = (f32::from(pixel[3]) * keep).round() as u8;
+62 -46
View File
@@ -269,6 +269,9 @@ pub(crate) fn age_text(env: &EnvView<'_>, then: i64, now: i64) -> String {
}
}
/// The host's own menu rows for a thread's message at an index.
type HostRows<'a, H> = Box<dyn Fn(&CommentThread, usize) -> Vec<Entry<H>> + 'a>;
/// Acrobat's right-hand comment list.
///
/// - Header ([`CommentsHeader::Own`]) "Comments N" with "N replies" under it, search, the Sort by menu, the funnel
@@ -307,7 +310,7 @@ pub struct CommentsPanel<'a, H: Value = NoHostRow> {
page_order: PageOrder,
reply_submit: SubmitKey,
select_mode: SelectMode,
host_rows: Option<Box<dyn Fn(&CommentThread, usize) -> Vec<Entry<H>> + 'a>>,
host_rows: Option<HostRows<'a, H>>,
}
/// The host row type of a panel whose cards' menus take no host rows: it has no value.
@@ -347,7 +350,6 @@ impl<'a> CommentsPanel<'a> {
/// The rows a card's menu appends behind a separator, from the thread and the card's message index; a row the
/// user picks is reported as `CommentsPanelOutput::host`.
#[must_use]
pub fn card_rows<H: Value>(self, rows: impl Fn(&CommentThread, usize) -> Vec<Entry<H>> + 'a) -> CommentsPanel<'a, H> {
let CommentsPanel { label, threads, state, read_only, now, page_label, header, page_order, reply_submit, select_mode, host_rows: _ } = self;
CommentsPanel {
@@ -368,28 +370,24 @@ impl<'a> CommentsPanel<'a> {
impl<'a, H: Value> CommentsPanel<'a, H> {
/// Who draws the header.
#[must_use]
pub fn header(mut self, header: CommentsHeader) -> Self {
self.header = header;
self
}
/// How threads on one page are ordered under the Page sort.
#[must_use]
pub fn page_order(mut self, order: PageOrder) -> Self {
self.page_order = order;
self
}
/// The key that submits the reply box; an inline editor keeps `CommandEnter`.
#[must_use]
pub fn reply_submit(mut self, key: SubmitKey) -> Self {
self.reply_submit = key;
self
}
/// How a click selects cards.
#[must_use]
pub fn select_mode(mut self, mode: SelectMode) -> Self {
self.select_mode = mode;
self
@@ -540,6 +538,62 @@ fn kind_name(words: &CommentsWords, kinds: &AnnotateWords, kind: Option<Annotati
kind.map_or_else(|| words.plain_kind.as_str().to_owned(), |kind| kinds.kind(kind).to_owned())
}
/// A group heading's title, with its page under the Page sort.
type Heading = (String, Option<usize>);
/// The list's rows: each shown thread's card under its group heading (by `sort`; none by date), with the group's
/// count, and a folded page group's heading without its cards.
fn row_entries<'t>(
threads: &[CommentThread],
shown: &[&'t CommentThread],
sort: CommentSort,
collapsed: &[usize],
heading_of: &dyn Fn(&CommentThread) -> Option<Heading>,
digits: &dyn Fn(usize) -> String,
) -> Vec<(CardKey, RowEntry<'t>)> {
let by_page = sort == CommentSort::Page;
let grouped = sort != CommentSort::Date;
let mut page_counts: BTreeMap<usize, usize> = BTreeMap::new();
for page in threads.iter().filter_map(|thread| thread.anchor.page()) {
*page_counts.entry(page).or_default() += 1;
}
let mut shown_counts: BTreeMap<String, usize> = BTreeMap::new();
for thread in shown {
if let Some((title, _)) = heading_of(thread) {
*shown_counts.entry(title).or_default() += 1;
}
}
let mut entries: Vec<(CardKey, RowEntry<'_>)> = Vec::new();
let mut last: Option<String> = None;
let mut groups = 0;
// The source lists the rows on show: a folded group keeps its heading and drops its cards.
let mut folded = false;
for &thread in shown {
let heading = if grouped { heading_of(thread) } else { None };
let depth = usize::from(heading.is_some());
if heading.is_none() {
folded = false;
}
if let Some((title, page)) = heading
&& last.as_deref() != Some(title.as_str())
{
let count = match page {
Some(number) if by_page => page_counts.get(&number).copied().unwrap_or_default(),
_ => shown_counts.get(&title).copied().unwrap_or_default(),
};
let open = !page.is_some_and(|number| collapsed.contains(&number));
folded = !open;
entries.push((CardKey::Group(groups), RowEntry::Group { title: title.clone(), count: digits(count), page, open }));
groups += 1;
last = Some(title);
}
if !folded {
entries.push((CardKey::Thread(thread.id), RowEntry::Card { thread, depth }));
}
}
entries
}
/// The heading a thread falls under for `sort`, with its page; `None` for none.
fn group_of(
words: &CommentsWords,
@@ -547,7 +601,7 @@ fn group_of(
page_label: &dyn Fn(usize) -> String,
thread: &CommentThread,
sort: CommentSort,
) -> Option<(String, Option<usize>)> {
) -> Option<Heading> {
match sort {
CommentSort::Page => thread.anchor.page().map(|page| (words.page.fill(&[("label", &page_label(page))]), Some(page))),
CommentSort::Author => {
@@ -632,46 +686,8 @@ impl<H: Value> CommentsPanel<'_, H> {
}
let by_page = state.sort == CommentSort::Page;
let grouped = state.sort != CommentSort::Date;
let mut page_counts: BTreeMap<usize, usize> = BTreeMap::new();
for page in threads.iter().filter_map(|thread| thread.anchor.page()) {
*page_counts.entry(page).or_default() += 1;
}
let heading_of = |thread: &CommentThread| group_of(&words, &kinds, &*page_label, thread, state.sort);
let mut shown_counts: BTreeMap<String, usize> = BTreeMap::new();
for thread in &shown {
if let Some((title, _)) = heading_of(thread) {
*shown_counts.entry(title).or_default() += 1;
}
}
let mut entries: Vec<(CardKey, RowEntry<'_>)> = Vec::new();
let mut last: Option<String> = None;
let mut groups = 0;
// The source lists the rows on show: a folded group keeps its heading and drops its cards.
let mut folded = false;
for thread in &shown {
let heading = if grouped { heading_of(thread) } else { None };
let depth = usize::from(heading.is_some());
if heading.is_none() {
folded = false;
}
if let Some((title, page)) = heading
&& last.as_deref() != Some(title.as_str())
{
let count = match page {
Some(number) if by_page => page_counts.get(&number).copied().unwrap_or_default(),
_ => shown_counts.get(&title).copied().unwrap_or_default(),
};
let open = !page.is_some_and(|number| state.collapsed_pages.contains(&number));
folded = !open;
entries.push((CardKey::Group(groups), RowEntry::Group { title: title.clone(), count: digits(count), page, open }));
groups += 1;
last = Some(title);
}
if !folded {
entries.push((CardKey::Thread(thread.id), RowEntry::Card { thread, depth }));
}
}
let source = Rows { entries };
let source = Rows { entries: row_entries(threads, &shown, state.sort, &state.collapsed_pages, &heading_of, &digits) };
let lead = state.selected.lead;
let chosen = state.selected.items.clone();
let mut selection = card_selection(&state.selected);
@@ -304,7 +304,6 @@ impl<'a> NotePopup<'a> {
}
/// The note's colour, straight RGB; `None` takes the default note colour.
#[must_use]
pub fn color(mut self, color: Option<[u8; 3]>) -> Self {
self.color = color;
self
@@ -313,28 +312,24 @@ impl<'a> NotePopup<'a> {
/// The annotation's screen rect (the first quad or the icon) and whether the host's page part is hovered: the
/// pop-up paints the faint connector from the mark to its window while `mark_hovered`, the window is hovered or the
/// note is selected, and only when the two do not overlap.
#[must_use]
pub fn anchor(mut self, mark: egui::Rect, mark_hovered: bool) -> Self {
self.anchor = Some((mark, mark_hovered));
self
}
/// Whether the note is the selected one.
#[must_use]
pub fn selected(mut self, selected: bool) -> Self {
self.selected = selected;
self
}
/// The current time in Unix seconds, which the ages count from.
#[must_use]
pub fn now(mut self, unix_seconds: i64) -> Self {
self.now = unix_seconds;
self
}
/// Whether the document allows commenting: replying and editing.
#[must_use]
pub fn allowed(mut self, allowed: bool) -> Self {
self.allowed = allowed;
self
+4 -6
View File
@@ -255,7 +255,6 @@ impl<'a> CommentComposer<'a> {
}
/// A header of `title` and the `author` above the field; the card is named `title`.
#[must_use]
pub fn header(mut self, title: impl Into<Label>, author: &'a str) -> Self {
self.header = Some((title.into(), author));
self
@@ -263,21 +262,18 @@ impl<'a> CommentComposer<'a> {
/// What the field asks for, in place of "Add a comment": its name and its placeholder ("Text to insert" for an
/// insertion).
#[must_use]
pub fn hint(mut self, hint: impl Into<Label>) -> Self {
self.hint = Some(hint.into());
self
}
/// The rule the post applies to the draft.
#[must_use]
pub fn draft_kind(mut self, kind: ComposerDraft) -> Self {
self.kind = kind;
self
}
/// When the composer closes.
#[must_use]
pub fn close(mut self, close: ComposerClose) -> Self {
self.close = close;
self
@@ -358,8 +354,10 @@ impl CommentComposer<'_> {
});
}
let hint = hint.clone().unwrap_or_else(|| words.add_comment.clone());
let field =
TextField::new(hint.clone(), Bind::bound(&mut *draft)).lines(COMPOSER_ROWS).placeholder(hint).submits().default_stop().show(ui);
let field = TextField::new(hint.clone(), Bind::bound(&mut *draft)).lines(COMPOSER_ROWS).placeholder(hint).submits().default_stop();
// An edit opens with the caret after the comment's text, so typing adds to it; a new comment's empty
// field has nothing to replace either way.
let field = if kind == ComposerDraft::New { field } else { field.keep_caret_on_open() }.show(ui);
cancel |= field.escaped;
let text = kind.posted(draft);
// The multi-line field submits on Cmd/Ctrl+Enter; plain Enter adds a line.
+7 -17
View File
@@ -163,8 +163,7 @@ fn eraser_reports_one_erase_per_annotation_crossing_a_b_a() {
#[trial]
fn per_stroke_ink_reports_a_create_per_release_and_a_dot_on_a_click() {
for kind in [AnnotationKind::Ink, AnnotationKind::FreehandHighlight] {
let mut options = DrawOptions::default();
options.ink = InkStrokes::PerStroke;
let options = DrawOptions { ink: InkStrokes::PerStroke, ..DrawOptions::default() };
let mut rig = rig(AnnotateTool::new(AnnotationTool::Draw(kind), 0).draw_options(options));
drag(&mut rig, Point::new(20.0, 20.0), Point::new(120.0, 60.0));
drag(&mut rig, Point::new(20.0, 100.0), Point::new(120.0, 140.0));
@@ -282,9 +281,7 @@ fn placing_kinds_report_a_place_and_a_short_text_box_drag_is_a_click() {
/// Ink and freehand highlights whose box its path reaches, and no stroke-by-stroke `Erase`.
#[trial]
fn the_path_eraser_reports_its_path_and_reach() {
let mut options = DrawOptions::default();
options.erase = EraseMode::Path;
options.eraser_radius = 6.0;
let options = DrawOptions { erase: EraseMode::Path, eraser_radius: 6.0, ..DrawOptions::default() };
let mut tool = AnnotateTool::new(AnnotationTool::Eraser, 0).draw_options(options);
let boxed = |id: u64, kind: AnnotationKind, rect: Rect| {
let mut a = annotation(id, kind, rect);
@@ -369,9 +366,7 @@ fn a_move_a_resize_and_a_shape_under_their_slips_commit_nothing() {
fn a_pass_through_tool_ignores_empty_and_markup_presses() {
let mut highlight = annotation(1, AnnotationKind::Highlight, Rect::new(100.0, 100.0, 200.0, 120.0));
highlight.points = vec![Point::new(100.0, 100.0), Point::new(200.0, 100.0), Point::new(200.0, 120.0), Point::new(100.0, 120.0)];
let mut options = SelectOptions::default();
options.empty_press = EmptyPress::PassThrough;
options.markup_press = MarkupPress::ClickOnly;
let options = SelectOptions { empty_press: EmptyPress::PassThrough, markup_press: MarkupPress::ClickOnly, ..SelectOptions::default() };
for (passes, tool) in
[(true, AnnotateTool::new(AnnotationTool::Select, 0).select_options(options)), (false, AnnotateTool::new(AnnotationTool::Select, 0))]
{
@@ -443,8 +438,7 @@ fn a_fixed_aspect_holds_on_every_corner_and_shift_takes_the_boxs_own() {
/// selected line's end draws a new line from there: the drawing tools do not take end and corner points.
#[trial]
fn while_drawing_edit_takes_resize_handles_but_not_point_handles() {
let mut options = SelectOptions::default();
options.handles_while_drawing = HandlesWhileDrawing::Edit;
let options = SelectOptions { handles_while_drawing: HandlesWhileDrawing::Edit, ..SelectOptions::default() };
let commits = |rig: &ToolFixture<AnnotateTool>| -> Vec<AnnotationEdit> {
rig.tool_mut()
.take_edits()
@@ -522,8 +516,7 @@ fn a_click_on_a_hosts_part_selects_toggles_and_opens_by_the_tools_rules() {
"a plain click on a selected comment keeps the others and makes it the primary"
);
let mut options = SelectOptions::default();
options.toggle = ToggleMods::ShiftOrCommand;
let mut options = SelectOptions { toggle: ToggleMods::ShiftOrCommand, ..SelectOptions::default() };
let mut tool = tool.select_options(options);
tool.click(AnnotationId(1), Mods::CMD, 1, &words);
assert_eq!(tool.selected, vec![AnnotationId(2)], "Command toggles under ShiftOrCommand");
@@ -601,8 +594,7 @@ fn colored_paths(shapes: &[Shape], color: Color32) -> Vec<&egui::epaint::PathSha
/// still previews the closing side); under the default `Angle45`, Shift snaps to 45-degree steps.
#[trial]
fn new_lines_arrows_and_poly_sides_honour_shift_lock() {
let mut ortho = SelectOptions::default();
ortho.shift_lock = ShiftLock::LevelOrPlumb;
let ortho = SelectOptions { shift_lock: ShiftLock::LevelOrPlumb, ..SelectOptions::default() };
let color = [0x10, 0x80, 0xE0];
let stroke_color = Color32::from_rgb(color[0], color[1], color[2]);
@@ -730,9 +722,7 @@ fn place_and_erase_drags_paint_their_preview_while_held() {
// Path eraser: swath stroke width matches 2 * eraser_radius while held, gone on release.
for radius in [6.0_f32, 36.0_f32] {
let mut options = DrawOptions::default();
options.erase = EraseMode::Path;
options.eraser_radius = radius;
let options = DrawOptions { erase: EraseMode::Path, eraser_radius: radius, ..DrawOptions::default() };
let mut eraser_rig = rig(AnnotateTool::new(AnnotationTool::Eraser, 0).draw_options(options));
let swath_widths = |shapes: &[Shape]| -> Vec<f32> {
shapes
+6 -4
View File
@@ -64,7 +64,7 @@ fn a_locked_comment_still_offers_reply_actions() {
});
fixture.settle();
let menus = fixture.by_role(Role::BUTTON);
let reply_menu = menus.into_iter().filter(|target| fixture.tree().name_of(target.node) == Some("More")).last().expect("the reply menu");
let reply_menu = menus.into_iter().rfind(|target| fixture.tree().name_of(target.node) == Some("More")).expect("the reply menu");
fixture.click(&reply_menu).settle();
let edit = fixture.by_label("Edit").expect("editing the reply is offered");
let delete = fixture.by_label("Delete").expect("deletion is shown");
@@ -201,8 +201,7 @@ fn the_filter_and_sorts_hide_and_order_threads() {
let mut reviewed = thread(9, 1, "Reviewed.");
reviewed.statuses = vec![reviewer("Ana", ReviewStatus::Accepted), reviewer("Bo", ReviewStatus::Rejected)];
let unreviewed = thread(10, 1, "Unreviewed.");
let mut filter = CommentFilter::default();
filter.hidden_statuses = vec![ReviewStatus::Accepted];
let mut filter = CommentFilter { hidden_statuses: vec![ReviewStatus::Accepted], ..CommentFilter::default() };
assert!(filter.shows(&reviewed), "Bo's Rejected still shows the thread");
assert!(filter.shows(&unreviewed), "a thread without statuses counts as None, which shows");
filter.hidden_statuses.push(ReviewStatus::Rejected);
@@ -407,9 +406,12 @@ fn an_editor_the_app_opens_takes_the_focus_once() {
assert_eq!(state.borrow().new_comment, "Elsewhere", "the add box keeps it");
}
/// A value the rig and its trial share.
type Shared<T> = Rc<RefCell<T>>;
/// A panel over 120 threads on page 1, scrolled by a reveal to thread 100; the threads are shared so a trial can
/// change them between frames.
fn long_list() -> (Rc<RefCell<Vec<CommentThread>>>, Rc<RefCell<CommentsPanelState>>, Fixture) {
fn long_list() -> (Shared<Vec<CommentThread>>, Shared<CommentsPanelState>, Fixture) {
let threads = Rc::new(RefCell::new((1..=120).map(|id| thread(id, 1, &format!("Note {id}."))).collect::<Vec<_>>()));
let state = Rc::new(RefCell::new(CommentsPanelState::default()));
let (shown_threads, shown_state) = (threads.clone(), state.clone());
+5 -3
View File
@@ -266,9 +266,11 @@ impl Section for Stored {
fn a_saved_image_round_trips_as_png_and_an_oversize_one_is_refused() {
let host = Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).settings(Arc::new(MemorySections::default())).build();
let initials = SavedSignature::Typed("AR".into());
let mut settings = SignatureSettings::default();
settings.signature = Some(SavedSignature::Image(SignatureImage::new(5, 1, PHOTO.to_vec())));
settings.initials = Some(initials.clone());
let settings = SignatureSettings {
signature: Some(SavedSignature::Image(SignatureImage::new(5, 1, PHOTO.to_vec()))),
initials: Some(initials.clone()),
..SignatureSettings::default()
};
host.set_setting(&settings);
let stored = host.setting::<Stored>();
+63 -49
View File
@@ -542,6 +542,68 @@ fn show_i_beam(cx: &mut Cx<'_, TextEditor<'_>>, phase: &PressPhase, vertical: bo
}
}
/// Applies one pass's editor input to `edits` in order: typing, the marked text, moves, deletes, selections and the
/// edit commands. Returns the text a Copy or Cut put on the clipboard.
fn apply_inputs(
edits: &mut Edits<'_>,
inputs: Vec<EditorInput>,
mode: EditorMode,
masked: bool,
pasted: Option<&str>,
fallback: Rect,
) -> Option<String> {
let mut copied: Option<String> = None;
let mut ending: Option<Range<usize>> = None;
for input in inputs {
if let Some(range) = ending.take() {
if let EditorInput::Text(text) = &input {
edits.commit_marked(range, text);
continue;
}
edits.drop_marked(range);
}
match input {
EditorInput::Preedit { text, cursor, .. } => {
let active = cursor.map(|bytes| byte_range_to_chars(&text, bytes));
ending = edits.preedit(&text, active);
}
EditorInput::ImeCommit => ending = edits.session.preedit.take(),
EditorInput::Text(text) => edits.done.changed |= edits.insert_typed(&text),
// In a field mode Enter (one-line) and Tab are the claimed keys that end the session, never text.
EditorInput::Newline if edits.session.preedit.is_none() && mode != EditorMode::FieldLine => {
edits.done.changed |= edits.insert_text("\n", EditKind::Typed);
}
EditorInput::Tab if mode == EditorMode::Canvas => edits.done.changed |= edits.insert_text("\t", EditKind::Typed),
EditorInput::Move(step, mods) => edits.motion(step, mods),
EditorInput::Delete { forward, by, .. } => edits.done.changed |= edits.delete(forward, by),
EditorInput::DeleteSurrounding { before, after, unit, .. } => edits.done.changed |= edits.delete_around(before, after, unit),
EditorInput::Select { anchor, focus, .. } => {
let lines = lines_of(&mut *edits.host, fallback);
edits.end_composition();
edits.selection = TextSelection { anchor: char_at(&lines, anchor), caret: char_at(&lines, focus) };
}
EditorInput::Edit(EditCommand::SelectAll) => edits.select_all(),
// A masked text never reaches the clipboard, and a Cut that cannot copy keeps the text.
EditorInput::Edit(EditCommand::Copy) if !masked => copied = edits.selected_text(),
EditorInput::Edit(EditCommand::Cut) if !masked => {
copied = edits.selected_text();
edits.done.changed |= edits.delete_selection();
}
EditorInput::Edit(EditCommand::Paste) => {
if let Some(text) = pasted {
let text = if mode == EditorMode::FieldLine { one_line(text) } else { text.to_string() };
edits.done.changed |= edits.insert_text(&text, EditKind::Pasted);
}
}
_ => {}
}
}
if let Some(range) = ending {
edits.drop_marked(range);
}
copied
}
/// The clipboard's text when the pass's input asks to paste and the clipboard has it ready.
fn pasted_text(cx: &mut Cx<'_, TextEditor<'_>>, inputs: &[EditorInput]) -> Option<std::sync::Arc<str>> {
if !inputs.iter().any(|input| matches!(input, EditorInput::Edit(EditCommand::Paste))) {
@@ -604,7 +666,6 @@ impl Component for TextEditor<'_> {
let now = cx.now();
let pasted = pasted_text(cx, &inputs);
let (mode, masked) = (self.mode, self.masked);
let mut copied: Option<String> = None;
let mut session = std::mem::take(cx.memory::<Session>());
let mut edits = Edits {
host: &mut *self.host,
@@ -620,54 +681,7 @@ impl Component for TextEditor<'_> {
edits.reconcile();
let fallback = space.doc_rect(cx.rect);
let mut ending: Option<Range<usize>> = None;
for input in inputs {
if let Some(range) = ending.take() {
if let EditorInput::Text(text) = &input {
edits.commit_marked(range, text);
continue;
}
edits.drop_marked(range);
}
match input {
EditorInput::Preedit { text, cursor, .. } => {
let active = cursor.map(|bytes| byte_range_to_chars(&text, bytes));
ending = edits.preedit(&text, active);
}
EditorInput::ImeCommit => ending = edits.session.preedit.take(),
EditorInput::Text(text) => edits.done.changed |= edits.insert_typed(&text),
// In a field mode Enter (one-line) and Tab are the claimed keys that end the session, never text.
EditorInput::Newline if edits.session.preedit.is_none() && mode != EditorMode::FieldLine => {
edits.done.changed |= edits.insert_text("\n", EditKind::Typed);
}
EditorInput::Tab if mode == EditorMode::Canvas => edits.done.changed |= edits.insert_text("\t", EditKind::Typed),
EditorInput::Move(step, mods) => edits.motion(step, mods),
EditorInput::Delete { forward, by, .. } => edits.done.changed |= edits.delete(forward, by),
EditorInput::DeleteSurrounding { before, after, unit, .. } => edits.done.changed |= edits.delete_around(before, after, unit),
EditorInput::Select { anchor, focus, .. } => {
let lines = lines_of(&mut *edits.host, fallback);
edits.end_composition();
edits.selection = TextSelection { anchor: char_at(&lines, anchor), caret: char_at(&lines, focus) };
}
EditorInput::Edit(EditCommand::SelectAll) => edits.select_all(),
// A masked text never reaches the clipboard, and a Cut that cannot copy keeps the text.
EditorInput::Edit(EditCommand::Copy) if !masked => copied = edits.selected_text(),
EditorInput::Edit(EditCommand::Cut) if !masked => {
copied = edits.selected_text();
edits.done.changed |= edits.delete_selection();
}
EditorInput::Edit(EditCommand::Paste) => {
if let Some(text) = &pasted {
let text = if mode == EditorMode::FieldLine { one_line(text) } else { text.to_string() };
edits.done.changed |= edits.insert_text(&text, EditKind::Pasted);
}
}
_ => {}
}
}
if let Some(range) = ending {
edits.drop_marked(range);
}
let copied = apply_inputs(&mut edits, inputs, mode, masked, pasted.as_deref(), fallback);
// A press is the pass's last pointer event (H0), so the pass's editor input came before it.
match press.phase {
PressPhase::Down { start, .. } if start.button == craft_behavior::PointerButton::Primary => {
+53 -28
View File
@@ -466,34 +466,12 @@ impl<'a> Canvas<'a> {
let mut zoom_anchor = None;
let wheel = cx.take_wheel();
let wheeled = wheel.is_some();
if let Some(wheel) = wheel {
let (line, os) = (self.navigation.wheel_line, cx.env.shell().os);
let mut zoomed = false;
if let Some(action) = motion.wheel.read(&wheel, line, os, &self.navigation) {
match action {
// The eased wheel hands a line's pan to the wheel service, which pays it out over the passes after.
WheelAction::Pan(delta) if self.navigation.eased_wheel && wheel.unit == WheelUnit::Line => line_pan = delta,
action => {
zoomed = !matches!(action, WheelAction::Pan(_));
// The pointer the wheel came at: the canvas's own widget is not hovered where an app widget in
// its body covers it.
let at = wheel.at.unwrap_or_else(|| view.rect.center());
let (anchor, zoom) = (WheelNavigation::zoom_anchor(&view, action, at, size), view.zoom);
jumped |= WheelNavigation::apply(&mut view, action, at, size, pixels_per_point);
if view.zoom != zoom {
zoom_anchor = anchor;
}
}
}
}
// A trackpad rotation or a twist of two fingers turns the view; a mirrored view turns the other way.
if let Some(degrees) = WheelNavigation::rotation(&WheelInput::of(&wheel, line, os), &self.navigation) {
view.rotation = normalized_angle(view.rotation + ViewTurn::screen_delta(degrees, view.flip_x));
jumped = true;
zoomed = true;
}
halt |= zoomed;
motion.glide.read(&wheel, now, !zoomed && self.navigation.touchpad_glide);
if let Some(wheel) = &wheel {
let read = self.read_wheel(cx, &mut motion, &mut view, wheel, now);
line_pan = read.line_pan;
jumped |= read.jumped;
zoom_anchor = read.zoom_anchor.or(zoom_anchor);
halt |= read.zoomed;
}
// Every pass feeds the ease, the line pan or nothing, so owed motion keeps paying; the service takes the time
// from its own clock, so a later pass of the same frame pays nothing.
@@ -622,6 +600,40 @@ impl<'a> Canvas<'a> {
Settled { target, shown, easing, keys, wheel, auto_scrolling, mark, swallowing, zoom_anchor }
}
/// One pass's wheel on `view`: a pan the eased wheel pays out later, or a pan, zoom or turn applied now, and the
/// touchpad glide's reading of it.
fn read_wheel(&self, cx: &mut Cx<'_, Self>, motion: &mut ViewMotion, view: &mut CanvasView, wheel: &Wheel, now: f64) -> WheelRead {
let pixels_per_point = cx.env.scale().0;
let size = self.document_size().unwrap_or(Size::ZERO);
let (line, os) = (self.navigation.wheel_line, cx.env.shell().os);
let mut read = WheelRead::default();
if let Some(action) = motion.wheel.read(wheel, line, os, &self.navigation) {
match action {
// The eased wheel hands a line's pan to the wheel service, which pays it out over the passes after.
WheelAction::Pan(delta) if self.navigation.eased_wheel && wheel.unit == WheelUnit::Line => read.line_pan = delta,
action => {
read.zoomed = !matches!(action, WheelAction::Pan(_));
// The pointer the wheel came at: the canvas's own widget is not hovered where an app widget in
// its body covers it.
let at = wheel.at.unwrap_or_else(|| view.rect.center());
let (anchor, zoom) = (WheelNavigation::zoom_anchor(view, action, at, size), view.zoom);
read.jumped |= WheelNavigation::apply(view, action, at, size, pixels_per_point);
if view.zoom != zoom {
read.zoom_anchor = anchor;
}
}
}
}
// A trackpad rotation or a twist of two fingers turns the view; a mirrored view turns the other way.
if let Some(degrees) = WheelNavigation::rotation(&WheelInput::of(wheel, line, os), &self.navigation) {
view.rotation = normalized_angle(view.rotation + ViewTurn::screen_delta(degrees, view.flip_x));
read.jumped = true;
read.zoomed = true;
}
motion.glide.read(wheel, now, !read.zoomed && self.navigation.touchpad_glide);
read
}
/// One pass of the middle button's autoscroll over `view`: a middle press on the background starts it under
/// [`MiddleButton::AutoScroll`] (away from the tool regions, and the press focuses the canvas); while it runs each
/// pass scrolls toward the pointer (the other way under Invert Middle) and asks for the next pass; any input ends
@@ -1077,3 +1089,16 @@ fn clamped(mut view: CanvasView, document: Option<Size>, navigation: &Navigation
}
view
}
/// What a pass's wheel did to the view ([`Canvas::read_wheel`]).
#[derive(Default)]
struct WheelRead {
/// A line's pan the eased wheel pays out over the passes after.
line_pan: Vec2,
/// Whether the view moved at once.
jumped: bool,
/// The screen point a zoom kept still.
zoom_anchor: Option<Pos2>,
/// Whether the wheel zoomed or turned the view.
zoomed: bool,
}
@@ -129,8 +129,7 @@ fn latch_middle(fixture: &mut Fixture) {
fn latched_middle_scroll(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let room = crate::testing::stage(ui);
let view = data.value("view", StoryDocument::STANDARD.view(room, ui.pixels_per_point(), LATCHED));
let mut navigation = NavigationOptions::default();
navigation.middle_button = MiddleButton::AutoScroll;
let navigation = NavigationOptions { middle_button: MiddleButton::AutoScroll, ..NavigationOptions::default() };
let target = ViewTarget::new(StoryDocument::STANDARD.rect().size());
let canvas = Canvas::new("Document").view(Bind::bound(view)).document(target).navigation(navigation);
canvas.show_at(ui, room, |ui, body| show_document(ui, body.rect, &StoryDocument::STANDARD)).output.into()
+4 -1
View File
@@ -359,6 +359,9 @@ impl<D> Outcome for SplitViewsOutput<D> {
}
}
/// Whether a tab drop of these documents may land on a target.
type AcceptsDrop<'a, D> = Box<dyn Fn(&[D], TabDropTarget) -> bool + 'a>;
/// One canvas area shown as views of one document, or a grid of panes the caller fills (one document each), in the
/// panes of a [`SplitLayout`]. The active pane is the app's: it routes tools and keys there. An inactive pane is a
/// Tab stop: a press, Enter or Space reports it in [`SplitViewsOutput::activated`]. By default the first press selects
@@ -384,7 +387,7 @@ pub struct SplitViews<'a, D: Clone + Send + Sync + 'static = ()> {
#[prop]
count: usize,
activated: Option<usize>,
accepts: Option<Box<dyn Fn(&[D], TabDropTarget) -> bool + 'a>>,
accepts: Option<AcceptsDrop<'a, D>>,
/// The tab drop released over the views in this pass.
tab_drop: Option<TabDrop<D>>,
}
+5 -4
View File
@@ -17,7 +17,8 @@ pub struct Entry<T> {
#[derive(Clone, Debug, PartialEq, crate::contract::MemoProps)]
enum Row<T> {
Item(Item<T>),
// Boxed: an item's labels make it far larger than a heading or a separator.
Item(Box<Item<T>>),
Heading(Label),
Separator,
}
@@ -39,7 +40,7 @@ impl<T> Entry<T> {
/// An entry reporting `value` when picked, shown as `label`: enabled and unchecked, without an icon.
pub fn new(value: T, label: impl Into<Label>) -> Self {
Entry {
row: Row::Item(Item {
row: Row::Item(Box::new(Item {
value,
label: label.into(),
closed: None,
@@ -49,7 +50,7 @@ impl<T> Entry<T> {
description: None,
checked: false,
stepped: true,
}),
})),
}
}
@@ -156,7 +157,7 @@ impl<T> Entry<T> {
/// The text a closed control shows for the entry: its closed label, else its label.
pub fn face_label(&self) -> &Label {
match &self.row {
Row::Item(Item { closed: Some(closed), .. }) => closed,
Row::Item(item) => item.closed.as_ref().unwrap_or(&item.label),
_ => self.label(),
}
}
@@ -138,9 +138,12 @@ pub(crate) fn scroll_moves(ctx: &Context, owner: Id, quiet: bool) -> Vec<(NavMov
})
}
/// Moves with their modifiers, in the order they came.
type Moves = Vec<(NavMove, MoveMods)>;
/// [`scroll_moves`] apart: the page and end moves a component inside left for its scroll owner, and the moves a
/// region's fallback collection takes as its own keys (every move, page and end included, L-319).
pub(crate) fn scroll_and_fallback_moves(ctx: &Context, owner: Id, quiet: bool) -> (Vec<(NavMove, MoveMods)>, Vec<(NavMove, MoveMods)>) {
pub(crate) fn scroll_and_fallback_moves(ctx: &Context, owner: Id, quiet: bool) -> (Moves, Moves) {
pass_state::with::<ScrollMoves, _>(ctx, |moves| {
let (mut scrolls, mut fallback) = (Vec::new(), Vec::new());
for &(id, mv, mods, through_fallback) in &moves.0 {
+4 -1
View File
@@ -504,12 +504,15 @@ impl WindowDropTarget<OsFiles> for ReadOnWindow {
}
}
/// The drops a window took: the pass each landed in, with each file's name and content.
type Drops = Vec<(usize, Vec<(String, Option<Vec<u8>>)>)>;
/// A window that takes dropped files with their content, and the pass of its frame each drop landed in.
#[derive(Component)]
struct ReadDrop<'a> {
#[common]
common: Common,
landed: &'a RefCell<Vec<(usize, Vec<(String, Option<Vec<u8>>)>)>>,
landed: &'a RefCell<Drops>,
pass: usize,
}
@@ -344,7 +344,6 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
/// While no value differs from the one the dialog opened with, a Close button stands in place of OK and Cancel (as
/// a Properties dialog does); the first edit brings them back.
#[must_use]
pub fn close_unchanged(mut self, on: bool) -> Self {
self.close_unchanged = on;
self
@@ -1248,7 +1248,7 @@ pub(crate) fn edited_rows(params: &[Param], before: &DialogFields, after: &Dialo
.iter()
.filter(|param| {
differs(&param.key)
|| param.unit_key().is_some_and(|key| differs(key))
|| param.unit_key().is_some_and(&differs)
|| matches!(&param.kind, ParamKind::Custom(row) if row.companions.iter().any(|key| differs(key)))
|| (matches!(param.kind, ParamKind::Files { .. }) && (differs(&param.folder_key()) || differs(&param.use_folder_key())))
})
@@ -274,21 +274,18 @@ impl<'a> PasswordFields<'a> {
}
/// Adds the Re-type field over `confirm`, with the mismatch help and the strength help and meter.
#[must_use]
pub fn confirm(mut self, confirm: Bind<'a, String>) -> Self {
self.confirm = Some(confirm);
self
}
/// With a confirmation field, two empty entries are valid too: they clear the password. Off by default.
#[must_use]
pub fn clearable(mut self, on: bool) -> Self {
self.clearable = on;
self
}
/// The line under the field, in the error colour.
#[must_use]
pub fn error(mut self, error: Option<Label>) -> Self {
self.error = error;
self
@@ -296,7 +293,6 @@ impl<'a> PasswordFields<'a> {
/// The first field stands across the width with no caption before it, its name its placeholder: a prompt that asks
/// for one password, as production's does.
#[must_use]
pub fn bare(mut self, bare: bool) -> Self {
self.bare = bare;
self
+3 -4
View File
@@ -475,7 +475,6 @@ impl<'a> StartScreen<'a> {
/// Shows `body` as a host section at `place` on the start screen, after the sections given there before it. Its
/// least width counts in whether the rail fits beside the page.
#[must_use]
pub fn section(mut self, place: StartPlace, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) + 'a) -> Self {
self.sections.push((place, RefCell::new(Box::new(body))));
self
@@ -1166,9 +1165,9 @@ fn shown_files(folder: &PinnedFolder) -> &[PinnedFile] {
fn folder_note(words: &ShellWords, folder: &PinnedFolder) -> Option<Label> {
match &folder.listing {
None => None,
Some(FolderListing::Pending) => Some(words.looking_for_files.clone().into()),
Some(FolderListing::Unavailable) => Some(words.folder_unavailable.clone().into()),
Some(FolderListing::Listed { files, .. }) if files.is_empty() => Some(words.folder_empty.clone().into()),
Some(FolderListing::Pending) => Some(words.looking_for_files.clone()),
Some(FolderListing::Unavailable) => Some(words.folder_unavailable.clone()),
Some(FolderListing::Listed { files, .. }) if files.is_empty() => Some(words.folder_empty.clone()),
Some(FolderListing::Listed { files, total }) if *total > files.len() => {
let (shown, total) = (files.len().to_string(), total.to_string());
Some(Label::from(words.newest_of.fill(&[("shown", shown.as_str()), ("total", total.as_str())])))
+3 -4
View File
@@ -4,7 +4,7 @@
use craft_ui::buttons::Button;
use craft_ui::contract::{Bind, Role, Show as _};
use craft_ui::display::Text;
use craft_ui::runtime::env::{Env, Label};
use craft_ui::runtime::env::Env;
use craft_ui::shell::{
FolderListing, PINNED_FILES_SHOWN, PinnedFile, PinnedFolder, RecentFile, RecentList, RecentSort, RecentView, ShellWords, StartAction,
StartLayout, StartLink, StartPlace, StartScreen, Template,
@@ -379,9 +379,8 @@ fn pinned_screen(folders: Vec<PinnedFolder>) -> (Fixture, Log, Pins, Notes) {
let folders = held.borrow().clone();
let env = Env::of(ui);
let words = env.words::<ShellWords>();
*words_seen.borrow_mut() = [&words.looking_for_files, &words.folder_unavailable]
.map(|word| env.view().resolve(&Label::from(word.clone())).as_str().to_owned())
.to_vec();
*words_seen.borrow_mut() =
[&words.looking_for_files, &words.folder_unavailable].map(|word| env.view().resolve(word).as_str().to_owned()).to_vec();
let out = StartScreen::new(Bind::bound(&mut view), Bind::bound(&mut sort), &[]).pinned(&folders).show(ui);
seen.borrow_mut().extend(out.actions);
});
+2 -2
View File
@@ -198,11 +198,11 @@ impl Component for Picture<'_> {
// A side past the cap is refused below; the saturating cast keeps that refusal for absurd sizes.
let (width, height) = (width as u32, height as u32);
let store = store(&cx.ctx);
let key = (cx.resolved.id, svg_key(*svg, width, height));
let key = (cx.resolved.id, svg_key(svg, width, height));
let texture = match store.state(&cx.ctx, &key, self.revision) {
TextureState::Ready(texture) => texture,
TextureState::Empty | TextureState::Failed { .. } => return,
_ => match rasterise_svg(*svg, width, height) {
_ => match rasterise_svg(svg, width, height) {
Some(image) => store.put(&cx.ctx, key, self.revision, image),
None => {
log::error!("picture {:?}: the SVG is refused or does not draw at {width}x{height}", cx.resolved.id);
+9 -3
View File
@@ -1,7 +1,7 @@
//! Painting a row's trailing items, toggles, thumbnails, text and cells.
use super::ListRow;
use super::placement::{Placed, action_link};
use super::placement::{Placed, StatusMeasure, action_link};
use super::show::{LINK, STATUS_ACTION, TEXT_CELL, TOGGLE};
use super::style::{ListRowStyle, RowForm, row_ink_of};
use super::thumb::{RowThumb, target_at};
@@ -292,8 +292,14 @@ impl ListRow<'_> {
let action = {
let draw = ui.draw();
// The action's slot is its part's rect, which `parts` declared from the link's measured width.
let slots =
self.status_slots(*at, cell, sizes, rtl, role, &|run| draw.layout(run, f32::INFINITY).size().x, &|_| cx.part(part).rect.width());
let slots = self.status_slots(
*at,
cell,
sizes,
rtl,
role,
StatusMeasure { text_width: &|run| draw.layout(run, f32::INFINITY).size().x, action_width: &|_| cx.part(part).rect.width() },
);
if let (Some(slot), Some(icon)) = (slots.icon, tone_icon(status.tone)) {
draw.icon(Rect::from_center_size(slot.center(), Vec2::splat(sizes.mark)), &IconSpec::svg(IconId::new(icon)).color(ink));
}
+9 -11
View File
@@ -394,19 +394,11 @@ impl ListRow<'_> {
}
/// The pieces of the status cell `at` in its `cell`, inset as a text cell's text is, for a text and a link in
/// `role` as `text_width` measures the text and `action_width` the action's link. The action keeps its whole width
/// `role` as `measure` measures the text and the action's link. The action keeps its whole width
/// where the cell has room for it; the text
/// takes what the icon and the action leave and is cut there.
pub(super) fn status_slots(
&self,
at: usize,
cell: Rect,
sizes: &Sizes,
rtl: bool,
role: TypeRole,
text_width: &dyn Fn(&TextRun<'_>) -> f32,
action_width: &dyn Fn(&Label) -> f32,
) -> StatusSlots {
pub(super) fn status_slots(&self, at: usize, cell: Rect, sizes: &Sizes, rtl: bool, role: TypeRole, measure: StatusMeasure<'_>) -> StatusSlots {
let StatusMeasure { text_width, action_width } = measure;
let status = &self.statuses[at].status;
let room = Flow::new(cell, rtl).span(sizes.cell_inset, sizes.cell_room(cell.width()));
let flow = Flow::new(room, rtl);
@@ -647,3 +639,9 @@ pub struct RowPlacement {
/// The label's least width under the fixed sizes.
pub min_label: f32,
}
/// How a status cell's pieces measure: the text's width and the action link's.
pub(super) struct StatusMeasure<'m> {
pub(super) text_width: &'m dyn Fn(&TextRun<'_>) -> f32,
pub(super) action_width: &'m dyn Fn(&Label) -> f32,
}
+50 -38
View File
@@ -3,7 +3,7 @@
use super::ListRowStyleKey;
use super::output::{RowEvent, RowOutput};
use super::paint::draw_clip_arrow;
use super::placement::{Sizes, action_link, lead_run};
use super::placement::{Placed, Sizes, StatusMeasure, action_link, lead_run};
use super::style::{FillKey, ListRowStyle, RowForm, fill_of, hued_ink, quiet_row_ink, row_ink_of, selected_outline};
use super::thumb::{RowThumb, target_at};
use super::trailing::{HostedSize, TrailingFace, TrailingItem, TrailingPart, below_key, cell_key, field_key};
@@ -207,39 +207,7 @@ impl Component for ListRow<'_> {
self.measure_hosted(cx);
let widths = self.widths(&cx.style.sizes, &|run| cx.layout_at(run, f32::INFINITY).size().x);
let placed = self.place(&cx.style.sizes, &widths, rect, cx.flow.is_rtl());
for (at, cell) in &placed.toggles {
let toggle = &self.toggles[*at];
let mut flags = Flags::empty();
flags.set(Flags::CHECKED, toggle.state == ToggleState::On);
flags.set(Flags::MIXED, toggle.state == ToggleState::Mixed);
let shape = if matches!(toggle.face, ToggleFace::Check) {
Rect::from_center_size(cell.center(), Vec2::splat(cx.style.sizes.icon))
} else {
*cell
};
let key = self.toggle_keys.iter().find(|(column, _)| *column == toggle.column).map(|(_, chord)| *chord);
let tip = match (&toggle.tooltip, key) {
(Some(tip), None) => Some(tip.clone()),
(tip, Some(chord)) => {
let base = match tip {
Some(tip) => cx.env.resolve(tip).as_str().to_owned(),
None => named(toggle.name_pattern(&cx.words::<ListWords>()), cx.resolved.label),
};
Some(Label::from(crate::contract::tooltip::with_chord(&base, &chord, crate::runtime::windows::os_of(cx.ui.ctx()))))
}
(None, None) => None,
};
let held = match &self.pressed {
Some(RowPressed::Cell(column)) => *column == toggle.column,
Some(RowPressed::Row) => toggle.row_press,
_ => false,
};
let part = cx.part(TOGGLE.at(*at as u64), shape).flags(flags).held(held);
let _ = match tip {
Some(tip) => part.tooltip(tip),
None => part,
};
}
self.toggle_parts(&placed, cx);
for (at, position, _) in &placed.texts {
if self.cell_selects(*at) {
cx.selectable_text(TEXT_CELL.at(*position as u64), &self.cell_run(cx.style, *at));
@@ -278,10 +246,17 @@ impl Component for ListRow<'_> {
let role = cx.style.cell.role;
for (at, position, cell) in &placed.statuses {
let cell = Rect::from_x_y_ranges(cell.x_range(), rect.y_range());
let slots =
self.status_slots(*at, cell, &cx.style.sizes, cx.flow.is_rtl(), role, &|run| cx.layout_at(run, f32::INFINITY).size().x, &|action| {
cx.face(action_link(action, role)).x
});
let slots = self.status_slots(
*at,
cell,
&cx.style.sizes,
cx.flow.is_rtl(),
role,
StatusMeasure {
text_width: &|run| cx.layout_at(run, f32::INFINITY).size().x,
action_width: &|action| cx.face(action_link(action, role)).x,
},
);
let status = &self.statuses[*at].status;
if let Some(tip) = &status.tip {
// The tip covers the icon and the text; the action keeps its own pointer target beside them.
@@ -756,4 +731,41 @@ impl ListRow<'_> {
fn part_name(&self, part: TrailingPart, name: &Label, words: &ListWords, row: &str) -> Label {
if part == TrailingPart::MENU { Label::from(named(&words.more, row)) } else { name.clone() }
}
/// The parts of the row's toggle cells: their flags, held state and tooltip with the toggle's key.
fn toggle_parts(&self, placed: &Placed, cx: &mut PartsCx<'_, Self>) {
for (at, cell) in &placed.toggles {
let toggle = &self.toggles[*at];
let mut flags = Flags::empty();
flags.set(Flags::CHECKED, toggle.state == ToggleState::On);
flags.set(Flags::MIXED, toggle.state == ToggleState::Mixed);
let shape = if matches!(toggle.face, ToggleFace::Check) {
Rect::from_center_size(cell.center(), Vec2::splat(cx.style.sizes.icon))
} else {
*cell
};
let key = self.toggle_keys.iter().find(|(column, _)| *column == toggle.column).map(|(_, chord)| *chord);
let tip = match (&toggle.tooltip, key) {
(Some(tip), None) => Some(tip.clone()),
(tip, Some(chord)) => {
let base = match tip {
Some(tip) => cx.env.resolve(tip).as_str().to_owned(),
None => named(toggle.name_pattern(&cx.words::<ListWords>()), cx.resolved.label),
};
Some(Label::from(crate::contract::tooltip::with_chord(&base, &chord, crate::runtime::windows::os_of(cx.ui.ctx()))))
}
(None, None) => None,
};
let held = match &self.pressed {
Some(RowPressed::Cell(column)) => *column == toggle.column,
Some(RowPressed::Row) => toggle.row_press,
_ => false,
};
let part = cx.part(TOGGLE.at(*at as u64), shape).flags(flags).held(held);
let _ = match tip {
Some(tip) => part.tooltip(tip),
None => part,
};
}
}
}
+4 -1
View File
@@ -324,10 +324,13 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Collection for List<'_, K> {
}
}
/// The texts a row's key matches by.
type KeyTexts<'a, K> = Box<dyn Fn(&K) -> Vec<Label> + 'a>;
/// What `List::filter` keeps: the query and the texts a row's key matches by.
struct Filter<'a, K> {
query: String,
texts: Box<dyn Fn(&K) -> Vec<Label> + 'a>,
texts: KeyTexts<'a, K>,
}
impl<K> Filter<'_, K> {
+17 -12
View File
@@ -693,18 +693,7 @@ impl Component for Notice<'_> {
y += size.y;
}
if !plan.action_rows.is_empty() {
y += stack.max(gap);
for (range, row_height) in &plan.action_rows {
let mut line = Flow::new(Rect::from_min_size(Pos2::new(rect.left(), y), Vec2::new(rect.width(), *row_height)), rtl);
for size in plan.actions.get(range.clone()).unwrap_or_default() {
let width = size.x.min(line.rect().width().max(0.0));
let (slot, rest) = line.take_start(width);
let top = y + (*row_height - size.y) / 2.0;
placed.actions.push(Rect::from_min_size(Pos2::new(slot.min.x, top), Vec2::new(width, size.y)));
line = rest.take_start(gap).1;
}
y += row_height + gap;
}
place_action_rows(&plan, rect, y + stack.max(gap), rtl, gap, &mut placed.actions);
}
} else {
let mut y = rect.top() + ((rect.height() - plan.height) / 2.0).max(0.0);
@@ -926,3 +915,19 @@ pub(crate) fn tone_icon(tone: Tone) -> Option<&'static str> {
_ => None,
}
}
/// Places a row notice's action rows across `rect` from `top` down, each action at its width and centred on its row.
fn place_action_rows(plan: &Plan, rect: Rect, top: f32, rtl: bool, gap: f32, actions: &mut Vec<Rect>) {
let mut y = top;
for (range, row_height) in &plan.action_rows {
let mut line = Flow::new(Rect::from_min_size(Pos2::new(rect.left(), y), Vec2::new(rect.width(), *row_height)), rtl);
for size in plan.actions.get(range.clone()).unwrap_or_default() {
let width = size.x.min(line.rect().width().max(0.0));
let (slot, rest) = line.take_start(width);
let top = y + (*row_height - size.y) / 2.0;
actions.push(Rect::from_min_size(Pos2::new(slot.min.x, top), Vec2::new(width, size.y)));
line = rest.take_start(gap).1;
}
y += row_height + gap;
}
}
+3 -3
View File
@@ -838,15 +838,15 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for TileGrid<'_, K>
let line = PaintShape::Path(vec![rect.center_top(), rect.center_bottom()]);
ui.draw().stroke(&line, StrokeWidth::Thick, style.insert);
}
let ink = if hovered { style.insert.clone() } else { style.insert_idle.clone() };
let ink = if hovered { style.insert } else { style.insert_idle };
// The insertion target must be discoverable before the pointer is over it.
let center = rect.center();
let radius = (rect.width() * 0.4).min(9.0);
let arm = radius * 0.45;
let draw = ui.draw();
draw.fill(&PaintShape::Circle(center, radius), style.pinned);
draw.stroke(&PaintShape::Circle(center, radius), StrokeWidth::Thin, ink.clone());
draw.stroke(&PaintShape::Path(vec![center - vec2(arm, 0.0), center + vec2(arm, 0.0)]), StrokeWidth::Medium, ink.clone());
draw.stroke(&PaintShape::Circle(center, radius), StrokeWidth::Thin, ink);
draw.stroke(&PaintShape::Path(vec![center - vec2(arm, 0.0), center + vec2(arm, 0.0)]), StrokeWidth::Medium, ink);
draw.stroke(&PaintShape::Path(vec![center - vec2(0.0, arm), center + vec2(0.0, arm)]), StrokeWidth::Medium, ink);
}
}
@@ -28,9 +28,12 @@ fn paragraph(text: &'static str, width: f32) -> Fixture {
fixture
}
/// A painted row: its top, its text in reading order, and each glyph's character, screen left and advance.
type PaintedRow = (f32, String, Vec<(char, f32, f32)>);
/// Each painted row of the text shape whose text holds `part`: its top, its text in reading order, and each glyph's
/// character, screen left and advance.
fn painted_rows(fixture: &mut Fixture, part: &str) -> Vec<(f32, String, Vec<(char, f32, f32)>)> {
fn painted_rows(fixture: &mut Fixture, part: &str) -> Vec<PaintedRow> {
let shapes = fixture.frame_shapes();
let shown = shapes
.iter()