use std::{ops::Range, sync::Arc, time::Duration};
use gpui_kit::{App, AppContext as _, Modifiers, MouseButton, Pixels, PlatformInfo, Task, px};
use web_time::Instant;
use crate::{
engine::{Branch, GroupInfo, Projection, SortDirection},
model::{ColumnIx, ColumnSet, GridColumns as _, GridRow, OwnedValue},
state::{
CellContent, ColumnZone, DropPlace, DropTarget, EditInput, GridSelection, RowDrag,
ScopedSelection, SelectionMode,
},
store::StoreSnapshot,
};
#[derive(Clone, Copy, Debug)]
pub struct ReorderContext {
now: Instant,
held_since: Instant,
pointer_inside: bool,
user_action: bool,
menu_open: bool,
tooltip_shown: bool,
editing: bool,
pending_edits: bool,
drag_over: bool,
column_chooser_open: bool,
}
impl ReorderContext {
pub(crate) fn new(
now: Instant,
held_since: Instant,
pointer_inside: bool,
user_action: bool,
) -> Self {
Self {
now,
held_since,
pointer_inside,
user_action,
menu_open: false,
tooltip_shown: false,
editing: false,
pending_edits: false,
drag_over: false,
column_chooser_open: false,
}
}
pub(crate) fn with_menu_open(mut self, menu_open: bool) -> Self {
self.menu_open = menu_open;
self
}
pub(crate) fn with_tooltip_shown(mut self, tooltip_shown: bool) -> Self {
self.tooltip_shown = tooltip_shown;
self
}
pub(crate) fn with_editing(mut self, editing: bool) -> Self {
self.editing = editing;
self
}
pub(crate) fn with_pending_edits(mut self, pending_edits: bool) -> Self {
self.pending_edits = pending_edits;
self
}
pub(crate) fn with_column_chooser_open(mut self, column_chooser_open: bool) -> Self {
self.column_chooser_open = column_chooser_open;
self
}
pub(crate) fn with_drag_over(mut self, drag_over: bool) -> Self {
self.drag_over = drag_over;
self
}
pub fn now(&self) -> Instant {
self.now
}
pub fn held_since(&self) -> Instant {
self.held_since
}
pub fn is_pointer_inside(&self) -> bool {
self.pointer_inside
}
pub fn is_user_action(&self) -> bool {
self.user_action
}
pub fn is_menu_open(&self) -> bool {
self.menu_open
}
pub fn is_tooltip_shown(&self) -> bool {
self.tooltip_shown
}
pub fn is_editing(&self) -> bool {
self.editing
}
pub fn has_pending_edits(&self) -> bool {
self.pending_edits
}
pub fn is_drag_over(&self) -> bool {
self.drag_over
}
pub fn is_column_chooser_open(&self) -> bool {
self.column_chooser_open
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReorderDecision {
Apply,
HoldUntil(Instant),
Hold,
}
pub trait ReorderPolicy: 'static {
fn decide(&self, context: &ReorderContext) -> ReorderDecision;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct LiveReorder;
impl ReorderPolicy for LiveReorder {
fn decide(&self, context: &ReorderContext) -> ReorderDecision {
if (context.is_menu_open() || context.is_editing()) && !context.is_user_action() {
ReorderDecision::Hold
} else {
ReorderDecision::Apply
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct HoldReorder {
max: Duration,
}
impl HoldReorder {
pub fn new(max: Duration) -> Self {
Self { max }
}
}
impl Default for HoldReorder {
fn default() -> Self {
Self::new(Duration::from_secs(3))
}
}
impl ReorderPolicy for HoldReorder {
fn decide(&self, context: &ReorderContext) -> ReorderDecision {
if context.is_user_action() {
return ReorderDecision::Apply;
}
if context.is_menu_open() || context.is_editing() {
return ReorderDecision::Hold;
}
if !context.is_pointer_inside() {
return ReorderDecision::Apply;
}
let deadline = context.held_since() + self.max;
if context.now() >= deadline {
ReorderDecision::Apply
} else {
ReorderDecision::HoldUntil(deadline)
}
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct ManualReorder;
impl ReorderPolicy for ManualReorder {
fn decide(&self, context: &ReorderContext) -> ReorderDecision {
if context.is_user_action() {
ReorderDecision::Apply
} else {
ReorderDecision::Hold
}
}
}
pub trait TaskRunner: 'static {
fn run(&self, job: Box<dyn FnOnce() + Send>, cx: &App) -> Task<()>;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct BackgroundRunner;
impl TaskRunner for BackgroundRunner {
fn run(&self, job: Box<dyn FnOnce() + Send>, cx: &App) -> Task<()> {
cx.background_spawn(async move { job() })
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct InlineRunner;
impl TaskRunner for InlineRunner {
fn run(&self, job: Box<dyn FnOnce() + Send>, _: &App) -> Task<()> {
job();
Task::ready(())
}
}
pub struct ColumnMoveContext<'a> {
zone: ColumnZone,
columns: &'a [ColumnIx],
visible: ColumnSet,
bands: &'a [Box<[&'static str]>],
}
impl<'a> ColumnMoveContext<'a> {
pub(crate) fn new(
zone: ColumnZone,
columns: &'a [ColumnIx],
visible: ColumnSet,
bands: &'a [Box<[&'static str]>],
) -> Self {
Self {
zone,
columns,
visible,
bands,
}
}
pub fn zone(&self) -> ColumnZone {
self.zone
}
pub fn columns(&self) -> &'a [ColumnIx] {
self.columns
}
pub fn is_visible(&self, column: ColumnIx) -> bool {
self.visible.contains(column)
}
pub fn bands(&self, column: ColumnIx) -> &'a [&'static str] {
self.bands.get(column.get()).map_or(&[], |bands| bands)
}
}
pub struct ColumnOrder<'a> {
order: &'a mut Vec<ColumnIx>,
zones: &'a mut [ColumnZone],
bands: &'a [Box<[&'static str]>],
}
impl<'a> ColumnOrder<'a> {
pub(crate) fn new(
order: &'a mut Vec<ColumnIx>,
zones: &'a mut [ColumnZone],
bands: &'a [Box<[&'static str]>],
) -> Self {
Self {
order,
zones,
bands,
}
}
pub fn columns(&self) -> &[ColumnIx] {
self.order
}
pub fn zone(&self, column: ColumnIx) -> ColumnZone {
self.zones.get(column.get()).copied().unwrap_or_default()
}
pub fn bands(&self, column: ColumnIx) -> &'a [&'static str] {
self.bands.get(column.get()).map_or(&[], |bands| bands)
}
pub fn set_zone(&mut self, column: ColumnIx, zone: ColumnZone) {
if let Some(slot) = self.zones.get_mut(column.get()) {
*slot = zone;
}
}
pub fn reorder(&mut self, columns: &[ColumnIx]) -> bool {
let set = |columns: &[ColumnIx]| {
columns.iter().fold(ColumnSet::EMPTY, |mut set, column| {
set.insert(*column);
set
})
};
if columns.len() != self.order.len() || set(columns) != set(self.order) {
return false;
}
self.order.clear();
self.order.extend_from_slice(columns);
true
}
}
pub trait ColumnMovePolicy: 'static {
fn is_allowed(&self, context: &ColumnMoveContext<'_>, block: Range<usize>, gap: usize) -> bool;
fn zone_block(&self, context: &ColumnMoveContext<'_>, column: ColumnIx) -> Range<usize>;
fn normalize(&self, _order: &mut ColumnOrder<'_>) {}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct BandedMove;
#[derive(Clone, Copy, PartialEq, Eq)]
enum BandChild {
Band(&'static str),
Column(ColumnIx),
}
fn band_child(context: &ColumnMoveContext<'_>, column: ColumnIx, level: usize) -> BandChild {
match context.bands(column).get(level) {
Some(band) => BandChild::Band(band),
None => BandChild::Column(column),
}
}
fn band_span(
context: &ColumnMoveContext<'_>,
level: usize,
band: &'static str,
) -> Option<Range<usize>> {
let columns = context.columns();
let is_member = |column: &ColumnIx| context.bands(*column).get(level) == Some(&band);
let start = columns.iter().position(is_member)?;
let end = columns.iter().rposition(is_member)? + 1;
Some(start..end)
}
impl ColumnMovePolicy for BandedMove {
fn is_allowed(&self, context: &ColumnMoveContext<'_>, block: Range<usize>, gap: usize) -> bool {
let columns = context.columns();
if block.is_empty() || block.end > columns.len() || gap > columns.len() {
return false;
}
let mut common = context.bands(columns[block.start]);
for column in &columns[block.clone()] {
let bands = context.bands(*column);
let shared = common.iter().zip(bands).take_while(|(a, b)| a == b).count();
common = &common[..shared];
}
while let Some((&deepest, outer)) = common.split_last()
&& band_span(context, outer.len(), deepest)
.is_some_and(|span| block.start <= span.start && span.end <= block.end)
{
common = outer;
}
let level = common.len();
let parent = match common.last() {
Some(&band) => match band_span(context, level - 1, band) {
Some(span) => span,
None => return false,
},
None => 0..columns.len(),
};
if gap < parent.start || gap > parent.end {
return false;
}
gap == parent.start
|| gap == parent.end
|| band_child(context, columns[gap - 1], level)
!= band_child(context, columns[gap], level)
}
fn zone_block(&self, context: &ColumnMoveContext<'_>, column: ColumnIx) -> Range<usize> {
let columns = context.columns();
let Some(position) = columns.iter().position(|c| *c == column) else {
return 0..0;
};
match context.bands(column).first() {
Some(&top) => band_span(context, 0, top).unwrap_or(position..position + 1),
None => position..position + 1,
}
}
fn normalize(&self, order: &mut ColumnOrder<'_>) {
let columns = order.columns().to_vec();
let mut zones: Vec<(&'static str, ColumnZone)> = Vec::new();
for &column in &columns {
let Some(&top) = order.bands(column).first() else {
continue;
};
match zones.iter().find(|(band, _)| *band == top) {
Some(&(_, zone)) => order.set_zone(column, zone),
None => zones.push((top, order.zone(column))),
}
}
let gathered = gather(&columns, 0, order);
order.reorder(&gathered);
}
}
fn gather(columns: &[ColumnIx], level: usize, order: &ColumnOrder<'_>) -> Vec<ColumnIx> {
let mut groups: Vec<(Option<&'static str>, Vec<ColumnIx>)> = Vec::new();
for &column in columns {
match order.bands(column).get(level) {
Some(&band) => match groups.iter_mut().find(|(key, _)| *key == Some(band)) {
Some((_, members)) => members.push(column),
None => groups.push((Some(band), vec![column])),
},
None => groups.push((None, vec![column])),
}
}
groups
.into_iter()
.flat_map(|(key, members)| match key {
Some(_) => gather(&members, level + 1, order),
None => members,
})
.collect()
}
#[derive(Clone, Copy, Debug, Default)]
pub struct FreeMove;
impl ColumnMovePolicy for FreeMove {
fn is_allowed(&self, context: &ColumnMoveContext<'_>, block: Range<usize>, gap: usize) -> bool {
!block.is_empty() && block.end <= context.columns().len() && gap <= context.columns().len()
}
fn zone_block(&self, context: &ColumnMoveContext<'_>, column: ColumnIx) -> Range<usize> {
context
.columns()
.iter()
.position(|c| *c == column)
.map_or(0..0, |position| position..position + 1)
}
}
pub struct AutofitContext<'a> {
header_width: Pixels,
pinned_width: Pixels,
summary_width: Pixels,
painted_rows: Range<usize>,
row_count: usize,
measure: &'a mut dyn FnMut(usize) -> Option<Pixels>,
}
impl<'a> AutofitContext<'a> {
pub(crate) fn new(
header_width: Pixels,
painted_rows: Range<usize>,
row_count: usize,
measure: &'a mut dyn FnMut(usize) -> Option<Pixels>,
) -> Self {
Self {
header_width,
pinned_width: Pixels::ZERO,
summary_width: Pixels::ZERO,
painted_rows,
row_count,
measure,
}
}
pub(crate) fn with_pinned_width(mut self, width: Pixels) -> Self {
self.pinned_width = width;
self
}
pub fn header_width(&self) -> Pixels {
self.header_width
}
pub fn pinned_width(&self) -> Pixels {
self.pinned_width
}
pub(crate) fn with_summary_width(mut self, width: Pixels) -> Self {
self.summary_width = width;
self
}
pub fn summary_width(&self) -> Pixels {
self.summary_width
}
pub fn painted_rows(&self) -> Range<usize> {
self.painted_rows.clone()
}
pub fn row_count(&self) -> usize {
self.row_count
}
pub fn measure_row(&mut self, display_ix: usize) -> Option<Pixels> {
(self.measure)(display_ix)
}
}
pub trait AutofitPolicy: 'static {
fn content_width(&self, context: &mut AutofitContext<'_>) -> Pixels;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct VisibleRowsAutofit;
impl AutofitPolicy for VisibleRowsAutofit {
fn content_width(&self, context: &mut AutofitContext<'_>) -> Pixels {
let floor = context
.header_width()
.max(context.pinned_width())
.max(context.summary_width());
context
.painted_rows()
.filter_map(|display_ix| context.measure_row(display_ix))
.fold(floor, |widest, width| widest.max(width))
}
}
#[derive(Clone, Copy, Debug)]
pub struct SortCycleContext<'a> {
sort: &'a [(ColumnIx, SortDirection)],
column: ColumnIx,
modifiers: Modifiers,
}
impl<'a> SortCycleContext<'a> {
pub(crate) fn new(
sort: &'a [(ColumnIx, SortDirection)],
column: ColumnIx,
modifiers: Modifiers,
) -> Self {
Self {
sort,
column,
modifiers,
}
}
pub fn sort(&self) -> &'a [(ColumnIx, SortDirection)] {
self.sort
}
pub fn column(&self) -> ColumnIx {
self.column
}
pub fn modifiers(&self) -> Modifiers {
self.modifiers
}
pub fn direction(&self) -> Option<SortDirection> {
self.sort
.iter()
.find(|(column, _)| *column == self.column)
.map(|(_, direction)| *direction)
}
}
pub trait SortCycle: 'static {
fn next_sort(&self, context: &SortCycleContext<'_>) -> Vec<(ColumnIx, SortDirection)>;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct StandardSortCycle;
impl SortCycle for StandardSortCycle {
fn next_sort(&self, context: &SortCycleContext<'_>) -> Vec<(ColumnIx, SortDirection)> {
let column = context.column();
let direction = context.direction();
if !context.modifiers().shift {
return match direction {
None => vec![(column, SortDirection::Ascending)],
Some(SortDirection::Ascending) => vec![(column, SortDirection::Descending)],
Some(SortDirection::Descending) => Vec::new(),
};
}
let mut sort = context.sort().to_vec();
match direction {
None => sort.push((column, SortDirection::Ascending)),
Some(SortDirection::Ascending) => {
for (sorted, direction) in &mut sort {
if *sorted == column {
*direction = SortDirection::Descending;
}
}
}
Some(SortDirection::Descending) => sort.retain(|(sorted, _)| *sorted != column),
}
sort
}
}
pub struct SelectionScopeContext<'a, R: GridRow> {
selection: &'a GridSelection<R::Key>,
projection: &'a Projection,
snapshot: &'a StoreSnapshot<R>,
mode: SelectionMode,
}
impl<'a, R: GridRow> SelectionScopeContext<'a, R> {
pub(crate) fn new(
selection: &'a GridSelection<R::Key>,
projection: &'a Projection,
snapshot: &'a StoreSnapshot<R>,
mode: SelectionMode,
) -> Self {
Self {
selection,
projection,
snapshot,
mode,
}
}
pub fn selection(&self) -> &'a GridSelection<R::Key> {
self.selection
}
pub fn projection(&self) -> &'a Projection {
self.projection
}
pub fn snapshot(&self) -> &'a StoreSnapshot<R> {
self.snapshot
}
pub fn mode(&self) -> SelectionMode {
self.mode
}
}
pub trait SelectionScope<R: GridRow>: 'static {
fn resolve(&self, context: &SelectionScopeContext<'_, R>) -> ScopedSelection<R::Key>;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct ProjectionScope;
fn shown_selection<R: GridRow>(context: &SelectionScopeContext<'_, R>) -> Vec<(R::Key, ColumnSet)> {
let (selection, projection, snapshot) = (
context.selection(),
context.projection(),
context.snapshot(),
);
if selection.is_empty() {
return Vec::new();
}
if selection.len() > projection.rows().len() / 8 {
return projection
.rows()
.iter()
.filter_map(|id| snapshot.row(*id))
.filter_map(|row| {
let columns = selection.columns(row.key());
(!columns.is_empty()).then(|| (row.key().clone(), columns))
})
.collect();
}
let mut shown: Vec<(usize, R::Key, ColumnSet)> = selection
.iter()
.filter_map(|key| {
let order_ix = projection.order_ix(snapshot.row_id(key)?)?;
Some((order_ix, key.clone(), selection.columns(key)))
})
.collect();
shown.sort_unstable_by_key(|(order_ix, _, _)| *order_ix);
shown
.into_iter()
.map(|(_, key, columns)| (key, columns))
.collect()
}
impl<R: GridRow> SelectionScope<R> for ProjectionScope {
fn resolve(&self, context: &SelectionScopeContext<'_, R>) -> ScopedSelection<R::Key> {
shown_selection(context).into_iter().collect()
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct StoreScope;
impl<R: GridRow> SelectionScope<R> for StoreScope {
fn resolve(&self, context: &SelectionScopeContext<'_, R>) -> ScopedSelection<R::Key> {
let (selection, projection, snapshot) = (
context.selection(),
context.projection(),
context.snapshot(),
);
let mut hidden: Vec<(u64, R::Key, ColumnSet)> = selection
.iter()
.filter_map(|key| {
let id = snapshot.row_id(key)?;
(!projection.contains(id))
.then(|| (snapshot.seq(id), key.clone(), selection.columns(key)))
})
.collect();
hidden.sort_unstable_by_key(|(seq, _, _)| *seq);
shown_selection(context)
.into_iter()
.chain(hidden.into_iter().map(|(_, key, columns)| (key, columns)))
.collect()
}
}
#[non_exhaustive]
pub enum SelectableLine<'a, R: GridRow> {
Row {
row: &'a R,
branch: Option<Branch>,
},
Caption {
group: GroupInfo<'a>,
},
}
pub struct LineScopeContext<'a, R: GridRow> {
line: SelectableLine<'a, R>,
under: Range<usize>,
projection: &'a Projection,
snapshot: &'a StoreSnapshot<R>,
mode: SelectionMode,
}
impl<'a, R: GridRow> LineScopeContext<'a, R> {
pub(crate) fn new(
line: SelectableLine<'a, R>,
under: Range<usize>,
projection: &'a Projection,
snapshot: &'a StoreSnapshot<R>,
mode: SelectionMode,
) -> Self {
Self {
line,
under,
projection,
snapshot,
mode,
}
}
pub fn line(&self) -> &SelectableLine<'a, R> {
&self.line
}
pub fn rows(&self) -> impl Iterator<Item = &'a Arc<R>> + 'a {
let snapshot = self.snapshot;
self.projection.rows()[self.under.clone()]
.iter()
.filter_map(move |id| snapshot.row(*id))
}
pub fn lines(&self) -> impl Iterator<Item = SelectableLine<'a, R>> + 'a {
let (projection, snapshot) = (self.projection, self.snapshot);
projection.rows()[self.under.clone()]
.iter()
.filter_map(move |id| {
Some(SelectableLine::Row {
row: &**snapshot.row(*id)?,
branch: projection.branch(*id),
})
})
}
pub fn projection(&self) -> &'a Projection {
self.projection
}
pub fn snapshot(&self) -> &'a StoreSnapshot<R> {
self.snapshot
}
pub fn mode(&self) -> SelectionMode {
self.mode
}
}
pub trait SelectionPolicy<R: GridRow>: 'static {
fn is_selectable(&self, line: &SelectableLine<'_, R>) -> bool;
fn line_scope(&self, context: &LineScopeContext<'_, R>) -> Option<ScopedSelection<R::Key>>;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct FocusCaptions;
impl<R: GridRow> SelectionPolicy<R> for FocusCaptions {
fn is_selectable(&self, line: &SelectableLine<'_, R>) -> bool {
match line {
SelectableLine::Row { .. } => true,
SelectableLine::Caption { .. } => false,
}
}
fn line_scope(&self, context: &LineScopeContext<'_, R>) -> Option<ScopedSelection<R::Key>> {
match context.line() {
SelectableLine::Caption { .. } => {
let columns = ColumnSet::first(R::Column::all().len());
Some(
context
.rows()
.map(|row| (row.key().clone(), columns))
.collect(),
)
}
SelectableLine::Row { .. } => None,
}
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct FocusBranches;
impl<R: GridRow> SelectionPolicy<R> for FocusBranches {
fn is_selectable(&self, line: &SelectableLine<'_, R>) -> bool {
match line {
SelectableLine::Row { branch, .. } => branch.is_none(),
SelectableLine::Caption { .. } => false,
}
}
fn line_scope(&self, context: &LineScopeContext<'_, R>) -> Option<ScopedSelection<R::Key>> {
match context.line() {
SelectableLine::Row {
branch: Some(_), ..
} => {
let columns = ColumnSet::first(R::Column::all().len());
Some(
context
.lines()
.filter_map(|line| match line {
SelectableLine::Row { row, branch: None } => {
Some((row.key().clone(), columns))
}
_ => None,
})
.collect(),
)
}
_ => FocusCaptions.line_scope(context),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum GestureInput {
Keyboard,
Pointer,
ContextPointer,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum SelectionEdit {
Replace,
Extend,
AddRange,
Toggle,
Keep,
}
#[derive(Clone, Copy, Debug)]
pub struct SelectionGestureContext {
input: GestureInput,
modifiers: Modifiers,
platform: PlatformInfo,
extending: bool,
target_selected: bool,
mode: SelectionMode,
}
impl SelectionGestureContext {
pub(crate) fn new(
input: GestureInput,
modifiers: Modifiers,
platform: PlatformInfo,
extending: bool,
target_selected: bool,
mode: SelectionMode,
) -> Self {
Self {
input,
modifiers,
platform,
extending,
target_selected,
mode,
}
}
pub fn input(&self) -> GestureInput {
self.input
}
pub fn modifiers(&self) -> Modifiers {
self.modifiers
}
pub fn platform_info(&self) -> PlatformInfo {
self.platform
}
pub fn is_extending(&self) -> bool {
self.extending
}
pub fn is_target_selected(&self) -> bool {
self.target_selected
}
pub fn mode(&self) -> SelectionMode {
self.mode
}
}
pub trait SelectionGesture: 'static {
fn edit(&self, context: &SelectionGestureContext) -> SelectionEdit;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct StandardSelectionGesture;
impl SelectionGesture for StandardSelectionGesture {
fn edit(&self, context: &SelectionGestureContext) -> SelectionEdit {
let modifiers = context.modifiers();
match context.input() {
GestureInput::Pointer => match (
modifiers.shift,
is_secondary_held(modifiers, context.platform_info()),
) {
(true, true) => SelectionEdit::AddRange,
(true, false) => SelectionEdit::Extend,
(false, true) => SelectionEdit::Toggle,
(false, false) => SelectionEdit::Replace,
},
GestureInput::ContextPointer if context.is_target_selected() => SelectionEdit::Keep,
GestureInput::ContextPointer => SelectionEdit::Replace,
GestureInput::Keyboard if context.is_extending() => SelectionEdit::Extend,
GestureInput::Keyboard => SelectionEdit::Replace,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum GridArea {
Body,
Header,
}
#[derive(Clone, Copy, Debug)]
pub struct ContextMenuGestureContext {
button: MouseButton,
modifiers: Modifiers,
platform: PlatformInfo,
click_count: usize,
area: GridArea,
}
impl ContextMenuGestureContext {
pub(crate) fn new(
button: MouseButton,
modifiers: Modifiers,
platform: PlatformInfo,
click_count: usize,
area: GridArea,
) -> Self {
Self {
button,
modifiers,
platform,
click_count,
area,
}
}
pub fn button(&self) -> MouseButton {
self.button
}
pub fn modifiers(&self) -> Modifiers {
self.modifiers
}
pub fn platform_info(&self) -> PlatformInfo {
self.platform
}
pub fn click_count(&self) -> usize {
self.click_count
}
pub fn area(&self) -> GridArea {
self.area
}
}
pub trait ContextMenuGesture: 'static {
fn opens_menu(&self, context: &ContextMenuGestureContext) -> bool;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct StandardContextMenuGesture;
impl ContextMenuGesture for StandardContextMenuGesture {
fn opens_menu(&self, context: &ContextMenuGestureContext) -> bool {
let (button, modifiers) = (context.button(), context.modifiers());
button == MouseButton::Right
|| (context.platform_info().is_mac()
&& button == MouseButton::Left
&& modifiers.control
&& !modifiers.platform)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ExpandArea {
Chevron,
Caption,
TreeCell,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ExpandEdit {
Toggle,
ToggleDeep,
}
#[derive(Clone, Copy, Debug)]
pub struct ExpandGestureContext {
area: ExpandArea,
button: MouseButton,
modifiers: Modifiers,
click_count: usize,
}
impl ExpandGestureContext {
pub(crate) fn new(
area: ExpandArea,
button: MouseButton,
modifiers: Modifiers,
click_count: usize,
) -> Self {
Self {
area,
button,
modifiers,
click_count,
}
}
pub fn area(&self) -> ExpandArea {
self.area
}
pub fn button(&self) -> MouseButton {
self.button
}
pub fn modifiers(&self) -> Modifiers {
self.modifiers
}
pub fn click_count(&self) -> usize {
self.click_count
}
}
pub trait ExpandGesture: 'static {
fn edit(&self, context: &ExpandGestureContext) -> Option<ExpandEdit>;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct StandardExpandGesture;
impl ExpandGesture for StandardExpandGesture {
fn edit(&self, context: &ExpandGestureContext) -> Option<ExpandEdit> {
if context.button() != MouseButton::Left {
return None;
}
match (context.area(), context.click_count()) {
(ExpandArea::Chevron, 1) if context.modifiers().alt => Some(ExpandEdit::ToggleDeep),
(ExpandArea::Chevron, 1) | (ExpandArea::Caption, 2) => Some(ExpandEdit::Toggle),
_ => None,
}
}
}
#[derive(Clone, Debug)]
pub struct EditGestureContext {
input: EditInput,
modifiers: Modifiers,
content: CellContent,
}
impl EditGestureContext {
pub(crate) fn new(input: EditInput, modifiers: Modifiers, content: CellContent) -> Self {
Self {
input,
modifiers,
content,
}
}
pub fn input(&self) -> &EditInput {
&self.input
}
pub fn modifiers(&self) -> Modifiers {
self.modifiers
}
pub fn content(&self) -> CellContent {
self.content
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EditCommitKey {
Enter,
Up,
Down,
Next,
Prev,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AfterCommit {
Stay,
Move(CellMove),
MoveAndEdit(CellMove),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CellMove {
Up,
Down,
Left,
Right,
NextEditable,
PrevEditable,
}
pub trait EditGesture: 'static {
fn starts_edit(&self, context: &EditGestureContext) -> bool;
fn after_commit(&self, key: EditCommitKey) -> AfterCommit;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct StandardEditGesture;
impl EditGesture for StandardEditGesture {
fn starts_edit(&self, context: &EditGestureContext) -> bool {
match context.input() {
EditInput::Press { click_count } => {
*click_count >= 2 && context.content() != CellContent::Control
}
_ => true,
}
}
fn after_commit(&self, key: EditCommitKey) -> AfterCommit {
AfterCommit::Move(match key {
EditCommitKey::Enter | EditCommitKey::Down => CellMove::Down,
EditCommitKey::Up => CellMove::Up,
EditCommitKey::Next => CellMove::Right,
EditCommitKey::Prev => CellMove::Left,
})
}
}
#[derive(Clone, Copy, Debug)]
pub struct EditPolicyContext<'a> {
base: &'a OwnedValue,
current: &'a OwnedValue,
draft: Option<&'a OwnedValue>,
dirty: bool,
}
impl<'a> EditPolicyContext<'a> {
pub(crate) fn new(
base: &'a OwnedValue,
current: &'a OwnedValue,
draft: Option<&'a OwnedValue>,
dirty: bool,
) -> Self {
Self {
base,
current,
draft,
dirty,
}
}
pub fn base(&self) -> &'a OwnedValue {
self.base
}
pub fn current(&self) -> &'a OwnedValue {
self.current
}
pub fn draft(&self) -> Option<&'a OwnedValue> {
self.draft
}
pub fn is_dirty(&self) -> bool {
self.dirty
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EditEnd {
Commit,
Cancel,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DraftAction {
Keep,
Replace,
Cancel,
}
pub trait EditPolicy: 'static {
fn on_blur(&self, context: &EditPolicyContext<'_>) -> EditEnd;
fn commit_unchanged(&self) -> bool {
false
}
fn on_value_change(&self, context: &EditPolicyContext<'_>) -> DraftAction;
fn on_hidden(&self, context: &EditPolicyContext<'_>) -> EditEnd;
fn settle_timeout(&self) -> Duration {
Duration::from_secs(5)
}
fn error_mark_timeout(&self) -> Option<Duration> {
None
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct FollowLiveValue;
impl EditPolicy for FollowLiveValue {
fn on_blur(&self, context: &EditPolicyContext<'_>) -> EditEnd {
StandardEditPolicy.on_blur(context)
}
fn on_value_change(&self, context: &EditPolicyContext<'_>) -> DraftAction {
if context.is_dirty() {
DraftAction::Keep
} else {
DraftAction::Replace
}
}
fn on_hidden(&self, context: &EditPolicyContext<'_>) -> EditEnd {
StandardEditPolicy.on_hidden(context)
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct StandardEditPolicy;
impl EditPolicy for StandardEditPolicy {
fn on_blur(&self, context: &EditPolicyContext<'_>) -> EditEnd {
if context.draft().is_some() {
EditEnd::Commit
} else {
EditEnd::Cancel
}
}
fn on_value_change(&self, _: &EditPolicyContext<'_>) -> DraftAction {
DraftAction::Keep
}
fn on_hidden(&self, _: &EditPolicyContext<'_>) -> EditEnd {
EditEnd::Cancel
}
}
pub struct RowDragPressContext<'a, R: GridRow> {
line: SelectableLine<'a, R>,
column: R::Column,
was_selected: bool,
modifiers: Modifiers,
platform: PlatformInfo,
mode: SelectionMode,
click_count: usize,
}
impl<'a, R: GridRow> RowDragPressContext<'a, R> {
pub(crate) fn new(
line: SelectableLine<'a, R>,
column: R::Column,
was_selected: bool,
modifiers: Modifiers,
platform: PlatformInfo,
mode: SelectionMode,
click_count: usize,
) -> Self {
Self {
line,
column,
was_selected,
modifiers,
platform,
mode,
click_count,
}
}
pub fn line(&self) -> &SelectableLine<'a, R> {
&self.line
}
pub fn column(&self) -> R::Column {
self.column
}
pub fn was_selected(&self) -> bool {
self.was_selected
}
pub fn modifiers(&self) -> Modifiers {
self.modifiers
}
pub fn platform_info(&self) -> PlatformInfo {
self.platform
}
pub fn mode(&self) -> SelectionMode {
self.mode
}
pub fn click_count(&self) -> usize {
self.click_count
}
}
fn is_secondary_held(modifiers: Modifiers, platform: PlatformInfo) -> bool {
if platform.is_mac() {
modifiers.platform
} else {
modifiers.control
}
}
pub trait RowDragGesture<R: GridRow>: 'static {
fn is_drag_press(&self, press: &RowDragPressContext<'_, R>) -> bool;
fn threshold(&self) -> Pixels {
px(10.)
}
fn is_enabled(&self) -> bool {
true
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct NoRowDrag;
impl<R: GridRow> RowDragGesture<R> for NoRowDrag {
fn is_drag_press(&self, _: &RowDragPressContext<'_, R>) -> bool {
false
}
fn is_enabled(&self) -> bool {
false
}
}
#[derive(Clone, Copy, Debug)]
pub struct SelectedRowsDrag {
threshold: Pixels,
}
impl SelectedRowsDrag {
pub fn new() -> Self {
Self { threshold: px(10.) }
}
pub fn with_threshold(mut self, threshold: Pixels) -> Self {
self.threshold = threshold;
self
}
}
impl Default for SelectedRowsDrag {
fn default() -> Self {
Self::new()
}
}
impl<R: GridRow> RowDragGesture<R> for SelectedRowsDrag {
fn is_drag_press(&self, press: &RowDragPressContext<'_, R>) -> bool {
let modifiers = press.modifiers();
press.was_selected()
&& press.click_count() == 1
&& !modifiers.shift
&& !is_secondary_held(modifiers, press.platform_info())
&& matches!(press.line(), SelectableLine::Row { .. })
}
fn threshold(&self) -> Pixels {
self.threshold
}
}
#[non_exhaustive]
pub enum DropLine<'a, R: GridRow> {
Row {
key: &'a R::Key,
branch: Option<Branch>,
},
Caption(GroupInfo<'a>),
Empty,
}
pub struct RowDropContext<'a, R: GridRow> {
line: DropLine<'a, R>,
offset: f32,
rows: Option<&'a RowDrag<R::Key>>,
value: Option<&'a dyn std::any::Any>,
own: bool,
modifiers: Modifiers,
sorted: bool,
grouped: bool,
tree: bool,
last_row: Option<&'a R::Key>,
snapshot: &'a crate::store::StoreSnapshot<R>,
}
impl<'a, R: GridRow> RowDropContext<'a, R> {
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
line: DropLine<'a, R>,
offset: f32,
rows: Option<&'a RowDrag<R::Key>>,
value: Option<&'a dyn std::any::Any>,
own: bool,
modifiers: Modifiers,
(sorted, grouped, tree): (bool, bool, bool),
last_row: Option<&'a R::Key>,
snapshot: &'a crate::store::StoreSnapshot<R>,
) -> Self {
Self {
line,
offset,
rows,
value,
own,
modifiers,
sorted,
grouped,
tree,
last_row,
snapshot,
}
}
pub fn line(&self) -> &DropLine<'a, R> {
&self.line
}
pub fn offset(&self) -> f32 {
self.offset
}
pub fn rows(&self) -> Option<&'a RowDrag<R::Key>> {
self.rows
}
pub fn payload<T: 'static>(&self) -> Option<&'a T> {
self.value?.downcast_ref()
}
pub fn is_own(&self) -> bool {
self.own
}
pub fn modifiers(&self) -> Modifiers {
self.modifiers
}
pub fn is_sorted(&self) -> bool {
self.sorted
}
pub fn is_grouped(&self) -> bool {
self.grouped
}
pub fn is_tree(&self) -> bool {
self.tree
}
pub fn last_row(&self) -> Option<&'a R::Key> {
self.last_row
}
pub fn row(&self, key: &R::Key) -> Option<&'a Arc<R>> {
self.snapshot.row(self.snapshot.row_id(key)?)
}
}
pub trait RowDropPolicy<R: GridRow>: 'static {
fn place(&self, drop: &RowDropContext<'_, R>) -> Option<DropTarget<R::Key>>;
fn is_enabled(&self) -> bool {
true
}
fn is_copy(&self, modifiers: Modifiers) -> bool {
modifiers.alt || modifiers.control
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct NoRowDrop;
impl<R: GridRow> RowDropPolicy<R> for NoRowDrop {
fn place(&self, _: &RowDropContext<'_, R>) -> Option<DropTarget<R::Key>> {
None
}
fn is_enabled(&self) -> bool {
false
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct DropOnRows;
impl<R: GridRow> RowDropPolicy<R> for DropOnRows {
fn place(&self, drop: &RowDropContext<'_, R>) -> Option<DropTarget<R::Key>> {
Some(match drop.line() {
DropLine::Row { key, .. } => DropTarget::Row {
key: (*key).clone(),
place: DropPlace::Onto,
},
DropLine::Caption(group) => DropTarget::Group(group.path().clone()),
DropLine::Empty => DropTarget::Empty,
})
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct DropBetweenRows;
impl<R: GridRow> RowDropPolicy<R> for DropBetweenRows {
fn place(&self, drop: &RowDropContext<'_, R>) -> Option<DropTarget<R::Key>> {
if drop.is_sorted() && !drop.is_grouped() && !drop.is_tree() {
return None;
}
let row = |key: &R::Key, place| DropTarget::Row {
key: key.clone(),
place,
};
Some(match drop.line() {
DropLine::Row { key, .. } if drop.is_tree() => {
let place = match drop.offset() {
offset if offset < 1. / 3. => DropPlace::Before,
offset if offset < 2. / 3. => DropPlace::Onto,
_ => DropPlace::After,
};
row(key, place)
}
DropLine::Row { key, .. } if drop.offset() < 0.5 => row(key, DropPlace::Before),
DropLine::Row { key, .. } => row(key, DropPlace::After),
DropLine::Caption(group) => DropTarget::Group(group.path().clone()),
DropLine::Empty => match drop.last_row() {
Some(key) => row(key, DropPlace::After),
None => DropTarget::Empty,
},
})
}
}
#[cfg(test)]
mod tests {
use gpui_kit::{OperatingSystem, PlatformTarget, px};
use super::*;
const MAC: PlatformInfo = PlatformInfo {
os: OperatingSystem::Mac,
target: PlatformTarget::Native,
};
const MAC_BROWSER: PlatformInfo = PlatformInfo {
os: OperatingSystem::Mac,
target: PlatformTarget::Web,
};
const LINUX: PlatformInfo = PlatformInfo {
os: OperatingSystem::Linux,
target: PlatformTarget::Native,
};
fn ix(i: u16) -> ColumnIx {
ColumnIx::new(i)
}
fn banded() -> (Vec<ColumnIx>, Vec<Box<[&'static str]>>) {
let columns = (0..6).map(ix).collect();
let bands: Vec<Box<[&'static str]>> = vec![
Box::new([]),
Box::new(["a"]),
Box::new(["a", "b"]),
Box::new(["a", "b"]),
Box::new(["a"]),
Box::new([]),
];
(columns, bands)
}
#[test]
fn test_banded_move_policy() {
let (columns, bands) = banded();
let visible = ColumnSet::first(6);
let context = ColumnMoveContext::new(ColumnZone::Scrolling, &columns, visible, &bands);
let allowed = |block: Range<usize>, gap: usize| BandedMove.is_allowed(&context, block, gap);
assert!(allowed(3..4, 2));
assert!(allowed(2..3, 4));
assert!(!allowed(2..3, 1), "out of B to the left");
assert!(!allowed(2..3, 5), "out of B to the right");
assert!(allowed(1..2, 4));
assert!(allowed(1..2, 5));
assert!(!allowed(1..2, 3), "inside the sibling band B");
assert!(!allowed(1..2, 0), "out of A");
assert!(allowed(2..4, 1));
assert!(allowed(2..4, 5));
assert!(!allowed(2..4, 0));
assert!(allowed(1..5, 0));
assert!(allowed(1..5, 6));
assert!(allowed(0..1, 5));
assert!(allowed(0..1, 6));
assert!(!allowed(0..1, 2));
assert!(!allowed(0..1, 4));
assert_eq!(BandedMove.zone_block(&context, ix(2)), 1..5);
assert_eq!(BandedMove.zone_block(&context, ix(4)), 1..5);
assert_eq!(BandedMove.zone_block(&context, ix(0)), 0..1);
assert_eq!(BandedMove.zone_block(&context, ix(9)), 0..0);
assert!(FreeMove.is_allowed(&context, 0..1, 2));
assert!(FreeMove.is_allowed(&context, 2..3, 6));
assert!(!FreeMove.is_allowed(&context, 2..3, 7));
assert_eq!(FreeMove.zone_block(&context, ix(2)), 2..3);
let mut zones = vec![ColumnZone::Scrolling; 6];
zones[4] = ColumnZone::FrozenRight;
let mut order = vec![ix(2), ix(0), ix(1), ix(3), ix(5), ix(4)];
BandedMove.normalize(&mut ColumnOrder::new(&mut order, &mut zones, &bands));
assert_eq!(order, [2, 3, 1, 4, 0, 5].map(ix));
assert_eq!(zones[4], ColumnZone::Scrolling);
let mut order = vec![ix(5), ix(1), ix(3), ix(2), ix(4), ix(0)];
let before = order.clone();
BandedMove.normalize(&mut ColumnOrder::new(&mut order, &mut zones, &bands));
assert_eq!(order, before);
let mut order = vec![ix(2), ix(0), ix(1), ix(3), ix(5), ix(4)];
FreeMove.normalize(&mut ColumnOrder::new(&mut order, &mut zones, &bands));
assert_eq!(order, [2, 0, 1, 3, 5, 4].map(ix));
let mut order = (0..6).map(ix).collect::<Vec<_>>();
let mut view = ColumnOrder::new(&mut order, &mut zones, &bands);
assert!(!view.reorder(&[ix(0), ix(0), ix(1), ix(2), ix(3), ix(4)]));
assert!(!view.reorder(&[ix(0)]));
assert!(view.reorder(&[5, 4, 3, 2, 1, 0].map(ix)));
assert_eq!(view.columns(), [5, 4, 3, 2, 1, 0].map(ix));
assert_eq!(view.bands(ix(3)), ["a", "b"]);
}
#[test]
fn test_visible_rows_autofit() {
let mut measured = Vec::new();
let mut measure = |display_ix: usize| {
measured.push(display_ix);
(display_ix != 4).then(|| px(display_ix as f32 * 10.))
};
let mut context = AutofitContext::new(px(25.), 3..6, 1_000, &mut measure);
assert_eq!(context.row_count(), 1_000);
assert_eq!(VisibleRowsAutofit.content_width(&mut context), px(50.));
assert_eq!(measured, [3, 4, 5], "rows off screen are not measured");
let mut measure = |_: usize| Some(px(10.));
let mut context = AutofitContext::new(px(80.), 0..3, 3, &mut measure);
assert_eq!(VisibleRowsAutofit.content_width(&mut context), px(80.));
let mut measure = |_: usize| None;
let mut context = AutofitContext::new(px(42.), 0..0, 0, &mut measure);
assert_eq!(context.pinned_width(), px(0.));
assert_eq!(VisibleRowsAutofit.content_width(&mut context), px(42.));
let mut measure = |_: usize| Some(px(30.));
let mut context =
AutofitContext::new(px(20.), 0..3, 3, &mut measure).with_pinned_width(px(64.));
assert_eq!(context.pinned_width(), px(64.));
assert_eq!(VisibleRowsAutofit.content_width(&mut context), px(64.));
let mut measure = |_: usize| Some(px(30.));
let mut context = AutofitContext::new(px(20.), 0..3, 3, &mut measure)
.with_pinned_width(px(64.))
.with_summary_width(px(90.));
assert_eq!(context.summary_width(), px(90.));
assert_eq!(VisibleRowsAutofit.content_width(&mut context), px(90.));
}
#[test]
fn test_standard_sort_cycle() {
use SortDirection::{Ascending, Descending};
let next = |sort: &[(ColumnIx, SortDirection)], column: u16, shift: bool| {
let modifiers = if shift {
Modifiers::shift()
} else {
Modifiers::default()
};
StandardSortCycle.next_sort(&SortCycleContext::new(sort, ix(column), modifiers))
};
assert_eq!(next(&[], 1, false), [(ix(1), Ascending)]);
assert_eq!(next(&[(ix(1), Ascending)], 1, false), [(ix(1), Descending)]);
assert_eq!(next(&[(ix(1), Descending)], 1, false), []);
assert_eq!(next(&[(ix(1), Descending)], 2, false), [(ix(2), Ascending)]);
let multi = [(ix(1), Ascending), (ix(2), Ascending), (ix(3), Descending)];
assert_eq!(next(&multi, 2, false), [(ix(2), Descending)]);
assert_eq!(next(&multi, 3, false), []);
assert_eq!(
next(&multi, 4, true),
[
(ix(1), Ascending),
(ix(2), Ascending),
(ix(3), Descending),
(ix(4), Ascending)
]
);
assert_eq!(
next(&multi, 1, true),
[(ix(1), Descending), (ix(2), Ascending), (ix(3), Descending)]
);
assert_eq!(
next(&[(ix(3), Descending), (ix(1), Ascending)], 3, true),
[(ix(1), Ascending)]
);
assert_eq!(next(&[], 1, true), [(ix(1), Ascending)]);
let context = SortCycleContext::new(&multi, ix(3), Modifiers::shift());
assert_eq!(context.sort(), multi);
assert_eq!(context.column(), ix(3));
assert!(context.modifiers().shift);
assert_eq!(context.direction(), Some(Descending));
}
#[test]
fn test_reorder_policies() {
let start = Instant::now();
let at = |ms: u64| start + Duration::from_millis(ms);
let context =
|now: u64, inside: bool, user: bool| ReorderContext::new(at(now), at(0), inside, user);
assert_eq!(
LiveReorder.decide(&context(0, true, false)),
ReorderDecision::Apply
);
let hold = HoldReorder::new(Duration::from_millis(500));
assert_eq!(
hold.decide(&context(100, true, false)),
ReorderDecision::HoldUntil(at(500))
);
assert_eq!(
hold.decide(&context(500, true, false)),
ReorderDecision::Apply
);
assert_eq!(
hold.decide(&context(100, false, false)),
ReorderDecision::Apply
);
assert_eq!(
hold.decide(&context(100, true, true)),
ReorderDecision::Apply
);
assert_eq!(
ManualReorder.decide(&context(100, false, false)),
ReorderDecision::Hold
);
assert_eq!(
ManualReorder.decide(&context(100, true, true)),
ReorderDecision::Apply
);
let menu =
|now: u64, inside: bool, user: bool| context(now, inside, user).with_menu_open(true);
let policies: [&dyn ReorderPolicy; 3] = [&LiveReorder, &hold, &ManualReorder];
for policy in policies {
for inside in [false, true] {
assert_eq!(
policy.decide(&menu(100, inside, false)),
ReorderDecision::Hold
);
assert_eq!(
policy.decide(&menu(100, inside, true)),
ReorderDecision::Apply
);
}
}
assert_eq!(hold.decide(&menu(900, true, false)), ReorderDecision::Hold);
assert_eq!(
hold.decide(&context(900, true, false)),
ReorderDecision::Apply
);
let tooltip = |now: u64, inside: bool| context(now, inside, false).with_tooltip_shown(true);
assert!(tooltip(0, true).is_tooltip_shown());
assert!(!context(0, true, false).is_tooltip_shown());
assert!(!context(0, true, false).is_menu_open());
assert_eq!(
LiveReorder.decide(&tooltip(100, true)),
ReorderDecision::Apply
);
assert_eq!(
hold.decide(&tooltip(100, true)),
ReorderDecision::HoldUntil(at(500))
);
assert_eq!(hold.decide(&tooltip(100, false)), ReorderDecision::Apply);
assert_eq!(
ManualReorder.decide(&tooltip(100, false)),
ReorderDecision::Hold
);
}
#[test]
fn test_standard_selection_gesture() {
use SelectionEdit::*;
let pointer = GestureInput::Pointer;
let keyboard = GestureInput::Keyboard;
for (platform, secondary, other) in [
(MAC, Modifiers::command(), Modifiers::control()),
(MAC_BROWSER, Modifiers::command(), Modifiers::control()),
(LINUX, Modifiers::control(), Modifiers::command()),
] {
let edit = |input, modifiers: Modifiers, extending, selected| {
StandardSelectionGesture.edit(&SelectionGestureContext::new(
input,
modifiers,
platform,
extending,
selected,
SelectionMode::RowSet,
))
};
let shift_secondary = Modifiers {
shift: true,
..secondary
};
assert_eq!(edit(pointer, Modifiers::default(), false, false), Replace);
assert_eq!(edit(pointer, Modifiers::default(), false, true), Replace);
assert_eq!(edit(pointer, Modifiers::shift(), false, false), Extend);
assert_eq!(edit(pointer, secondary, false, true), Toggle);
assert_eq!(edit(pointer, shift_secondary, false, false), AddRange);
assert_eq!(edit(pointer, other, false, true), Replace);
let context = GestureInput::ContextPointer;
assert_eq!(edit(context, Modifiers::default(), false, false), Replace);
assert_eq!(edit(context, Modifiers::default(), false, true), Keep);
assert_eq!(edit(keyboard, Modifiers::default(), false, true), Replace);
assert_eq!(edit(keyboard, Modifiers::default(), true, false), Extend);
}
let context = SelectionGestureContext::new(
keyboard,
Modifiers::shift(),
LINUX,
true,
true,
SelectionMode::CellSet,
);
assert_eq!(context.input(), keyboard);
assert!(context.modifiers().shift);
assert_eq!(context.platform_info(), LINUX);
assert!(context.is_extending());
assert!(context.is_target_selected());
assert_eq!(context.mode(), SelectionMode::CellSet);
}
#[test]
fn test_standard_context_menu_gesture() {
let control = Modifiers::control();
let control_command = Modifiers {
platform: true,
..control
};
for (platform, macos) in [(MAC, true), (MAC_BROWSER, true), (LINUX, false)] {
let opens = |button, modifiers, click_count, area| {
StandardContextMenuGesture.opens_menu(&ContextMenuGestureContext::new(
button,
modifiers,
platform,
click_count,
area,
))
};
for area in [GridArea::Body, GridArea::Header] {
for modifiers in [Modifiers::default(), Modifiers::shift(), control] {
assert!(opens(MouseButton::Right, modifiers, 1, area));
}
assert!(opens(MouseButton::Right, Modifiers::default(), 2, area));
assert!(!opens(MouseButton::Left, Modifiers::default(), 1, area));
assert!(!opens(MouseButton::Left, Modifiers::shift(), 1, area));
assert!(!opens(MouseButton::Left, Modifiers::command(), 1, area));
assert_eq!(opens(MouseButton::Left, control, 1, area), macos);
assert_eq!(opens(MouseButton::Left, control, 2, area), macos);
assert!(!opens(MouseButton::Left, control_command, 1, area));
assert!(!opens(MouseButton::Middle, Modifiers::default(), 1, area));
assert!(!opens(MouseButton::Middle, control, 1, area));
}
}
let context = ContextMenuGestureContext::new(
MouseButton::Middle,
control,
LINUX,
2,
GridArea::Header,
);
assert_eq!(context.button(), MouseButton::Middle);
assert!(context.modifiers().control);
assert_eq!(context.platform_info(), LINUX);
assert_eq!(context.click_count(), 2);
assert_eq!(context.area(), GridArea::Header);
}
#[test]
fn test_drop_policies() {
use std::time::Instant;
use crate::{
highlight::HighlightPolicy,
model::{CellValue, GridColumns},
store::Ingest,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct Only;
impl GridColumns for Only {
fn all() -> &'static [Self] {
&[Only]
}
fn id(self) -> &'static str {
"only"
}
fn ix(self) -> ColumnIx {
ColumnIx::new(0)
}
}
struct Row(u32);
impl GridRow for Row {
type Key = u32;
type Column = Only;
fn key(&self) -> &u32 {
&self.0
}
fn value(&self, _: Only) -> CellValue<'_> {
CellValue::Empty
}
}
let held = |alt, control| Modifiers {
alt,
control,
..Modifiers::default()
};
assert!(RowDropPolicy::<Row>::is_copy(&NoRowDrop, held(true, false)));
assert!(RowDropPolicy::<Row>::is_copy(&NoRowDrop, held(false, true)));
assert!(!RowDropPolicy::<Row>::is_copy(
&NoRowDrop,
held(false, false)
));
struct NeverCopy;
impl RowDropPolicy<Row> for NeverCopy {
fn place(&self, _: &RowDropContext<'_, Row>) -> Option<DropTarget<u32>> {
None
}
fn is_copy(&self, _: Modifiers) -> bool {
false
}
}
assert!(!NeverCopy.is_copy(held(true, true)));
let snapshot = Ingest::<Row>::new(HighlightPolicy::default(), Instant::now()).snapshot();
let (key, last) = (3, 9);
let place = |policy: &dyn RowDropPolicy<Row>,
row: Option<f32>,
view: (bool, bool, bool),
last_row: Option<&u32>| {
let line = match row {
Some(_) => DropLine::Row {
key: &key,
branch: None,
},
None => DropLine::Empty,
};
policy.place(&RowDropContext::new(
line,
row.unwrap_or(0.),
None,
None,
false,
Modifiers::default(),
view,
last_row,
&snapshot,
))
};
let at = |key, place| Some(DropTarget::Row { key, place });
let flat = (false, false, false);
assert!(!RowDropPolicy::<Row>::is_enabled(&NoRowDrop));
assert_eq!(place(&NoRowDrop, Some(0.5), flat, None), None);
assert_eq!(
place(&DropOnRows, Some(0.1), flat, None),
at(3, DropPlace::Onto)
);
assert_eq!(
place(&DropOnRows, None, flat, None),
Some(DropTarget::Empty)
);
assert_eq!(
place(&DropBetweenRows, Some(0.4), flat, None),
at(3, DropPlace::Before)
);
assert_eq!(
place(&DropBetweenRows, Some(0.6), flat, None),
at(3, DropPlace::After)
);
let tree = (false, false, true);
assert_eq!(
place(&DropBetweenRows, Some(0.2), tree, None),
at(3, DropPlace::Before)
);
assert_eq!(
place(&DropBetweenRows, Some(0.5), tree, None),
at(3, DropPlace::Onto)
);
assert_eq!(
place(&DropBetweenRows, Some(0.8), tree, None),
at(3, DropPlace::After)
);
assert_eq!(
place(&DropBetweenRows, None, flat, Some(&last)),
at(9, DropPlace::After)
);
assert_eq!(
place(&DropBetweenRows, None, flat, None),
Some(DropTarget::Empty)
);
assert_eq!(
place(&DropBetweenRows, Some(0.6), (true, false, false), None),
None
);
assert_eq!(
place(&DropBetweenRows, Some(0.6), (true, true, false), None),
at(3, DropPlace::After)
);
}
#[test]
fn test_selection_scopes() {
use std::{sync::Arc, time::Instant};
use crate::{
engine::{ProjectionEngine as _, Rebuild, ViewSpec},
highlight::HighlightPolicy,
model::{CellValue, GridColumns},
store::{Ingest, Op},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct Price;
impl GridColumns for Price {
fn all() -> &'static [Self] {
&[Price]
}
fn id(self) -> &'static str {
"price"
}
fn ix(self) -> ColumnIx {
ColumnIx::new(0)
}
}
struct Row(u32, i64);
impl GridRow for Row {
type Key = u32;
type Column = Price;
fn key(&self) -> &u32 {
&self.0
}
fn value(&self, _: Price) -> CellValue<'_> {
CellValue::Int(self.1)
}
}
let mut ingest = Ingest::new(HighlightPolicy::default(), Instant::now());
ingest.apply(
(0..10).map(|id| Op::Upsert(Arc::new(Row(id, id.into())))),
Instant::now(),
);
let view = ViewSpec::new()
.with_sort([(Price, SortDirection::Descending)])
.with_filter(ColumnSet::first(1), |row: &Row| row.0 % 2 == 1);
let projection = Rebuild::default().rebuild(&ingest.snapshot(), &view);
ingest.apply([Op::Remove(5), Op::Remove(4)], Instant::now());
let snapshot = ingest.snapshot();
let row = ColumnSet::first(1);
let resolve = |scope: &dyn SelectionScope<Row>, keys: &[u32]| {
let selection = GridSelection::from_rows(keys.iter().map(|key| (*key, row)));
let scoped = scope.resolve(&SelectionScopeContext::new(
&selection,
&projection,
&snapshot,
SelectionMode::RowSet,
));
assert!((0..scoped.len()).all(|ix| scoped.columns(ix) == row));
assert_eq!(scoped.columns(scoped.len()), ColumnSet::EMPTY);
scoped.keys().to_vec()
};
let few = [1, 6, 2, 5, 9, 4, 42];
let many: Vec<u32> = (0..10).chain([42]).collect();
assert_eq!(resolve(&ProjectionScope, &few), [9, 1]);
assert_eq!(resolve(&ProjectionScope, &many), [9, 7, 3, 1]);
assert!(resolve(&ProjectionScope, &[]).is_empty());
assert_eq!(resolve(&StoreScope, &few), [9, 1, 2, 6]);
assert_eq!(resolve(&StoreScope, &many), [9, 7, 3, 1, 0, 2, 6, 8]);
let empty = GridSelection::default();
let context =
SelectionScopeContext::new(&empty, &projection, &snapshot, SelectionMode::CellSet);
assert_eq!(context.mode(), SelectionMode::CellSet);
assert_eq!(context.projection().len(), 5);
assert_eq!(context.snapshot().len(), 8);
assert!(context.selection().is_empty());
let scoped: ScopedSelection<u32> = [(3, row)].into_iter().collect();
assert_eq!((scoped.len(), scoped.is_empty()), (1, false));
}
#[test]
fn test_standard_expand_gesture() {
let edit = |area, button, modifiers, click_count| {
StandardExpandGesture.edit(&ExpandGestureContext::new(
area,
button,
modifiers,
click_count,
))
};
let (left, plain) = (MouseButton::Left, Modifiers::default());
let alt = Modifiers::alt();
assert_eq!(
edit(ExpandArea::Chevron, left, plain, 1),
Some(ExpandEdit::Toggle)
);
assert_eq!(
edit(ExpandArea::Chevron, left, alt, 1),
Some(ExpandEdit::ToggleDeep)
);
assert_eq!(edit(ExpandArea::Chevron, left, plain, 2), None);
assert_eq!(edit(ExpandArea::Caption, left, plain, 1), None);
assert_eq!(
edit(ExpandArea::Caption, left, plain, 2),
Some(ExpandEdit::Toggle)
);
assert_eq!(edit(ExpandArea::Caption, left, plain, 3), None);
assert_eq!(edit(ExpandArea::TreeCell, left, plain, 1), None);
assert_eq!(edit(ExpandArea::TreeCell, left, plain, 2), None);
assert_eq!(
edit(ExpandArea::Chevron, MouseButton::Right, plain, 1),
None
);
assert_eq!(
edit(ExpandArea::Chevron, MouseButton::Middle, plain, 1),
None
);
let context = ExpandGestureContext::new(ExpandArea::TreeCell, left, alt, 2);
assert_eq!(context.area(), ExpandArea::TreeCell);
assert_eq!(context.button(), left);
assert!(context.modifiers().alt);
assert_eq!(context.click_count(), 2);
}
#[test]
fn test_focus_captions() {
use std::{sync::Arc, time::Instant};
use crate::{
engine::{GroupBy, ProjectionEngine as _, Rebuild, ViewSpec},
highlight::HighlightPolicy,
model::{CellValue, GridColumns},
store::{Ingest, Op},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum Col {
Side,
Qty,
}
impl GridColumns for Col {
fn all() -> &'static [Self] {
&[Col::Side, Col::Qty]
}
fn id(self) -> &'static str {
match self {
Col::Side => "side",
Col::Qty => "qty",
}
}
fn ix(self) -> ColumnIx {
ColumnIx::new(self as u16)
}
}
struct Row(u32, &'static str);
impl GridRow for Row {
type Key = u32;
type Column = Col;
fn key(&self) -> &u32 {
&self.0
}
fn value(&self, column: Col) -> CellValue<'_> {
match column {
Col::Side => CellValue::Text(self.1),
Col::Qty => CellValue::Int(self.0.into()),
}
}
}
let mut ingest = Ingest::new(HighlightPolicy::default(), Instant::now());
ingest.apply(
(0..6).map(|id| {
let side = if id % 2 == 0 { "Buy" } else { "Sell" };
Op::Upsert(Arc::new(Row(id, side)))
}),
Instant::now(),
);
let view = ViewSpec::new()
.with_sort([(Col::Qty, SortDirection::Descending)])
.with_group_by([GroupBy::column(Col::Side)]);
let projection = Rebuild::default().rebuild(&ingest.snapshot(), &view);
ingest.apply([Op::Remove(2)], Instant::now());
let snapshot = ingest.snapshot();
let buy = projection.groups().iter().next().expect("the Buy group");
let rows = projection.order_ix(buy.rows()[0]).expect("in the order");
let policy: &dyn SelectionPolicy<Row> = &FocusCaptions;
let caption = SelectableLine::Caption { group: buy };
assert!(!policy.is_selectable(&caption));
let context = LineScopeContext::new(
caption,
rows..rows + buy.rows().len(),
&projection,
&snapshot,
SelectionMode::CellSet,
);
assert_eq!(context.mode(), SelectionMode::CellSet);
assert_eq!(context.projection().len(), projection.len());
assert_eq!(context.snapshot().len(), 5);
let scope = policy.line_scope(&context).expect("a caption's scope");
assert_eq!(scope.keys(), [4, 0]);
assert_eq!(scope.columns(0), ColumnSet::first(2));
let row = snapshot.get(&3).expect("row 3");
let line = SelectableLine::Row {
row: &**row,
branch: None,
};
assert!(policy.is_selectable(&line));
let context =
LineScopeContext::new(line, 0..0, &projection, &snapshot, SelectionMode::RowSet);
assert_eq!(context.rows().count(), 0);
assert!(policy.line_scope(&context).is_none());
}
#[test]
fn test_focus_branches_policy() {
use std::{sync::Arc, time::Instant};
use crate::{
engine::{ExpandDepth, GroupBy, ProjectionEngine as _, Rebuild, TreeSpec, ViewSpec},
highlight::HighlightPolicy,
model::{CellValue, GridColumns},
store::{Ingest, Op},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum Col {
Id,
Kind,
}
impl GridColumns for Col {
fn all() -> &'static [Self] {
&[Col::Id, Col::Kind]
}
fn id(self) -> &'static str {
match self {
Col::Id => "id",
Col::Kind => "kind",
}
}
fn ix(self) -> ColumnIx {
ColumnIx::new(self as u16)
}
}
struct Node {
id: u32,
parent: Option<u32>,
}
impl GridRow for Node {
type Key = u32;
type Column = Col;
fn key(&self) -> &u32 {
&self.id
}
fn value(&self, column: Col) -> CellValue<'_> {
match column {
Col::Id => CellValue::Int(self.id.into()),
Col::Kind => CellValue::Text(if self.id % 2 == 0 { "even" } else { "odd" }),
}
}
fn parent_key(&self) -> Option<&u32> {
self.parent.as_ref()
}
}
let parent = |id| match id {
1 | 2 | 6 => Some(0),
3 | 4 => Some(1),
5 => Some(2),
_ => None,
};
let mut ingest = Ingest::new(HighlightPolicy::default(), Instant::now());
ingest.apply(
(0..8).map(|id| {
Op::Upsert(Arc::new(Node {
id,
parent: parent(id),
}))
}),
Instant::now(),
);
let view = ViewSpec::new()
.with_sort([(Col::Id, SortDirection::Ascending)])
.with_tree(TreeSpec::new())
.with_tree_expansion(ExpandDepth::All, [2]);
let projection = Rebuild::default().rebuild(&ingest.snapshot(), &view);
let snapshot = ingest.snapshot();
let order: Vec<u32> = projection
.rows()
.iter()
.map(|id| snapshot.row(*id).expect("live").id)
.collect();
assert_eq!(order, [0, 1, 3, 4, 2, 5, 6, 7]);
let policy: &dyn SelectionPolicy<Node> = &FocusBranches;
let line = |key: u32| {
let id = snapshot.row_id(&key).expect("a row");
SelectableLine::Row {
row: &**snapshot.row(id).expect("live"),
branch: projection.branch(id),
}
};
let scope = |key: u32, snapshot: &StoreSnapshot<Node>| {
let id = snapshot.row_id(&key).expect("a row");
let order_ix = projection.order_ix(id).expect("in the order");
let under = projection
.branch(id)
.map_or(0, |branch| branch.descendant_count());
let context = LineScopeContext::new(
line(key),
order_ix + 1..order_ix + 1 + under,
&projection,
snapshot,
SelectionMode::CellSet,
);
policy.line_scope(&context)
};
for (key, selectable) in [(0, false), (1, false), (2, false), (3, true), (6, true)] {
assert_eq!(policy.is_selectable(&line(key)), selectable, "{key}");
}
assert!(FocusCaptions.is_selectable(&line(0)), "a node is a row");
let all = scope(0, &snapshot).expect("a branch's scope");
assert_eq!(all.keys(), [3, 4, 5, 6]);
assert_eq!(all.columns(0), ColumnSet::first(2));
assert_eq!(scope(1, &snapshot).expect("a branch").keys(), [3, 4]);
assert_eq!(scope(2, &snapshot).expect("a branch").keys(), [5]);
assert!(scope(3, &snapshot).is_none());
assert!(scope(7, &snapshot).is_none());
ingest.apply([Op::Remove(4)], Instant::now());
let after = ingest.snapshot();
assert_eq!(scope(1, &after).expect("a branch").keys(), [3]);
let grouped = Rebuild::default().rebuild(
&snapshot,
&ViewSpec::new()
.with_sort([(Col::Id, SortDirection::Ascending)])
.with_group_by([GroupBy::column(Col::Kind)]),
);
let even = grouped.groups().iter().next().expect("the even group");
let start = grouped.order_ix(even.rows()[0]).expect("in the order");
let caption = SelectableLine::Caption { group: even };
assert!(!policy.is_selectable(&caption));
let context = LineScopeContext::new(
caption,
start..start + even.rows().len(),
&grouped,
&snapshot,
SelectionMode::RowSet,
);
assert_eq!(
policy
.line_scope(&context)
.expect("a caption's scope")
.keys(),
[0, 2, 4, 6]
);
assert_eq!(context.lines().count(), 4);
}
}