Skip to main content

gpui_kit_grid/
policy.rs

1//! Replaceable behaviors of the view (AGENTS.md, "Replaceable Behavior"):
2//! when a new display order is shown, where background work runs, how
3//! columns move, how autofit measures, how a header click changes the sort,
4//! which selected rows a command acts on, which lines take the selection
5//! and what a command over a line acts on, how a press or a key edits the
6//! selection, which press opens the context menu, which press expands a
7//! group caption or a tree row, which input opens a cell editor and how an
8//! edit behaves under live data.
9
10use std::{ops::Range, sync::Arc, time::Duration};
11
12use gpui_kit::{App, AppContext as _, Modifiers, MouseButton, Pixels, PlatformInfo, Task, px};
13use web_time::Instant;
14
15use crate::{
16    engine::{Branch, GroupInfo, Projection, SortDirection},
17    model::{ColumnIx, ColumnSet, GridColumns as _, GridRow, OwnedValue},
18    state::{
19        CellContent, ColumnZone, DropPlace, DropTarget, EditInput, GridSelection, RowDrag,
20        ScopedSelection, SelectionMode,
21    },
22    store::StoreSnapshot,
23};
24
25/// What a [`ReorderPolicy`] knows when a new display order is ready.
26#[derive(Clone, Copy, Debug)]
27pub struct ReorderContext {
28    now: Instant,
29    held_since: Instant,
30    pointer_inside: bool,
31    user_action: bool,
32    menu_open: bool,
33    tooltip_shown: bool,
34    // Editing, waiting commits, row drags and the column chooser.
35    editing: bool,
36    pending_edits: bool,
37    drag_over: bool,
38    column_chooser_open: bool,
39}
40
41impl ReorderContext {
42    pub(crate) fn new(
43        now: Instant,
44        held_since: Instant,
45        pointer_inside: bool,
46        user_action: bool,
47    ) -> Self {
48        Self {
49            now,
50            held_since,
51            pointer_inside,
52            user_action,
53            menu_open: false,
54            tooltip_shown: false,
55            editing: false,
56            pending_edits: false,
57            drag_over: false,
58            column_chooser_open: false,
59        }
60    }
61
62    /// This context with the grid's context menu open or closed.
63    pub(crate) fn with_menu_open(mut self, menu_open: bool) -> Self {
64        self.menu_open = menu_open;
65        self
66    }
67
68    /// This context with a cell tooltip shown or not.
69    pub(crate) fn with_tooltip_shown(mut self, tooltip_shown: bool) -> Self {
70        self.tooltip_shown = tooltip_shown;
71        self
72    }
73
74    /// This context with a cell editor open or not.
75    pub(crate) fn with_editing(mut self, editing: bool) -> Self {
76        self.editing = editing;
77        self
78    }
79
80    /// This context with commits waiting or not.
81    pub(crate) fn with_pending_edits(mut self, pending_edits: bool) -> Self {
82        self.pending_edits = pending_edits;
83        self
84    }
85
86    /// This context with the grid's column chooser open or not.
87    pub(crate) fn with_column_chooser_open(mut self, column_chooser_open: bool) -> Self {
88        self.column_chooser_open = column_chooser_open;
89        self
90    }
91
92    /// This context with a drag over the rows or not.
93    pub(crate) fn with_drag_over(mut self, drag_over: bool) -> Self {
94        self.drag_over = drag_over;
95        self
96    }
97
98    /// The current time of the store clock.
99    pub fn now(&self) -> Instant {
100        self.now
101    }
102
103    /// When the shown order became outdated (equals `now` for a fresh one).
104    pub fn held_since(&self) -> Instant {
105        self.held_since
106    }
107
108    /// Returns true if the pointer is over the grid body.
109    pub fn is_pointer_inside(&self) -> bool {
110        self.pointer_inside
111    }
112
113    /// Returns true if the new order comes from a user action (a sort click,
114    /// a new view, a new data set) rather than from streaming data.
115    pub fn is_user_action(&self) -> bool {
116        self.user_action
117    }
118
119    /// Returns true while the grid's context menu is open. The built-in
120    /// policies hold the order then, except for a user action: the rows of
121    /// the menu's target stay where they were.
122    pub fn is_menu_open(&self) -> bool {
123        self.menu_open
124    }
125
126    /// Returns true while a cell tooltip is shown: GPUI built it for the
127    /// hovered cell, which has not changed since, and no button was pressed.
128    /// The built-in policies ignore it, since a resting pointer would hold
129    /// the order without end; a policy of the application may hold on it.
130    pub fn is_tooltip_shown(&self) -> bool {
131        self.tooltip_shown
132    }
133
134    /// Returns true while a cell editor is open: the built-in policies then
135    /// hold the order, as for the context menu, unless the new order comes
136    /// from a user action.
137    pub fn is_editing(&self) -> bool {
138        self.editing
139    }
140
141    /// Returns true while commits wait for `LiveGridState::resolve_edit`
142    /// or for the store. The built-in policies ignore it; a policy may hold
143    /// on it.
144    pub fn has_pending_edits(&self) -> bool {
145        self.pending_edits
146    }
147
148    /// Returns true while a row drag is over this grid's rows. The built-in
149    /// policies ignore it.
150    pub fn is_drag_over(&self) -> bool {
151        self.drag_over
152    }
153
154    /// Returns true while the grid's column chooser is open. The built-in
155    /// policies ignore it.
156    pub fn is_column_chooser_open(&self) -> bool {
157        self.column_chooser_open
158    }
159}
160
161/// What to do with a new display order.
162#[derive(Clone, Copy, Debug, PartialEq, Eq)]
163pub enum ReorderDecision {
164    /// Show it now.
165    Apply,
166    /// Keep the current order until this instant, then ask again.
167    HoldUntil(Instant),
168    /// Keep the current order until the pointer leaves, the application calls
169    /// [`crate::LiveGridState::apply_held_order`], or a user action arrives.
170    Hold,
171}
172
173/// Decides when a new display order replaces the shown one, so rows do not
174/// jump under the user's pointer more than the application wants.
175///
176/// The default is [`LiveReorder`], the industry standard, as in AG Grid and
177/// DevExpress; [`HoldReorder`] and [`ManualReorder`] are the built-in
178/// alternatives. All three hold the order while the context menu or a cell
179/// editor is open ([`ReorderContext::is_menu_open`],
180/// [`ReorderContext::is_editing`]), unless the new order comes from a user
181/// action. None holds it for commits that wait
182/// ([`ReorderContext::has_pending_edits`]): a policy of the application may.
183pub trait ReorderPolicy: 'static {
184    /// Called when a new order is ready, when the pointer leaves the grid,
185    /// when the context menu or a cell editor closes, and when a
186    /// [`ReorderDecision::HoldUntil`] deadline passes.
187    fn decide(&self, context: &ReorderContext) -> ReorderDecision;
188}
189
190/// Show every new order at once (throttled by `min_rebuild_interval`); hold
191/// it only while the context menu or a cell editor is open: the row under
192/// the field stays where it is.
193#[derive(Clone, Copy, Debug, Default)]
194pub struct LiveReorder;
195
196impl ReorderPolicy for LiveReorder {
197    fn decide(&self, context: &ReorderContext) -> ReorderDecision {
198        if (context.is_menu_open() || context.is_editing()) && !context.is_user_action() {
199            ReorderDecision::Hold
200        } else {
201            ReorderDecision::Apply
202        }
203    }
204}
205
206/// Keep the order while the pointer is over the grid, at most `max`, and
207/// while the context menu or a cell editor is open, however long.
208#[derive(Clone, Copy, Debug)]
209pub struct HoldReorder {
210    max: Duration,
211}
212
213impl HoldReorder {
214    /// Holds for at most `max` while the pointer is over the grid.
215    pub fn new(max: Duration) -> Self {
216        Self { max }
217    }
218}
219
220impl Default for HoldReorder {
221    fn default() -> Self {
222        Self::new(Duration::from_secs(3))
223    }
224}
225
226impl ReorderPolicy for HoldReorder {
227    fn decide(&self, context: &ReorderContext) -> ReorderDecision {
228        if context.is_user_action() {
229            return ReorderDecision::Apply;
230        }
231        // The menu and the editor close by an explicit act, so this hold has
232        // an end.
233        if context.is_menu_open() || context.is_editing() {
234            return ReorderDecision::Hold;
235        }
236        if !context.is_pointer_inside() {
237            return ReorderDecision::Apply;
238        }
239        let deadline = context.held_since() + self.max;
240        if context.now() >= deadline {
241            ReorderDecision::Apply
242        } else {
243            ReorderDecision::HoldUntil(deadline)
244        }
245    }
246}
247
248/// Keep the order until the application applies it (for example from a
249/// "Refresh order" button); user actions still apply at once. An open
250/// context menu changes nothing: the order is held anyway.
251#[derive(Clone, Copy, Debug, Default)]
252pub struct ManualReorder;
253
254impl ReorderPolicy for ManualReorder {
255    fn decide(&self, context: &ReorderContext) -> ReorderDecision {
256        if context.is_user_action() {
257            ReorderDecision::Apply
258        } else {
259            ReorderDecision::Hold
260        }
261    }
262}
263
264/// Runs the view's background jobs (projection rebuilds and compactions).
265///
266/// The default, [`BackgroundRunner`], uses GPUI's background executor.
267/// [`InlineRunner`] runs jobs on the calling thread, for platforms without
268/// background threads (WebAssembly without `SharedArrayBuffer`).
269pub trait TaskRunner: 'static {
270    /// Runs `job`; the returned task completes when it is done.
271    fn run(&self, job: Box<dyn FnOnce() + Send>, cx: &App) -> Task<()>;
272}
273
274/// Runs jobs on GPUI's background executor.
275#[derive(Clone, Copy, Debug, Default)]
276pub struct BackgroundRunner;
277
278impl TaskRunner for BackgroundRunner {
279    fn run(&self, job: Box<dyn FnOnce() + Send>, cx: &App) -> Task<()> {
280        cx.background_spawn(async move { job() })
281    }
282}
283
284/// Runs jobs at once on the calling (UI) thread.
285#[derive(Clone, Copy, Debug, Default)]
286pub struct InlineRunner;
287
288impl TaskRunner for InlineRunner {
289    fn run(&self, job: Box<dyn FnOnce() + Send>, _: &App) -> Task<()> {
290        job();
291        Task::ready(())
292    }
293}
294
295/// One zone of the column layout, as a [`ColumnMovePolicy`] sees it.
296pub struct ColumnMoveContext<'a> {
297    zone: ColumnZone,
298    columns: &'a [ColumnIx],
299    visible: ColumnSet,
300    bands: &'a [Box<[&'static str]>],
301}
302
303impl<'a> ColumnMoveContext<'a> {
304    pub(crate) fn new(
305        zone: ColumnZone,
306        columns: &'a [ColumnIx],
307        visible: ColumnSet,
308        bands: &'a [Box<[&'static str]>],
309    ) -> Self {
310        Self {
311            zone,
312            columns,
313            visible,
314            bands,
315        }
316    }
317
318    /// The zone.
319    pub fn zone(&self) -> ColumnZone {
320        self.zone
321    }
322
323    /// The zone's columns in display order, hidden ones included.
324    pub fn columns(&self) -> &'a [ColumnIx] {
325        self.columns
326    }
327
328    /// Returns true if `column` is shown.
329    pub fn is_visible(&self, column: ColumnIx) -> bool {
330        self.visible.contains(column)
331    }
332
333    /// Ids of the bands that contain `column`, outermost first.
334    pub fn bands(&self, column: ColumnIx) -> &'a [&'static str] {
335        self.bands.get(column.get()).map_or(&[], |bands| bands)
336    }
337}
338
339/// The whole column order, as [`ColumnMovePolicy::normalize`] may change
340/// it: it can only reorder columns and change their zones. The grid then
341/// sorts the order by zone, keeping the order within each zone.
342pub struct ColumnOrder<'a> {
343    order: &'a mut Vec<ColumnIx>,
344    zones: &'a mut [ColumnZone],
345    bands: &'a [Box<[&'static str]>],
346}
347
348impl<'a> ColumnOrder<'a> {
349    pub(crate) fn new(
350        order: &'a mut Vec<ColumnIx>,
351        zones: &'a mut [ColumnZone],
352        bands: &'a [Box<[&'static str]>],
353    ) -> Self {
354        Self {
355            order,
356            zones,
357            bands,
358        }
359    }
360
361    /// Every column of the schema in display order, hidden ones included.
362    pub fn columns(&self) -> &[ColumnIx] {
363        self.order
364    }
365
366    /// The zone of `column`.
367    pub fn zone(&self, column: ColumnIx) -> ColumnZone {
368        self.zones.get(column.get()).copied().unwrap_or_default()
369    }
370
371    /// Ids of the bands that contain `column`, outermost first.
372    pub fn bands(&self, column: ColumnIx) -> &'a [&'static str] {
373        self.bands.get(column.get()).map_or(&[], |bands| bands)
374    }
375
376    /// Moves `column` to `zone`.
377    pub fn set_zone(&mut self, column: ColumnIx, zone: ColumnZone) {
378        if let Some(slot) = self.zones.get_mut(column.get()) {
379            *slot = zone;
380        }
381    }
382
383    /// Replaces the order. Returns false, changing nothing, unless `columns`
384    /// is a permutation of [`Self::columns`].
385    pub fn reorder(&mut self, columns: &[ColumnIx]) -> bool {
386        let set = |columns: &[ColumnIx]| {
387            columns.iter().fold(ColumnSet::EMPTY, |mut set, column| {
388                set.insert(*column);
389                set
390            })
391        };
392        if columns.len() != self.order.len() || set(columns) != set(self.order) {
393            return false;
394        }
395        self.order.clear();
396        self.order.extend_from_slice(columns);
397        true
398    }
399}
400
401/// Decides which columns move together and where they may go, for header
402/// drags, `move_column`, `move_band`, zone changes and the move Actions.
403///
404/// The default is [`BandedMove`]: a [`ColumnBand`](crate::ColumnBand) stays
405/// together, as in DevExpress, Syncfusion, Kendo and Infragistics.
406/// [`FreeMove`] lets a column leave its band, as AG Grid does.
407pub trait ColumnMovePolicy: 'static {
408    /// Whether `block` (a range of `context.columns()`) may be inserted at
409    /// `gap` (`0..=columns().len()`, counted before the block is removed).
410    fn is_allowed(&self, context: &ColumnMoveContext<'_>, block: Range<usize>, gap: usize) -> bool;
411
412    /// The columns that change zone together with `column`: a range of
413    /// `context.columns()` that contains it.
414    fn zone_block(&self, context: &ColumnMoveContext<'_>, column: ColumnIx) -> Range<usize>;
415
416    /// Restores the policy's invariants after the schema is built or a layout
417    /// is restored. Stable: a valid order stays as it is.
418    fn normalize(&self, _order: &mut ColumnOrder<'_>) {}
419}
420
421/// A band stays together: a column moves only among the children of its
422/// innermost band, a band moves as a whole, and a zone change takes the
423/// whole top-level band.
424#[derive(Clone, Copy, Debug, Default)]
425pub struct BandedMove;
426
427/// A child of a band (or of a zone): a nested band or a column.
428#[derive(Clone, Copy, PartialEq, Eq)]
429enum BandChild {
430    Band(&'static str),
431    Column(ColumnIx),
432}
433
434fn band_child(context: &ColumnMoveContext<'_>, column: ColumnIx, level: usize) -> BandChild {
435    match context.bands(column).get(level) {
436        Some(band) => BandChild::Band(band),
437        None => BandChild::Column(column),
438    }
439}
440
441/// The range of `columns` whose bands at `level` are `band`, from the first
442/// to the last of them.
443fn band_span(
444    context: &ColumnMoveContext<'_>,
445    level: usize,
446    band: &'static str,
447) -> Option<Range<usize>> {
448    let columns = context.columns();
449    let is_member = |column: &ColumnIx| context.bands(*column).get(level) == Some(&band);
450    let start = columns.iter().position(is_member)?;
451    let end = columns.iter().rposition(is_member)? + 1;
452    Some(start..end)
453}
454
455impl ColumnMovePolicy for BandedMove {
456    fn is_allowed(&self, context: &ColumnMoveContext<'_>, block: Range<usize>, gap: usize) -> bool {
457        let columns = context.columns();
458        if block.is_empty() || block.end > columns.len() || gap > columns.len() {
459            return false;
460        }
461        // The bands every column of the block is in.
462        let mut common = context.bands(columns[block.start]);
463        for column in &columns[block.clone()] {
464            let bands = context.bands(*column);
465            let shared = common.iter().zip(bands).take_while(|(a, b)| a == b).count();
466            common = &common[..shared];
467        }
468        // A block that is a whole band moves among that band's siblings (and
469        // a band that is all of its parent band, among the parent's).
470        while let Some((&deepest, outer)) = common.split_last()
471            && band_span(context, outer.len(), deepest)
472                .is_some_and(|span| block.start <= span.start && span.end <= block.end)
473        {
474            common = outer;
475        }
476        let level = common.len();
477        let parent = match common.last() {
478            Some(&band) => match band_span(context, level - 1, band) {
479                Some(span) => span,
480                None => return false,
481            },
482            None => 0..columns.len(),
483        };
484        if gap < parent.start || gap > parent.end {
485            return false;
486        }
487        gap == parent.start
488            || gap == parent.end
489            || band_child(context, columns[gap - 1], level)
490                != band_child(context, columns[gap], level)
491    }
492
493    fn zone_block(&self, context: &ColumnMoveContext<'_>, column: ColumnIx) -> Range<usize> {
494        let columns = context.columns();
495        let Some(position) = columns.iter().position(|c| *c == column) else {
496            return 0..0;
497        };
498        match context.bands(column).first() {
499            Some(&top) => band_span(context, 0, top).unwrap_or(position..position + 1),
500            None => position..position + 1,
501        }
502    }
503
504    fn normalize(&self, order: &mut ColumnOrder<'_>) {
505        let columns = order.columns().to_vec();
506        // Every top-level band takes the zone of its first column.
507        let mut zones: Vec<(&'static str, ColumnZone)> = Vec::new();
508        for &column in &columns {
509            let Some(&top) = order.bands(column).first() else {
510                continue;
511            };
512            match zones.iter().find(|(band, _)| *band == top) {
513                Some(&(_, zone)) => order.set_zone(column, zone),
514                None => zones.push((top, order.zone(column))),
515            }
516        }
517        let gathered = gather(&columns, 0, order);
518        order.reorder(&gathered);
519    }
520}
521
522/// Gathers every band at `level` into one run at the place of its first
523/// column, keeping the order inside it; then the bands one level deeper.
524fn gather(columns: &[ColumnIx], level: usize, order: &ColumnOrder<'_>) -> Vec<ColumnIx> {
525    let mut groups: Vec<(Option<&'static str>, Vec<ColumnIx>)> = Vec::new();
526    for &column in columns {
527        match order.bands(column).get(level) {
528            Some(&band) => match groups.iter_mut().find(|(key, _)| *key == Some(band)) {
529                Some((_, members)) => members.push(column),
530                None => groups.push((Some(band), vec![column])),
531            },
532            None => groups.push((None, vec![column])),
533        }
534    }
535    groups
536        .into_iter()
537        .flat_map(|(key, members)| match key {
538            Some(_) => gather(&members, level + 1, order),
539            None => members,
540        })
541        .collect()
542}
543
544/// Any column moves anywhere in its zone, out of its band too: a band then
545/// shows one header cell per run of its columns, as AG Grid does.
546#[derive(Clone, Copy, Debug, Default)]
547pub struct FreeMove;
548
549impl ColumnMovePolicy for FreeMove {
550    fn is_allowed(&self, context: &ColumnMoveContext<'_>, block: Range<usize>, gap: usize) -> bool {
551        !block.is_empty() && block.end <= context.columns().len() && gap <= context.columns().len()
552    }
553
554    fn zone_block(&self, context: &ColumnMoveContext<'_>, column: ColumnIx) -> Range<usize> {
555        context
556            .columns()
557            .iter()
558            .position(|c| *c == column)
559            .map_or(0..0, |position| position..position + 1)
560    }
561}
562
563/// What an [`AutofitPolicy`] can measure for one column. Widths are text
564/// widths, without cell padding.
565pub struct AutofitContext<'a> {
566    header_width: Pixels,
567    pinned_width: Pixels,
568    // The texts of the painted aggregates.
569    summary_width: Pixels,
570    painted_rows: Range<usize>,
571    row_count: usize,
572    measure: &'a mut dyn FnMut(usize) -> Option<Pixels>,
573}
574
575impl<'a> AutofitContext<'a> {
576    pub(crate) fn new(
577        header_width: Pixels,
578        painted_rows: Range<usize>,
579        row_count: usize,
580        measure: &'a mut dyn FnMut(usize) -> Option<Pixels>,
581    ) -> Self {
582        Self {
583            header_width,
584            pinned_width: Pixels::ZERO,
585            summary_width: Pixels::ZERO,
586            painted_rows,
587            row_count,
588            measure,
589        }
590    }
591
592    /// Sets the widest text of the column in the painted pinned rows.
593    pub(crate) fn with_pinned_width(mut self, width: Pixels) -> Self {
594        self.pinned_width = width;
595        self
596    }
597
598    /// The header title plus the sort indicator lane; a header icon and its
599    /// gap before the title, or the icon alone in place of it.
600    pub fn header_width(&self) -> Pixels {
601        self.header_width
602    }
603
604    /// The widest text of the column in the pinned rows painted in this
605    /// frame, both bands; zero without pinned rows.
606    pub fn pinned_width(&self) -> Pixels {
607        self.pinned_width
608    }
609
610    /// Sets the widest aggregate text of the column on the summary lines
611    /// painted in this frame.
612    pub(crate) fn with_summary_width(mut self, width: Pixels) -> Self {
613        self.summary_width = width;
614        self
615    }
616
617    /// The widest aggregate text of the column in the group captions, group
618    /// footers and totals row painted in this frame, the totals label
619    /// "Total" in its column included, each in the weight it is painted
620    /// in; zero without them. A caption's own text, which runs across
621    /// columns, is not part of it.
622    pub fn summary_width(&self) -> Pixels {
623        self.summary_width
624    }
625
626    /// Display rows painted in this frame.
627    pub fn painted_rows(&self) -> Range<usize> {
628        self.painted_rows.clone()
629    }
630
631    /// Rows in the projection.
632    pub fn row_count(&self) -> usize {
633        self.row_count
634    }
635
636    /// Text width of the column's cell in a display row; `None` for a
637    /// removed row or one past the end.
638    pub fn measure_row(&mut self, display_ix: usize) -> Option<Pixels> {
639        (self.measure)(display_ix)
640    }
641}
642
643/// Chooses the text width a column needs when it is autofitted (a double
644/// click on its resize handle, `autofit_column`, `autofit_columns`). The
645/// grid adds the cell padding and clamps to the column's limits.
646///
647/// Called once per column when the fit is applied, never per frame.
648pub trait AutofitPolicy: 'static {
649    /// The text width the column needs.
650    fn content_width(&self, context: &mut AutofitContext<'_>) -> Pixels;
651}
652
653/// Fits the header title, the pinned rows, the aggregates and the data rows
654/// painted in the frame of the fit; rows off screen are not measured, so the
655/// cost does not grow with the row count (AG Grid does the same).
656#[derive(Clone, Copy, Debug, Default)]
657pub struct VisibleRowsAutofit;
658
659impl AutofitPolicy for VisibleRowsAutofit {
660    fn content_width(&self, context: &mut AutofitContext<'_>) -> Pixels {
661        let floor = context
662            .header_width()
663            .max(context.pinned_width())
664            .max(context.summary_width());
665        context
666            .painted_rows()
667            .filter_map(|display_ix| context.measure_row(display_ix))
668            .fold(floor, |widest, width| widest.max(width))
669    }
670}
671
672/// What a [`SortCycle`] knows about a header click.
673#[derive(Clone, Copy, Debug)]
674pub struct SortCycleContext<'a> {
675    sort: &'a [(ColumnIx, SortDirection)],
676    column: ColumnIx,
677    modifiers: Modifiers,
678}
679
680impl<'a> SortCycleContext<'a> {
681    pub(crate) fn new(
682        sort: &'a [(ColumnIx, SortDirection)],
683        column: ColumnIx,
684        modifiers: Modifiers,
685    ) -> Self {
686        Self {
687            sort,
688            column,
689            modifiers,
690        }
691    }
692
693    /// The sort before the click, most significant column first.
694    pub fn sort(&self) -> &'a [(ColumnIx, SortDirection)] {
695        self.sort
696    }
697
698    /// The column whose header was clicked.
699    pub fn column(&self) -> ColumnIx {
700        self.column
701    }
702
703    /// The modifier keys held during the click.
704    pub fn modifiers(&self) -> Modifiers {
705        self.modifiers
706    }
707
708    /// The direction of the clicked column in the sort, if it is sorted.
709    pub fn direction(&self) -> Option<SortDirection> {
710        self.sort
711            .iter()
712            .find(|(column, _)| *column == self.column)
713            .map(|(_, direction)| *direction)
714    }
715}
716
717/// How a header click changes the sort.
718///
719/// The default is [`StandardSortCycle`]: ascending, descending, unsorted;
720/// Shift adds the column to a multi-column sort. Called once per click on
721/// the UI thread, and only for a column with
722/// [`GridColumn::is_sortable`](crate::GridColumn::is_sortable). The grid
723/// drops repeated columns of the result (the first one stays) and columns
724/// outside the schema's column type.
725pub trait SortCycle: 'static {
726    /// The sort after a click on `context.column()`, most significant column
727    /// first; empty for the insertion order.
728    fn next_sort(&self, context: &SortCycleContext<'_>) -> Vec<(ColumnIx, SortDirection)>;
729}
730
731/// Ascending, then descending, then unsorted (the insertion order), as in AG
732/// Grid, Syncfusion and MUI X.
733///
734/// A click without Shift steps the clicked column from its own direction and
735/// drops every other column, even from a multi-column sort. A Shift-click
736/// adds the column as the least significant one, flips it in place, then
737/// removes it; the others keep their order. Shift on every platform: on
738/// macOS Cmd-click means "add to the selection", not "add to the sort".
739#[derive(Clone, Copy, Debug, Default)]
740pub struct StandardSortCycle;
741
742impl SortCycle for StandardSortCycle {
743    fn next_sort(&self, context: &SortCycleContext<'_>) -> Vec<(ColumnIx, SortDirection)> {
744        let column = context.column();
745        let direction = context.direction();
746        if !context.modifiers().shift {
747            return match direction {
748                None => vec![(column, SortDirection::Ascending)],
749                Some(SortDirection::Ascending) => vec![(column, SortDirection::Descending)],
750                Some(SortDirection::Descending) => Vec::new(),
751            };
752        }
753        let mut sort = context.sort().to_vec();
754        match direction {
755            None => sort.push((column, SortDirection::Ascending)),
756            Some(SortDirection::Ascending) => {
757                for (sorted, direction) in &mut sort {
758                    if *sorted == column {
759                        *direction = SortDirection::Descending;
760                    }
761                }
762            }
763            Some(SortDirection::Descending) => sort.retain(|(sorted, _)| *sorted != column),
764        }
765        sort
766    }
767}
768
769/// What a [`SelectionScope`] knows when a command asks what it acts on.
770pub struct SelectionScopeContext<'a, R: GridRow> {
771    selection: &'a GridSelection<R::Key>,
772    projection: &'a Projection,
773    snapshot: &'a StoreSnapshot<R>,
774    mode: SelectionMode,
775}
776
777impl<'a, R: GridRow> SelectionScopeContext<'a, R> {
778    pub(crate) fn new(
779        selection: &'a GridSelection<R::Key>,
780        projection: &'a Projection,
781        snapshot: &'a StoreSnapshot<R>,
782        mode: SelectionMode,
783    ) -> Self {
784        Self {
785            selection,
786            projection,
787            snapshot,
788            mode,
789        }
790    }
791
792    /// The whole selection, by key; it may hold rows a filter hides.
793    pub fn selection(&self) -> &'a GridSelection<R::Key> {
794        self.selection
795    }
796
797    /// The projection on screen (not one being built or held back).
798    pub fn projection(&self) -> &'a Projection {
799        self.projection
800    }
801
802    /// The snapshot the screen shows.
803    pub fn snapshot(&self) -> &'a StoreSnapshot<R> {
804        self.snapshot
805    }
806
807    /// The selection mode.
808    pub fn mode(&self) -> SelectionMode {
809        self.mode
810    }
811}
812
813/// Which selected rows and cells a command acts on: Enter, a double click,
814/// the primary menu command, copying. Called once per command on the UI
815/// thread.
816///
817/// The default is [`ProjectionScope`]: the selection within the rows on
818/// screen. [`StoreScope`] also takes selected rows a filter hides.
819pub trait SelectionScope<R: GridRow>: 'static {
820    /// The rows and cells, in the order the command sees them.
821    fn resolve(&self, context: &SelectionScopeContext<'_, R>) -> ScopedSelection<R::Key>;
822}
823
824/// The selection within the projection on screen, in its order: rows a
825/// filter hides and rows removed since are left out; selected rows of a
826/// collapsed group are in. The default.
827#[derive(Clone, Copy, Debug, Default)]
828pub struct ProjectionScope;
829
830/// The selected rows `projection` passes, in its order (`rows()`): a row
831/// of a collapsed group too. One pass over the projection when most of it
832/// is selected, else a lookup per selected row and a sort by position.
833fn shown_selection<R: GridRow>(context: &SelectionScopeContext<'_, R>) -> Vec<(R::Key, ColumnSet)> {
834    let (selection, projection, snapshot) = (
835        context.selection(),
836        context.projection(),
837        context.snapshot(),
838    );
839    if selection.is_empty() {
840        return Vec::new();
841    }
842    if selection.len() > projection.rows().len() / 8 {
843        return projection
844            .rows()
845            .iter()
846            .filter_map(|id| snapshot.row(*id))
847            .filter_map(|row| {
848                let columns = selection.columns(row.key());
849                (!columns.is_empty()).then(|| (row.key().clone(), columns))
850            })
851            .collect();
852    }
853    let mut shown: Vec<(usize, R::Key, ColumnSet)> = selection
854        .iter()
855        .filter_map(|key| {
856            let order_ix = projection.order_ix(snapshot.row_id(key)?)?;
857            Some((order_ix, key.clone(), selection.columns(key)))
858        })
859        .collect();
860    shown.sort_unstable_by_key(|(order_ix, _, _)| *order_ix);
861    shown
862        .into_iter()
863        .map(|(_, key, columns)| (key, columns))
864        .collect()
865}
866
867impl<R: GridRow> SelectionScope<R> for ProjectionScope {
868    fn resolve(&self, context: &SelectionScopeContext<'_, R>) -> ScopedSelection<R::Key> {
869        shown_selection(context).into_iter().collect()
870    }
871}
872
873/// The selection within the store: the rows on screen in display order,
874/// then selected rows a filter hides, in insertion order. Removed rows never
875/// are.
876#[derive(Clone, Copy, Debug, Default)]
877pub struct StoreScope;
878
879impl<R: GridRow> SelectionScope<R> for StoreScope {
880    fn resolve(&self, context: &SelectionScopeContext<'_, R>) -> ScopedSelection<R::Key> {
881        let (selection, projection, snapshot) = (
882            context.selection(),
883            context.projection(),
884            context.snapshot(),
885        );
886        let mut hidden: Vec<(u64, R::Key, ColumnSet)> = selection
887            .iter()
888            .filter_map(|key| {
889                let id = snapshot.row_id(key)?;
890                (!projection.contains(id))
891                    .then(|| (snapshot.seq(id), key.clone(), selection.columns(key)))
892            })
893            .collect();
894        hidden.sort_unstable_by_key(|(seq, _, _)| *seq);
895        shown_selection(context)
896            .into_iter()
897            .chain(hidden.into_iter().map(|(_, key, columns)| (key, columns)))
898            .collect()
899    }
900}
901
902/// A line the selection may take, as a [`SelectionPolicy`] sees it.
903#[non_exhaustive]
904pub enum SelectableLine<'a, R: GridRow> {
905    /// A data row; `branch` is set for a tree row with shown children.
906    Row {
907        /// The row.
908        row: &'a R,
909        /// The row's children, in a tree.
910        branch: Option<Branch>,
911    },
912    /// A group caption.
913    Caption {
914        /// The group, in the projection on screen.
915        group: GroupInfo<'a>,
916    },
917}
918
919/// What [`SelectionPolicy::line_scope`] knows: the target line of a
920/// command in the projection on screen, the snapshot it is drawn from and
921/// the selection mode.
922pub struct LineScopeContext<'a, R: GridRow> {
923    line: SelectableLine<'a, R>,
924    /// The live rows under the line: a range of `Projection::rows`.
925    under: Range<usize>,
926    projection: &'a Projection,
927    snapshot: &'a StoreSnapshot<R>,
928    mode: SelectionMode,
929}
930
931impl<'a, R: GridRow> LineScopeContext<'a, R> {
932    pub(crate) fn new(
933        line: SelectableLine<'a, R>,
934        under: Range<usize>,
935        projection: &'a Projection,
936        snapshot: &'a StoreSnapshot<R>,
937        mode: SelectionMode,
938    ) -> Self {
939        Self {
940            line,
941            under,
942            projection,
943            snapshot,
944            mode,
945        }
946    }
947
948    /// The target line.
949    pub fn line(&self) -> &SelectableLine<'a, R> {
950        &self.line
951    }
952
953    /// The live rows under the line, in the order of `Projection::rows`:
954    /// every row of a caption's group, its collapsed subgroups' too; the
955    /// descendants of a tree row; none under any other row. Rows removed
956    /// since the projection was built are left out.
957    pub fn rows(&self) -> impl Iterator<Item = &'a Arc<R>> + 'a {
958        let snapshot = self.snapshot;
959        self.projection.rows()[self.under.clone()]
960            .iter()
961            .filter_map(move |id| snapshot.row(*id))
962    }
963
964    /// The rows of [`Self::rows`] as lines, each with its own children in
965    /// a tree: what [`SelectionPolicy::is_selectable`] is asked about them.
966    pub fn lines(&self) -> impl Iterator<Item = SelectableLine<'a, R>> + 'a {
967        let (projection, snapshot) = (self.projection, self.snapshot);
968        projection.rows()[self.under.clone()]
969            .iter()
970            .filter_map(move |id| {
971                Some(SelectableLine::Row {
972                    row: &**snapshot.row(*id)?,
973                    branch: projection.branch(*id),
974                })
975            })
976    }
977
978    /// The projection on screen.
979    pub fn projection(&self) -> &'a Projection {
980        self.projection
981    }
982
983    /// The snapshot the screen shows.
984    pub fn snapshot(&self) -> &'a StoreSnapshot<R> {
985        self.snapshot
986    }
987
988    /// The selection mode.
989    pub fn mode(&self) -> SelectionMode {
990        self.mode
991    }
992}
993
994/// Which lines can be selected, and what a command over a line acts on: a
995/// group caption, or a tree row with children.
996///
997/// `is_selectable` is asked per line by Cmd/Ctrl+A, Shift ranges and
998/// drags; `line_scope` once per command, for its target: the focused line
999/// for Enter and Cmd/Ctrl+C, the menu's target, a double-clicked row. Both
1000/// run on the UI thread.
1001///
1002/// The default is [`FocusCaptions`]: tree rows are data rows and take the
1003/// selection, as in AG Grid's tree data and DevExpress TreeList. Built in
1004/// too, [`FocusBranches`]: tree rows with children take the focus but not
1005/// the selection, and a command over one acts on its subtree's leaves.
1006/// Another plausible one: selectable captions whose selection takes their
1007/// group's rows (AG Grid's `groupSelectsChildren`).
1008pub trait SelectionPolicy<R: GridRow>: 'static {
1009    /// Returns true if `line` can be selected. A selectable caption adds
1010    /// its group's live rows to the selection; a selectable row itself.
1011    fn is_selectable(&self, line: &SelectableLine<'_, R>) -> bool;
1012
1013    /// The scope of a command whose target is `context.line()`; `None`:
1014    /// the command acts on `scoped_selection()`.
1015    fn line_scope(&self, context: &LineScopeContext<'_, R>) -> Option<ScopedSelection<R::Key>>;
1016}
1017
1018/// Captions take the focus, never the selection; a command over a caption
1019/// acts on every live row of its group, collapsed subgroups included, in
1020/// the order of `Projection::rows`, with every column. Data rows, tree rows
1021/// with children included, are selectable, and a command over one acts on
1022/// `scoped_selection()`. The default.
1023#[derive(Clone, Copy, Debug, Default)]
1024pub struct FocusCaptions;
1025
1026impl<R: GridRow> SelectionPolicy<R> for FocusCaptions {
1027    fn is_selectable(&self, line: &SelectableLine<'_, R>) -> bool {
1028        match line {
1029            SelectableLine::Row { .. } => true,
1030            SelectableLine::Caption { .. } => false,
1031        }
1032    }
1033
1034    fn line_scope(&self, context: &LineScopeContext<'_, R>) -> Option<ScopedSelection<R::Key>> {
1035        match context.line() {
1036            SelectableLine::Caption { .. } => {
1037                let columns = ColumnSet::first(R::Column::all().len());
1038                Some(
1039                    context
1040                        .rows()
1041                        .map(|row| (row.key().clone(), columns))
1042                        .collect(),
1043                )
1044            }
1045            SelectableLine::Row { .. } => None,
1046        }
1047    }
1048}
1049
1050/// Branches as captions: a tree row with shown children (a branch) takes
1051/// the focus but not the selection, as a group caption does, and a command
1052/// over one acts on the leaves of its subtree that pass the view, those
1053/// under collapsed branches too, in the order of `Projection::rows`, with
1054/// every column. Cmd/Ctrl+A, Shift ranges and drags leave branches out.
1055/// Group captions and leaves behave as with [`FocusCaptions`].
1056///
1057/// A leaf that gets children stays selected (by key); new gestures leave
1058/// it out.
1059#[derive(Clone, Copy, Debug, Default)]
1060pub struct FocusBranches;
1061
1062impl<R: GridRow> SelectionPolicy<R> for FocusBranches {
1063    fn is_selectable(&self, line: &SelectableLine<'_, R>) -> bool {
1064        match line {
1065            SelectableLine::Row { branch, .. } => branch.is_none(),
1066            SelectableLine::Caption { .. } => false,
1067        }
1068    }
1069
1070    fn line_scope(&self, context: &LineScopeContext<'_, R>) -> Option<ScopedSelection<R::Key>> {
1071        match context.line() {
1072            SelectableLine::Row {
1073                branch: Some(_), ..
1074            } => {
1075                let columns = ColumnSet::first(R::Column::all().len());
1076                Some(
1077                    context
1078                        .lines()
1079                        .filter_map(|line| match line {
1080                            SelectableLine::Row { row, branch: None } => {
1081                                Some((row.key().clone(), columns))
1082                            }
1083                            _ => None,
1084                        })
1085                        .collect(),
1086                )
1087            }
1088            _ => FocusCaptions.line_scope(context),
1089        }
1090    }
1091}
1092
1093/// Where a selection gesture comes from.
1094#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1095#[non_exhaustive]
1096pub enum GestureInput {
1097    /// A navigation Action.
1098    Keyboard,
1099    /// A primary-button press.
1100    Pointer,
1101    /// A press that opens the context menu ([`ContextMenuGesture`]), before
1102    /// the menu.
1103    ContextPointer,
1104}
1105
1106/// How a gesture changes the selection; the target always gets the focus.
1107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1108#[non_exhaustive]
1109pub enum SelectionEdit {
1110    /// Select only the target; it becomes the anchor.
1111    Replace,
1112    /// Select the range from the anchor to the target, dropping the rest.
1113    Extend,
1114    /// Add the range from the anchor to the target to the selection.
1115    AddRange,
1116    /// Flip the target; it becomes the anchor.
1117    Toggle,
1118    /// Leave the selection and the anchor as they are.
1119    Keep,
1120}
1121
1122/// What a [`SelectionGesture`] knows about a press or a navigation command.
1123#[derive(Clone, Copy, Debug)]
1124pub struct SelectionGestureContext {
1125    input: GestureInput,
1126    modifiers: Modifiers,
1127    platform: PlatformInfo,
1128    extending: bool,
1129    target_selected: bool,
1130    mode: SelectionMode,
1131}
1132
1133impl SelectionGestureContext {
1134    pub(crate) fn new(
1135        input: GestureInput,
1136        modifiers: Modifiers,
1137        platform: PlatformInfo,
1138        extending: bool,
1139        target_selected: bool,
1140        mode: SelectionMode,
1141    ) -> Self {
1142        Self {
1143            input,
1144            modifiers,
1145            platform,
1146            extending,
1147            target_selected,
1148            mode,
1149        }
1150    }
1151
1152    /// Where the gesture comes from.
1153    pub fn input(&self) -> GestureInput {
1154        self.input
1155    }
1156
1157    /// The pointer's modifiers; none for keyboard input.
1158    pub fn modifiers(&self) -> Modifiers {
1159        self.modifiers
1160    }
1161
1162    /// The host whose conventions apply, as `App::platform_info`: a browser
1163    /// on macOS is a macOS host, so the secondary modifier is Cmd there.
1164    pub fn platform_info(&self) -> PlatformInfo {
1165        self.platform
1166    }
1167
1168    /// Returns true for a keyboard `ExtendSelection…` command.
1169    pub fn is_extending(&self) -> bool {
1170        self.extending
1171    }
1172
1173    /// Returns true if the target row (in the cell modes, cell) is selected
1174    /// now.
1175    pub fn is_target_selected(&self) -> bool {
1176        self.target_selected
1177    }
1178
1179    /// The selection mode.
1180    pub fn mode(&self) -> SelectionMode {
1181        self.mode
1182    }
1183}
1184
1185/// How a press or a navigation command edits the selection. Called once
1186/// per gesture on the UI thread. Space toggles and Cmd/Ctrl+A selects all
1187/// whatever it says.
1188///
1189/// The default is [`StandardSelectionGesture`], the Windows and macOS
1190/// conventions with Excel's "navigation selects". Others are plausible: as
1191/// AG Grid (navigation only moves the focus, `Keep`, and Space selects), as
1192/// Finder (Shift adds a range), or touch (a press toggles).
1193pub trait SelectionGesture: 'static {
1194    /// The edit the gesture makes.
1195    fn edit(&self, context: &SelectionGestureContext) -> SelectionEdit;
1196}
1197
1198/// Windows and macOS conventions; navigation selects, as in Excel.
1199///
1200/// A press replaces the selection; Shift extends it from the anchor;
1201/// Cmd on macOS, Ctrl elsewhere, toggles; both add a range. A context press
1202/// selects an unselected row and keeps a selected one. A navigation command
1203/// replaces; its `ExtendSelection…` variant extends.
1204#[derive(Clone, Copy, Debug, Default)]
1205pub struct StandardSelectionGesture;
1206
1207impl SelectionGesture for StandardSelectionGesture {
1208    fn edit(&self, context: &SelectionGestureContext) -> SelectionEdit {
1209        let modifiers = context.modifiers();
1210        match context.input() {
1211            GestureInput::Pointer => match (
1212                modifiers.shift,
1213                is_secondary_held(modifiers, context.platform_info()),
1214            ) {
1215                (true, true) => SelectionEdit::AddRange,
1216                (true, false) => SelectionEdit::Extend,
1217                (false, true) => SelectionEdit::Toggle,
1218                (false, false) => SelectionEdit::Replace,
1219            },
1220            GestureInput::ContextPointer if context.is_target_selected() => SelectionEdit::Keep,
1221            GestureInput::ContextPointer => SelectionEdit::Replace,
1222            GestureInput::Keyboard if context.is_extending() => SelectionEdit::Extend,
1223            GestureInput::Keyboard => SelectionEdit::Replace,
1224        }
1225    }
1226}
1227
1228/// The part of the grid a press lands on.
1229#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1230#[non_exhaustive]
1231pub enum GridArea {
1232    /// The rows and the empty area below them.
1233    Body,
1234    /// The column header: its cells, bands and resize handles, and the
1235    /// header right of the columns.
1236    Header,
1237}
1238
1239/// What a [`ContextMenuGesture`] knows about a press.
1240#[derive(Clone, Copy, Debug)]
1241pub struct ContextMenuGestureContext {
1242    button: MouseButton,
1243    modifiers: Modifiers,
1244    platform: PlatformInfo,
1245    click_count: usize,
1246    area: GridArea,
1247}
1248
1249impl ContextMenuGestureContext {
1250    pub(crate) fn new(
1251        button: MouseButton,
1252        modifiers: Modifiers,
1253        platform: PlatformInfo,
1254        click_count: usize,
1255        area: GridArea,
1256    ) -> Self {
1257        Self {
1258            button,
1259            modifiers,
1260            platform,
1261            click_count,
1262            area,
1263        }
1264    }
1265
1266    /// The pressed button.
1267    pub fn button(&self) -> MouseButton {
1268        self.button
1269    }
1270
1271    /// The modifier keys held during the press.
1272    pub fn modifiers(&self) -> Modifiers {
1273        self.modifiers
1274    }
1275
1276    /// The host whose conventions apply, as `App::platform_info`: a browser
1277    /// on macOS is a macOS host, where Ctrl+click opens the menu.
1278    pub fn platform_info(&self) -> PlatformInfo {
1279        self.platform
1280    }
1281
1282    /// The press's place in a click series: 1 for a single press, 2 for the
1283    /// second press of a double click.
1284    pub fn click_count(&self) -> usize {
1285        self.click_count
1286    }
1287
1288    /// Where the press lands.
1289    pub fn area(&self) -> GridArea {
1290        self.area
1291    }
1292}
1293
1294/// Which press opens the context menu. Called once per press on the UI
1295/// thread, on the body and on the header; the `ShowContextMenu` Action
1296/// opens the menu whatever it says.
1297///
1298/// On the body, a press that opens the menu first edits the selection as
1299/// [`GestureInput::ContextPointer`] through the [`SelectionGesture`]; any
1300/// other primary-button press is a [`GestureInput::Pointer`] press. On the
1301/// header it opens the column's menu instead of sorting or resizing.
1302///
1303/// The default is [`StandardContextMenuGesture`]. Others are plausible: the
1304/// right button only, so a Ctrl+click on macOS is a plain press; Ctrl+click
1305/// on every platform; no pointer menu at all, only the keyboard's.
1306pub trait ContextMenuGesture: 'static {
1307    /// Returns true if the press opens the context menu.
1308    fn opens_menu(&self, context: &ContextMenuGestureContext) -> bool;
1309}
1310
1311/// The platform conventions: a right click, and on a macOS host (a browser
1312/// there too) a Ctrl+click without Cmd, open the menu, on the body and on
1313/// the header alike. On macOS Cmd+click toggles the selection, so
1314/// Ctrl+click is free.
1315#[derive(Clone, Copy, Debug, Default)]
1316pub struct StandardContextMenuGesture;
1317
1318impl ContextMenuGesture for StandardContextMenuGesture {
1319    fn opens_menu(&self, context: &ContextMenuGestureContext) -> bool {
1320        let (button, modifiers) = (context.button(), context.modifiers());
1321        button == MouseButton::Right
1322            || (context.platform_info().is_mac()
1323                && button == MouseButton::Left
1324                && modifiers.control
1325                && !modifiers.platform)
1326    }
1327}
1328
1329/// Where a press lands on a line that expands: a group caption or a tree
1330/// row with children.
1331#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1332#[non_exhaustive]
1333pub enum ExpandArea {
1334    /// The disclosure chevron of a caption or a tree row.
1335    Chevron,
1336    /// A caption outside its chevron: its text or an aggregate cell.
1337    Caption,
1338    /// The tree column's cell of a tree row, outside its chevron.
1339    TreeCell,
1340}
1341
1342/// How a press expands or collapses its line.
1343#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1344#[non_exhaustive]
1345pub enum ExpandEdit {
1346    /// The line takes the other state.
1347    Toggle,
1348    /// The line takes the other state, and every line below it the same.
1349    ToggleDeep,
1350}
1351
1352/// What an [`ExpandGesture`] knows about a press.
1353#[derive(Clone, Copy, Debug)]
1354pub struct ExpandGestureContext {
1355    area: ExpandArea,
1356    button: MouseButton,
1357    modifiers: Modifiers,
1358    click_count: usize,
1359}
1360
1361impl ExpandGestureContext {
1362    pub(crate) fn new(
1363        area: ExpandArea,
1364        button: MouseButton,
1365        modifiers: Modifiers,
1366        click_count: usize,
1367    ) -> Self {
1368        Self {
1369            area,
1370            button,
1371            modifiers,
1372            click_count,
1373        }
1374    }
1375
1376    /// Where the press lands.
1377    pub fn area(&self) -> ExpandArea {
1378        self.area
1379    }
1380
1381    /// The pressed button.
1382    pub fn button(&self) -> MouseButton {
1383        self.button
1384    }
1385
1386    /// The modifier keys held during the press.
1387    pub fn modifiers(&self) -> Modifiers {
1388        self.modifiers
1389    }
1390
1391    /// The press's place in a click series: 1 for a single press, 2 for the
1392    /// second press of a double click.
1393    pub fn click_count(&self) -> usize {
1394        self.click_count
1395    }
1396}
1397
1398/// Which press expands or collapses a group caption or a tree row. Called
1399/// once per press on such a line, on the UI thread, after the
1400/// [`ContextMenuGesture`]. A press on a caption still focuses it; a press
1401/// on a tree row's chevron leaves the focus and the selection as they are,
1402/// as Finder's disclosure triangle does; a press on a chevron is never a
1403/// click. The keys (`ExpandRow`, `CollapseRow`, ←/→ on a caption) expand
1404/// whatever it says.
1405///
1406/// The default is [`StandardExpandGesture`]. Others are plausible: a single
1407/// press on a caption toggles (Syncfusion); a double click on a caption
1408/// confirms instead; no double click at all.
1409pub trait ExpandGesture: 'static {
1410    /// The edit the press makes, if any.
1411    fn edit(&self, context: &ExpandGestureContext) -> Option<ExpandEdit>;
1412}
1413
1414/// A press on a chevron toggles, with Alt (Option on macOS) the line and
1415/// everything below it, as Finder's disclosure triangle; only the first
1416/// press of a series counts. The second press of a double click on a
1417/// caption toggles it (DevExpress, Windows Explorer). A press on a tree
1418/// row's cell does nothing here: a double click confirms, as on any row.
1419#[derive(Clone, Copy, Debug, Default)]
1420pub struct StandardExpandGesture;
1421
1422impl ExpandGesture for StandardExpandGesture {
1423    fn edit(&self, context: &ExpandGestureContext) -> Option<ExpandEdit> {
1424        if context.button() != MouseButton::Left {
1425            return None;
1426        }
1427        match (context.area(), context.click_count()) {
1428            (ExpandArea::Chevron, 1) if context.modifiers().alt => Some(ExpandEdit::ToggleDeep),
1429            (ExpandArea::Chevron, 1) | (ExpandArea::Caption, 2) => Some(ExpandEdit::Toggle),
1430            _ => None,
1431        }
1432    }
1433}
1434
1435// The edit seams: which input opens a cell editor, and how an edit behaves
1436// under live data.
1437
1438/// What an [`EditGesture`] knows about an input on a cell that could edit
1439/// it: a cell of a column with an editor that the delegate's
1440/// `is_editable` lets edit.
1441#[derive(Clone, Debug)]
1442pub struct EditGestureContext {
1443    input: EditInput,
1444    modifiers: Modifiers,
1445    content: CellContent,
1446}
1447
1448impl EditGestureContext {
1449    pub(crate) fn new(input: EditInput, modifiers: Modifiers, content: CellContent) -> Self {
1450        Self {
1451            input,
1452            modifiers,
1453            content,
1454        }
1455    }
1456
1457    /// The input: typing, a press, a command.
1458    pub fn input(&self) -> &EditInput {
1459        &self.input
1460    }
1461
1462    /// The modifiers held.
1463    pub fn modifiers(&self) -> Modifiers {
1464        self.modifiers
1465    }
1466
1467    /// What the cell's column paints: a press on a `Control` cell is the
1468    /// element's own.
1469    pub fn content(&self) -> CellContent {
1470        self.content
1471    }
1472}
1473
1474/// The Action that committed an editor: which key, as the editor's key
1475/// bindings name it (`CommitEdit`, `CommitEditUp`, `CommitEditDown`,
1476/// `CommitEditNext`, `CommitEditPrev`).
1477#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1478#[non_exhaustive]
1479pub enum EditCommitKey {
1480    /// Enter (`CommitEdit`).
1481    Enter,
1482    /// Shift+Enter or ↑ (`CommitEditUp`).
1483    Up,
1484    /// ↓ (`CommitEditDown`).
1485    Down,
1486    /// Tab (`CommitEditNext`).
1487    Next,
1488    /// Shift+Tab (`CommitEditPrev`).
1489    Prev,
1490}
1491
1492/// Where the focus goes after a commit.
1493#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1494#[non_exhaustive]
1495pub enum AfterCommit {
1496    /// The committed cell keeps the focus.
1497    Stay,
1498    /// The focus moves.
1499    Move(CellMove),
1500    /// The focus moves and the editor opens there, if that cell takes an
1501    /// edit.
1502    MoveAndEdit(CellMove),
1503}
1504
1505/// A move of the focus after a commit.
1506#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1507#[non_exhaustive]
1508pub enum CellMove {
1509    /// To the row above.
1510    Up,
1511    /// To the row below.
1512    Down,
1513    /// To the visible column on the left.
1514    Left,
1515    /// To the visible column on the right.
1516    Right,
1517    /// To the next cell that takes an edit, left to right, then down.
1518    NextEditable,
1519    /// To the previous cell that takes an edit, right to left, then up.
1520    PrevEditable,
1521}
1522
1523/// Which input opens the editor of an editable cell, and where the focus
1524/// goes after a commit. Asked once per input on the UI thread.
1525///
1526/// The default is [`StandardEditGesture`], Excel's. An AG Grid-like gesture
1527/// opens the editor on a single click, stays on Enter and edits the next
1528/// editable cell on Tab (`MoveAndEdit(CellMove::NextEditable)`).
1529pub trait EditGesture: 'static {
1530    /// Returns true if `context.input()` opens the editor. `Command` (F2)
1531    /// and `Clear` (Backspace, Delete) are Actions: rebind their keys
1532    /// instead of refusing them here.
1533    fn starts_edit(&self, context: &EditGestureContext) -> bool;
1534
1535    /// Where the focus goes after a commit by `key`.
1536    fn after_commit(&self, key: EditCommitKey) -> AfterCommit;
1537}
1538
1539/// Excel's: typing and a double click edit (not on a `Control` cell,
1540/// whose element takes its own presses), a single click does not; Enter
1541/// commits and moves down, Shift+Enter and ↑ up, ↓ down, Tab right,
1542/// Shift+Tab left.
1543#[derive(Clone, Copy, Debug, Default)]
1544pub struct StandardEditGesture;
1545
1546impl EditGesture for StandardEditGesture {
1547    fn starts_edit(&self, context: &EditGestureContext) -> bool {
1548        match context.input() {
1549            EditInput::Press { click_count } => {
1550                *click_count >= 2 && context.content() != CellContent::Control
1551            }
1552            _ => true,
1553        }
1554    }
1555
1556    fn after_commit(&self, key: EditCommitKey) -> AfterCommit {
1557        AfterCommit::Move(match key {
1558            EditCommitKey::Enter | EditCommitKey::Down => CellMove::Down,
1559            EditCommitKey::Up => CellMove::Up,
1560            EditCommitKey::Next => CellMove::Right,
1561            EditCommitKey::Prev => CellMove::Left,
1562        })
1563    }
1564}
1565
1566/// What an [`EditPolicy`] knows about the open edit.
1567#[derive(Clone, Copy, Debug)]
1568pub struct EditPolicyContext<'a> {
1569    base: &'a OwnedValue,
1570    current: &'a OwnedValue,
1571    draft: Option<&'a OwnedValue>,
1572    dirty: bool,
1573}
1574
1575impl<'a> EditPolicyContext<'a> {
1576    pub(crate) fn new(
1577        base: &'a OwnedValue,
1578        current: &'a OwnedValue,
1579        draft: Option<&'a OwnedValue>,
1580        dirty: bool,
1581    ) -> Self {
1582        Self {
1583            base,
1584            current,
1585            draft,
1586            dirty,
1587        }
1588    }
1589
1590    /// The cell's value when the edit started.
1591    pub fn base(&self) -> &'a OwnedValue {
1592        self.base
1593    }
1594
1595    /// The cell's value in the store now.
1596    pub fn current(&self) -> &'a OwnedValue {
1597        self.current
1598    }
1599
1600    /// The draft as a value of the column; `None` if it does not parse.
1601    pub fn draft(&self) -> Option<&'a OwnedValue> {
1602        self.draft
1603    }
1604
1605    /// Returns true if the user changed the draft since the editor opened.
1606    pub fn is_dirty(&self) -> bool {
1607        self.dirty
1608    }
1609}
1610
1611/// How an edit that leaves the editor ends.
1612#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1613#[non_exhaustive]
1614pub enum EditEnd {
1615    /// Commit the draft.
1616    Commit,
1617    /// Close the editor without a commit.
1618    Cancel,
1619}
1620
1621/// What happens to the draft when the edited cell's value changes in the
1622/// store.
1623#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1624#[non_exhaustive]
1625pub enum DraftAction {
1626    /// Keep the draft; the editor shows the conflict.
1627    Keep,
1628    /// Replace the draft with the new value.
1629    Replace,
1630    /// Close the editor without a commit.
1631    Cancel,
1632}
1633
1634/// How an edit session behaves around its commit and under live data.
1635/// Asked once per event on the UI thread.
1636///
1637/// The default is [`StandardEditPolicy`].
1638pub trait EditPolicy: 'static {
1639    /// The focus left an open editor, or a press landed outside it.
1640    fn on_blur(&self, context: &EditPolicyContext<'_>) -> EditEnd;
1641
1642    /// Returns true if a commit equal to the value the edit started from
1643    /// still emits `EditCommit`. Default: no, the editor closes with
1644    /// `EditCancel { reason: Unchanged }`.
1645    fn commit_unchanged(&self) -> bool {
1646        false
1647    }
1648
1649    /// The edited cell's value changed in the store.
1650    fn on_value_change(&self, context: &EditPolicyContext<'_>) -> DraftAction;
1651
1652    /// The edited row left the shown lines without a user action: a
1653    /// filter, a collapsed group.
1654    fn on_hidden(&self, context: &EditPolicyContext<'_>) -> EditEnd;
1655
1656    /// How long an accepted value is shown while the store does not have it
1657    /// yet. Default: 5 s.
1658    fn settle_timeout(&self) -> Duration {
1659        Duration::from_secs(5)
1660    }
1661
1662    /// How long the error mark of a failed commit stays; `None` (the
1663    /// default): until the cell is edited again or
1664    /// `LiveGridState::clear_edit_error`.
1665    fn error_mark_timeout(&self) -> Option<Duration> {
1666        None
1667    }
1668}
1669
1670/// As [`StandardEditPolicy`], but a draft the user has not touched follows
1671/// the store: a new value replaces it (`DraftAction::Replace`); a touched
1672/// draft is kept and shows the conflict.
1673#[derive(Clone, Copy, Debug, Default)]
1674pub struct FollowLiveValue;
1675
1676impl EditPolicy for FollowLiveValue {
1677    fn on_blur(&self, context: &EditPolicyContext<'_>) -> EditEnd {
1678        StandardEditPolicy.on_blur(context)
1679    }
1680
1681    fn on_value_change(&self, context: &EditPolicyContext<'_>) -> DraftAction {
1682        if context.is_dirty() {
1683            DraftAction::Keep
1684        } else {
1685            DraftAction::Replace
1686        }
1687    }
1688
1689    fn on_hidden(&self, context: &EditPolicyContext<'_>) -> EditEnd {
1690        StandardEditPolicy.on_hidden(context)
1691    }
1692}
1693
1694/// The default edit policy: leaving the editor commits a valid draft and
1695/// cancels an invalid one; a draft is kept when the store changes the
1696/// cell, and the conflict shows; an edited row that leaves the shown lines
1697/// cancels the edit; an accepted value waits 5 s for the store; an error
1698/// mark stays until the next edit.
1699#[derive(Clone, Copy, Debug, Default)]
1700pub struct StandardEditPolicy;
1701
1702impl EditPolicy for StandardEditPolicy {
1703    fn on_blur(&self, context: &EditPolicyContext<'_>) -> EditEnd {
1704        if context.draft().is_some() {
1705            EditEnd::Commit
1706        } else {
1707            EditEnd::Cancel
1708        }
1709    }
1710
1711    fn on_value_change(&self, _: &EditPolicyContext<'_>) -> DraftAction {
1712        DraftAction::Keep
1713    }
1714
1715    fn on_hidden(&self, _: &EditPolicyContext<'_>) -> EditEnd {
1716        EditEnd::Cancel
1717    }
1718}
1719
1720// Which presses drag rows.
1721
1722/// A primary press on a data row, as a [`RowDragGesture`] sees it.
1723pub struct RowDragPressContext<'a, R: GridRow> {
1724    line: SelectableLine<'a, R>,
1725    column: R::Column,
1726    was_selected: bool,
1727    modifiers: Modifiers,
1728    platform: PlatformInfo,
1729    mode: SelectionMode,
1730    click_count: usize,
1731}
1732
1733impl<'a, R: GridRow> RowDragPressContext<'a, R> {
1734    pub(crate) fn new(
1735        line: SelectableLine<'a, R>,
1736        column: R::Column,
1737        was_selected: bool,
1738        modifiers: Modifiers,
1739        platform: PlatformInfo,
1740        mode: SelectionMode,
1741        click_count: usize,
1742    ) -> Self {
1743        Self {
1744            line,
1745            column,
1746            was_selected,
1747            modifiers,
1748            platform,
1749            mode,
1750            click_count,
1751        }
1752    }
1753
1754    /// The pressed line: a data row, a tree row too. Group captions,
1755    /// chevrons, pinned rows and the empty area below the rows never drag.
1756    pub fn line(&self) -> &SelectableLine<'a, R> {
1757        &self.line
1758    }
1759
1760    /// The pressed cell's column: a drag handle's, for a gesture that
1761    /// drags from one column only.
1762    pub fn column(&self) -> R::Column {
1763        self.column
1764    }
1765
1766    /// Returns true if the pressed row was selected before the press.
1767    pub fn was_selected(&self) -> bool {
1768        self.was_selected
1769    }
1770
1771    /// The modifiers held.
1772    pub fn modifiers(&self) -> Modifiers {
1773        self.modifiers
1774    }
1775
1776    /// The host whose conventions apply, as `App::platform_info`: a browser
1777    /// on macOS is a macOS host, so the secondary modifier is Cmd there.
1778    pub fn platform_info(&self) -> PlatformInfo {
1779        self.platform
1780    }
1781
1782    /// The grid's selection mode.
1783    pub fn mode(&self) -> SelectionMode {
1784        self.mode
1785    }
1786
1787    /// The press's place in a series: 2 for the second press of a double
1788    /// click.
1789    pub fn click_count(&self) -> usize {
1790        self.click_count
1791    }
1792}
1793
1794/// Whether the secondary modifier is held: Cmd on a macOS host, Ctrl
1795/// elsewhere, as `Modifiers::secondary` (which needs the `App`).
1796fn is_secondary_held(modifiers: Modifiers, platform: PlatformInfo) -> bool {
1797    if platform.is_mac() {
1798        modifiers.platform
1799    } else {
1800        modifiers.control
1801    }
1802}
1803
1804/// Which presses on the rows may become a row drag. A press that may starts
1805/// no drag-selection; past [`Self::threshold`] the drag starts, carrying the
1806/// command scope of the pressed row. Asked once per press.
1807///
1808/// The default is [`NoRowDrag`]: rows do not drag. [`SelectedRowsDrag`] is
1809/// the built-in alternative, LiveGrid's two-phase gesture.
1810pub trait RowDragGesture<R: GridRow>: 'static {
1811    /// Returns true if `press` may become a row drag.
1812    fn is_drag_press(&self, press: &RowDragPressContext<'_, R>) -> bool;
1813
1814    /// How far the pointer travels from the press before the drag starts.
1815    /// Default: 10 px.
1816    fn threshold(&self) -> Pixels {
1817        px(10.)
1818    }
1819
1820    /// Returns false if no press ever drags: the grid then installs no drag
1821    /// listeners at all. Default: true.
1822    fn is_enabled(&self) -> bool {
1823        true
1824    }
1825}
1826
1827/// No press drags rows. The default: without an application handling
1828/// `Drop`, a drag would only get in the way of the selection.
1829#[derive(Clone, Copy, Debug, Default)]
1830pub struct NoRowDrag;
1831
1832impl<R: GridRow> RowDragGesture<R> for NoRowDrag {
1833    fn is_drag_press(&self, _: &RowDragPressContext<'_, R>) -> bool {
1834        false
1835    }
1836
1837    fn is_enabled(&self) -> bool {
1838        false
1839    }
1840}
1841
1842/// LiveGrid's two-phase gesture: the first press of a series, without Shift
1843/// and without the platform toggle (Cmd on macOS, Ctrl elsewhere), on a data
1844/// row selected before the press drags the selection once the pointer is
1845/// 10 px away. A press on an unselected row selects it and drag-selects as
1846/// before.
1847#[derive(Clone, Copy, Debug)]
1848pub struct SelectedRowsDrag {
1849    threshold: Pixels,
1850}
1851
1852impl SelectedRowsDrag {
1853    /// The gesture with a 10 px threshold.
1854    pub fn new() -> Self {
1855        Self { threshold: px(10.) }
1856    }
1857
1858    /// Sets how far the pointer travels before the drag starts, such as the
1859    /// system's 3 or 4 px.
1860    pub fn with_threshold(mut self, threshold: Pixels) -> Self {
1861        self.threshold = threshold;
1862        self
1863    }
1864}
1865
1866impl Default for SelectedRowsDrag {
1867    fn default() -> Self {
1868        Self::new()
1869    }
1870}
1871
1872impl<R: GridRow> RowDragGesture<R> for SelectedRowsDrag {
1873    fn is_drag_press(&self, press: &RowDragPressContext<'_, R>) -> bool {
1874        let modifiers = press.modifiers();
1875        press.was_selected()
1876            && press.click_count() == 1
1877            && !modifiers.shift
1878            && !is_secondary_held(modifiers, press.platform_info())
1879            && matches!(press.line(), SelectableLine::Row { .. })
1880    }
1881
1882    fn threshold(&self) -> Pixels {
1883        self.threshold
1884    }
1885}
1886
1887// Where drops land.
1888
1889/// The line under a drag over the rows.
1890#[non_exhaustive]
1891pub enum DropLine<'a, R: GridRow> {
1892    /// A data row; `branch` is set for a tree row with shown children.
1893    Row {
1894        /// The row's key.
1895        key: &'a R::Key,
1896        /// The row's children, in a tree.
1897        branch: Option<Branch>,
1898    },
1899    /// A group caption.
1900    Caption(GroupInfo<'a>),
1901    /// Below the last row, a row fading out, or an empty grid.
1902    Empty,
1903}
1904
1905/// A drag over the rows, as a [`RowDropPolicy`] sees it.
1906pub struct RowDropContext<'a, R: GridRow> {
1907    line: DropLine<'a, R>,
1908    offset: f32,
1909    rows: Option<&'a RowDrag<R::Key>>,
1910    value: Option<&'a dyn std::any::Any>,
1911    own: bool,
1912    modifiers: Modifiers,
1913    sorted: bool,
1914    grouped: bool,
1915    tree: bool,
1916    last_row: Option<&'a R::Key>,
1917    snapshot: &'a crate::store::StoreSnapshot<R>,
1918}
1919
1920impl<'a, R: GridRow> RowDropContext<'a, R> {
1921    #[allow(clippy::too_many_arguments)]
1922    pub(crate) fn new(
1923        line: DropLine<'a, R>,
1924        offset: f32,
1925        rows: Option<&'a RowDrag<R::Key>>,
1926        value: Option<&'a dyn std::any::Any>,
1927        own: bool,
1928        modifiers: Modifiers,
1929        (sorted, grouped, tree): (bool, bool, bool),
1930        last_row: Option<&'a R::Key>,
1931        snapshot: &'a crate::store::StoreSnapshot<R>,
1932    ) -> Self {
1933        Self {
1934            line,
1935            offset,
1936            rows,
1937            value,
1938            own,
1939            modifiers,
1940            sorted,
1941            grouped,
1942            tree,
1943            last_row,
1944            snapshot,
1945        }
1946    }
1947
1948    /// The line under the pointer.
1949    pub fn line(&self) -> &DropLine<'a, R> {
1950        &self.line
1951    }
1952
1953    /// Where the pointer is within the line's height: 0.0 at its top, 1.0
1954    /// at its bottom.
1955    pub fn offset(&self) -> f32 {
1956        self.offset
1957    }
1958
1959    /// The dragged rows of a grid with this key type; `None` for a value
1960    /// of a type registered with `with_drop_payload`.
1961    pub fn rows(&self) -> Option<&'a RowDrag<R::Key>> {
1962        self.rows
1963    }
1964
1965    /// The dragged value of a registered type `T`.
1966    pub fn payload<T: 'static>(&self) -> Option<&'a T> {
1967        self.value?.downcast_ref()
1968    }
1969
1970    /// Returns true if the rows come from this grid.
1971    pub fn is_own(&self) -> bool {
1972        self.own
1973    }
1974
1975    /// The modifiers held.
1976    pub fn modifiers(&self) -> Modifiers {
1977        self.modifiers
1978    }
1979
1980    /// Returns true if the view is sorted: a place between rows would not
1981    /// hold.
1982    pub fn is_sorted(&self) -> bool {
1983        self.sorted
1984    }
1985
1986    /// Returns true if the view is grouped.
1987    pub fn is_grouped(&self) -> bool {
1988        self.grouped
1989    }
1990
1991    /// Returns true if the view is a tree.
1992    pub fn is_tree(&self) -> bool {
1993        self.tree
1994    }
1995
1996    /// The last data row shown, for a drop below the rows; `None` in an
1997    /// empty grid.
1998    pub fn last_row(&self) -> Option<&'a R::Key> {
1999        self.last_row
2000    }
2001
2002    /// A row of the snapshot shown.
2003    pub fn row(&self, key: &R::Key) -> Option<&'a Arc<R>> {
2004        self.snapshot.row(self.snapshot.row_id(key)?)
2005    }
2006}
2007
2008/// Where a drag over the rows would land, or whether the grid refuses it.
2009/// Asked on every move of a drag over the rows and once more at the drop;
2010/// pinned bands, group footers and totals refuse without asking.
2011///
2012/// The default is [`NoRowDrop`]: the grid takes no drop. [`DropOnRows`]
2013/// and [`DropBetweenRows`] are built in.
2014pub trait RowDropPolicy<R: GridRow>: 'static {
2015    /// Where a drop at `drop` lands; `None` refuses it.
2016    fn place(&self, drop: &RowDropContext<'_, R>) -> Option<DropTarget<R::Key>>;
2017
2018    /// Returns false if the grid takes no drop at all: it then installs no
2019    /// drop listener. Default: true.
2020    fn is_enabled(&self) -> bool {
2021        true
2022    }
2023
2024    /// Returns true if a drop with `modifiers` held copies rather than
2025    /// moves: the grid then shows the copy cursor over a target. What a
2026    /// drop does stays the application's, which reads the modifiers of
2027    /// `LiveGridEvent::Drop`. Default: Option (Alt) or Ctrl, on every
2028    /// platform.
2029    fn is_copy(&self, modifiers: Modifiers) -> bool {
2030        modifiers.alt || modifiers.control
2031    }
2032}
2033
2034/// The grid takes no drop. The default.
2035#[derive(Clone, Copy, Debug, Default)]
2036pub struct NoRowDrop;
2037
2038impl<R: GridRow> RowDropPolicy<R> for NoRowDrop {
2039    fn place(&self, _: &RowDropContext<'_, R>) -> Option<DropTarget<R::Key>> {
2040        None
2041    }
2042
2043    fn is_enabled(&self) -> bool {
2044        false
2045    }
2046}
2047
2048/// Onto data rows (tree rows too), group captions and the empty area below
2049/// the rows; any source.
2050#[derive(Clone, Copy, Debug, Default)]
2051pub struct DropOnRows;
2052
2053impl<R: GridRow> RowDropPolicy<R> for DropOnRows {
2054    fn place(&self, drop: &RowDropContext<'_, R>) -> Option<DropTarget<R::Key>> {
2055        Some(match drop.line() {
2056            DropLine::Row { key, .. } => DropTarget::Row {
2057                key: (*key).clone(),
2058                place: DropPlace::Onto,
2059            },
2060            DropLine::Caption(group) => DropTarget::Group(group.path().clone()),
2061            DropLine::Empty => DropTarget::Empty,
2062        })
2063    }
2064}
2065
2066/// Before or after a data row by the half the pointer is in; in a tree the
2067/// top third is before, the middle onto, the bottom third after. Onto group
2068/// captions. Below the rows, after the last one; an empty grid takes
2069/// `Empty`. Refuses in a sorted flat view, where a place between rows would
2070/// not hold.
2071#[derive(Clone, Copy, Debug, Default)]
2072pub struct DropBetweenRows;
2073
2074impl<R: GridRow> RowDropPolicy<R> for DropBetweenRows {
2075    fn place(&self, drop: &RowDropContext<'_, R>) -> Option<DropTarget<R::Key>> {
2076        if drop.is_sorted() && !drop.is_grouped() && !drop.is_tree() {
2077            return None;
2078        }
2079        let row = |key: &R::Key, place| DropTarget::Row {
2080            key: key.clone(),
2081            place,
2082        };
2083        Some(match drop.line() {
2084            DropLine::Row { key, .. } if drop.is_tree() => {
2085                let place = match drop.offset() {
2086                    offset if offset < 1. / 3. => DropPlace::Before,
2087                    offset if offset < 2. / 3. => DropPlace::Onto,
2088                    _ => DropPlace::After,
2089                };
2090                row(key, place)
2091            }
2092            DropLine::Row { key, .. } if drop.offset() < 0.5 => row(key, DropPlace::Before),
2093            DropLine::Row { key, .. } => row(key, DropPlace::After),
2094            DropLine::Caption(group) => DropTarget::Group(group.path().clone()),
2095            DropLine::Empty => match drop.last_row() {
2096                Some(key) => row(key, DropPlace::After),
2097                None => DropTarget::Empty,
2098            },
2099        })
2100    }
2101}
2102
2103#[cfg(test)]
2104mod tests {
2105    use gpui_kit::{OperatingSystem, PlatformTarget, px};
2106
2107    use super::*;
2108
2109    const MAC: PlatformInfo = PlatformInfo {
2110        os: OperatingSystem::Mac,
2111        target: PlatformTarget::Native,
2112    };
2113    /// A browser on macOS follows the Mac conventions.
2114    const MAC_BROWSER: PlatformInfo = PlatformInfo {
2115        os: OperatingSystem::Mac,
2116        target: PlatformTarget::Web,
2117    };
2118    const LINUX: PlatformInfo = PlatformInfo {
2119        os: OperatingSystem::Linux,
2120        target: PlatformTarget::Native,
2121    };
2122
2123    fn ix(i: u16) -> ColumnIx {
2124        ColumnIx::new(i)
2125    }
2126
2127    /// c0, band A [c1, band B [c2, c3], c4], c5, all visible.
2128    fn banded() -> (Vec<ColumnIx>, Vec<Box<[&'static str]>>) {
2129        let columns = (0..6).map(ix).collect();
2130        let bands: Vec<Box<[&'static str]>> = vec![
2131            Box::new([]),
2132            Box::new(["a"]),
2133            Box::new(["a", "b"]),
2134            Box::new(["a", "b"]),
2135            Box::new(["a"]),
2136            Box::new([]),
2137        ];
2138        (columns, bands)
2139    }
2140
2141    #[test]
2142    fn test_banded_move_policy() {
2143        let (columns, bands) = banded();
2144        let visible = ColumnSet::first(6);
2145        let context = ColumnMoveContext::new(ColumnZone::Scrolling, &columns, visible, &bands);
2146        let allowed = |block: Range<usize>, gap: usize| BandedMove.is_allowed(&context, block, gap);
2147
2148        // c2 moves only among the children of B.
2149        assert!(allowed(3..4, 2));
2150        assert!(allowed(2..3, 4));
2151        assert!(!allowed(2..3, 1), "out of B to the left");
2152        assert!(!allowed(2..3, 5), "out of B to the right");
2153        // c1 moves among the children of A: around B as a whole, never into it.
2154        assert!(allowed(1..2, 4));
2155        assert!(allowed(1..2, 5));
2156        assert!(!allowed(1..2, 3), "inside the sibling band B");
2157        assert!(!allowed(1..2, 0), "out of A");
2158        // B as a whole is a child of A.
2159        assert!(allowed(2..4, 1));
2160        assert!(allowed(2..4, 5));
2161        assert!(!allowed(2..4, 0));
2162        // A as a whole moves among the zone's top-level items.
2163        assert!(allowed(1..5, 0));
2164        assert!(allowed(1..5, 6));
2165        // c0 cannot land inside A.
2166        assert!(allowed(0..1, 5));
2167        assert!(allowed(0..1, 6));
2168        assert!(!allowed(0..1, 2));
2169        assert!(!allowed(0..1, 4));
2170
2171        // A zone change takes the whole top-level band.
2172        assert_eq!(BandedMove.zone_block(&context, ix(2)), 1..5);
2173        assert_eq!(BandedMove.zone_block(&context, ix(4)), 1..5);
2174        assert_eq!(BandedMove.zone_block(&context, ix(0)), 0..1);
2175        assert_eq!(BandedMove.zone_block(&context, ix(9)), 0..0);
2176
2177        // Free moves: every gap of the zone, one column at a time.
2178        assert!(FreeMove.is_allowed(&context, 0..1, 2));
2179        assert!(FreeMove.is_allowed(&context, 2..3, 6));
2180        assert!(!FreeMove.is_allowed(&context, 2..3, 7));
2181        assert_eq!(FreeMove.zone_block(&context, ix(2)), 2..3);
2182
2183        // `normalize` gathers each band at the place of its first column,
2184        // nested bands too, in the zone of its first column.
2185        let mut zones = vec![ColumnZone::Scrolling; 6];
2186        zones[4] = ColumnZone::FrozenRight;
2187        let mut order = vec![ix(2), ix(0), ix(1), ix(3), ix(5), ix(4)];
2188        BandedMove.normalize(&mut ColumnOrder::new(&mut order, &mut zones, &bands));
2189        assert_eq!(order, [2, 3, 1, 4, 0, 5].map(ix));
2190        assert_eq!(zones[4], ColumnZone::Scrolling);
2191        // A valid order stays as it is.
2192        let mut order = vec![ix(5), ix(1), ix(3), ix(2), ix(4), ix(0)];
2193        let before = order.clone();
2194        BandedMove.normalize(&mut ColumnOrder::new(&mut order, &mut zones, &bands));
2195        assert_eq!(order, before);
2196        // Free moves keep any order.
2197        let mut order = vec![ix(2), ix(0), ix(1), ix(3), ix(5), ix(4)];
2198        FreeMove.normalize(&mut ColumnOrder::new(&mut order, &mut zones, &bands));
2199        assert_eq!(order, [2, 0, 1, 3, 5, 4].map(ix));
2200
2201        // `reorder` accepts permutations only.
2202        let mut order = (0..6).map(ix).collect::<Vec<_>>();
2203        let mut view = ColumnOrder::new(&mut order, &mut zones, &bands);
2204        assert!(!view.reorder(&[ix(0), ix(0), ix(1), ix(2), ix(3), ix(4)]));
2205        assert!(!view.reorder(&[ix(0)]));
2206        assert!(view.reorder(&[5, 4, 3, 2, 1, 0].map(ix)));
2207        assert_eq!(view.columns(), [5, 4, 3, 2, 1, 0].map(ix));
2208        assert_eq!(view.bands(ix(3)), ["a", "b"]);
2209    }
2210
2211    #[test]
2212    fn test_visible_rows_autofit() {
2213        let mut measured = Vec::new();
2214        let mut measure = |display_ix: usize| {
2215            measured.push(display_ix);
2216            // Row 4 was removed; row 5 is the widest painted one.
2217            (display_ix != 4).then(|| px(display_ix as f32 * 10.))
2218        };
2219        let mut context = AutofitContext::new(px(25.), 3..6, 1_000, &mut measure);
2220        assert_eq!(context.row_count(), 1_000);
2221        assert_eq!(VisibleRowsAutofit.content_width(&mut context), px(50.));
2222        assert_eq!(measured, [3, 4, 5], "rows off screen are not measured");
2223
2224        // The header is wider than every painted row.
2225        let mut measure = |_: usize| Some(px(10.));
2226        let mut context = AutofitContext::new(px(80.), 0..3, 3, &mut measure);
2227        assert_eq!(VisibleRowsAutofit.content_width(&mut context), px(80.));
2228        // An empty projection fits the header alone.
2229        let mut measure = |_: usize| None;
2230        let mut context = AutofitContext::new(px(42.), 0..0, 0, &mut measure);
2231        assert_eq!(context.pinned_width(), px(0.));
2232        assert_eq!(VisibleRowsAutofit.content_width(&mut context), px(42.));
2233
2234        // A pinned row (a total) wider than the header and the data rows.
2235        let mut measure = |_: usize| Some(px(30.));
2236        let mut context =
2237            AutofitContext::new(px(20.), 0..3, 3, &mut measure).with_pinned_width(px(64.));
2238        assert_eq!(context.pinned_width(), px(64.));
2239        assert_eq!(VisibleRowsAutofit.content_width(&mut context), px(64.));
2240
2241        // A total wider than everything else.
2242        let mut measure = |_: usize| Some(px(30.));
2243        let mut context = AutofitContext::new(px(20.), 0..3, 3, &mut measure)
2244            .with_pinned_width(px(64.))
2245            .with_summary_width(px(90.));
2246        assert_eq!(context.summary_width(), px(90.));
2247        assert_eq!(VisibleRowsAutofit.content_width(&mut context), px(90.));
2248    }
2249
2250    #[test]
2251    fn test_standard_sort_cycle() {
2252        use SortDirection::{Ascending, Descending};
2253        let next = |sort: &[(ColumnIx, SortDirection)], column: u16, shift: bool| {
2254            let modifiers = if shift {
2255                Modifiers::shift()
2256            } else {
2257                Modifiers::default()
2258            };
2259            StandardSortCycle.next_sort(&SortCycleContext::new(sort, ix(column), modifiers))
2260        };
2261
2262        // Without Shift: ascending, descending, unsorted.
2263        assert_eq!(next(&[], 1, false), [(ix(1), Ascending)]);
2264        assert_eq!(next(&[(ix(1), Ascending)], 1, false), [(ix(1), Descending)]);
2265        assert_eq!(next(&[(ix(1), Descending)], 1, false), []);
2266        // Another column replaces the sort.
2267        assert_eq!(next(&[(ix(1), Descending)], 2, false), [(ix(2), Ascending)]);
2268        // From a multi-column sort, the column steps from its own direction
2269        // and the others go (as AG Grid).
2270        let multi = [(ix(1), Ascending), (ix(2), Ascending), (ix(3), Descending)];
2271        assert_eq!(next(&multi, 2, false), [(ix(2), Descending)]);
2272        assert_eq!(next(&multi, 3, false), []);
2273
2274        // Shift adds the column last.
2275        assert_eq!(
2276            next(&multi, 4, true),
2277            [
2278                (ix(1), Ascending),
2279                (ix(2), Ascending),
2280                (ix(3), Descending),
2281                (ix(4), Ascending)
2282            ]
2283        );
2284        // Shift on an ascending column flips it in place, keeping its priority.
2285        assert_eq!(
2286            next(&multi, 1, true),
2287            [(ix(1), Descending), (ix(2), Ascending), (ix(3), Descending)]
2288        );
2289        // Shift on a descending column removes it; the rest move up.
2290        assert_eq!(
2291            next(&[(ix(3), Descending), (ix(1), Ascending)], 3, true),
2292            [(ix(1), Ascending)]
2293        );
2294        assert_eq!(next(&[], 1, true), [(ix(1), Ascending)]);
2295
2296        let context = SortCycleContext::new(&multi, ix(3), Modifiers::shift());
2297        assert_eq!(context.sort(), multi);
2298        assert_eq!(context.column(), ix(3));
2299        assert!(context.modifiers().shift);
2300        assert_eq!(context.direction(), Some(Descending));
2301    }
2302
2303    #[test]
2304    fn test_reorder_policies() {
2305        let start = Instant::now();
2306        let at = |ms: u64| start + Duration::from_millis(ms);
2307        let context =
2308            |now: u64, inside: bool, user: bool| ReorderContext::new(at(now), at(0), inside, user);
2309
2310        assert_eq!(
2311            LiveReorder.decide(&context(0, true, false)),
2312            ReorderDecision::Apply
2313        );
2314
2315        let hold = HoldReorder::new(Duration::from_millis(500));
2316        assert_eq!(
2317            hold.decide(&context(100, true, false)),
2318            ReorderDecision::HoldUntil(at(500))
2319        );
2320        assert_eq!(
2321            hold.decide(&context(500, true, false)),
2322            ReorderDecision::Apply
2323        );
2324        assert_eq!(
2325            hold.decide(&context(100, false, false)),
2326            ReorderDecision::Apply
2327        );
2328        assert_eq!(
2329            hold.decide(&context(100, true, true)),
2330            ReorderDecision::Apply
2331        );
2332
2333        assert_eq!(
2334            ManualReorder.decide(&context(100, false, false)),
2335            ReorderDecision::Hold
2336        );
2337        assert_eq!(
2338            ManualReorder.decide(&context(100, true, true)),
2339            ReorderDecision::Apply
2340        );
2341
2342        // An open menu holds the order under every built-in policy, except
2343        // for a user action.
2344        let menu =
2345            |now: u64, inside: bool, user: bool| context(now, inside, user).with_menu_open(true);
2346        let policies: [&dyn ReorderPolicy; 3] = [&LiveReorder, &hold, &ManualReorder];
2347        for policy in policies {
2348            for inside in [false, true] {
2349                assert_eq!(
2350                    policy.decide(&menu(100, inside, false)),
2351                    ReorderDecision::Hold
2352                );
2353                assert_eq!(
2354                    policy.decide(&menu(100, inside, true)),
2355                    ReorderDecision::Apply
2356                );
2357            }
2358        }
2359        // Past `max`, `HoldReorder` still holds while the menu is open, and
2360        // applies once it closes.
2361        assert_eq!(hold.decide(&menu(900, true, false)), ReorderDecision::Hold);
2362        assert_eq!(
2363            hold.decide(&context(900, true, false)),
2364            ReorderDecision::Apply
2365        );
2366        // A shown tooltip changes nothing for the built-in policies.
2367        let tooltip = |now: u64, inside: bool| context(now, inside, false).with_tooltip_shown(true);
2368        assert!(tooltip(0, true).is_tooltip_shown());
2369        assert!(!context(0, true, false).is_tooltip_shown());
2370        assert!(!context(0, true, false).is_menu_open());
2371        assert_eq!(
2372            LiveReorder.decide(&tooltip(100, true)),
2373            ReorderDecision::Apply
2374        );
2375        assert_eq!(
2376            hold.decide(&tooltip(100, true)),
2377            ReorderDecision::HoldUntil(at(500))
2378        );
2379        assert_eq!(hold.decide(&tooltip(100, false)), ReorderDecision::Apply);
2380        assert_eq!(
2381            ManualReorder.decide(&tooltip(100, false)),
2382            ReorderDecision::Hold
2383        );
2384    }
2385
2386    #[test]
2387    fn test_standard_selection_gesture() {
2388        use SelectionEdit::*;
2389        let pointer = GestureInput::Pointer;
2390        let keyboard = GestureInput::Keyboard;
2391        // The secondary modifier is the host's: Cmd on macOS, in a browser
2392        // there too, Ctrl elsewhere; the other one is a plain press.
2393        for (platform, secondary, other) in [
2394            (MAC, Modifiers::command(), Modifiers::control()),
2395            (MAC_BROWSER, Modifiers::command(), Modifiers::control()),
2396            (LINUX, Modifiers::control(), Modifiers::command()),
2397        ] {
2398            let edit = |input, modifiers: Modifiers, extending, selected| {
2399                StandardSelectionGesture.edit(&SelectionGestureContext::new(
2400                    input,
2401                    modifiers,
2402                    platform,
2403                    extending,
2404                    selected,
2405                    SelectionMode::RowSet,
2406                ))
2407            };
2408            let shift_secondary = Modifiers {
2409                shift: true,
2410                ..secondary
2411            };
2412            // The standard gesture, case by case.
2413            assert_eq!(edit(pointer, Modifiers::default(), false, false), Replace);
2414            assert_eq!(edit(pointer, Modifiers::default(), false, true), Replace);
2415            assert_eq!(edit(pointer, Modifiers::shift(), false, false), Extend);
2416            assert_eq!(edit(pointer, secondary, false, true), Toggle);
2417            assert_eq!(edit(pointer, shift_secondary, false, false), AddRange);
2418            assert_eq!(edit(pointer, other, false, true), Replace);
2419            let context = GestureInput::ContextPointer;
2420            assert_eq!(edit(context, Modifiers::default(), false, false), Replace);
2421            assert_eq!(edit(context, Modifiers::default(), false, true), Keep);
2422            assert_eq!(edit(keyboard, Modifiers::default(), false, true), Replace);
2423            assert_eq!(edit(keyboard, Modifiers::default(), true, false), Extend);
2424        }
2425
2426        let context = SelectionGestureContext::new(
2427            keyboard,
2428            Modifiers::shift(),
2429            LINUX,
2430            true,
2431            true,
2432            SelectionMode::CellSet,
2433        );
2434        assert_eq!(context.input(), keyboard);
2435        assert!(context.modifiers().shift);
2436        assert_eq!(context.platform_info(), LINUX);
2437        assert!(context.is_extending());
2438        assert!(context.is_target_selected());
2439        assert_eq!(context.mode(), SelectionMode::CellSet);
2440    }
2441
2442    #[test]
2443    fn test_standard_context_menu_gesture() {
2444        let control = Modifiers::control();
2445        let control_command = Modifiers {
2446            platform: true,
2447            ..control
2448        };
2449        for (platform, macos) in [(MAC, true), (MAC_BROWSER, true), (LINUX, false)] {
2450            let opens = |button, modifiers, click_count, area| {
2451                StandardContextMenuGesture.opens_menu(&ContextMenuGestureContext::new(
2452                    button,
2453                    modifiers,
2454                    platform,
2455                    click_count,
2456                    area,
2457                ))
2458            };
2459            for area in [GridArea::Body, GridArea::Header] {
2460                // The right button, whatever the modifiers and the series.
2461                for modifiers in [Modifiers::default(), Modifiers::shift(), control] {
2462                    assert!(opens(MouseButton::Right, modifiers, 1, area));
2463                }
2464                assert!(opens(MouseButton::Right, Modifiers::default(), 2, area));
2465                // The left button: Ctrl without Cmd on a macOS host only. Cmd
2466                // on macOS and Ctrl elsewhere toggle the selection.
2467                assert!(!opens(MouseButton::Left, Modifiers::default(), 1, area));
2468                assert!(!opens(MouseButton::Left, Modifiers::shift(), 1, area));
2469                assert!(!opens(MouseButton::Left, Modifiers::command(), 1, area));
2470                assert_eq!(opens(MouseButton::Left, control, 1, area), macos);
2471                assert_eq!(opens(MouseButton::Left, control, 2, area), macos);
2472                assert!(!opens(MouseButton::Left, control_command, 1, area));
2473                // Other buttons never.
2474                assert!(!opens(MouseButton::Middle, Modifiers::default(), 1, area));
2475                assert!(!opens(MouseButton::Middle, control, 1, area));
2476            }
2477        }
2478
2479        let context = ContextMenuGestureContext::new(
2480            MouseButton::Middle,
2481            control,
2482            LINUX,
2483            2,
2484            GridArea::Header,
2485        );
2486        assert_eq!(context.button(), MouseButton::Middle);
2487        assert!(context.modifiers().control);
2488        assert_eq!(context.platform_info(), LINUX);
2489        assert_eq!(context.click_count(), 2);
2490        assert_eq!(context.area(), GridArea::Header);
2491    }
2492
2493    #[test]
2494    fn test_drop_policies() {
2495        use std::time::Instant;
2496
2497        use crate::{
2498            highlight::HighlightPolicy,
2499            model::{CellValue, GridColumns},
2500            store::Ingest,
2501        };
2502
2503        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2504        struct Only;
2505
2506        impl GridColumns for Only {
2507            fn all() -> &'static [Self] {
2508                &[Only]
2509            }
2510
2511            fn id(self) -> &'static str {
2512                "only"
2513            }
2514
2515            fn ix(self) -> ColumnIx {
2516                ColumnIx::new(0)
2517            }
2518        }
2519
2520        struct Row(u32);
2521
2522        impl GridRow for Row {
2523            type Key = u32;
2524            type Column = Only;
2525
2526            fn key(&self) -> &u32 {
2527                &self.0
2528            }
2529
2530            fn value(&self, _: Only) -> CellValue<'_> {
2531                CellValue::Empty
2532            }
2533        }
2534
2535        // The copy cursor: Option or Ctrl by default; a policy may decide
2536        // otherwise.
2537        let held = |alt, control| Modifiers {
2538            alt,
2539            control,
2540            ..Modifiers::default()
2541        };
2542        assert!(RowDropPolicy::<Row>::is_copy(&NoRowDrop, held(true, false)));
2543        assert!(RowDropPolicy::<Row>::is_copy(&NoRowDrop, held(false, true)));
2544        assert!(!RowDropPolicy::<Row>::is_copy(
2545            &NoRowDrop,
2546            held(false, false)
2547        ));
2548        struct NeverCopy;
2549        impl RowDropPolicy<Row> for NeverCopy {
2550            fn place(&self, _: &RowDropContext<'_, Row>) -> Option<DropTarget<u32>> {
2551                None
2552            }
2553
2554            fn is_copy(&self, _: Modifiers) -> bool {
2555                false
2556            }
2557        }
2558        assert!(!NeverCopy.is_copy(held(true, true)));
2559
2560        let snapshot = Ingest::<Row>::new(HighlightPolicy::default(), Instant::now()).snapshot();
2561        let (key, last) = (3, 9);
2562        // A drag at `offset` over the row of `key` (`None`: below the rows)
2563        // in a view `(sorted, grouped, tree)`.
2564        let place = |policy: &dyn RowDropPolicy<Row>,
2565                     row: Option<f32>,
2566                     view: (bool, bool, bool),
2567                     last_row: Option<&u32>| {
2568            let line = match row {
2569                Some(_) => DropLine::Row {
2570                    key: &key,
2571                    branch: None,
2572                },
2573                None => DropLine::Empty,
2574            };
2575            policy.place(&RowDropContext::new(
2576                line,
2577                row.unwrap_or(0.),
2578                None,
2579                None,
2580                false,
2581                Modifiers::default(),
2582                view,
2583                last_row,
2584                &snapshot,
2585            ))
2586        };
2587        let at = |key, place| Some(DropTarget::Row { key, place });
2588        let flat = (false, false, false);
2589        assert!(!RowDropPolicy::<Row>::is_enabled(&NoRowDrop));
2590        assert_eq!(place(&NoRowDrop, Some(0.5), flat, None), None);
2591        assert_eq!(
2592            place(&DropOnRows, Some(0.1), flat, None),
2593            at(3, DropPlace::Onto)
2594        );
2595        assert_eq!(
2596            place(&DropOnRows, None, flat, None),
2597            Some(DropTarget::Empty)
2598        );
2599        // Between rows by the half, in a tree by the third.
2600        assert_eq!(
2601            place(&DropBetweenRows, Some(0.4), flat, None),
2602            at(3, DropPlace::Before)
2603        );
2604        assert_eq!(
2605            place(&DropBetweenRows, Some(0.6), flat, None),
2606            at(3, DropPlace::After)
2607        );
2608        let tree = (false, false, true);
2609        assert_eq!(
2610            place(&DropBetweenRows, Some(0.2), tree, None),
2611            at(3, DropPlace::Before)
2612        );
2613        assert_eq!(
2614            place(&DropBetweenRows, Some(0.5), tree, None),
2615            at(3, DropPlace::Onto)
2616        );
2617        assert_eq!(
2618            place(&DropBetweenRows, Some(0.8), tree, None),
2619            at(3, DropPlace::After)
2620        );
2621        // Below the rows: after the last one; an empty grid takes `Empty`.
2622        assert_eq!(
2623            place(&DropBetweenRows, None, flat, Some(&last)),
2624            at(9, DropPlace::After)
2625        );
2626        assert_eq!(
2627            place(&DropBetweenRows, None, flat, None),
2628            Some(DropTarget::Empty)
2629        );
2630        // Sorted: refused when flat, kept when grouped.
2631        assert_eq!(
2632            place(&DropBetweenRows, Some(0.6), (true, false, false), None),
2633            None
2634        );
2635        assert_eq!(
2636            place(&DropBetweenRows, Some(0.6), (true, true, false), None),
2637            at(3, DropPlace::After)
2638        );
2639    }
2640
2641    #[test]
2642    fn test_selection_scopes() {
2643        use std::{sync::Arc, time::Instant};
2644
2645        use crate::{
2646            engine::{ProjectionEngine as _, Rebuild, ViewSpec},
2647            highlight::HighlightPolicy,
2648            model::{CellValue, GridColumns},
2649            store::{Ingest, Op},
2650        };
2651
2652        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2653        struct Price;
2654
2655        impl GridColumns for Price {
2656            fn all() -> &'static [Self] {
2657                &[Price]
2658            }
2659
2660            fn id(self) -> &'static str {
2661                "price"
2662            }
2663
2664            fn ix(self) -> ColumnIx {
2665                ColumnIx::new(0)
2666            }
2667        }
2668
2669        struct Row(u32, i64);
2670
2671        impl GridRow for Row {
2672            type Key = u32;
2673            type Column = Price;
2674
2675            fn key(&self) -> &u32 {
2676                &self.0
2677            }
2678
2679            fn value(&self, _: Price) -> CellValue<'_> {
2680                CellValue::Int(self.1)
2681            }
2682        }
2683
2684        // Ten rows sorted by price descending (key 9 first); odd keys shown.
2685        let mut ingest = Ingest::new(HighlightPolicy::default(), Instant::now());
2686        ingest.apply(
2687            (0..10).map(|id| Op::Upsert(Arc::new(Row(id, id.into())))),
2688            Instant::now(),
2689        );
2690        let view = ViewSpec::new()
2691            .with_sort([(Price, SortDirection::Descending)])
2692            .with_filter(ColumnSet::first(1), |row: &Row| row.0 % 2 == 1);
2693        let projection = Rebuild::default().rebuild(&ingest.snapshot(), &view);
2694        // Removed after the projection was built: a tombstone on screen.
2695        ingest.apply([Op::Remove(5), Op::Remove(4)], Instant::now());
2696        let snapshot = ingest.snapshot();
2697
2698        let row = ColumnSet::first(1);
2699        let resolve = |scope: &dyn SelectionScope<Row>, keys: &[u32]| {
2700            // Key 42 never existed; 4 and 5 are removed; 2 and 6 hidden.
2701            let selection = GridSelection::from_rows(keys.iter().map(|key| (*key, row)));
2702            let scoped = scope.resolve(&SelectionScopeContext::new(
2703                &selection,
2704                &projection,
2705                &snapshot,
2706                SelectionMode::RowSet,
2707            ));
2708            assert!((0..scoped.len()).all(|ix| scoped.columns(ix) == row));
2709            assert_eq!(scoped.columns(scoped.len()), ColumnSet::EMPTY);
2710            scoped.keys().to_vec()
2711        };
2712        let few = [1, 6, 2, 5, 9, 4, 42];
2713        let many: Vec<u32> = (0..10).chain([42]).collect();
2714        // The selection within the screen, in display order, both paths.
2715        assert_eq!(resolve(&ProjectionScope, &few), [9, 1]);
2716        assert_eq!(resolve(&ProjectionScope, &many), [9, 7, 3, 1]);
2717        assert!(resolve(&ProjectionScope, &[]).is_empty());
2718        // Hidden rows after the shown ones, by insertion; removed never.
2719        assert_eq!(resolve(&StoreScope, &few), [9, 1, 2, 6]);
2720        assert_eq!(resolve(&StoreScope, &many), [9, 7, 3, 1, 0, 2, 6, 8]);
2721
2722        let empty = GridSelection::default();
2723        let context =
2724            SelectionScopeContext::new(&empty, &projection, &snapshot, SelectionMode::CellSet);
2725        assert_eq!(context.mode(), SelectionMode::CellSet);
2726        assert_eq!(context.projection().len(), 5);
2727        assert_eq!(context.snapshot().len(), 8);
2728        assert!(context.selection().is_empty());
2729        // A scope is collected from (key, columns) pairs.
2730        let scoped: ScopedSelection<u32> = [(3, row)].into_iter().collect();
2731        assert_eq!((scoped.len(), scoped.is_empty()), (1, false));
2732    }
2733
2734    #[test]
2735    fn test_standard_expand_gesture() {
2736        let edit = |area, button, modifiers, click_count| {
2737            StandardExpandGesture.edit(&ExpandGestureContext::new(
2738                area,
2739                button,
2740                modifiers,
2741                click_count,
2742            ))
2743        };
2744        let (left, plain) = (MouseButton::Left, Modifiers::default());
2745        let alt = Modifiers::alt();
2746        // A chevron toggles on the first press of a series; with Alt, deep.
2747        assert_eq!(
2748            edit(ExpandArea::Chevron, left, plain, 1),
2749            Some(ExpandEdit::Toggle)
2750        );
2751        assert_eq!(
2752            edit(ExpandArea::Chevron, left, alt, 1),
2753            Some(ExpandEdit::ToggleDeep)
2754        );
2755        assert_eq!(edit(ExpandArea::Chevron, left, plain, 2), None);
2756        // A caption toggles on the second press of a double click.
2757        assert_eq!(edit(ExpandArea::Caption, left, plain, 1), None);
2758        assert_eq!(
2759            edit(ExpandArea::Caption, left, plain, 2),
2760            Some(ExpandEdit::Toggle)
2761        );
2762        assert_eq!(edit(ExpandArea::Caption, left, plain, 3), None);
2763        // A tree cell never: a double click confirms its row.
2764        assert_eq!(edit(ExpandArea::TreeCell, left, plain, 1), None);
2765        assert_eq!(edit(ExpandArea::TreeCell, left, plain, 2), None);
2766        // Other buttons never.
2767        assert_eq!(
2768            edit(ExpandArea::Chevron, MouseButton::Right, plain, 1),
2769            None
2770        );
2771        assert_eq!(
2772            edit(ExpandArea::Chevron, MouseButton::Middle, plain, 1),
2773            None
2774        );
2775
2776        let context = ExpandGestureContext::new(ExpandArea::TreeCell, left, alt, 2);
2777        assert_eq!(context.area(), ExpandArea::TreeCell);
2778        assert_eq!(context.button(), left);
2779        assert!(context.modifiers().alt);
2780        assert_eq!(context.click_count(), 2);
2781    }
2782
2783    #[test]
2784    fn test_focus_captions() {
2785        use std::{sync::Arc, time::Instant};
2786
2787        use crate::{
2788            engine::{GroupBy, ProjectionEngine as _, Rebuild, ViewSpec},
2789            highlight::HighlightPolicy,
2790            model::{CellValue, GridColumns},
2791            store::{Ingest, Op},
2792        };
2793
2794        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2795        enum Col {
2796            Side,
2797            Qty,
2798        }
2799
2800        impl GridColumns for Col {
2801            fn all() -> &'static [Self] {
2802                &[Col::Side, Col::Qty]
2803            }
2804
2805            fn id(self) -> &'static str {
2806                match self {
2807                    Col::Side => "side",
2808                    Col::Qty => "qty",
2809                }
2810            }
2811
2812            fn ix(self) -> ColumnIx {
2813                ColumnIx::new(self as u16)
2814            }
2815        }
2816
2817        struct Row(u32, &'static str);
2818
2819        impl GridRow for Row {
2820            type Key = u32;
2821            type Column = Col;
2822
2823            fn key(&self) -> &u32 {
2824                &self.0
2825            }
2826
2827            fn value(&self, column: Col) -> CellValue<'_> {
2828                match column {
2829                    Col::Side => CellValue::Text(self.1),
2830                    Col::Qty => CellValue::Int(self.0.into()),
2831                }
2832            }
2833        }
2834
2835        // Six rows in two groups, Buy (even keys) and Sell (odd keys).
2836        let mut ingest = Ingest::new(HighlightPolicy::default(), Instant::now());
2837        ingest.apply(
2838            (0..6).map(|id| {
2839                let side = if id % 2 == 0 { "Buy" } else { "Sell" };
2840                Op::Upsert(Arc::new(Row(id, side)))
2841            }),
2842            Instant::now(),
2843        );
2844        let view = ViewSpec::new()
2845            .with_sort([(Col::Qty, SortDirection::Descending)])
2846            .with_group_by([GroupBy::column(Col::Side)]);
2847        let projection = Rebuild::default().rebuild(&ingest.snapshot(), &view);
2848        // Removed after the projection was built: left out of the scope.
2849        ingest.apply([Op::Remove(2)], Instant::now());
2850        let snapshot = ingest.snapshot();
2851        let buy = projection.groups().iter().next().expect("the Buy group");
2852        let rows = projection.order_ix(buy.rows()[0]).expect("in the order");
2853
2854        let policy: &dyn SelectionPolicy<Row> = &FocusCaptions;
2855        let caption = SelectableLine::Caption { group: buy };
2856        assert!(!policy.is_selectable(&caption));
2857        let context = LineScopeContext::new(
2858            caption,
2859            rows..rows + buy.rows().len(),
2860            &projection,
2861            &snapshot,
2862            SelectionMode::CellSet,
2863        );
2864        assert_eq!(context.mode(), SelectionMode::CellSet);
2865        assert_eq!(context.projection().len(), projection.len());
2866        assert_eq!(context.snapshot().len(), 5);
2867        // Every live row of the group in order, with every column, in the
2868        // cell modes too.
2869        let scope = policy.line_scope(&context).expect("a caption's scope");
2870        assert_eq!(scope.keys(), [4, 0]);
2871        assert_eq!(scope.columns(0), ColumnSet::first(2));
2872
2873        // A row is selectable, and a command over it acts on the selection.
2874        let row = snapshot.get(&3).expect("row 3");
2875        let line = SelectableLine::Row {
2876            row: &**row,
2877            branch: None,
2878        };
2879        assert!(policy.is_selectable(&line));
2880        let context =
2881            LineScopeContext::new(line, 0..0, &projection, &snapshot, SelectionMode::RowSet);
2882        assert_eq!(context.rows().count(), 0);
2883        assert!(policy.line_scope(&context).is_none());
2884    }
2885
2886    #[test]
2887    fn test_focus_branches_policy() {
2888        use std::{sync::Arc, time::Instant};
2889
2890        use crate::{
2891            engine::{ExpandDepth, GroupBy, ProjectionEngine as _, Rebuild, TreeSpec, ViewSpec},
2892            highlight::HighlightPolicy,
2893            model::{CellValue, GridColumns},
2894            store::{Ingest, Op},
2895        };
2896
2897        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2898        enum Col {
2899            Id,
2900            Kind,
2901        }
2902
2903        impl GridColumns for Col {
2904            fn all() -> &'static [Self] {
2905                &[Col::Id, Col::Kind]
2906            }
2907
2908            fn id(self) -> &'static str {
2909                match self {
2910                    Col::Id => "id",
2911                    Col::Kind => "kind",
2912                }
2913            }
2914
2915            fn ix(self) -> ColumnIx {
2916                ColumnIx::new(self as u16)
2917            }
2918        }
2919
2920        struct Node {
2921            id: u32,
2922            parent: Option<u32>,
2923        }
2924
2925        impl GridRow for Node {
2926            type Key = u32;
2927            type Column = Col;
2928
2929            fn key(&self) -> &u32 {
2930                &self.id
2931            }
2932
2933            fn value(&self, column: Col) -> CellValue<'_> {
2934                match column {
2935                    Col::Id => CellValue::Int(self.id.into()),
2936                    Col::Kind => CellValue::Text(if self.id % 2 == 0 { "even" } else { "odd" }),
2937                }
2938            }
2939
2940            fn parent_key(&self) -> Option<&u32> {
2941                self.parent.as_ref()
2942            }
2943        }
2944
2945        // 0 ─┬─ 1 ─┬─ 3
2946        //    │     └─ 4
2947        //    ├─ 2 ─── 5   (2 collapsed)
2948        //    └─ 6
2949        // 7
2950        let parent = |id| match id {
2951            1 | 2 | 6 => Some(0),
2952            3 | 4 => Some(1),
2953            5 => Some(2),
2954            _ => None,
2955        };
2956        let mut ingest = Ingest::new(HighlightPolicy::default(), Instant::now());
2957        ingest.apply(
2958            (0..8).map(|id| {
2959                Op::Upsert(Arc::new(Node {
2960                    id,
2961                    parent: parent(id),
2962                }))
2963            }),
2964            Instant::now(),
2965        );
2966        let view = ViewSpec::new()
2967            .with_sort([(Col::Id, SortDirection::Ascending)])
2968            .with_tree(TreeSpec::new())
2969            .with_tree_expansion(ExpandDepth::All, [2]);
2970        let projection = Rebuild::default().rebuild(&ingest.snapshot(), &view);
2971        let snapshot = ingest.snapshot();
2972        let order: Vec<u32> = projection
2973            .rows()
2974            .iter()
2975            .map(|id| snapshot.row(*id).expect("live").id)
2976            .collect();
2977        assert_eq!(order, [0, 1, 3, 4, 2, 5, 6, 7]);
2978
2979        let policy: &dyn SelectionPolicy<Node> = &FocusBranches;
2980        let line = |key: u32| {
2981            let id = snapshot.row_id(&key).expect("a row");
2982            SelectableLine::Row {
2983                row: &**snapshot.row(id).expect("live"),
2984                branch: projection.branch(id),
2985            }
2986        };
2987        let scope = |key: u32, snapshot: &StoreSnapshot<Node>| {
2988            let id = snapshot.row_id(&key).expect("a row");
2989            let order_ix = projection.order_ix(id).expect("in the order");
2990            let under = projection
2991                .branch(id)
2992                .map_or(0, |branch| branch.descendant_count());
2993            let context = LineScopeContext::new(
2994                line(key),
2995                order_ix + 1..order_ix + 1 + under,
2996                &projection,
2997                snapshot,
2998                SelectionMode::CellSet,
2999            );
3000            policy.line_scope(&context)
3001        };
3002        // A branch is not selectable, a leaf is: 2 too, though collapsed.
3003        for (key, selectable) in [(0, false), (1, false), (2, false), (3, true), (6, true)] {
3004            assert_eq!(policy.is_selectable(&line(key)), selectable, "{key}");
3005        }
3006        assert!(FocusCaptions.is_selectable(&line(0)), "a node is a row");
3007        // A command over a branch: the leaves of its subtree in the order of
3008        // `rows()`, the one under the collapsed branch 2 too, without the
3009        // branches themselves; every column, in the cell modes too.
3010        let all = scope(0, &snapshot).expect("a branch's scope");
3011        assert_eq!(all.keys(), [3, 4, 5, 6]);
3012        assert_eq!(all.columns(0), ColumnSet::first(2));
3013        assert_eq!(scope(1, &snapshot).expect("a branch").keys(), [3, 4]);
3014        assert_eq!(scope(2, &snapshot).expect("a branch").keys(), [5]);
3015        // Over a leaf, the scoped selection.
3016        assert!(scope(3, &snapshot).is_none());
3017        assert!(scope(7, &snapshot).is_none());
3018        // A row removed since the projection was built is left out.
3019        ingest.apply([Op::Remove(4)], Instant::now());
3020        let after = ingest.snapshot();
3021        assert_eq!(scope(1, &after).expect("a branch").keys(), [3]);
3022
3023        // Group captions as with `FocusCaptions`: focus, no selection, the
3024        // group's rows.
3025        let grouped = Rebuild::default().rebuild(
3026            &snapshot,
3027            &ViewSpec::new()
3028                .with_sort([(Col::Id, SortDirection::Ascending)])
3029                .with_group_by([GroupBy::column(Col::Kind)]),
3030        );
3031        let even = grouped.groups().iter().next().expect("the even group");
3032        let start = grouped.order_ix(even.rows()[0]).expect("in the order");
3033        let caption = SelectableLine::Caption { group: even };
3034        assert!(!policy.is_selectable(&caption));
3035        let context = LineScopeContext::new(
3036            caption,
3037            start..start + even.rows().len(),
3038            &grouped,
3039            &snapshot,
3040            SelectionMode::RowSet,
3041        );
3042        assert_eq!(
3043            policy
3044                .line_scope(&context)
3045                .expect("a caption's scope")
3046                .keys(),
3047            [0, 2, 4, 6]
3048        );
3049        assert_eq!(context.lines().count(), 4);
3050    }
3051}