1use 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#[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: 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 pub(crate) fn with_menu_open(mut self, menu_open: bool) -> Self {
64 self.menu_open = menu_open;
65 self
66 }
67
68 pub(crate) fn with_tooltip_shown(mut self, tooltip_shown: bool) -> Self {
70 self.tooltip_shown = tooltip_shown;
71 self
72 }
73
74 pub(crate) fn with_editing(mut self, editing: bool) -> Self {
76 self.editing = editing;
77 self
78 }
79
80 pub(crate) fn with_pending_edits(mut self, pending_edits: bool) -> Self {
82 self.pending_edits = pending_edits;
83 self
84 }
85
86 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 pub(crate) fn with_drag_over(mut self, drag_over: bool) -> Self {
94 self.drag_over = drag_over;
95 self
96 }
97
98 pub fn now(&self) -> Instant {
100 self.now
101 }
102
103 pub fn held_since(&self) -> Instant {
105 self.held_since
106 }
107
108 pub fn is_pointer_inside(&self) -> bool {
110 self.pointer_inside
111 }
112
113 pub fn is_user_action(&self) -> bool {
116 self.user_action
117 }
118
119 pub fn is_menu_open(&self) -> bool {
123 self.menu_open
124 }
125
126 pub fn is_tooltip_shown(&self) -> bool {
131 self.tooltip_shown
132 }
133
134 pub fn is_editing(&self) -> bool {
138 self.editing
139 }
140
141 pub fn has_pending_edits(&self) -> bool {
145 self.pending_edits
146 }
147
148 pub fn is_drag_over(&self) -> bool {
151 self.drag_over
152 }
153
154 pub fn is_column_chooser_open(&self) -> bool {
157 self.column_chooser_open
158 }
159}
160
161#[derive(Clone, Copy, Debug, PartialEq, Eq)]
163pub enum ReorderDecision {
164 Apply,
166 HoldUntil(Instant),
168 Hold,
171}
172
173pub trait ReorderPolicy: 'static {
184 fn decide(&self, context: &ReorderContext) -> ReorderDecision;
188}
189
190#[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#[derive(Clone, Copy, Debug)]
209pub struct HoldReorder {
210 max: Duration,
211}
212
213impl HoldReorder {
214 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 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#[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
264pub trait TaskRunner: 'static {
270 fn run(&self, job: Box<dyn FnOnce() + Send>, cx: &App) -> Task<()>;
272}
273
274#[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#[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
295pub 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 pub fn zone(&self) -> ColumnZone {
320 self.zone
321 }
322
323 pub fn columns(&self) -> &'a [ColumnIx] {
325 self.columns
326 }
327
328 pub fn is_visible(&self, column: ColumnIx) -> bool {
330 self.visible.contains(column)
331 }
332
333 pub fn bands(&self, column: ColumnIx) -> &'a [&'static str] {
335 self.bands.get(column.get()).map_or(&[], |bands| bands)
336 }
337}
338
339pub 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 pub fn columns(&self) -> &[ColumnIx] {
363 self.order
364 }
365
366 pub fn zone(&self, column: ColumnIx) -> ColumnZone {
368 self.zones.get(column.get()).copied().unwrap_or_default()
369 }
370
371 pub fn bands(&self, column: ColumnIx) -> &'a [&'static str] {
373 self.bands.get(column.get()).map_or(&[], |bands| bands)
374 }
375
376 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 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
401pub trait ColumnMovePolicy: 'static {
408 fn is_allowed(&self, context: &ColumnMoveContext<'_>, block: Range<usize>, gap: usize) -> bool;
411
412 fn zone_block(&self, context: &ColumnMoveContext<'_>, column: ColumnIx) -> Range<usize>;
415
416 fn normalize(&self, _order: &mut ColumnOrder<'_>) {}
419}
420
421#[derive(Clone, Copy, Debug, Default)]
425pub struct BandedMove;
426
427#[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
441fn 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 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 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 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
522fn 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#[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
563pub struct AutofitContext<'a> {
566 header_width: Pixels,
567 pinned_width: Pixels,
568 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 pub(crate) fn with_pinned_width(mut self, width: Pixels) -> Self {
594 self.pinned_width = width;
595 self
596 }
597
598 pub fn header_width(&self) -> Pixels {
601 self.header_width
602 }
603
604 pub fn pinned_width(&self) -> Pixels {
607 self.pinned_width
608 }
609
610 pub(crate) fn with_summary_width(mut self, width: Pixels) -> Self {
613 self.summary_width = width;
614 self
615 }
616
617 pub fn summary_width(&self) -> Pixels {
623 self.summary_width
624 }
625
626 pub fn painted_rows(&self) -> Range<usize> {
628 self.painted_rows.clone()
629 }
630
631 pub fn row_count(&self) -> usize {
633 self.row_count
634 }
635
636 pub fn measure_row(&mut self, display_ix: usize) -> Option<Pixels> {
639 (self.measure)(display_ix)
640 }
641}
642
643pub trait AutofitPolicy: 'static {
649 fn content_width(&self, context: &mut AutofitContext<'_>) -> Pixels;
651}
652
653#[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#[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 pub fn sort(&self) -> &'a [(ColumnIx, SortDirection)] {
695 self.sort
696 }
697
698 pub fn column(&self) -> ColumnIx {
700 self.column
701 }
702
703 pub fn modifiers(&self) -> Modifiers {
705 self.modifiers
706 }
707
708 pub fn direction(&self) -> Option<SortDirection> {
710 self.sort
711 .iter()
712 .find(|(column, _)| *column == self.column)
713 .map(|(_, direction)| *direction)
714 }
715}
716
717pub trait SortCycle: 'static {
726 fn next_sort(&self, context: &SortCycleContext<'_>) -> Vec<(ColumnIx, SortDirection)>;
729}
730
731#[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
769pub 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 pub fn selection(&self) -> &'a GridSelection<R::Key> {
794 self.selection
795 }
796
797 pub fn projection(&self) -> &'a Projection {
799 self.projection
800 }
801
802 pub fn snapshot(&self) -> &'a StoreSnapshot<R> {
804 self.snapshot
805 }
806
807 pub fn mode(&self) -> SelectionMode {
809 self.mode
810 }
811}
812
813pub trait SelectionScope<R: GridRow>: 'static {
820 fn resolve(&self, context: &SelectionScopeContext<'_, R>) -> ScopedSelection<R::Key>;
822}
823
824#[derive(Clone, Copy, Debug, Default)]
828pub struct ProjectionScope;
829
830fn 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#[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#[non_exhaustive]
904pub enum SelectableLine<'a, R: GridRow> {
905 Row {
907 row: &'a R,
909 branch: Option<Branch>,
911 },
912 Caption {
914 group: GroupInfo<'a>,
916 },
917}
918
919pub struct LineScopeContext<'a, R: GridRow> {
923 line: SelectableLine<'a, R>,
924 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 pub fn line(&self) -> &SelectableLine<'a, R> {
950 &self.line
951 }
952
953 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 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 pub fn projection(&self) -> &'a Projection {
980 self.projection
981 }
982
983 pub fn snapshot(&self) -> &'a StoreSnapshot<R> {
985 self.snapshot
986 }
987
988 pub fn mode(&self) -> SelectionMode {
990 self.mode
991 }
992}
993
994pub trait SelectionPolicy<R: GridRow>: 'static {
1009 fn is_selectable(&self, line: &SelectableLine<'_, R>) -> bool;
1012
1013 fn line_scope(&self, context: &LineScopeContext<'_, R>) -> Option<ScopedSelection<R::Key>>;
1016}
1017
1018#[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#[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1095#[non_exhaustive]
1096pub enum GestureInput {
1097 Keyboard,
1099 Pointer,
1101 ContextPointer,
1104}
1105
1106#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1108#[non_exhaustive]
1109pub enum SelectionEdit {
1110 Replace,
1112 Extend,
1114 AddRange,
1116 Toggle,
1118 Keep,
1120}
1121
1122#[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 pub fn input(&self) -> GestureInput {
1154 self.input
1155 }
1156
1157 pub fn modifiers(&self) -> Modifiers {
1159 self.modifiers
1160 }
1161
1162 pub fn platform_info(&self) -> PlatformInfo {
1165 self.platform
1166 }
1167
1168 pub fn is_extending(&self) -> bool {
1170 self.extending
1171 }
1172
1173 pub fn is_target_selected(&self) -> bool {
1176 self.target_selected
1177 }
1178
1179 pub fn mode(&self) -> SelectionMode {
1181 self.mode
1182 }
1183}
1184
1185pub trait SelectionGesture: 'static {
1194 fn edit(&self, context: &SelectionGestureContext) -> SelectionEdit;
1196}
1197
1198#[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1230#[non_exhaustive]
1231pub enum GridArea {
1232 Body,
1234 Header,
1237}
1238
1239#[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 pub fn button(&self) -> MouseButton {
1268 self.button
1269 }
1270
1271 pub fn modifiers(&self) -> Modifiers {
1273 self.modifiers
1274 }
1275
1276 pub fn platform_info(&self) -> PlatformInfo {
1279 self.platform
1280 }
1281
1282 pub fn click_count(&self) -> usize {
1285 self.click_count
1286 }
1287
1288 pub fn area(&self) -> GridArea {
1290 self.area
1291 }
1292}
1293
1294pub trait ContextMenuGesture: 'static {
1307 fn opens_menu(&self, context: &ContextMenuGestureContext) -> bool;
1309}
1310
1311#[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1332#[non_exhaustive]
1333pub enum ExpandArea {
1334 Chevron,
1336 Caption,
1338 TreeCell,
1340}
1341
1342#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1344#[non_exhaustive]
1345pub enum ExpandEdit {
1346 Toggle,
1348 ToggleDeep,
1350}
1351
1352#[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 pub fn area(&self) -> ExpandArea {
1378 self.area
1379 }
1380
1381 pub fn button(&self) -> MouseButton {
1383 self.button
1384 }
1385
1386 pub fn modifiers(&self) -> Modifiers {
1388 self.modifiers
1389 }
1390
1391 pub fn click_count(&self) -> usize {
1394 self.click_count
1395 }
1396}
1397
1398pub trait ExpandGesture: 'static {
1410 fn edit(&self, context: &ExpandGestureContext) -> Option<ExpandEdit>;
1412}
1413
1414#[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#[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 pub fn input(&self) -> &EditInput {
1459 &self.input
1460 }
1461
1462 pub fn modifiers(&self) -> Modifiers {
1464 self.modifiers
1465 }
1466
1467 pub fn content(&self) -> CellContent {
1470 self.content
1471 }
1472}
1473
1474#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1478#[non_exhaustive]
1479pub enum EditCommitKey {
1480 Enter,
1482 Up,
1484 Down,
1486 Next,
1488 Prev,
1490}
1491
1492#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1494#[non_exhaustive]
1495pub enum AfterCommit {
1496 Stay,
1498 Move(CellMove),
1500 MoveAndEdit(CellMove),
1503}
1504
1505#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1507#[non_exhaustive]
1508pub enum CellMove {
1509 Up,
1511 Down,
1513 Left,
1515 Right,
1517 NextEditable,
1519 PrevEditable,
1521}
1522
1523pub trait EditGesture: 'static {
1530 fn starts_edit(&self, context: &EditGestureContext) -> bool;
1534
1535 fn after_commit(&self, key: EditCommitKey) -> AfterCommit;
1537}
1538
1539#[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#[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 pub fn base(&self) -> &'a OwnedValue {
1592 self.base
1593 }
1594
1595 pub fn current(&self) -> &'a OwnedValue {
1597 self.current
1598 }
1599
1600 pub fn draft(&self) -> Option<&'a OwnedValue> {
1602 self.draft
1603 }
1604
1605 pub fn is_dirty(&self) -> bool {
1607 self.dirty
1608 }
1609}
1610
1611#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1613#[non_exhaustive]
1614pub enum EditEnd {
1615 Commit,
1617 Cancel,
1619}
1620
1621#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1624#[non_exhaustive]
1625pub enum DraftAction {
1626 Keep,
1628 Replace,
1630 Cancel,
1632}
1633
1634pub trait EditPolicy: 'static {
1639 fn on_blur(&self, context: &EditPolicyContext<'_>) -> EditEnd;
1641
1642 fn commit_unchanged(&self) -> bool {
1646 false
1647 }
1648
1649 fn on_value_change(&self, context: &EditPolicyContext<'_>) -> DraftAction;
1651
1652 fn on_hidden(&self, context: &EditPolicyContext<'_>) -> EditEnd;
1655
1656 fn settle_timeout(&self) -> Duration {
1659 Duration::from_secs(5)
1660 }
1661
1662 fn error_mark_timeout(&self) -> Option<Duration> {
1666 None
1667 }
1668}
1669
1670#[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#[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
1720pub 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 pub fn line(&self) -> &SelectableLine<'a, R> {
1757 &self.line
1758 }
1759
1760 pub fn column(&self) -> R::Column {
1763 self.column
1764 }
1765
1766 pub fn was_selected(&self) -> bool {
1768 self.was_selected
1769 }
1770
1771 pub fn modifiers(&self) -> Modifiers {
1773 self.modifiers
1774 }
1775
1776 pub fn platform_info(&self) -> PlatformInfo {
1779 self.platform
1780 }
1781
1782 pub fn mode(&self) -> SelectionMode {
1784 self.mode
1785 }
1786
1787 pub fn click_count(&self) -> usize {
1790 self.click_count
1791 }
1792}
1793
1794fn is_secondary_held(modifiers: Modifiers, platform: PlatformInfo) -> bool {
1797 if platform.is_mac() {
1798 modifiers.platform
1799 } else {
1800 modifiers.control
1801 }
1802}
1803
1804pub trait RowDragGesture<R: GridRow>: 'static {
1811 fn is_drag_press(&self, press: &RowDragPressContext<'_, R>) -> bool;
1813
1814 fn threshold(&self) -> Pixels {
1817 px(10.)
1818 }
1819
1820 fn is_enabled(&self) -> bool {
1823 true
1824 }
1825}
1826
1827#[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#[derive(Clone, Copy, Debug)]
1848pub struct SelectedRowsDrag {
1849 threshold: Pixels,
1850}
1851
1852impl SelectedRowsDrag {
1853 pub fn new() -> Self {
1855 Self { threshold: px(10.) }
1856 }
1857
1858 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#[non_exhaustive]
1891pub enum DropLine<'a, R: GridRow> {
1892 Row {
1894 key: &'a R::Key,
1896 branch: Option<Branch>,
1898 },
1899 Caption(GroupInfo<'a>),
1901 Empty,
1903}
1904
1905pub 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 pub fn line(&self) -> &DropLine<'a, R> {
1950 &self.line
1951 }
1952
1953 pub fn offset(&self) -> f32 {
1956 self.offset
1957 }
1958
1959 pub fn rows(&self) -> Option<&'a RowDrag<R::Key>> {
1962 self.rows
1963 }
1964
1965 pub fn payload<T: 'static>(&self) -> Option<&'a T> {
1967 self.value?.downcast_ref()
1968 }
1969
1970 pub fn is_own(&self) -> bool {
1972 self.own
1973 }
1974
1975 pub fn modifiers(&self) -> Modifiers {
1977 self.modifiers
1978 }
1979
1980 pub fn is_sorted(&self) -> bool {
1983 self.sorted
1984 }
1985
1986 pub fn is_grouped(&self) -> bool {
1988 self.grouped
1989 }
1990
1991 pub fn is_tree(&self) -> bool {
1993 self.tree
1994 }
1995
1996 pub fn last_row(&self) -> Option<&'a R::Key> {
1999 self.last_row
2000 }
2001
2002 pub fn row(&self, key: &R::Key) -> Option<&'a Arc<R>> {
2004 self.snapshot.row(self.snapshot.row_id(key)?)
2005 }
2006}
2007
2008pub trait RowDropPolicy<R: GridRow>: 'static {
2015 fn place(&self, drop: &RowDropContext<'_, R>) -> Option<DropTarget<R::Key>>;
2017
2018 fn is_enabled(&self) -> bool {
2021 true
2022 }
2023
2024 fn is_copy(&self, modifiers: Modifiers) -> bool {
2030 modifiers.alt || modifiers.control
2031 }
2032}
2033
2034#[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#[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#[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 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 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 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 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 assert!(allowed(2..4, 1));
2160 assert!(allowed(2..4, 5));
2161 assert!(!allowed(2..4, 0));
2162 assert!(allowed(1..5, 0));
2164 assert!(allowed(1..5, 6));
2165 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 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 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 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 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 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 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 (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 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 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 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 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 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 assert_eq!(next(&[(ix(1), Descending)], 2, false), [(ix(2), Ascending)]);
2268 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 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 assert_eq!(
2286 next(&multi, 1, true),
2287 [(ix(1), Descending), (ix(2), Ascending), (ix(3), Descending)]
2288 );
2289 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 assert_eq!(resolve(&ProjectionScope, &few), [9, 1]);
2716 assert_eq!(resolve(&ProjectionScope, &many), [9, 7, 3, 1]);
2717 assert!(resolve(&ProjectionScope, &[]).is_empty());
2718 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 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 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 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 assert_eq!(edit(ExpandArea::TreeCell, left, plain, 1), None);
2765 assert_eq!(edit(ExpandArea::TreeCell, left, plain, 2), None);
2766 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 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 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 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 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 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 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 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 assert!(scope(3, &snapshot).is_none());
3017 assert!(scope(7, &snapshot).is_none());
3018 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 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}