1use std::{fmt, hash::Hash, ops::RangeInclusive, sync::Arc};
15
16use gpui_kit::base::AutoScroll;
17use gpui_kit::base::actions::{
18 Cancel, Confirm, SelectDown, SelectFirst, SelectLast, SelectNextColumn, SelectPageDown,
19 SelectPageUp, SelectPrevColumn, SelectUp,
20};
21use gpui_kit::{
22 Context, InteractiveElement, Modifiers, MouseButton, MouseDownEvent, Pixels, Point, px,
23};
24use rustc_hash::FxHashMap;
25
26use super::{
27 ColumnOf, KeyOf, LiveGridDelegate, LiveGridEvent, LiveGridState, SelectionOrigin, ViewColumnIx,
28 a11y::SelectionUnit,
29 columns::{ColumnLayout, column_of},
30 scroll::page_size,
31};
32use crate::{
33 actions::{
34 ExtendSelectionDown, ExtendSelectionNextColumn, ExtendSelectionPageDown,
35 ExtendSelectionPageUp, ExtendSelectionPrevColumn, ExtendSelectionToFirst,
36 ExtendSelectionToFirstCell, ExtendSelectionToFirstRow, ExtendSelectionToLast,
37 ExtendSelectionToLastCell, ExtendSelectionToLastRow, ExtendSelectionUp, SelectAll,
38 SelectFirstCell, SelectFirstRow, SelectLastCell, SelectLastRow, ToggleSelection,
39 },
40 engine::{DisplayRow, GroupInfo, GroupPath, Projection},
41 model::{ColumnIx, ColumnSet, GridColumns, GridRow},
42 policy::{
43 ContextMenuGesture, ContextMenuGestureContext, ExpandArea, FocusCaptions, GestureInput,
44 GridArea, LineScopeContext, SelectableLine, SelectionEdit, SelectionGesture,
45 SelectionGestureContext, SelectionPolicy, SelectionScope, SelectionScopeContext,
46 },
47 store::{PinnedEdge, RowId, StoreSnapshot},
48};
49
50const DRAG_THRESHOLD: Pixels = px(2.);
53
54pub(super) fn is_past_drag_threshold(origin: Point<Pixels>, position: Point<Pixels>) -> bool {
57 (position.x - origin.x).abs() > DRAG_THRESHOLD || (position.y - origin.y).abs() > DRAG_THRESHOLD
58}
59
60#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
62pub enum SelectionMode {
63 #[default]
65 RowSingle,
66 RowSet,
68 CellSingle,
70 CellSet,
72}
73
74impl SelectionMode {
75 fn selects_cells(self) -> bool {
76 matches!(self, Self::CellSingle | Self::CellSet)
77 }
78
79 pub(super) fn is_single(self) -> bool {
82 matches!(self, Self::RowSingle | Self::CellSingle)
83 }
84
85 pub(super) fn selection_unit(self) -> SelectionUnit {
88 if self.selects_cells() {
89 SelectionUnit::Cell
90 } else {
91 SelectionUnit::Row
92 }
93 }
94}
95
96#[derive(Clone)]
99pub struct GridSelection<K> {
100 rows: Arc<FxHashMap<K, ColumnSet>>,
101}
102
103impl<K> Default for GridSelection<K> {
104 fn default() -> Self {
105 Self {
106 rows: Arc::default(),
107 }
108 }
109}
110
111impl<K: fmt::Debug> fmt::Debug for GridSelection<K> {
112 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113 let mut debug = f.debug_struct("GridSelection");
115 debug.field("len", &self.rows.len());
116 if self.rows.len() <= 8 {
117 debug.field("rows", &*self.rows);
118 }
119 debug.finish()
120 }
121}
122
123impl<K: Eq + Hash> GridSelection<K> {
124 fn from_map(rows: FxHashMap<K, ColumnSet>) -> Self {
125 Self {
126 rows: Arc::new(rows),
127 }
128 }
129
130 pub(crate) fn from_rows(rows: impl IntoIterator<Item = (K, ColumnSet)>) -> Self {
133 Self::from_map(
134 rows.into_iter()
135 .filter(|(_, columns)| !columns.is_empty())
136 .collect(),
137 )
138 }
139
140 pub fn len(&self) -> usize {
142 self.rows.len()
143 }
144
145 pub fn is_empty(&self) -> bool {
147 self.rows.is_empty()
148 }
149
150 pub fn contains(&self, key: &K) -> bool {
152 self.rows.contains_key(key)
153 }
154
155 pub fn contains_cell(&self, key: &K, column: ColumnIx) -> bool {
157 self.columns(key).contains(column)
158 }
159
160 pub fn columns(&self, key: &K) -> ColumnSet {
163 self.rows.get(key).copied().unwrap_or(ColumnSet::EMPTY)
164 }
165
166 pub fn iter(&self) -> impl Iterator<Item = &K> + '_ {
168 self.rows.keys()
169 }
170
171 fn same_as(&self, other: &Self) -> bool {
173 Arc::ptr_eq(&self.rows, &other.rows)
174 || (self.rows.len() == other.rows.len()
175 && self
176 .rows
177 .iter()
178 .all(|(key, columns)| other.rows.get(key) == Some(columns)))
179 }
180}
181
182impl<K: Clone + Eq + Hash> GridSelection<K> {
183 fn rows_mut(&mut self) -> &mut FxHashMap<K, ColumnSet> {
185 Arc::make_mut(&mut self.rows)
186 }
187
188 fn union_with(&mut self, other: &Self) -> bool {
190 let new = other.rows.iter().any(|(key, columns)| {
191 let mut union = self.columns(key);
192 union.union_with(*columns);
193 union != self.columns(key)
194 });
195 if new {
196 let rows = self.rows_mut();
197 for (key, columns) in other.rows.iter() {
198 rows.entry(key.clone()).or_default().union_with(*columns);
199 }
200 }
201 new
202 }
203
204 fn retain(&mut self, missing: impl Fn(&K) -> bool) -> bool {
206 let gone = self.rows.keys().any(&missing);
207 if gone {
208 self.rows_mut().retain(|key, _| !missing(key));
209 }
210 gone
211 }
212
213 fn flip(&mut self, key: &K, column: ColumnIx, item: ColumnSet) {
216 let selected = self.columns(key);
217 let rows = self.rows_mut();
218 if selected.contains(column) {
219 let rest = difference(selected, item);
220 if rest.is_empty() {
221 rows.remove(key);
222 } else {
223 rows.insert(key.clone(), rest);
224 }
225 } else {
226 let mut columns = selected;
227 columns.union_with(item);
228 rows.insert(key.clone(), columns);
229 }
230 }
231}
232
233#[derive(Clone, Debug, PartialEq, Eq)]
236pub struct FocusedCell<K, C> {
237 row: Option<K>,
238 group: Option<GroupPath>,
239 column: C,
240}
241
242impl<K, C: Copy> FocusedCell<K, C> {
243 pub(crate) fn new(row: K, column: C) -> Self {
244 Self {
245 row: Some(row),
246 group: None,
247 column,
248 }
249 }
250
251 pub(crate) fn caption(path: GroupPath, column: C) -> Self {
254 Self {
255 row: None,
256 group: Some(path),
257 column,
258 }
259 }
260
261 pub fn row(&self) -> Option<&K> {
263 self.row.as_ref()
264 }
265
266 pub fn group(&self) -> Option<&GroupPath> {
268 self.group.as_ref()
269 }
270
271 pub fn column(&self) -> C {
274 self.column
275 }
276}
277
278#[derive(Clone, Debug, PartialEq, Eq)]
281pub(crate) enum LineTarget<K> {
282 Row(K),
283 Group(GroupPath),
284}
285
286impl<K: Clone, C: Copy> FocusedCell<K, C> {
287 pub(crate) fn line(&self) -> Option<LineTarget<K>> {
289 match (&self.row, &self.group) {
290 (Some(key), _) => Some(LineTarget::Row(key.clone())),
291 (None, Some(path)) => Some(LineTarget::Group(path.clone())),
292 (None, None) => None,
293 }
294 }
295}
296
297#[derive(Clone, Debug)]
300pub struct ScopedSelection<K> {
301 keys: Arc<[K]>,
302 columns: Arc<[ColumnSet]>,
303}
304
305impl<K> Default for ScopedSelection<K> {
306 fn default() -> Self {
307 Self {
308 keys: Vec::new().into(),
309 columns: Vec::new().into(),
310 }
311 }
312}
313
314impl<K> FromIterator<(K, ColumnSet)> for ScopedSelection<K> {
315 fn from_iter<I: IntoIterator<Item = (K, ColumnSet)>>(rows: I) -> Self {
316 let (keys, columns): (Vec<K>, Vec<ColumnSet>) = rows.into_iter().unzip();
317 Self {
318 keys: keys.into(),
319 columns: columns.into(),
320 }
321 }
322}
323
324impl<K> ScopedSelection<K> {
325 pub fn keys(&self) -> &[K] {
327 &self.keys
328 }
329
330 pub fn columns(&self, ix: usize) -> ColumnSet {
333 self.columns.get(ix).copied().unwrap_or(ColumnSet::EMPTY)
334 }
335
336 pub fn len(&self) -> usize {
338 self.keys.len()
339 }
340
341 pub fn is_empty(&self) -> bool {
343 self.keys.is_empty()
344 }
345
346 pub(crate) fn shared_keys(&self) -> Arc<[K]> {
348 self.keys.clone()
349 }
350}
351
352#[derive(Clone, Debug)]
356pub(crate) struct PointerTarget<K> {
357 row: Option<K>,
360 group: Option<GroupPath>,
362 column: Option<ColumnIx>,
364 button: MouseButton,
365 position: Point<Pixels>,
366 pinned: Option<PinnedEdge>,
369}
370
371impl<K> PointerTarget<K> {
372 pub(crate) fn row(&self) -> Option<&K> {
373 self.row.as_ref()
374 }
375
376 pub(crate) fn group(&self) -> Option<&GroupPath> {
378 self.group.as_ref()
379 }
380
381 pub(crate) fn pinned(&self) -> Option<PinnedEdge> {
383 self.pinned
384 }
385
386 pub(crate) fn column(&self) -> Option<ColumnIx> {
387 self.column
388 }
389
390 #[expect(dead_code, reason = "no caller reads the pressed button yet")]
391 pub(crate) fn button(&self) -> MouseButton {
392 self.button
393 }
394
395 pub(crate) fn position(&self) -> Point<Pixels> {
396 self.position
397 }
398}
399
400pub(super) struct ShownRows<'a, R: GridRow> {
407 projection: &'a Projection,
408 snapshot: &'a StoreSnapshot<R>,
409 policy: &'a dyn SelectionPolicy<R>,
410}
411
412impl<R: GridRow> Clone for ShownRows<'_, R> {
413 fn clone(&self) -> Self {
414 *self
415 }
416}
417
418impl<R: GridRow> Copy for ShownRows<'_, R> {}
419
420impl<'a, R: GridRow> ShownRows<'a, R> {
421 pub(super) fn new(projection: &'a Projection, snapshot: &'a StoreSnapshot<R>) -> Self {
423 Self {
424 projection,
425 snapshot,
426 policy: &FocusCaptions,
427 }
428 }
429
430 pub(super) fn with_policy(mut self, policy: &'a dyn SelectionPolicy<R>) -> Self {
431 self.policy = policy;
432 self
433 }
434
435 fn len(&self) -> usize {
436 self.projection.len()
437 }
438
439 fn key_at(&self, display_ix: usize) -> Option<&'a R::Key> {
441 let id = self.projection.row(display_ix)?;
442 self.snapshot.row(id).map(|row| row.key())
443 }
444
445 fn group_at(&self, display_ix: usize) -> Option<GroupInfo<'a>> {
447 match self.projection.line(display_ix)? {
448 DisplayRow::GroupCaption { group, .. } => self.projection.groups().get(group),
449 _ => None,
450 }
451 }
452
453 fn display_ix(&self, key: &R::Key) -> Option<usize> {
455 self.snapshot
456 .row_id(key)
457 .and_then(|id| self.projection.display_ix(id))
458 }
459
460 pub(super) fn caption_ix(&self, path: &GroupPath) -> Option<usize> {
463 let group = self.projection.groups().find(path)?;
464 self.projection.group_line(group.id())
465 }
466
467 fn line_of<C: Copy>(&self, cell: &FocusedCell<R::Key, C>) -> Option<usize> {
469 match (cell.row(), cell.group()) {
470 (Some(key), _) => self.display_ix(key),
471 (None, Some(path)) => self.caption_ix(path),
472 (None, None) => None,
473 }
474 }
475
476 fn is_focusable(&self, display_ix: usize) -> bool {
479 self.key_at(display_ix).is_some() || self.group_at(display_ix).is_some()
480 }
481
482 fn takes_selection<C: Copy>(&self, cell: &FocusedCell<R::Key, C>) -> bool {
488 let Some(key) = cell.row() else {
489 return false;
490 };
491 let Some((id, row)) = self
492 .snapshot
493 .row_id(key)
494 .and_then(|id| Some((id, self.snapshot.row(id)?)))
495 else {
496 return true;
497 };
498 self.policy.is_selectable(&SelectableLine::Row {
499 row: &**row,
500 branch: self.projection.branch(id),
501 })
502 }
503
504 fn cell_at(
506 &self,
507 display_ix: usize,
508 column: R::Column,
509 ) -> Option<FocusedCell<R::Key, R::Column>> {
510 if let Some(key) = self.key_at(display_ix) {
511 return Some(FocusedCell::new(key.clone(), column));
512 }
513 let group = self.group_at(display_ix)?;
514 Some(FocusedCell::caption(group.path().clone(), column))
515 }
516
517 fn select_lines(
520 &self,
521 lines: impl Iterator<Item = usize>,
522 item: ColumnSet,
523 map: &mut FxHashMap<R::Key, ColumnSet>,
524 ) {
525 let (projection, snapshot, policy) = (self.projection, self.snapshot, self.policy);
526 let groups = projection.groups();
527 for display_ix in lines {
528 match projection.line(display_ix) {
529 Some(DisplayRow::Data { row: id, .. }) => {
530 if let Some(row) = snapshot.row(id)
531 && policy.is_selectable(&SelectableLine::Row {
532 row: &**row,
533 branch: projection.branch(id),
534 })
535 {
536 map.insert(row.key().clone(), item);
537 }
538 }
539 Some(DisplayRow::GroupCaption { group, .. }) => {
540 let Some(group) = groups.get(group) else {
541 continue;
542 };
543 if policy.is_selectable(&SelectableLine::Caption { group }) {
544 for row in group.rows().iter().filter_map(|id| snapshot.row(*id)) {
545 map.insert(row.key().clone(), item);
546 }
547 }
548 }
549 _ => {}
550 }
551 }
552 }
553
554 fn first_focusable(&self) -> Option<usize> {
556 (0..self.len()).find(|ix| self.is_focusable(*ix))
557 }
558
559 fn last_focusable(&self) -> Option<usize> {
560 (0..self.len()).rev().find(|ix| self.is_focusable(*ix))
561 }
562
563 fn nearest_live(&self, display_ix: usize) -> Option<usize> {
566 let display_ix = display_ix.min(self.len().checked_sub(1)?);
567 (display_ix..self.len())
568 .find(|ix| self.key_at(*ix).is_some())
569 .or_else(|| (0..display_ix).rev().find(|ix| self.key_at(*ix).is_some()))
570 }
571
572 fn focusable_toward(&self, origin: usize, target: usize) -> usize {
577 let focusable = |ix: &usize| self.is_focusable(*ix);
578 if target > origin {
579 (target..self.len())
580 .find(focusable)
581 .or_else(|| (origin + 1..target).rev().find(focusable))
582 .unwrap_or(origin)
583 } else if target < origin {
584 (0..=target)
585 .rev()
586 .find(focusable)
587 .or_else(|| (target + 1..origin).find(focusable))
588 .unwrap_or(origin)
589 } else {
590 origin
591 }
592 }
593
594 fn scope_line(
598 &self,
599 target: &LineTarget<R::Key>,
600 ) -> Option<(SelectableLine<'a, R>, std::ops::Range<usize>)> {
601 let (projection, snapshot) = (self.projection, self.snapshot);
602 match target {
603 LineTarget::Row(key) => {
604 let id = snapshot.row_id(key)?;
605 let row = snapshot.row(id)?;
606 let branch = projection.branch(id);
607 let under = match (branch, projection.order_ix(id)) {
608 (Some(branch), Some(ix)) => ix + 1..ix + 1 + branch.descendant_count(),
609 _ => 0..0,
610 };
611 Some((
612 SelectableLine::Row {
613 row: &**row,
614 branch,
615 },
616 under,
617 ))
618 }
619 LineTarget::Group(path) => {
620 let group = projection.groups().find(path)?;
621 let start = group
622 .rows()
623 .first()
624 .and_then(|id| projection.order_ix(*id))
625 .unwrap_or(0);
626 Some((
627 SelectableLine::Caption { group },
628 start..start + group.rows().len(),
629 ))
630 }
631 }
632 }
633}
634
635pub(super) trait ColumnView {
639 fn view_column_ix(&self, column: ColumnIx) -> Option<ViewColumnIx>;
640 fn column_at(&self, view: ViewColumnIx) -> Option<ColumnIx>;
641 fn visible_count(&self) -> usize;
642 fn visible_set(&self) -> ColumnSet;
643 fn visible_neighbour(&self, column: ColumnIx) -> Option<ColumnIx>;
646}
647
648impl<C: GridColumns> ColumnView for ColumnLayout<C> {
649 fn view_column_ix(&self, column: ColumnIx) -> Option<ViewColumnIx> {
650 ColumnLayout::view_column_ix(self, column)
651 }
652
653 fn column_at(&self, view: ViewColumnIx) -> Option<ColumnIx> {
654 ColumnLayout::column_at(self, view)
655 }
656
657 fn visible_count(&self) -> usize {
658 ColumnLayout::visible_set(self).len()
659 }
660
661 fn visible_set(&self) -> ColumnSet {
662 ColumnLayout::visible_set(self)
663 }
664
665 fn visible_neighbour(&self, column: ColumnIx) -> Option<ColumnIx> {
666 let order = self.order();
667 let position = order.iter().position(|ix| *ix == column)?;
668 order[position + 1..]
669 .iter()
670 .chain(order[..position].iter().rev())
671 .copied()
672 .find(|ix| self.is_visible(*ix))
673 }
674}
675
676fn first_column(columns: &impl ColumnView) -> Option<ColumnIx> {
677 columns.column_at(ViewColumnIx::new(0))
678}
679
680fn last_column(columns: &impl ColumnView) -> Option<ColumnIx> {
681 let last = columns.visible_count().checked_sub(1)?;
682 columns.column_at(ViewColumnIx::new(last as u16))
683}
684
685fn step_column(column: ColumnIx, step: isize, columns: &impl ColumnView) -> ColumnIx {
687 let Some(view) = columns.view_column_ix(column) else {
688 return column;
689 };
690 let last = columns.visible_count().saturating_sub(1);
691 let target = view.get().saturating_add_signed(step).min(last);
692 columns
693 .column_at(ViewColumnIx::new(target as u16))
694 .unwrap_or(column)
695}
696
697fn difference(columns: ColumnSet, drop: ColumnSet) -> ColumnSet {
699 (0..128u16)
700 .map(ColumnIx::new)
701 .filter(|ix| columns.contains(*ix) && !drop.contains(*ix))
702 .fold(ColumnSet::EMPTY, |mut set, ix| {
703 set.insert(ix);
704 set
705 })
706}
707
708pub(super) fn successor<T>(
713 previous: &Projection,
714 id: Option<RowId>,
715 accept: impl Fn(RowId) -> Option<T>,
716) -> Option<T> {
717 let accept_at = |display_ix: usize| previous.row(display_ix).and_then(&accept);
718 match id.and_then(|id| previous.display_ix(id)) {
719 Some(ix) => (ix + 1..previous.len())
720 .find_map(accept_at)
721 .or_else(|| (0..ix).rev().find_map(accept_at)),
722 None => (0..previous.len()).find_map(accept_at),
723 }
724}
725
726#[derive(Clone, Copy, Debug, PartialEq, Eq)]
728pub(super) enum Navigation {
729 Up,
730 Down,
731 PrevColumn,
732 NextColumn,
733 PageUp,
734 PageDown,
735 First,
737 Last,
739 FirstRow,
740 LastRow,
741 FirstCell,
742 LastCell,
743}
744
745pub(super) struct ChangeMark<K, C> {
749 revision: u64,
750 focus: Option<FocusedCell<K, C>>,
751}
752
753struct Drag<K, C> {
756 target: FocusedCell<K, C>,
757 base: Option<GridSelection<K>>,
760}
761
762pub(super) struct SelectionPainter<'a, K> {
766 selection: Option<&'a GridSelection<K>>,
767 range: Option<(RangeInclusive<usize>, ColumnSet)>,
768}
769
770impl<K: Eq + Hash> SelectionPainter<'_, K> {
771 pub(super) fn columns(&self, key: &K, display_ix: usize) -> ColumnSet {
773 let mut columns = self
774 .selection
775 .map_or(ColumnSet::EMPTY, |selection| selection.columns(key));
776 if let Some((rows, range)) = &self.range
777 && rows.contains(&display_ix)
778 {
779 columns.union_with(*range);
780 }
781 columns
782 }
783}
784
785pub(super) struct SelectionModel<K, C> {
787 mode: SelectionMode,
788 all: ColumnSet,
790 selection: GridSelection<K>,
791 revision: u64,
794 focus: Option<FocusedCell<K, C>>,
795 anchor: Option<FocusedCell<K, C>>,
797 drag: Option<Drag<K, C>>,
798}
799
800impl<K: Clone + Eq + Hash, C: GridColumns> SelectionModel<K, C> {
801 pub(super) fn new(mode: SelectionMode) -> Self {
802 Self {
803 mode,
804 all: ColumnSet::first(C::all().len()),
805 selection: GridSelection::default(),
806 revision: 0,
807 focus: None,
808 anchor: None,
809 drag: None,
810 }
811 }
812
813 fn set_selection(&mut self, selection: GridSelection<K>) {
815 if !self.selection.same_as(&selection) {
816 self.selection = selection;
817 self.revision += 1;
818 }
819 }
820
821 pub(super) fn mode(&self) -> SelectionMode {
822 self.mode
823 }
824
825 pub(super) fn selection(&self) -> &GridSelection<K> {
826 &self.selection
827 }
828
829 pub(super) fn focus(&self) -> Option<&FocusedCell<K, C>> {
830 self.focus.as_ref()
831 }
832
833 pub(super) fn is_dragging(&self) -> bool {
834 self.drag.is_some()
835 }
836
837 pub(super) fn mark(&self) -> ChangeMark<K, C> {
838 ChangeMark {
839 revision: self.revision,
840 focus: self.focus.clone(),
841 }
842 }
843
844 pub(super) fn changes_since(&self, mark: &ChangeMark<K, C>) -> (bool, bool) {
846 (self.revision != mark.revision, self.focus != mark.focus)
847 }
848
849 fn item(&self, column: ColumnIx) -> ColumnSet {
852 if self.mode.selects_cells() {
853 let mut cell = ColumnSet::EMPTY;
854 cell.insert(column);
855 cell
856 } else {
857 self.all
858 }
859 }
860
861 fn row_item(&self, columns: &impl ColumnView) -> ColumnSet {
864 match self.mode {
865 SelectionMode::RowSingle | SelectionMode::RowSet => self.all,
866 SelectionMode::CellSet => columns.visible_set(),
867 SelectionMode::CellSingle => self
868 .focus_column(columns)
869 .map_or(ColumnSet::EMPTY, |column| self.item(column)),
870 }
871 }
872
873 fn focus_column(&self, columns: &impl ColumnView) -> Option<ColumnIx> {
875 self.focus
876 .as_ref()
877 .map(|focus| focus.column().ix())
878 .filter(|column| columns.view_column_ix(*column).is_some())
879 .or_else(|| first_column(columns))
880 }
881
882 fn only(&self, target: &FocusedCell<K, C>) -> GridSelection<K> {
883 target.row().map_or_else(GridSelection::default, |key| {
884 GridSelection::from_rows([(key.clone(), self.item(target.column().ix()))])
885 })
886 }
887
888 pub(super) fn is_selected(&self, target: &FocusedCell<K, C>) -> bool {
890 target
891 .row()
892 .is_some_and(|key| self.selection.contains_cell(key, target.column().ix()))
893 }
894
895 pub(super) fn holds_more_than(&self, target: &FocusedCell<K, C>) -> bool {
898 target.row().is_some_and(|key| {
899 self.selection.len() > 1
900 || self.selection.columns(key) != self.item(target.column().ix())
901 })
902 }
903
904 pub(super) fn apply<R>(
911 &mut self,
912 edit: SelectionEdit,
913 target: FocusedCell<K, C>,
914 rows: ShownRows<'_, R>,
915 columns: &impl ColumnView,
916 ) where
917 R: GridRow<Key = K, Column = C>,
918 {
919 let selectable = rows.takes_selection(&target);
920 let edit = match edit {
921 SelectionEdit::Extend | SelectionEdit::AddRange if self.mode.is_single() => {
922 SelectionEdit::Replace
923 }
924 edit => edit,
925 };
926 let edit = match edit {
927 SelectionEdit::Replace | SelectionEdit::Toggle if !selectable => SelectionEdit::Keep,
928 edit => edit,
929 };
930 match edit {
931 SelectionEdit::Replace => self.replace(&target),
932 SelectionEdit::Extend | SelectionEdit::AddRange => {
933 let range = self
934 .anchor
935 .as_ref()
936 .and_then(|anchor| self.range(anchor, &target, rows, columns));
937 match range {
938 Some(range) if edit == SelectionEdit::AddRange => {
939 if self.selection.union_with(&range) {
940 self.revision += 1;
941 }
942 }
943 Some(range) => self.set_selection(range),
944 None if !selectable => {}
948 None => self.replace(&target),
949 }
950 }
951 SelectionEdit::Toggle => {
952 self.toggle(&target);
953 self.anchor = Some(target.clone());
954 }
955 SelectionEdit::Keep => {}
956 }
957 self.focus = Some(target);
958 }
959
960 fn replace(&mut self, target: &FocusedCell<K, C>) {
961 self.set_selection(self.only(target));
962 self.anchor = Some(target.clone());
963 }
964
965 fn toggle(&mut self, target: &FocusedCell<K, C>) {
966 let Some(key) = target.row() else {
967 return;
968 };
969 let column = target.column().ix();
970 if self.mode.is_single() {
971 let toggled = if self.selection.contains_cell(key, column) {
973 GridSelection::default()
974 } else {
975 self.only(target)
976 };
977 self.set_selection(toggled);
978 return;
979 }
980 let item = self.item(column);
981 self.selection.flip(key, column, item);
982 self.revision += 1;
983 }
984
985 fn before_toggle(&self, target: &FocusedCell<K, C>) -> GridSelection<K> {
988 let mut selection = self.selection.clone();
989 if let Some(key) = target.row() {
990 let column = target.column().ix();
991 selection.flip(key, column, self.item(column));
992 }
993 selection
994 }
995
996 fn range<R>(
1001 &self,
1002 anchor: &FocusedCell<K, C>,
1003 target: &FocusedCell<K, C>,
1004 rows: ShownRows<'_, R>,
1005 columns: &impl ColumnView,
1006 ) -> Option<GridSelection<K>>
1007 where
1008 R: GridRow<Key = K, Column = C>,
1009 {
1010 let from = rows.line_of(anchor)?;
1011 let to = rows.line_of(target)?;
1012 let item = self.range_columns(anchor.column().ix(), target.column().ix(), columns);
1013 let (start, end) = (from.min(to), from.max(to));
1014 let mut map = FxHashMap::with_capacity_and_hasher(end - start + 1, Default::default());
1015 rows.select_lines(start..=end, item, &mut map);
1016 Some(GridSelection::from_map(map))
1017 }
1018
1019 fn range_columns(&self, from: ColumnIx, to: ColumnIx, columns: &impl ColumnView) -> ColumnSet {
1022 if !self.mode.selects_cells() {
1023 return self.all;
1024 }
1025 let (Some(from), Some(to)) = (columns.view_column_ix(from), columns.view_column_ix(to))
1026 else {
1027 return self.item(to);
1029 };
1030 let (start, end) = (from.get().min(to.get()), from.get().max(to.get()));
1031 (start..=end)
1032 .filter_map(|view| columns.column_at(ViewColumnIx::new(view as u16)))
1033 .fold(ColumnSet::EMPTY, |mut set, column| {
1034 set.insert(column);
1035 set
1036 })
1037 }
1038
1039 pub(super) fn navigation_target<R>(
1044 &self,
1045 navigation: Navigation,
1046 page: usize,
1047 rows: ShownRows<'_, R>,
1048 columns: &impl ColumnView,
1049 ) -> Option<FocusedCell<K, C>>
1050 where
1051 R: GridRow<Key = K, Column = C>,
1052 {
1053 let first = first_column(columns)?;
1054 let last = last_column(columns)?;
1055 let focus = self.focus.as_ref().and_then(|focus| {
1056 let display_ix = rows.line_of(focus)?;
1057 let column = Some(focus.column().ix())
1058 .filter(|column| columns.view_column_ix(*column).is_some())
1059 .unwrap_or(first);
1060 Some((display_ix, column))
1061 });
1062 let (display_ix, column) = match focus {
1063 None => {
1064 let top = rows.first_focusable()?;
1065 let bottom = rows.last_focusable().unwrap_or(top);
1066 match navigation {
1067 Navigation::Last => (top, last),
1068 Navigation::LastRow => (bottom, first),
1069 Navigation::LastCell => (bottom, last),
1070 _ => (top, first),
1071 }
1072 }
1073 Some((origin, column)) => {
1074 let end = rows.len().saturating_sub(1);
1075 let page = page.max(1);
1076 let (target, column) = match navigation {
1077 Navigation::Up => (origin.saturating_sub(1), column),
1078 Navigation::Down => ((origin + 1).min(end), column),
1079 Navigation::PageUp => (origin.saturating_sub(page), column),
1080 Navigation::PageDown => ((origin + page).min(end), column),
1081 Navigation::PrevColumn => (origin, step_column(column, -1, columns)),
1082 Navigation::NextColumn => (origin, step_column(column, 1, columns)),
1083 Navigation::First => (origin, first),
1084 Navigation::Last => (origin, last),
1085 Navigation::FirstRow => (0, column),
1086 Navigation::LastRow => (end, column),
1087 Navigation::FirstCell => (0, first),
1088 Navigation::LastCell => (end, last),
1089 };
1090 (rows.focusable_toward(origin, target), column)
1091 }
1092 };
1093 rows.cell_at(display_ix, column_of(column))
1094 }
1095
1096 pub(super) fn focus_on(&mut self, target: FocusedCell<K, C>) {
1098 self.focus = Some(target);
1099 }
1100
1101 pub(super) fn focus_caption<R>(
1106 &mut self,
1107 path: &GroupPath,
1108 rows: ShownRows<'_, R>,
1109 columns: &impl ColumnView,
1110 ) -> bool
1111 where
1112 R: GridRow<Key = K, Column = C>,
1113 {
1114 let Some(column) = self.focus_column(columns) else {
1115 return false;
1116 };
1117 if rows.caption_ix(path).is_none() {
1118 return false;
1119 }
1120 self.focus = Some(FocusedCell::caption(path.clone(), column_of(column)));
1121 true
1122 }
1123
1124 pub(super) fn toggle_focused<R>(
1127 &mut self,
1128 rows: ShownRows<'_, R>,
1129 columns: &impl ColumnView,
1130 ) -> bool
1131 where
1132 R: GridRow<Key = K, Column = C>,
1133 {
1134 let Some(focus) = self.focus.clone() else {
1135 return false;
1136 };
1137 if focus.row().and_then(|key| rows.display_ix(key)).is_none()
1140 || !rows.takes_selection(&focus)
1141 {
1142 return false;
1143 }
1144 let edit = if self.mode.is_single() {
1145 SelectionEdit::Replace
1146 } else {
1147 SelectionEdit::Toggle
1148 };
1149 self.apply(edit, focus, rows, columns);
1150 true
1151 }
1152
1153 pub(super) fn select_all<R>(
1160 &mut self,
1161 rows: ShownRows<'_, R>,
1162 columns: &impl ColumnView,
1163 ) -> bool
1164 where
1165 R: GridRow<Key = K, Column = C>,
1166 {
1167 if self.mode.is_single() {
1168 return false;
1169 }
1170 let item = if self.mode.selects_cells() {
1171 columns.visible_set()
1172 } else {
1173 self.all
1174 };
1175 let mut map = FxHashMap::with_capacity_and_hasher(rows.len(), Default::default());
1176 rows.select_lines(0..rows.len(), item, &mut map);
1177 self.set_selection(GridSelection::from_map(map));
1178 true
1179 }
1180
1181 pub(super) fn clear(&mut self) {
1182 if !self.selection.is_empty() {
1183 self.set_selection(GridSelection::default());
1184 }
1185 }
1186
1187 pub(super) fn set_mode(&mut self, mode: SelectionMode) {
1190 if mode == self.mode {
1191 return;
1192 }
1193 let unit_changed = mode.selects_cells() != self.mode.selects_cells();
1194 self.mode = mode;
1195 self.drag = None;
1196 if unit_changed {
1197 self.clear();
1198 } else if mode.is_single() {
1199 let kept = self
1200 .focus
1201 .as_ref()
1202 .filter(|focus| self.is_selected(focus))
1203 .map(|focus| self.only(focus));
1204 self.set_selection(kept.unwrap_or_default());
1205 }
1206 }
1207
1208 pub(super) fn set_rows<R>(
1211 &mut self,
1212 keys: impl IntoIterator<Item = K>,
1213 snapshot: &StoreSnapshot<R>,
1214 columns: &impl ColumnView,
1215 ) where
1216 R: GridRow<Key = K, Column = C>,
1217 {
1218 let item = self.row_item(columns);
1219 let limit = if self.mode.is_single() { 1 } else { usize::MAX };
1220 self.set_selection(GridSelection::from_rows(
1221 keys.into_iter()
1222 .filter(|key| snapshot.row_id(key).is_some())
1223 .take(limit)
1224 .map(|key| (key, item)),
1225 ));
1226 }
1227
1228 pub(super) fn set_cells<R>(
1231 &mut self,
1232 cells: impl IntoIterator<Item = (K, C)>,
1233 snapshot: &StoreSnapshot<R>,
1234 ) where
1235 R: GridRow<Key = K, Column = C>,
1236 {
1237 let mut map: FxHashMap<K, ColumnSet> = FxHashMap::default();
1238 for (key, column) in cells {
1239 if snapshot.row_id(&key).is_none() {
1240 continue;
1241 }
1242 if self.mode.is_single() && !map.is_empty() {
1243 break;
1244 }
1245 map.entry(key)
1246 .or_default()
1247 .union_with(self.item(column.ix()));
1248 }
1249 self.set_selection(GridSelection::from_map(map));
1250 }
1251
1252 pub(super) fn select_row<R>(
1256 &mut self,
1257 key: Option<K>,
1258 rows: ShownRows<'_, R>,
1259 columns: &impl ColumnView,
1260 ) where
1261 R: GridRow<Key = K, Column = C>,
1262 {
1263 let key = key.filter(|key| rows.snapshot.row_id(key).is_some());
1264 let (Some(key), Some(column)) = (key, self.focus_column(columns)) else {
1265 self.clear();
1266 return;
1267 };
1268 let target = FocusedCell::new(key, column_of(column));
1269 self.set_selection(self.only(&target));
1270 if target.row().and_then(|key| rows.display_ix(key)).is_some() {
1271 self.focus = Some(target.clone());
1272 self.anchor = Some(target);
1273 }
1274 }
1275
1276 pub(super) fn set_focus<R>(
1280 &mut self,
1281 key: &K,
1282 column: Option<C>,
1283 rows: ShownRows<'_, R>,
1284 columns: &impl ColumnView,
1285 ) -> bool
1286 where
1287 R: GridRow<Key = K, Column = C>,
1288 {
1289 if rows.display_ix(key).is_none() {
1290 return false;
1291 }
1292 let column = column
1293 .map(|column| column.ix())
1294 .filter(|column| columns.view_column_ix(*column).is_some())
1295 .or_else(|| self.focus_column(columns));
1296 let Some(column) = column else {
1297 return false;
1298 };
1299 let target = FocusedCell::new(key.clone(), column_of(column));
1300 self.focus = Some(target.clone());
1301 self.anchor = Some(target);
1302 true
1303 }
1304
1305 pub(super) fn remove_rows<R>(&mut self, removed: &[RowId], previous: &StoreSnapshot<R>)
1309 where
1310 R: GridRow<Key = K>,
1311 {
1312 let remove = |selection: &mut GridSelection<K>| {
1313 let mut changed = false;
1314 for id in removed {
1315 if let Some(row) = previous.row(*id)
1316 && selection.contains(row.key())
1317 {
1318 selection.rows_mut().remove(row.key());
1319 changed = true;
1320 }
1321 }
1322 changed
1323 };
1324 if !self.selection.is_empty() && remove(&mut self.selection) {
1325 self.revision += 1;
1326 }
1327 if let Some(base) = self.drag.as_mut().and_then(|drag| drag.base.as_mut()) {
1328 remove(base);
1329 }
1330 }
1331
1332 pub(super) fn retain_present<R>(&mut self, snapshot: &StoreSnapshot<R>)
1335 where
1336 R: GridRow<Key = K>,
1337 {
1338 let missing = |key: &K| snapshot.row_id(key).is_none();
1339 if self.selection.retain(missing) {
1340 self.revision += 1;
1341 }
1342 if let Some(base) = self.drag.as_mut().and_then(|drag| drag.base.as_mut()) {
1343 base.retain(missing);
1344 }
1345 for cell in [&mut self.focus, &mut self.anchor] {
1346 if cell
1347 .as_ref()
1348 .and_then(|cell| cell.row())
1349 .is_some_and(missing)
1350 {
1351 *cell = None;
1352 }
1353 }
1354 }
1355
1356 pub(super) fn follow_removed<R>(
1360 &mut self,
1361 projection: &Projection,
1362 previous: &StoreSnapshot<R>,
1363 current: &StoreSnapshot<R>,
1364 ) where
1365 R: GridRow<Key = K>,
1366 {
1367 for cell in [&mut self.focus, &mut self.anchor] {
1368 let Some(focused) = cell.as_ref() else {
1369 continue;
1370 };
1371 let Some(id) = focused.row().and_then(|key| previous.row_id(key)) else {
1372 continue;
1373 };
1374 if current.row(id).is_some() {
1375 continue;
1376 }
1377 let column = focused.column();
1378 *cell = successor(projection, Some(id), |id| {
1379 current.row(id).map(|row| row.key().clone())
1380 })
1381 .map(|key| FocusedCell::new(key, column));
1382 }
1383 }
1384
1385 pub(super) fn follow_filtered<R>(
1389 &mut self,
1390 previous: &Projection,
1391 shown: &Projection,
1392 snapshot: &StoreSnapshot<R>,
1393 ) where
1394 R: GridRow<Key = K>,
1395 {
1396 for cell in [&mut self.focus, &mut self.anchor] {
1397 let Some(focused) = cell.as_ref().filter(|cell| cell.group().is_none()) else {
1399 continue;
1400 };
1401 let id = focused.row().and_then(|key| snapshot.row_id(key));
1402 if id.is_some_and(|id| shown.contains(id)) {
1403 continue;
1404 }
1405 let column = focused.column();
1406 *cell = successor(previous, id, |id| {
1407 shown
1408 .contains(id)
1409 .then(|| snapshot.row(id))
1410 .flatten()
1411 .map(|row| row.key().clone())
1412 })
1413 .map(|key| FocusedCell::new(key, column));
1414 }
1415 }
1416
1417 pub(super) fn move_off_hidden(&mut self, columns: &impl ColumnView) {
1420 for cell in [&mut self.focus, &mut self.anchor].into_iter().flatten() {
1421 let column = cell.column().ix();
1422 if columns.view_column_ix(column).is_none()
1423 && let Some(neighbour) = columns.visible_neighbour(column)
1424 {
1425 cell.column = column_of(neighbour);
1426 }
1427 }
1428 }
1429
1430 pub(super) fn begin_drag(
1434 &mut self,
1435 adds: bool,
1436 base: GridSelection<K>,
1437 target: FocusedCell<K, C>,
1438 ) {
1439 self.drag = Some(Drag {
1440 target,
1441 base: adds.then_some(base),
1442 });
1443 }
1444
1445 pub(super) fn drag_to(&mut self, target: FocusedCell<K, C>) -> bool {
1447 match &mut self.drag {
1448 Some(drag) if drag.target != target => {
1449 drag.target = target;
1450 true
1451 }
1452 _ => false,
1453 }
1454 }
1455
1456 pub(super) fn drag_target(&self) -> Option<&FocusedCell<K, C>> {
1457 self.drag.as_ref().map(|drag| &drag.target)
1458 }
1459
1460 pub(super) fn finish_drag<R>(&mut self, rows: ShownRows<'_, R>, columns: &impl ColumnView)
1463 where
1464 R: GridRow<Key = K, Column = C>,
1465 {
1466 let Some(drag) = self.drag.take() else {
1467 return;
1468 };
1469 if drag
1470 .target
1471 .row()
1472 .and_then(|key| rows.display_ix(key))
1473 .is_none()
1474 {
1475 return;
1477 }
1478 let edit = match drag.base {
1479 Some(base) => {
1480 self.set_selection(base);
1481 SelectionEdit::AddRange
1482 }
1483 None => SelectionEdit::Extend,
1484 };
1485 self.apply(edit, drag.target, rows, columns);
1486 }
1487
1488 pub(super) fn painter<'a, R>(
1490 &'a self,
1491 rows: ShownRows<'_, R>,
1492 columns: &impl ColumnView,
1493 ) -> SelectionPainter<'a, K>
1494 where
1495 R: GridRow<Key = K, Column = C>,
1496 {
1497 let Some(drag) = &self.drag else {
1498 return SelectionPainter {
1499 selection: Some(&self.selection),
1500 range: None,
1501 };
1502 };
1503 let target = drag.target.row().and_then(|key| rows.display_ix(key));
1504 let anchor = self
1505 .anchor
1506 .as_ref()
1507 .filter(|_| !self.mode.is_single())
1508 .and_then(|anchor| Some((rows.display_ix(anchor.row()?)?, anchor.column().ix())));
1509 let range = target.map(|to| {
1510 let to_column = drag.target.column().ix();
1511 let (from, from_column) = anchor.unwrap_or((to, to_column));
1512 (
1513 from.min(to)..=from.max(to),
1514 self.range_columns(from_column, to_column, columns),
1515 )
1516 });
1517 SelectionPainter {
1518 selection: drag.base.as_ref().filter(|_| !self.mode.is_single()),
1519 range,
1520 }
1521 }
1522}
1523
1524pub(super) struct Press<K, C> {
1526 mark: ChangeMark<K, C>,
1529 base: Option<GridSelection<K>>,
1533 target: FocusedCell<K, C>,
1534 origin: Point<Pixels>,
1535 deferred: bool,
1538 adds: bool,
1540 moved: bool,
1542 focus_only: bool,
1544 drag_candidate: Option<Modifiers>,
1547 drag_tried: bool,
1550}
1551
1552impl<D: LiveGridDelegate> LiveGridState<D> {
1553 pub fn with_selection_mode(mut self, mode: SelectionMode) -> Self {
1556 self.selection.set_mode(mode);
1557 self
1558 }
1559
1560 pub fn with_selection_scope(mut self, scope: impl SelectionScope<D::Row>) -> Self {
1564 self.selection_scope = Box::new(scope);
1565 self
1566 }
1567
1568 pub fn with_selection_gesture(mut self, gesture: impl SelectionGesture) -> Self {
1571 self.selection_gesture = Box::new(gesture);
1572 self
1573 }
1574
1575 pub fn with_context_menu_gesture(mut self, gesture: impl ContextMenuGesture) -> Self {
1580 self.context_menu_gesture = Box::new(gesture);
1581 self
1582 }
1583
1584 pub fn with_selection_policy(mut self, policy: impl SelectionPolicy<D::Row>) -> Self {
1589 self.selection_policy = Box::new(policy);
1590 self
1591 }
1592
1593 fn shown_rows<'a>(
1595 projection: &'a Projection,
1596 snapshot: &'a StoreSnapshot<D::Row>,
1597 policy: &'a dyn SelectionPolicy<D::Row>,
1598 ) -> ShownRows<'a, D::Row> {
1599 ShownRows::new(projection, snapshot).with_policy(policy)
1600 }
1601
1602 pub(super) fn is_context_press(
1605 &self,
1606 button: MouseButton,
1607 modifiers: Modifiers,
1608 click_count: usize,
1609 area: GridArea,
1610 ) -> bool {
1611 self.context_menu_gesture
1612 .opens_menu(&ContextMenuGestureContext::new(
1613 button,
1614 modifiers,
1615 self.platform,
1616 click_count,
1617 area,
1618 ))
1619 }
1620
1621 pub fn selection_mode(&self) -> SelectionMode {
1623 self.selection.mode()
1624 }
1625
1626 pub fn selection(&self) -> &GridSelection<KeyOf<D>> {
1629 self.selection.selection()
1630 }
1631
1632 pub fn scoped_selection(&self) -> ScopedSelection<KeyOf<D>> {
1635 self.selection_scope.resolve(&SelectionScopeContext::new(
1636 self.selection.selection(),
1637 &self.projection,
1638 &self.snapshot,
1639 self.selection.mode(),
1640 ))
1641 }
1642
1643 pub fn focused_cell(&self) -> Option<&FocusedCell<KeyOf<D>, ColumnOf<D>>> {
1645 self.selection.focus()
1646 }
1647
1648 pub fn is_cell_selected(&self, key: &KeyOf<D>, column: ColumnOf<D>) -> bool {
1651 self.selection.selection().contains_cell(key, column.ix())
1652 }
1653
1654 #[cfg(any(test, feature = "test-support"))]
1657 pub fn is_focus_visible(&self) -> bool {
1658 self.focus_visible
1659 }
1660
1661 pub fn visible_keys(&self) -> Vec<KeyOf<D>> {
1664 self.painted
1665 .iter()
1666 .filter_map(|line| self.snapshot.row(line.row()?))
1667 .map(|row| row.key().clone())
1668 .collect()
1669 }
1670
1671 pub fn set_selection_mode(&mut self, mode: SelectionMode, cx: &mut Context<Self>) {
1675 self.edit_selection(SelectionOrigin::Programmatic, cx, |model, _, _| {
1676 model.set_mode(mode)
1677 });
1678 }
1679
1680 pub fn select_key(&mut self, key: Option<KeyOf<D>>, cx: &mut Context<Self>) {
1685 self.edit_selection(SelectionOrigin::Programmatic, cx, |model, rows, columns| {
1686 model.select_row(key, rows, columns)
1687 });
1688 }
1689
1690 pub fn set_selected_keys(
1694 &mut self,
1695 keys: impl IntoIterator<Item = KeyOf<D>>,
1696 cx: &mut Context<Self>,
1697 ) {
1698 self.edit_selection(SelectionOrigin::Programmatic, cx, |model, rows, columns| {
1699 model.set_rows(keys, rows.snapshot, columns)
1700 });
1701 }
1702
1703 pub fn set_selected_cells(
1707 &mut self,
1708 cells: impl IntoIterator<Item = (KeyOf<D>, ColumnOf<D>)>,
1709 cx: &mut Context<Self>,
1710 ) {
1711 self.edit_selection(SelectionOrigin::Programmatic, cx, |model, rows, _| {
1712 model.set_cells(cells, rows.snapshot)
1713 });
1714 }
1715
1716 pub fn select_all(&mut self, cx: &mut Context<Self>) {
1719 self.edit_selection(SelectionOrigin::Programmatic, cx, |model, rows, columns| {
1720 model.select_all(rows, columns)
1721 });
1722 }
1723
1724 pub fn clear_selection(&mut self, cx: &mut Context<Self>) {
1726 self.edit_selection(SelectionOrigin::Programmatic, cx, |model, _, _| {
1727 model.clear()
1728 });
1729 }
1730
1731 pub fn set_focused_cell(
1735 &mut self,
1736 key: &KeyOf<D>,
1737 column: Option<ColumnOf<D>>,
1738 cx: &mut Context<Self>,
1739 ) -> bool {
1740 let focused =
1741 self.edit_selection(SelectionOrigin::Programmatic, cx, |model, rows, columns| {
1742 model.set_focus(key, column, rows, columns)
1743 });
1744 if focused {
1745 self.reveal_focus();
1746 cx.notify();
1747 }
1748 focused
1749 }
1750
1751 pub fn set_focused_group(&mut self, path: &GroupPath, cx: &mut Context<Self>) -> bool {
1757 let focused =
1758 self.edit_selection(SelectionOrigin::Programmatic, cx, |model, rows, columns| {
1759 model.focus_caption(path, rows, columns)
1760 });
1761 if focused {
1762 self.reveal_focus();
1763 cx.notify();
1764 }
1765 focused
1766 }
1767
1768 pub(crate) fn pointer_target(&self) -> Option<&PointerTarget<KeyOf<D>>> {
1770 self.pointer_target.as_ref()
1771 }
1772
1773 pub(crate) fn command_scope(
1779 &self,
1780 target: Option<&LineTarget<KeyOf<D>>>,
1781 ) -> ScopedSelection<KeyOf<D>> {
1782 target
1783 .and_then(|target| self.line_scope(target))
1784 .unwrap_or_else(|| self.scoped_selection())
1785 }
1786
1787 fn line_scope(&self, target: &LineTarget<KeyOf<D>>) -> Option<ScopedSelection<KeyOf<D>>> {
1792 let rows = Self::shown_rows(&self.projection, &self.snapshot, &*self.selection_policy);
1793 let Some((line, under)) = rows.scope_line(target) else {
1794 return match target {
1795 LineTarget::Group(_) => Some(ScopedSelection::default()),
1796 LineTarget::Row(_) => None,
1797 };
1798 };
1799 let context = LineScopeContext::new(
1800 line,
1801 under,
1802 &self.projection,
1803 &self.snapshot,
1804 self.selection.mode(),
1805 );
1806 self.selection_policy.line_scope(&context)
1807 }
1808
1809 pub(crate) fn focus_target(&self) -> Option<LineTarget<KeyOf<D>>> {
1811 self.selection.focus().and_then(FocusedCell::line)
1812 }
1813
1814 pub(crate) fn confirm(&mut self, secondary: bool, cx: &mut Context<Self>) -> bool {
1820 let scoped = self.command_scope(self.focus_target().as_ref());
1821 if scoped.is_empty() {
1822 return false;
1823 }
1824 cx.emit(LiveGridEvent::Confirm {
1825 keys: scoped.shared_keys(),
1826 secondary,
1827 });
1828 true
1829 }
1830
1831 fn edit_selection<T>(
1834 &mut self,
1835 origin: SelectionOrigin,
1836 cx: &mut Context<Self>,
1837 edit: impl FnOnce(
1838 &mut SelectionModel<KeyOf<D>, ColumnOf<D>>,
1839 ShownRows<'_, D::Row>,
1840 &ColumnLayout<ColumnOf<D>>,
1841 ) -> T,
1842 ) -> T {
1843 let mark = self.selection.mark();
1844 let (projection, snapshot) = (self.projection.clone(), self.snapshot.clone());
1845 let result = edit(
1846 &mut self.selection,
1847 Self::shown_rows(&projection, &snapshot, &*self.selection_policy),
1848 &self.columns,
1849 );
1850 self.finish_change(mark, origin, cx);
1851 result
1852 }
1853
1854 pub(super) fn finish_change(
1858 &mut self,
1859 mark: ChangeMark<KeyOf<D>, ColumnOf<D>>,
1860 origin: SelectionOrigin,
1861 cx: &mut Context<Self>,
1862 ) -> bool {
1863 let (selection, focus) = self.selection.changes_since(&mark);
1864 if selection {
1865 cx.emit(LiveGridEvent::SelectionChange {
1866 selection: self.selection.selection().clone(),
1867 origin,
1868 });
1869 }
1870 if focus {
1871 if let Some(cell) = self.selection.focus() {
1872 self.set_current_column(cell.column().ix());
1873 }
1874 cx.emit(LiveGridEvent::FocusChange {
1875 cell: self.selection.focus().cloned(),
1876 origin,
1877 });
1878 }
1879 if selection || focus {
1880 cx.notify();
1881 }
1882 selection || focus
1883 }
1884
1885 pub(super) fn move_focus_off_hidden(
1887 &mut self,
1888 origin: SelectionOrigin,
1889 cx: &mut Context<Self>,
1890 ) {
1891 self.edit_selection(origin, cx, |model, _, columns| {
1892 model.move_off_hidden(columns)
1893 });
1894 }
1895
1896 fn page_rows(&self) -> usize {
1898 page_size(self.rows_area_height(), self.row_height)
1899 }
1900
1901 pub(super) fn navigate(
1904 &mut self,
1905 navigation: Navigation,
1906 extending: bool,
1907 cx: &mut Context<Self>,
1908 ) {
1909 if matches!(navigation, Navigation::PrevColumn | Navigation::NextColumn)
1912 && let Some(path) = self
1913 .selection
1914 .focus()
1915 .and_then(|focus| focus.group())
1916 .cloned()
1917 {
1918 self.caption_arrow(&path, navigation == Navigation::NextColumn, cx);
1919 return;
1920 }
1921 let page = self.page_rows();
1922 let (projection, snapshot) = (self.projection.clone(), self.snapshot.clone());
1923 let rows = Self::shown_rows(&projection, &snapshot, &*self.selection_policy);
1924 let Some(target) = self
1925 .selection
1926 .navigation_target(navigation, page, rows, &self.columns)
1927 else {
1928 return;
1929 };
1930 let context = SelectionGestureContext::new(
1931 GestureInput::Keyboard,
1932 Modifiers::default(),
1933 self.platform,
1934 extending,
1935 self.selection.is_selected(&target),
1936 self.selection.mode(),
1937 );
1938 let edit = self.selection_gesture.edit(&context);
1939 let mark = self.selection.mark();
1940 self.selection.apply(edit, target, rows, &self.columns);
1941 match navigation {
1943 Navigation::PageDown => self.scroll_row += page,
1944 Navigation::PageUp => self.scroll_row = self.scroll_row.saturating_sub(page),
1945 _ => {}
1946 }
1947 self.clamp_scroll();
1948 self.reveal_focus();
1949 self.finish_change(mark, SelectionOrigin::User, cx);
1950 cx.notify();
1951 }
1952
1953 pub(super) fn reveal_focus(&mut self) {
1957 let Some(focus) = self.selection.focus() else {
1958 return;
1959 };
1960 let column = focus.column().ix();
1961 let is_caption = focus.group().is_some();
1962 let display_ix = ShownRows::new(&self.projection, &self.snapshot).line_of(focus);
1963 if let Some(display_ix) = display_ix {
1964 self.reveal_row(display_ix);
1965 }
1966 if !is_caption {
1967 let mut columns = ColumnSet::EMPTY;
1968 columns.insert(column);
1969 self.reveal_columns(columns);
1970 }
1971 self.clamp_scroll();
1972 }
1973
1974 pub(super) fn bind_selection_actions<E: InteractiveElement>(root: E, cx: &Context<Self>) -> E {
1976 use Navigation::*;
1977 root.on_action(cx.listener(|this, _: &SelectUp, _, cx| this.navigate(Up, false, cx)))
1978 .on_action(cx.listener(|this, _: &SelectDown, _, cx| this.navigate(Down, false, cx)))
1979 .on_action(
1980 cx.listener(|this, _: &SelectPrevColumn, _, cx| {
1981 this.navigate(PrevColumn, false, cx)
1982 }),
1983 )
1984 .on_action(
1985 cx.listener(|this, _: &SelectNextColumn, _, cx| {
1986 this.navigate(NextColumn, false, cx)
1987 }),
1988 )
1989 .on_action(
1990 cx.listener(|this, _: &SelectPageUp, _, cx| this.navigate(PageUp, false, cx)),
1991 )
1992 .on_action(
1993 cx.listener(|this, _: &SelectPageDown, _, cx| this.navigate(PageDown, false, cx)),
1994 )
1995 .on_action(cx.listener(|this, _: &SelectFirst, _, cx| this.navigate(First, false, cx)))
1996 .on_action(cx.listener(|this, _: &SelectLast, _, cx| this.navigate(Last, false, cx)))
1997 .on_action(
1998 cx.listener(|this, _: &SelectFirstRow, _, cx| this.navigate(FirstRow, false, cx)),
1999 )
2000 .on_action(
2001 cx.listener(|this, _: &SelectLastRow, _, cx| this.navigate(LastRow, false, cx)),
2002 )
2003 .on_action(
2004 cx.listener(|this, _: &SelectFirstCell, _, cx| this.navigate(FirstCell, false, cx)),
2005 )
2006 .on_action(
2007 cx.listener(|this, _: &SelectLastCell, _, cx| this.navigate(LastCell, false, cx)),
2008 )
2009 .on_action(
2010 cx.listener(|this, _: &ExtendSelectionUp, _, cx| this.navigate(Up, true, cx)),
2011 )
2012 .on_action(
2013 cx.listener(|this, _: &ExtendSelectionDown, _, cx| this.navigate(Down, true, cx)),
2014 )
2015 .on_action(cx.listener(|this, _: &ExtendSelectionPrevColumn, _, cx| {
2016 this.navigate(PrevColumn, true, cx)
2017 }))
2018 .on_action(cx.listener(|this, _: &ExtendSelectionNextColumn, _, cx| {
2019 this.navigate(NextColumn, true, cx)
2020 }))
2021 .on_action(
2022 cx.listener(|this, _: &ExtendSelectionPageUp, _, cx| {
2023 this.navigate(PageUp, true, cx)
2024 }),
2025 )
2026 .on_action(cx.listener(|this, _: &ExtendSelectionPageDown, _, cx| {
2027 this.navigate(PageDown, true, cx)
2028 }))
2029 .on_action(
2030 cx.listener(|this, _: &ExtendSelectionToFirst, _, cx| {
2031 this.navigate(First, true, cx)
2032 }),
2033 )
2034 .on_action(
2035 cx.listener(|this, _: &ExtendSelectionToLast, _, cx| this.navigate(Last, true, cx)),
2036 )
2037 .on_action(cx.listener(|this, _: &ExtendSelectionToFirstRow, _, cx| {
2038 this.navigate(FirstRow, true, cx)
2039 }))
2040 .on_action(cx.listener(|this, _: &ExtendSelectionToLastRow, _, cx| {
2041 this.navigate(LastRow, true, cx)
2042 }))
2043 .on_action(cx.listener(|this, _: &ExtendSelectionToFirstCell, _, cx| {
2044 this.navigate(FirstCell, true, cx)
2045 }))
2046 .on_action(cx.listener(|this, _: &ExtendSelectionToLastCell, _, cx| {
2047 this.navigate(LastCell, true, cx)
2048 }))
2049 .on_action(cx.listener(Self::on_select_all))
2050 .on_action(cx.listener(Self::on_toggle_selection))
2051 .on_action(cx.listener(Self::on_confirm))
2052 .on_action(cx.listener(Self::on_cancel))
2053 }
2054
2055 fn on_select_all(&mut self, _: &SelectAll, _: &mut gpui_kit::Window, cx: &mut Context<Self>) {
2057 let handled = self.edit_selection(SelectionOrigin::User, cx, |model, rows, columns| {
2058 model.select_all(rows, columns)
2059 });
2060 if !handled {
2061 cx.propagate();
2062 }
2063 }
2064
2065 fn on_toggle_selection(
2067 &mut self,
2068 _: &ToggleSelection,
2069 _: &mut gpui_kit::Window,
2070 cx: &mut Context<Self>,
2071 ) {
2072 let handled = self.edit_selection(SelectionOrigin::User, cx, |model, rows, columns| {
2073 model.toggle_focused(rows, columns)
2074 });
2075 if !handled {
2076 cx.propagate();
2077 }
2078 }
2079
2080 fn on_confirm(&mut self, action: &Confirm, _: &mut gpui_kit::Window, cx: &mut Context<Self>) {
2083 if !self.confirm(action.secondary, cx) {
2084 cx.propagate();
2085 }
2086 }
2087
2088 fn on_cancel(&mut self, _: &Cancel, window: &mut gpui_kit::Window, cx: &mut Context<Self>) {
2092 if self.cancel_row_drag(window, cx) {
2093 return;
2094 }
2095 if self.selection.selection().is_empty() {
2096 cx.propagate();
2097 return;
2098 }
2099 self.edit_selection(SelectionOrigin::User, cx, |model, _, _| model.clear());
2100 }
2101
2102 fn row_at(&self, position: Point<Pixels>) -> Option<KeyOf<D>> {
2104 self.line_at(position)
2105 .and_then(|line| self.painted.get(line)?.row())
2106 .and_then(|id| self.snapshot.row(id))
2107 .map(|row| row.key().clone())
2108 }
2109
2110 fn column_toward(&self, position: Point<Pixels>) -> Option<ColumnIx> {
2113 self.column_at_position(position).or_else(|| {
2114 if position.x < self.body_bounds.origin.x {
2115 first_column(&self.columns)
2116 } else {
2117 last_column(&self.columns)
2118 }
2119 })
2120 }
2121
2122 pub(crate) fn on_body_mouse_down(
2130 &mut self,
2131 event: &MouseDownEvent,
2132 window: &mut gpui_kit::Window,
2133 cx: &mut Context<Self>,
2134 ) {
2135 let context = self.is_context_press(
2136 event.button,
2137 event.modifiers,
2138 event.click_count,
2139 GridArea::Body,
2140 );
2141 if self.is_menu_open() && !context {
2145 self.press_series = None;
2146 return;
2147 }
2148 let (pinned, row) = match self.pinned_row_at(event.position) {
2150 Some((edge, key)) => (Some(edge), Some(key)),
2151 None => (None, self.row_at(event.position)),
2152 };
2153 let caption = pinned
2155 .is_none()
2156 .then(|| self.caption_hit(event.position))
2157 .flatten();
2158 let column = match &caption {
2159 Some((_, column)) => *column,
2160 None => row.as_ref().and(self.column_toward(event.position)),
2161 };
2162 self.pointer_target = Some(PointerTarget {
2163 row,
2164 group: caption.map(|(path, _)| path),
2165 column,
2166 button: event.button,
2167 position: event.position,
2168 pinned,
2169 });
2170 if context {
2171 self.context_press(event.modifiers, cx);
2172 self.open_body_menu(window, cx);
2173 return;
2174 }
2175 let disclosure = pinned
2177 .is_none()
2178 .then(|| self.disclosure_hit(event.position))
2179 .flatten();
2180 if let Some((line, area)) = &disclosure {
2181 self.press_disclosure(line, *area, event, cx);
2182 }
2183 let chevron = disclosure
2184 .as_ref()
2185 .and_then(|(line, area)| (*area == ExpandArea::Chevron).then_some(line));
2186 if chevron.is_none()
2189 && let Some(target) = self.pressed_target()
2190 {
2191 self.begin_click(target, event);
2192 }
2193 if pinned.is_some() {
2194 self.finish_press(cx);
2198 self.press_series = None;
2199 } else if event.button == MouseButton::Left {
2200 let group = self
2201 .pointer_target
2202 .as_ref()
2203 .and_then(|pointer| pointer.group())
2204 .cloned();
2205 if let Some(group) = group {
2206 if let Some(column) = self.focus_column_or_first() {
2208 self.focus_press(FocusedCell::caption(group, column), cx);
2209 }
2210 } else if chevron.is_some() {
2211 self.finish_press(cx);
2215 self.press_series = None;
2216 } else {
2217 self.primary_press(event.modifiers, event.click_count, window, cx);
2218 }
2219 }
2220 }
2221
2222 fn focus_column_or_first(&self) -> Option<ColumnOf<D>> {
2224 self.selection
2225 .focus()
2226 .map(|focus| focus.column().ix())
2227 .filter(|column| self.columns.view_column_ix(*column).is_some())
2228 .or_else(|| first_column(&self.columns))
2229 .map(column_of)
2230 }
2231
2232 pub(super) fn focus_press(
2236 &mut self,
2237 target: FocusedCell<KeyOf<D>, ColumnOf<D>>,
2238 cx: &mut Context<Self>,
2239 ) {
2240 self.finish_press(cx);
2241 self.press_series = None;
2242 let mark = self.selection.mark();
2243 self.selection.focus_on(target.clone());
2244 let origin = self
2245 .pointer_target
2246 .as_ref()
2247 .map_or(Point::default(), PointerTarget::position);
2248 self.press = Some(Press {
2249 mark,
2250 base: None,
2251 target,
2252 origin,
2253 deferred: false,
2254 adds: false,
2255 moved: false,
2256 focus_only: true,
2257 drag_candidate: None,
2258 drag_tried: false,
2259 });
2260 cx.notify();
2261 }
2262
2263 fn pressed_cell(&self) -> Option<FocusedCell<KeyOf<D>, ColumnOf<D>>> {
2266 let pointer = self
2267 .pointer_target
2268 .as_ref()
2269 .filter(|pointer| pointer.pinned.is_none())?;
2270 let key = pointer.row()?.clone();
2271 Some(FocusedCell::new(key, column_of(pointer.column()?)))
2272 }
2273
2274 pub(super) fn primary_press(
2279 &mut self,
2280 modifiers: Modifiers,
2281 click_count: usize,
2282 window: &mut gpui_kit::Window,
2283 cx: &mut Context<Self>,
2284 ) {
2285 self.finish_press(cx);
2287 let pressed = self.pressed_cell();
2288 if click_count >= 2 {
2289 if self.start_edit_by_press(click_count, window, cx) {
2293 return;
2294 }
2295 if self.links.series_on_link {
2298 return;
2299 }
2300 if let Some(key) = self.press_series.clone() {
2301 self.confirm_row(&key, cx);
2302 }
2303 return;
2304 }
2305 self.press_series = pressed.as_ref().and_then(|cell| cell.row().cloned());
2306 self.links.series_on_link = self.is_pointer_on_link();
2307 let Some(target) = pressed else {
2309 return;
2310 };
2311 let selected = self.selection.is_selected(&target);
2312 let drag_candidate = target
2314 .row()
2315 .is_some_and(|key| {
2316 self.is_row_drag_press(key, target.column(), selected, modifiers, click_count)
2317 })
2318 .then_some(modifiers);
2319 let context = SelectionGestureContext::new(
2320 GestureInput::Pointer,
2321 modifiers,
2322 self.platform,
2323 false,
2324 selected,
2325 self.selection.mode(),
2326 );
2327 let edit = self.selection_gesture.edit(&context);
2328 let mark = self.selection.mark();
2329 let base = (edit == SelectionEdit::AddRange).then(|| self.selection.selection().clone());
2330 let deferred =
2331 edit == SelectionEdit::Replace && selected && self.selection.holds_more_than(&target);
2332 if deferred {
2333 self.selection.focus_on(target.clone());
2334 } else {
2335 let (projection, snapshot) = (self.projection.clone(), self.snapshot.clone());
2336 self.selection.apply(
2337 edit,
2338 target.clone(),
2339 Self::shown_rows(&projection, &snapshot, &*self.selection_policy),
2340 &self.columns,
2341 );
2342 }
2343 let origin = self
2344 .pointer_target
2345 .as_ref()
2346 .map_or(Point::default(), PointerTarget::position);
2347 self.press = Some(Press {
2348 mark,
2349 base,
2350 target,
2351 origin,
2352 deferred,
2353 adds: matches!(edit, SelectionEdit::Toggle | SelectionEdit::AddRange),
2354 moved: false,
2355 focus_only: false,
2356 drag_candidate,
2357 drag_tried: false,
2358 });
2359 cx.notify();
2360 }
2361
2362 pub(super) fn context_press(&mut self, modifiers: Modifiers, cx: &mut Context<Self>) {
2367 self.finish_press(cx);
2368 if let Some(group) = self
2369 .pointer_target
2370 .as_ref()
2371 .and_then(|pointer| pointer.group())
2372 .cloned()
2373 {
2374 self.edit_selection(SelectionOrigin::User, cx, |model, rows, columns| {
2375 model.focus_caption(&group, rows, columns)
2376 });
2377 return;
2378 }
2379 let Some(target) = self.pressed_cell() else {
2380 return;
2381 };
2382 let context = SelectionGestureContext::new(
2383 GestureInput::ContextPointer,
2384 modifiers,
2385 self.platform,
2386 false,
2387 self.selection.is_selected(&target),
2388 self.selection.mode(),
2389 );
2390 let edit = self.selection_gesture.edit(&context);
2391 self.edit_selection(SelectionOrigin::User, cx, |model, rows, columns| {
2392 model.apply(edit, target, rows, columns)
2393 });
2394 }
2395
2396 fn confirm_row(&mut self, key: &KeyOf<D>, cx: &mut Context<Self>) {
2401 let scoped = match self.line_scope(&LineTarget::Row(key.clone())) {
2402 Some(scope) => Some(scope).filter(|scope| !scope.is_empty()),
2403 None => Some(self.scoped_selection()).filter(|scope| scope.keys().contains(key)),
2404 };
2405 if let Some(scoped) = scoped {
2406 cx.emit(LiveGridEvent::Confirm {
2407 keys: scoped.shared_keys(),
2408 secondary: false,
2409 });
2410 }
2411 }
2412
2413 pub(crate) fn on_body_drag_move(&mut self, position: Point<Pixels>, cx: &mut Context<Self>) {
2416 let Some(press) = &mut self.press else {
2417 return;
2418 };
2419 if press.focus_only {
2421 return;
2422 }
2423 if !self.selection.is_dragging() {
2424 if !is_past_drag_threshold(press.origin, position) {
2425 return;
2426 }
2427 press.moved = true;
2428 if let Some(modifiers) = press.drag_candidate {
2432 let distance = (position - press.origin).magnitude();
2433 let threshold = f64::from(f32::from(self.drag.threshold()));
2434 if !press.drag_tried && distance >= threshold {
2435 press.drag_tried = true;
2436 if let Some(pressed) = press.target.row().cloned() {
2437 self.arm_row_drag(&pressed, modifiers, cx);
2438 }
2439 }
2440 return;
2441 }
2442 if press.deferred {
2443 return;
2446 }
2447 let target = press.target.clone();
2448 let adds = press.adds;
2449 let base = match press.base.take() {
2450 Some(base) => base,
2451 None if adds => self.selection.before_toggle(&target),
2452 None => GridSelection::default(),
2453 };
2454 self.selection.begin_drag(adds, base, target);
2455 }
2456 self.drag_scroll.last_drag_position = Some(position);
2457 self.update_drag_target(position, cx);
2458 let delta = AutoScroll::compute_delta(position.y, self.rows_bounds());
2461 self.drag_scroll.set(delta, cx, |delta, state, cx| {
2462 state.auto_scroll_rows(delta, cx)
2463 });
2464 }
2465
2466 fn update_drag_target(&mut self, position: Point<Pixels>, cx: &mut Context<Self>) {
2469 let Some(target) = self.drag_target_at(position) else {
2470 return;
2471 };
2472 if self.selection.drag_to(target) {
2473 cx.notify();
2474 }
2475 }
2476
2477 fn drag_target_at(
2478 &self,
2479 position: Point<Pixels>,
2480 ) -> Option<FocusedCell<KeyOf<D>, ColumnOf<D>>> {
2481 let rows = ShownRows::new(&self.projection, &self.snapshot);
2482 let lines = ((self.rows_area_height() + self.scroll_offset) / self.row_height).ceil();
2483 let lines = (lines as usize).max(1);
2484 let y = position.y - self.rows_bounds().origin.y + self.scroll_offset;
2485 let line = if y < px(0.) {
2486 0
2487 } else {
2488 ((y / self.row_height).floor() as usize).min(lines - 1)
2489 };
2490 let display_ix = rows.nearest_live(self.scroll_row + line)?;
2491 let key = rows.key_at(display_ix)?.clone();
2492 let column = self
2493 .column_at_position(position)
2494 .or_else(|| {
2495 self.selection
2496 .drag_target()
2497 .map(|target| target.column().ix())
2498 })
2499 .or_else(|| self.column_toward(position))?;
2500 Some(FocusedCell::new(key, column_of(column)))
2501 }
2502
2503 fn auto_scroll_rows(&mut self, delta: Pixels, cx: &mut Context<Self>) {
2506 if !self.selection.is_dragging() {
2507 self.drag_scroll.stop();
2508 return;
2509 }
2510 let before = (self.scroll_row, self.scroll_offset);
2511 self.scroll_rows_by(delta);
2512 if (self.scroll_row, self.scroll_offset) == before {
2513 return;
2514 }
2515 if let Some(position) = self.drag_scroll.last_drag_position {
2516 self.update_drag_target(position, cx);
2517 }
2518 cx.notify();
2519 }
2520
2521 pub(crate) fn on_body_mouse_up(&mut self, cx: &mut Context<Self>) {
2523 self.finish_press(cx);
2524 }
2525
2526 fn finish_press(&mut self, cx: &mut Context<Self>) {
2530 let Some(press) = self.press.take() else {
2531 return;
2532 };
2533 self.drag_scroll.stop();
2534 self.unarm_row_drag();
2536 let (projection, snapshot) = (self.projection.clone(), self.snapshot.clone());
2537 let rows = Self::shown_rows(&projection, &snapshot, &*self.selection_policy);
2538 if self.selection.is_dragging() {
2539 self.selection.finish_drag(rows, &self.columns);
2540 } else if press.deferred
2541 && !press.moved
2542 && press
2543 .target
2544 .row()
2545 .and_then(|key| rows.display_ix(key))
2546 .is_some()
2547 {
2548 self.selection
2549 .apply(SelectionEdit::Replace, press.target, rows, &self.columns);
2550 }
2551 self.finish_change(press.mark, SelectionOrigin::User, cx);
2552 cx.notify();
2553 }
2554}
2555
2556#[cfg(test)]
2557mod tests {
2558 use std::{
2559 collections::{HashMap, HashSet},
2560 sync::Arc,
2561 time::Instant,
2562 };
2563
2564 use super::*;
2565 use crate::{
2566 engine::{ProjectionEngine as _, Rebuild, SortDirection, ViewSpec},
2567 highlight::HighlightPolicy,
2568 model::CellValue,
2569 policy::{ProjectionScope, StandardSelectionGesture},
2570 store::{Ingest, Op},
2571 };
2572
2573 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2574 struct Col(u16);
2575
2576 const COLUMNS: [Col; 4] = [Col(0), Col(1), Col(2), Col(3)];
2577
2578 impl GridColumns for Col {
2579 fn all() -> &'static [Self] {
2580 &COLUMNS
2581 }
2582
2583 fn id(self) -> &'static str {
2584 ["c0", "c1", "c2", "c3"][self.0 as usize]
2585 }
2586
2587 fn ix(self) -> ColumnIx {
2588 ColumnIx::new(self.0)
2589 }
2590 }
2591
2592 #[derive(Debug)]
2593 struct Row {
2594 id: u32,
2595 price: i64,
2596 }
2597
2598 impl GridRow for Row {
2599 type Key = u32;
2600 type Column = Col;
2601
2602 fn key(&self) -> &u32 {
2603 &self.id
2604 }
2605
2606 fn value(&self, column: Col) -> CellValue<'_> {
2607 match column.0 {
2608 0 => CellValue::Int(self.id.into()),
2609 1 => CellValue::Int(self.price),
2610 _ => CellValue::Empty,
2611 }
2612 }
2613 }
2614
2615 fn row(id: u32, price: i64) -> Op<Row> {
2616 Op::Upsert(Arc::new(Row { id, price }))
2617 }
2618
2619 struct Visible(Vec<ColumnIx>);
2621
2622 impl ColumnView for Visible {
2623 fn view_column_ix(&self, column: ColumnIx) -> Option<ViewColumnIx> {
2624 let position = self.0.iter().position(|ix| *ix == column)?;
2625 Some(ViewColumnIx::new(position as u16))
2626 }
2627
2628 fn column_at(&self, view: ViewColumnIx) -> Option<ColumnIx> {
2629 self.0.get(view.get()).copied()
2630 }
2631
2632 fn visible_count(&self) -> usize {
2633 self.0.len()
2634 }
2635
2636 fn visible_set(&self) -> ColumnSet {
2637 set(self.0.iter().copied())
2638 }
2639
2640 fn visible_neighbour(&self, column: ColumnIx) -> Option<ColumnIx> {
2641 let right = self.0.iter().copied().filter(|ix| *ix > column).min();
2643 right.or_else(|| self.0.iter().copied().filter(|ix| *ix < column).max())
2644 }
2645 }
2646
2647 fn set(columns: impl IntoIterator<Item = ColumnIx>) -> ColumnSet {
2648 columns.into_iter().fold(ColumnSet::EMPTY, |mut set, ix| {
2649 set.insert(ix);
2650 set
2651 })
2652 }
2653
2654 fn cols(columns: &[u16]) -> ColumnSet {
2655 set(columns.iter().copied().map(ColumnIx::new))
2656 }
2657
2658 fn all_visible() -> Visible {
2659 Visible((0..4).map(ColumnIx::new).collect())
2660 }
2661
2662 struct World {
2664 ingest: Ingest<Row>,
2665 snapshot: Arc<StoreSnapshot<Row>>,
2666 projection: Projection,
2667 }
2668
2669 impl World {
2670 fn new(count: u32) -> Self {
2672 let mut ingest = Ingest::new(HighlightPolicy::default(), Instant::now());
2673 ingest.apply((0..count).map(|id| row(id, id.into())), Instant::now());
2674 let snapshot = ingest.snapshot();
2675 let projection = Rebuild::default().rebuild(&snapshot, &ViewSpec::new());
2676 Self {
2677 ingest,
2678 snapshot,
2679 projection,
2680 }
2681 }
2682
2683 fn rows(&self) -> ShownRows<'_, Row> {
2684 ShownRows::new(&self.projection, &self.snapshot)
2685 }
2686
2687 fn apply(
2689 &mut self,
2690 ops: impl IntoIterator<Item = Op<Row>>,
2691 ) -> (Arc<StoreSnapshot<Row>>, crate::store::ChangeSet) {
2692 let changes = self.ingest.apply(ops, Instant::now());
2693 let previous = std::mem::replace(&mut self.snapshot, self.ingest.snapshot());
2694 (previous, changes)
2695 }
2696
2697 fn rebuild(&mut self, view: &ViewSpec<Row>) -> Projection {
2699 std::mem::replace(
2700 &mut self.projection,
2701 Rebuild::default().rebuild(&self.snapshot, view),
2702 )
2703 }
2704 }
2705
2706 fn at(key: u32, column: u16) -> FocusedCell<u32, Col> {
2707 FocusedCell::new(key, Col(column))
2708 }
2709
2710 fn keys(model: &SelectionModel<u32, Col>) -> Vec<u32> {
2711 let mut keys: Vec<u32> = model.selection().iter().copied().collect();
2712 keys.sort_unstable();
2713 keys
2714 }
2715
2716 #[test]
2717 fn test_selection_edits() {
2718 use SelectionEdit::*;
2719 let world = World::new(20);
2720 let columns = all_visible();
2721 let rows = world.rows();
2722
2723 let mut model = SelectionModel::<u32, Col>::new(SelectionMode::RowSet);
2725 model.apply(Replace, at(3, 1), rows, &columns);
2726 assert_eq!(keys(&model), [3]);
2727 assert_eq!(model.selection().columns(&3), ColumnSet::first(4));
2728 model.apply(Extend, at(6, 2), rows, &columns);
2729 assert_eq!(keys(&model), [3, 4, 5, 6]);
2730 assert_eq!(model.focus(), Some(&at(6, 2)));
2731 model.apply(Extend, at(1, 0), rows, &columns);
2732 assert_eq!(keys(&model), [1, 2, 3], "Extend drops the rest");
2733 model.apply(Toggle, at(9, 0), rows, &columns);
2734 assert_eq!(keys(&model), [1, 2, 3, 9]);
2735 model.apply(AddRange, at(11, 0), rows, &columns);
2736 assert_eq!(keys(&model), [1, 2, 3, 9, 10, 11], "the anchor is 9");
2737 model.apply(Toggle, at(2, 0), rows, &columns);
2738 assert_eq!(keys(&model), [1, 3, 9, 10, 11]);
2739 model.apply(Keep, at(15, 3), rows, &columns);
2740 assert_eq!(keys(&model), [1, 3, 9, 10, 11]);
2741 assert_eq!(model.focus(), Some(&at(15, 3)));
2742 model.apply(Extend, at(4, 0), rows, &columns);
2744 assert_eq!(keys(&model), [2, 3, 4]);
2745
2746 let mut model = SelectionModel::<u32, Col>::new(SelectionMode::RowSingle);
2748 model.apply(Replace, at(3, 0), rows, &columns);
2749 model.apply(Extend, at(6, 0), rows, &columns);
2750 assert_eq!(keys(&model), [6]);
2751 model.apply(AddRange, at(8, 0), rows, &columns);
2752 assert_eq!(keys(&model), [8]);
2753 model.apply(Toggle, at(8, 0), rows, &columns);
2754 assert!(model.selection().is_empty());
2755 model.apply(Toggle, at(2, 0), rows, &columns);
2756 assert_eq!(keys(&model), [2]);
2757
2758 let shuffled = Visible([0, 3, 1].map(ColumnIx::new).to_vec());
2761 let mut model = SelectionModel::<u32, Col>::new(SelectionMode::CellSet);
2762 model.apply(Replace, at(3, 0), rows, &shuffled);
2763 assert_eq!(model.selection().columns(&3), cols(&[0]));
2764 model.apply(Extend, at(5, 3), rows, &shuffled);
2765 assert_eq!(keys(&model), [3, 4, 5]);
2766 assert_eq!(model.selection().columns(&4), cols(&[0, 3]));
2767 model.apply(Extend, at(4, 1), rows, &shuffled);
2768 assert_eq!(keys(&model), [3, 4]);
2769 assert_eq!(model.selection().columns(&3), cols(&[0, 1, 3]));
2770 assert!(!model.selection().contains_cell(&3, ColumnIx::new(2)));
2771 model.apply(Toggle, at(3, 3), rows, &shuffled);
2772 assert_eq!(model.selection().columns(&3), cols(&[0, 1]));
2773 model.apply(Toggle, at(10, 1), rows, &shuffled);
2774 model.apply(AddRange, at(11, 1), rows, &shuffled);
2775 assert_eq!(model.selection().columns(&11), cols(&[1]));
2776 assert_eq!(model.selection().columns(&4), cols(&[0, 1, 3]));
2777 model.apply(Toggle, at(11, 1), rows, &shuffled);
2779 assert!(!model.selection().contains(&11));
2780 assert!(model.holds_more_than(&at(4, 0)));
2782 assert!(model.is_selected(&at(4, 0)));
2783 assert!(!model.is_selected(&at(4, 2)));
2784
2785 let mut model = SelectionModel::<u32, Col>::new(SelectionMode::CellSingle);
2787 model.apply(Replace, at(3, 0), rows, &shuffled);
2788 model.apply(Extend, at(5, 1), rows, &shuffled);
2789 assert_eq!(keys(&model), [5]);
2790 assert_eq!(model.selection().columns(&5), cols(&[1]));
2791 assert!(!model.holds_more_than(&at(5, 1)));
2792
2793 let mut world = World::new(20);
2795 world.apply([Op::Remove(4), Op::Remove(5)]);
2796 let mut model = SelectionModel::<u32, Col>::new(SelectionMode::RowSet);
2797 model.apply(Replace, at(3, 0), world.rows(), &columns);
2798 model.apply(Extend, at(7, 0), world.rows(), &columns);
2799 assert_eq!(keys(&model), [3, 6, 7]);
2800 assert!(model.select_all(world.rows(), &columns));
2801 assert_eq!(model.selection().len(), 18);
2802 let mut model = SelectionModel::<u32, Col>::new(SelectionMode::CellSet);
2805 assert!(model.select_all(world.rows(), &shuffled));
2806 assert_eq!(model.selection().columns(&0), cols(&[0, 1, 3]));
2807 let mut model = SelectionModel::<u32, Col>::new(SelectionMode::RowSingle);
2808 assert!(!model.select_all(world.rows(), &columns));
2809 }
2810
2811 #[test]
2812 fn test_mode_changes_and_programmatic_selection() {
2813 let world = World::new(10);
2814 let columns = all_visible();
2815 let rows = world.rows();
2816 let mut model = SelectionModel::<u32, Col>::new(SelectionMode::RowSet);
2817 model.apply(SelectionEdit::Replace, at(2, 1), rows, &columns);
2818 model.apply(SelectionEdit::Extend, at(4, 1), rows, &columns);
2819 model.set_mode(SelectionMode::RowSingle);
2821 assert_eq!(keys(&model), [4]);
2822 model.set_mode(SelectionMode::CellSingle);
2824 assert!(model.selection().is_empty());
2825
2826 let mut model = SelectionModel::<u32, Col>::new(SelectionMode::RowSet);
2827 model.set_rows([1, 3, 99], &world.snapshot, &columns);
2828 assert_eq!(keys(&model), [1, 3], "a key the snapshot lacks is dropped");
2829 model.set_cells([(5, Col(2)), (6, Col(1))], &world.snapshot);
2830 assert_eq!(keys(&model), [5, 6]);
2831 assert_eq!(model.selection().columns(&5), ColumnSet::first(4));
2832 model.set_mode(SelectionMode::CellSet);
2833 model.set_cells([(5, Col(2)), (5, Col(1)), (99, Col(1))], &world.snapshot);
2834 assert_eq!(model.selection().columns(&5), cols(&[1, 2]));
2835 model.set_rows([7], &world.snapshot, &columns);
2836 assert_eq!(model.selection().columns(&7), ColumnSet::first(4));
2837
2838 let mut model = SelectionModel::<u32, Col>::new(SelectionMode::RowSingle);
2840 model.select_row(Some(8), rows, &columns);
2841 assert_eq!(keys(&model), [8]);
2842 assert_eq!(model.focus(), Some(&at(8, 0)));
2843 model.select_row(Some(99), rows, &columns);
2844 assert!(model.selection().is_empty());
2845 assert_eq!(model.focus(), Some(&at(8, 0)));
2846 assert!(model.set_focus(&3, Some(Col(2)), rows, &columns));
2847 assert_eq!(model.focus(), Some(&at(3, 2)));
2848 assert!(model.set_focus(&5, None, rows, &columns));
2849 assert_eq!(model.focus(), Some(&at(5, 2)), "None keeps the column");
2850 assert!(!model.set_focus(&99, None, rows, &columns));
2851
2852 let mut model = SelectionModel::<u32, Col>::new(SelectionMode::RowSingle);
2854 model.set_focus(&3, Some(Col(1)), rows, &columns);
2855 model.move_off_hidden(&Visible([0, 2, 3].map(ColumnIx::new).to_vec()));
2856 assert_eq!(model.focus(), Some(&at(3, 2)));
2857 model.set_focus(&3, Some(Col(3)), rows, &columns);
2858 model.move_off_hidden(&Visible([0, 1].map(ColumnIx::new).to_vec()));
2859 assert_eq!(model.focus(), Some(&at(3, 1)));
2860
2861 assert_eq!(SelectionMode::RowSet.selection_unit(), SelectionUnit::Row);
2862 assert_eq!(
2863 SelectionMode::CellSingle.selection_unit(),
2864 SelectionUnit::Cell
2865 );
2866 }
2867
2868 #[test]
2869 fn test_navigation_targets() {
2870 let mut world = World::new(20);
2871 let columns = Visible([0, 3, 1].map(ColumnIx::new).to_vec());
2872 let mut model = SelectionModel::<u32, Col>::new(SelectionMode::RowSingle);
2873 let target = |model: &SelectionModel<u32, Col>, world: &World, navigation| {
2874 model
2875 .navigation_target(navigation, 5, world.rows(), &columns)
2876 .expect("a target")
2877 };
2878 assert_eq!(target(&model, &world, Navigation::Down), at(0, 0));
2880 assert_eq!(target(&model, &world, Navigation::Last), at(0, 1));
2881 assert_eq!(target(&model, &world, Navigation::LastCell), at(19, 1));
2882 assert_eq!(target(&model, &world, Navigation::LastRow), at(19, 0));
2883
2884 model.set_focus(&10, Some(Col(3)), world.rows(), &columns);
2885 assert_eq!(target(&model, &world, Navigation::Up), at(9, 3));
2886 assert_eq!(target(&model, &world, Navigation::PageDown), at(15, 3));
2887 assert_eq!(target(&model, &world, Navigation::PageUp), at(5, 3));
2888 assert_eq!(target(&model, &world, Navigation::PrevColumn), at(10, 0));
2889 assert_eq!(target(&model, &world, Navigation::NextColumn), at(10, 1));
2890 assert_eq!(target(&model, &world, Navigation::First), at(10, 0));
2891 assert_eq!(target(&model, &world, Navigation::FirstCell), at(0, 0));
2892 assert_eq!(target(&model, &world, Navigation::LastRow), at(19, 3));
2893 model.set_focus(&19, Some(Col(1)), world.rows(), &columns);
2895 assert_eq!(target(&model, &world, Navigation::Down), at(19, 1));
2896 assert_eq!(target(&model, &world, Navigation::NextColumn), at(19, 1));
2897 assert_eq!(target(&model, &world, Navigation::PageDown), at(19, 1));
2898
2899 world.apply([Op::Remove(11), Op::Remove(12), Op::Remove(0)]);
2902 model.set_focus(&10, None, world.rows(), &columns);
2903 assert_eq!(target(&model, &world, Navigation::Down), at(13, 1));
2904 assert_eq!(target(&model, &world, Navigation::FirstRow), at(1, 1));
2905 model.set_focus(&1, None, world.rows(), &columns);
2906 assert_eq!(target(&model, &world, Navigation::Up), at(1, 1));
2907 }
2908
2909 #[test]
2910 fn test_successor_rule() {
2911 let columns = all_visible();
2912 let mut world = World::new(10);
2913 let mut model = SelectionModel::<u32, Col>::new(SelectionMode::RowSingle);
2914 model.apply(SelectionEdit::Replace, at(5, 2), world.rows(), &columns);
2915
2916 let (previous, _) = world.apply([Op::Remove(5)]);
2918 model.follow_removed(&world.projection, &previous, &world.snapshot);
2919 assert_eq!(model.focus(), Some(&at(6, 2)));
2920 assert_eq!(model.anchor, Some(at(6, 2)), "the anchor follows too");
2921 model.remove_rows(&[], &previous);
2923 let (previous, _) = world.apply([6, 7, 8, 9].map(Op::Remove));
2925 model.follow_removed(&world.projection, &previous, &world.snapshot);
2926 assert_eq!(model.focus(), Some(&at(4, 2)));
2927 let (previous, _) = world.apply([0, 1, 2, 3, 4].map(Op::Remove));
2929 model.follow_removed(&world.projection, &previous, &world.snapshot);
2930 assert_eq!(model.focus(), None);
2931
2932 let mut world = World::new(10);
2934 let mut model = SelectionModel::<u32, Col>::new(SelectionMode::RowSet);
2935 model.apply(SelectionEdit::Replace, at(5, 0), world.rows(), &columns);
2936 let even = ViewSpec::new().with_filter(ColumnSet::first(1), |row: &Row| row.id % 2 == 0);
2937 let previous = world.rebuild(&even);
2938 model.follow_filtered(&previous, &world.projection, &world.snapshot);
2939 assert_eq!(model.focus(), Some(&at(6, 0)));
2940 assert_eq!(keys(&model), [5], "a filter keeps the selection");
2941 model.set_focus(&8, None, world.rows(), &columns);
2943 let low = ViewSpec::new().with_filter(ColumnSet::first(1), |row: &Row| row.id < 5);
2944 let previous = world.rebuild(&low);
2945 model.follow_filtered(&previous, &world.projection, &world.snapshot);
2946 assert_eq!(model.focus(), Some(&at(4, 0)));
2947 let descending = ViewSpec::new().with_sort([(Col(1), SortDirection::Descending)]);
2949 let previous = world.rebuild(&descending);
2950 model.follow_filtered(&previous, &world.projection, &world.snapshot);
2951 assert_eq!(model.focus(), Some(&at(4, 0)));
2952 let none = ViewSpec::new().with_filter(ColumnSet::first(1), |_: &Row| false);
2954 let previous = world.rebuild(&none);
2955 model.follow_filtered(&previous, &world.projection, &world.snapshot);
2956 assert_eq!(model.focus(), None);
2957 }
2958
2959 #[test]
2960 fn test_removed_and_reset_keys() {
2961 let columns = all_visible();
2962 let mut world = World::new(10);
2963 let mut model = SelectionModel::<u32, Col>::new(SelectionMode::RowSet);
2964 model.apply(SelectionEdit::Replace, at(2, 0), world.rows(), &columns);
2965 model.apply(SelectionEdit::Extend, at(5, 0), world.rows(), &columns);
2966
2967 let (previous, changes) = world.apply([Op::Remove(3)]);
2968 model.remove_rows(changes.removed(), &previous);
2969 assert_eq!(keys(&model), [2, 4, 5]);
2970 let (previous, changes) = world.apply([Op::Remove(4), row(4, 4)]);
2972 model.remove_rows(changes.removed(), &previous);
2973 assert_eq!(keys(&model), [2, 5]);
2974 assert!(world.snapshot.get(&4).is_some());
2975
2976 let (previous, changes) = world.apply([Op::ReplaceAll(
2979 [2, 8].map(|id| Arc::new(Row { id, price: 0 })).to_vec(),
2980 )]);
2981 assert!(changes.is_reset());
2982 model.remove_rows(changes.removed(), &previous);
2983 model.retain_present(&world.snapshot);
2984 assert_eq!(keys(&model), [2]);
2985 assert_eq!(model.focus(), None);
2986 assert_eq!(model.anchor, Some(at(2, 0)));
2987 }
2988
2989 #[test]
2990 fn test_drag_painter_and_finish() {
2991 let world = World::new(20);
2992 let columns = all_visible();
2993 let mut model = SelectionModel::<u32, Col>::new(SelectionMode::RowSet);
2994 model.apply(SelectionEdit::Replace, at(2, 0), world.rows(), &columns);
2995 let base = model.selection().clone();
2996 model.begin_drag(false, base.clone(), at(2, 0));
2998 assert!(model.drag_to(at(5, 0)));
2999 assert!(!model.drag_to(at(5, 0)));
3000 let painter = model.painter(world.rows(), &columns);
3001 assert_eq!(painter.columns(&4, 4), ColumnSet::first(4));
3002 assert_eq!(painter.columns(&6, 6), ColumnSet::EMPTY);
3003 assert_eq!(keys(&model), [2], "nothing is selected before the release");
3004 model.finish_drag(world.rows(), &columns);
3005 assert_eq!(keys(&model), [2, 3, 4, 5]);
3006 assert_eq!(model.focus(), Some(&at(5, 0)));
3007
3008 model.apply(SelectionEdit::Toggle, at(10, 0), world.rows(), &columns);
3010 model.begin_drag(true, base, at(10, 0));
3011 model.drag_to(at(12, 0));
3012 let painter = model.painter(world.rows(), &columns);
3013 assert_eq!(painter.columns(&2, 2), ColumnSet::first(4));
3014 assert_eq!(painter.columns(&3, 3), ColumnSet::EMPTY, "not in the base");
3015 assert_eq!(painter.columns(&11, 11), ColumnSet::first(4));
3016 model.finish_drag(world.rows(), &columns);
3017 assert_eq!(keys(&model), [2, 10, 11, 12]);
3018 }
3019
3020 #[derive(Default)]
3026 struct Reference {
3027 store: HashMap<u32, (i64, u64)>,
3028 generation: HashMap<u32, u64>,
3029 next_seq: u64,
3030 shown: Vec<(u32, u64)>,
3031 selected: HashSet<u32>,
3032 focus: Option<u32>,
3033 anchor: Option<u32>,
3034 single: bool,
3035 }
3036
3037 impl Reference {
3038 fn generation_of(generation: &HashMap<u32, u64>, key: u32) -> u64 {
3039 generation.get(&key).copied().unwrap_or(0)
3040 }
3041
3042 fn is_live(&self, (key, generation): (u32, u64)) -> bool {
3043 self.store.contains_key(&key)
3044 && Self::generation_of(&self.generation, key) == generation
3045 }
3046
3047 fn position(&self, key: u32) -> Option<usize> {
3049 self.shown
3050 .iter()
3051 .position(|entry| entry.0 == key && self.is_live(*entry))
3052 }
3053
3054 fn live_keys(&self) -> Vec<u32> {
3055 self.shown
3056 .iter()
3057 .filter(|entry| self.is_live(**entry))
3058 .map(|entry| entry.0)
3059 .collect()
3060 }
3061
3062 fn upsert(&mut self, key: u32, price: i64) {
3063 match self.store.get_mut(&key) {
3064 Some(entry) => entry.0 = price,
3065 None => {
3066 self.store.insert(key, (price, self.next_seq));
3067 self.next_seq += 1;
3068 }
3069 }
3070 }
3071
3072 fn remove(&mut self, key: u32) -> bool {
3074 let removed = self.store.remove(&key).is_some();
3075 if removed {
3076 *self.generation.entry(key).or_default() += 1;
3077 self.selected.remove(&key);
3078 }
3079 removed
3080 }
3081
3082 fn rebuild(&self, sort: i8, filter: Option<u32>) -> Vec<(u32, u64)> {
3083 let mut rows: Vec<(u32, i64, u64)> = self
3084 .store
3085 .iter()
3086 .filter(|(key, _)| filter.is_none_or(|r| **key % 3 != r))
3087 .map(|(key, (price, seq))| (*key, *price, *seq))
3088 .collect();
3089 rows.sort_by_key(|(_, price, seq)| (i64::from(sort) * price, *seq));
3090 rows.into_iter()
3091 .map(|(key, _, _)| (key, self.generation.get(&key).copied().unwrap_or(0)))
3092 .collect()
3093 }
3094
3095 fn successor(
3097 order: &[(u32, u64)],
3098 key: u32,
3099 accept: impl Fn((u32, u64)) -> bool,
3100 ) -> Option<u32> {
3101 let position = order.iter().position(|entry| entry.0 == key);
3102 match position {
3103 Some(position) => order[position + 1..]
3104 .iter()
3105 .copied()
3106 .find(|entry| accept(*entry))
3107 .or_else(|| {
3108 order[..position]
3109 .iter()
3110 .rev()
3111 .copied()
3112 .find(|entry| accept(*entry))
3113 })
3114 .map(|entry| entry.0),
3115 None => order
3116 .iter()
3117 .copied()
3118 .find(|entry| accept(*entry))
3119 .map(|entry| entry.0),
3120 }
3121 }
3122
3123 fn range(&self, from: u32, to: u32) -> Option<Vec<u32>> {
3124 let (from, to) = (self.position(from)?, self.position(to)?);
3125 Some(
3126 self.shown[from.min(to)..=from.max(to)]
3127 .iter()
3128 .filter(|entry| self.is_live(**entry))
3129 .map(|entry| entry.0)
3130 .collect(),
3131 )
3132 }
3133
3134 fn apply(&mut self, edit: SelectionEdit, target: u32) {
3135 let edit = match edit {
3136 SelectionEdit::Extend | SelectionEdit::AddRange if self.single => {
3137 SelectionEdit::Replace
3138 }
3139 edit => edit,
3140 };
3141 let range = self.anchor.and_then(|anchor| self.range(anchor, target));
3142 match (edit, range) {
3143 (SelectionEdit::Extend, Some(range)) => self.selected = range.into_iter().collect(),
3144 (SelectionEdit::AddRange, Some(range)) => self.selected.extend(range),
3145 (SelectionEdit::Replace | SelectionEdit::Extend | SelectionEdit::AddRange, _) => {
3146 self.selected = HashSet::from([target]);
3147 self.anchor = Some(target);
3148 }
3149 (SelectionEdit::Toggle, _) => {
3150 if self.single {
3151 self.selected = if self.selected.contains(&target) {
3152 HashSet::new()
3153 } else {
3154 HashSet::from([target])
3155 };
3156 } else if !self.selected.remove(&target) {
3157 self.selected.insert(target);
3158 }
3159 self.anchor = Some(target);
3160 }
3161 _ => {}
3162 }
3163 self.focus = Some(target);
3164 }
3165
3166 fn navigate(&self, navigation: Navigation, page: usize) -> Option<u32> {
3167 let live: Vec<usize> = (0..self.shown.len())
3168 .filter(|ix| self.is_live(self.shown[*ix]))
3169 .collect();
3170 let Some(origin) = self.focus.and_then(|key| self.position(key)) else {
3171 let ix = match navigation {
3172 Navigation::LastRow | Navigation::LastCell => live.last()?,
3173 _ => live.first()?,
3174 };
3175 return Some(self.shown[*ix].0);
3176 };
3177 let end = self.shown.len() - 1;
3178 let target = match navigation {
3179 Navigation::Up => origin.saturating_sub(1),
3180 Navigation::Down => (origin + 1).min(end),
3181 Navigation::PageUp => origin.saturating_sub(page),
3182 Navigation::PageDown => (origin + page).min(end),
3183 Navigation::FirstRow | Navigation::FirstCell => 0,
3184 Navigation::LastRow | Navigation::LastCell => end,
3185 _ => origin,
3186 };
3187 let ix = if target > origin {
3188 live.iter().copied().find(|ix| *ix >= target).or_else(|| {
3189 live.iter()
3190 .copied()
3191 .rev()
3192 .find(|ix| *ix > origin && *ix < target)
3193 })
3194 } else if target < origin {
3195 live.iter()
3196 .copied()
3197 .rev()
3198 .find(|ix| *ix <= target)
3199 .or_else(|| live.iter().copied().find(|ix| *ix > target && *ix < origin))
3200 } else {
3201 None
3202 };
3203 Some(self.shown[ix.unwrap_or(origin)].0)
3204 }
3205 }
3206
3207 fn view(sort: i8, filter: Option<u32>) -> ViewSpec<Row> {
3208 let view = match sort {
3209 1 => ViewSpec::new().with_sort([(Col(1), SortDirection::Ascending)]),
3210 -1 => ViewSpec::new().with_sort([(Col(1), SortDirection::Descending)]),
3211 _ => ViewSpec::new(),
3212 };
3213 match filter {
3214 Some(r) => view.with_filter(ColumnSet::first(1), move |row: &Row| row.id % 3 != r),
3215 None => view,
3216 }
3217 }
3218
3219 #[test]
3220 fn test_selection_matches_reference_model() {
3221 const PAGE: usize = 3;
3222 const PLATFORM: gpui_kit::PlatformInfo = gpui_kit::PlatformInfo {
3224 os: gpui_kit::OperatingSystem::Linux,
3225 target: gpui_kit::PlatformTarget::Native,
3226 };
3227 let columns = Visible(vec![ColumnIx::new(0)]);
3228 let gesture = StandardSelectionGesture;
3229 for seed in 0..60 {
3230 let mut rng = fastrand::Rng::with_seed(seed);
3231 let mode = if rng.bool() {
3232 SelectionMode::RowSet
3233 } else {
3234 SelectionMode::RowSingle
3235 };
3236 let mut world = World::new(0);
3237 let mut model = SelectionModel::<u32, Col>::new(mode);
3238 let mut reference = Reference {
3239 single: mode == SelectionMode::RowSingle,
3240 ..Reference::default()
3241 };
3242 let initial: Vec<Op<Row>> = (0..20)
3243 .map(|id| {
3244 let price = rng.i64(0..50);
3245 reference.upsert(id, price);
3246 row(id, price)
3247 })
3248 .collect();
3249 world.apply(initial);
3250 let (mut sort, mut filter) = (0i8, None);
3251 world.rebuild(&view(sort, filter));
3252 reference.shown = reference.rebuild(sort, filter);
3253
3254 for step in 0..40 {
3255 let context = format!("seed {seed}, step {step}");
3256 let mut ops = Vec::new();
3259 let mut removed = HashSet::new();
3260 let reset = rng.u8(..20) == 0;
3261 if reset {
3262 let count = rng.u32(0..30);
3263 let mut rows: Vec<Arc<Row>> = Vec::new();
3264 for id in 0..count {
3265 if rng.bool() {
3266 rows.push(Arc::new(Row {
3267 id,
3268 price: rng.i64(0..50),
3269 }));
3270 }
3271 }
3272 for key in reference.store.keys() {
3275 *reference.generation.entry(*key).or_default() += 1;
3276 }
3277 reference.store.clear();
3278 for row in &rows {
3279 reference.upsert(row.id, row.price);
3280 }
3281 ops.push(Op::ReplaceAll(rows));
3282 } else {
3283 for _ in 0..rng.usize(0..4) {
3284 let key = rng.u32(0..40);
3285 match rng.u8(..4) {
3286 0 => {
3287 if reference.remove(key) {
3288 removed.insert(key);
3289 }
3290 ops.push(Op::Remove(key));
3291 }
3292 1 => {
3293 if reference.remove(key) {
3294 removed.insert(key);
3295 }
3296 ops.push(Op::Remove(key));
3297 let price = rng.i64(0..50);
3298 reference.upsert(key, price);
3299 ops.push(row(key, price));
3300 }
3301 _ => {
3302 let price = rng.i64(0..50);
3303 reference.upsert(key, price);
3304 ops.push(row(key, price));
3305 }
3306 }
3307 }
3308 }
3309 let (previous, changes) = world.apply(ops);
3310 model.remove_rows(changes.removed(), &previous);
3311 if changes.is_reset() {
3312 model.retain_present(&world.snapshot);
3313 let store = reference.store.clone();
3314 reference.selected.retain(|key| store.contains_key(key));
3315 reference.focus = reference.focus.filter(|key| store.contains_key(key));
3316 reference.anchor = reference.anchor.filter(|key| store.contains_key(key));
3317 } else if !changes.removed().is_empty() {
3318 model.follow_removed(&world.projection, &previous, &world.snapshot);
3319 let moved = [reference.focus, reference.anchor].map(|cell| {
3322 let key = cell?;
3323 if !removed.contains(&key) {
3324 return Some(key);
3325 }
3326 Reference::successor(&reference.shown, key, |entry| {
3327 reference.is_live(entry)
3328 })
3329 });
3330 [reference.focus, reference.anchor] = moved;
3331 }
3332
3333 if reset || rng.u8(..3) == 0 {
3337 if rng.bool() {
3338 sort = rng.i8(-1..=1);
3339 filter = rng.bool().then(|| rng.u32(0..3));
3340 }
3341 let previous = world.rebuild(&view(sort, filter));
3342 model.follow_filtered(&previous, &world.projection, &world.snapshot);
3343 let shown = reference.rebuild(sort, filter);
3344 let old = std::mem::replace(&mut reference.shown, shown);
3345 let new: HashSet<u32> = reference.shown.iter().map(|entry| entry.0).collect();
3346 let moved = [reference.focus, reference.anchor].map(|cell| {
3347 let key = cell?;
3348 if new.contains(&key) {
3349 return Some(key);
3350 }
3351 Reference::successor(&old, key, |entry| {
3352 new.contains(&entry.0) && reference.is_live(entry)
3353 })
3354 });
3355 [reference.focus, reference.anchor] = moved;
3356 }
3357
3358 let live = reference.live_keys();
3360 let rows = world.rows();
3361 match rng.u8(..6) {
3362 0 | 1 if !live.is_empty() => {
3363 let key = live[rng.usize(..live.len())];
3364 let mut modifiers = Modifiers::default();
3365 modifiers.shift = rng.bool();
3366 modifiers.platform = rng.bool();
3367 modifiers.control = modifiers.platform;
3368 let target = at(key, 0);
3369 let edit = gesture.edit(&SelectionGestureContext::new(
3370 GestureInput::Pointer,
3371 modifiers,
3372 PLATFORM,
3373 false,
3374 model.is_selected(&target),
3375 mode,
3376 ));
3377 model.apply(edit, target, rows, &columns);
3378 reference.apply(edit, key);
3379 }
3380 2 => {
3381 let navigation = [
3382 Navigation::Up,
3383 Navigation::Down,
3384 Navigation::PageUp,
3385 Navigation::PageDown,
3386 Navigation::FirstRow,
3387 Navigation::LastRow,
3388 ][rng.usize(..6)];
3389 let extending = rng.bool();
3390 let target = model.navigation_target(navigation, PAGE, rows, &columns);
3391 let expected = reference.navigate(navigation, PAGE);
3392 assert_eq!(
3393 target.as_ref().and_then(|cell| cell.row().copied()),
3394 expected,
3395 "{context}"
3396 );
3397 if let Some(target) = target {
3398 let edit = gesture.edit(&SelectionGestureContext::new(
3399 GestureInput::Keyboard,
3400 Modifiers::default(),
3401 PLATFORM,
3402 extending,
3403 model.is_selected(&target),
3404 mode,
3405 ));
3406 let key = *target.row().expect("a row");
3407 model.apply(edit, target, rows, &columns);
3408 reference.apply(edit, key);
3409 }
3410 }
3411 3 => {
3412 let toggled = model.toggle_focused(rows, &columns);
3413 let focus = reference
3414 .focus
3415 .filter(|key| reference.position(*key).is_some());
3416 assert_eq!(toggled, focus.is_some(), "{context}");
3417 if let Some(key) = focus {
3418 let edit = if reference.single {
3419 SelectionEdit::Replace
3420 } else {
3421 SelectionEdit::Toggle
3422 };
3423 reference.apply(edit, key);
3424 }
3425 }
3426 4 => {
3427 if model.select_all(rows, &columns) {
3428 reference.selected = live.iter().copied().collect();
3429 }
3430 }
3431 _ => {
3432 model.clear();
3433 reference.selected.clear();
3434 }
3435 }
3436
3437 let selected: HashSet<u32> = model.selection().iter().copied().collect();
3440 assert_eq!(selected, reference.selected, "{context}");
3441 let scoped = ProjectionScope.resolve(&SelectionScopeContext::new(
3443 model.selection(),
3444 &world.projection,
3445 &world.snapshot,
3446 mode,
3447 ));
3448 let expected: Vec<u32> = reference
3449 .live_keys()
3450 .into_iter()
3451 .filter(|key| reference.selected.contains(key))
3452 .collect();
3453 assert_eq!(scoped.keys(), expected, "{context}");
3454 let focus = model.focus().and_then(|cell| cell.row().copied());
3456 assert_eq!(focus, reference.focus, "{context}");
3457 if let Some(key) = focus {
3458 assert!(world.rows().display_ix(&key).is_some(), "{context}");
3459 }
3460 assert_eq!(
3461 model.anchor.as_ref().and_then(|cell| cell.row().copied()),
3462 reference.anchor,
3463 "{context}"
3464 );
3465 }
3466 }
3467 }
3468}