mod a11y;
mod change;
mod click;
mod columns;
mod chooser;
mod copy;
mod export;
mod disclosure;
mod drag;
mod edit;
mod editors;
mod events;
mod fade;
mod frame;
mod ghost;
mod group_panel;
mod handle;
mod link;
mod grouping;
mod groups;
mod header;
mod images;
mod layout;
mod menu;
mod pending;
mod pinned;
mod progress;
mod projection;
mod scroll;
mod selection;
mod stats;
mod style;
mod summary;
mod tooltip;
mod tree;
mod widgets;
use std::{
hash::{Hash, Hasher as _},
sync::Arc,
};
use gpui_kit::base::{AutoScroll, Scrollbar, TestSupportExt as _};
use gpui_kit::component::{ActiveTheme as _, Size as ComponentSize};
use gpui_kit::{
App, Bounds, Context, EventEmitter, FocusHandle, Focusable, InteractiveElement as _,
IntoElement, KeyContext, ParentElement as _, Pixels, PlatformInfo, Render, SharedString,
StatefulInteractiveElement as _, Styled as _, Task, Window, div, prelude::FluentBuilder as _,
px,
};
use web_time::Instant;
pub(crate) use self::{
a11y::{A11yPlan, FOCUS_CELL_ID},
tooltip::CellHover,
};
use self::{
a11y::{RowNumbering, root_role},
click::PendingClick,
columns::ColumnLayout,
frame::PaintedLine,
ghost::GhostTextStyle,
grouping::ExpansionRevision,
groups::CaptionTexts,
header::HeaderState,
menu::OpenMenu,
pinned::PaintedBands,
progress::ProgressSlot,
projection::{Coverage, HeldOrder, PendingWork},
scroll::{GridScrollHandle, LineAnchor, ScrollReset},
selection::{PointerTarget, Press, SelectionModel},
summary::SummaryTexts,
tooltip::TooltipState,
};
pub use self::{
change::{ChangePaint, ChangePainter, ChangePalette, DirectionalChanges, UniformChanges},
chooser::{
ColumnChooserContext, ColumnChooserFactory, ColumnChooserPanel, PopoverColumnChooser,
},
columns::{
CellContent, ColumnAlign, ColumnBand, ColumnZone, GridColumn, GridSchema, HeaderLabel,
MIN_COLUMN_WIDTH, ViewColumnIx,
},
drag::{DragPayload, DropPlace, DropSource, DropTarget, RowDrag, RowDragContext},
edit::{
CellEditor, EditCancelReason, EditError, EditId, EditInput, EditMessageContext, EditOrigin,
EditState, EditValidateContext, EditableContext, EditorCell, EditorField, EditorMark,
EditorOpen, EditorStart,
},
editors::{
CellEditHandle, CheckboxEditor, DateEditor, NumberEditor, NumberKind, SelectEditor,
SelectOption, TextEditor,
},
events::{
ExpandTarget, GroupOrigin, LayoutOrigin, LayoutPart, LayoutParts, LiveGridEvent,
SelectionOrigin, SortOrigin,
},
export::{EmptyExport, ExportHeader, ExportJob, ExportOutcome, ExportProgress, ExportRequest},
groups::{CaptionTag, GroupCaptionContext},
handle::{BandInfo, ColumnInfo, GridHandleEvent, LiveGridHandle, WeakLiveGridHandle},
images::{AssetImageSource, CellImage, CellImageSource, CellImages, ImageFit},
link::{LinkOpener, OpenInBrowser},
menu::{GridMenuContext, GridTarget},
progress::ProgressContext,
projection::FlushOutcome,
selection::{FocusedCell, GridSelection, ScopedSelection, SelectionMode},
stats::{GridStats, GridTuning},
style::{
AggregateLine, AggregateStyleContext, CellChange, CellStyle, CellStyleContext,
LiveGridDelegate,
},
tooltip::{CellTooltip, CellTooltipContext, HeaderTooltipContext},
widgets::CellElementContext,
};
use crate::{
actions::{CELL_CONTENT_KEY, KEY_CONTEXT},
element::GridBody,
engine::{GroupPath, Projection, ProjectionEngine, Rebuild, ViewSpec},
model::{ColumnIx, ColumnSet, GridColumns as _, GridRow},
policy::{
AutofitPolicy, BackgroundRunner, BandedMove, ColumnMovePolicy, ContextMenuGesture,
ExpandGesture, FocusCaptions, LiveReorder, ProjectionScope, ReorderPolicy,
SelectionGesture, SelectionPolicy, SelectionScope, SortCycle, StandardContextMenuGesture,
StandardExpandGesture, StandardSelectionGesture, StandardSortCycle, TaskRunner,
VisibleRowsAutofit,
},
quick_filter::{ContainsAllTerms, QuickFilterMatcher},
store::{GridStore, GridWriter, PinnedEdge, StoreOptions, StoreSnapshot},
text::{TextCaches, TextStats},
};
type ColumnOf<D> = <<D as LiveGridDelegate>::Row as GridRow>::Column;
type KeyOf<D> = <<D as LiveGridDelegate>::Row as GridRow>::Key;
const CELL_PADDING: Pixels = px(6.);
pub(crate) fn key_hash<K: Hash + ?Sized>(key: &K) -> u64 {
let mut hasher = rustc_hash::FxHasher::default();
key.hash(&mut hasher);
hasher.finish()
}
pub(crate) fn group_hash(path: &GroupPath) -> u64 {
key_hash(&("live-grid-group", path))
}
pub(crate) fn footer_hash(path: &GroupPath) -> u64 {
key_hash(&("live-grid-group-footer", path))
}
pub(crate) fn totals_hash(edge: PinnedEdge) -> u64 {
key_hash(&(
"live-grid-totals",
match edge {
PinnedEdge::Top => "top",
PinnedEdge::Bottom => "bottom",
},
))
}
pub struct LiveGridState<D: LiveGridDelegate> {
delegate: D,
store: GridStore<D::Row>,
snapshot: Arc<StoreSnapshot<D::Row>>,
projection: Arc<Projection>,
view: ViewSpec<D::Row>,
engine: Arc<dyn ProjectionEngine<D::Row>>,
tuning: GridTuning,
pending: PendingWork,
rebuild_task: Option<Task<()>>,
rebuild_timer: Option<Task<()>>,
last_rebuild_started: Option<Instant>,
pending_user_action: bool,
pending_scroll_reset: ScrollReset,
expansion_revision: ExpansionRevision,
shown_revision: ExpansionRevision,
aggregates_changed: bool,
expand_anchor: Option<LineAnchor>,
expand_gesture: Box<dyn ExpandGesture>,
caption_texts: CaptionTexts,
totals: Option<PinnedEdge>,
summary_texts: SummaryTexts,
reorder: Box<dyn ReorderPolicy>,
runner: Box<dyn TaskRunner>,
sort_cycle: Box<dyn SortCycle>,
quick_filter_matcher: Arc<dyn QuickFilterMatcher>,
quick_filter_columns: Option<ColumnSet>,
quick_filter_text: SharedString,
held: Option<HeldOrder>,
pointer_inside: bool,
last_removal_version: u64,
columns: ColumnLayout<ColumnOf<D>>,
layout: layout::LayoutSlot<D::Row>,
column_move: Box<dyn ColumnMovePolicy>,
autofit: Box<dyn AutofitPolicy>,
pending_autofit: Option<(ColumnSet, LayoutOrigin)>,
current_column: Option<ColumnIx>,
header: HeaderState,
scroll_row: usize,
scroll_offset: Pixels,
scroll_x: Pixels,
row_height: Pixels,
body_bounds: Bounds<Pixels>,
painted: Vec<PaintedLine>,
painted_pinned: PaintedBands<D::Row>,
coverage: Coverage,
progress: ProgressSlot,
scroll_handle: GridScrollHandle,
selection: SelectionModel<KeyOf<D>, ColumnOf<D>>,
selection_scope: Box<dyn SelectionScope<D::Row>>,
selection_policy: Box<dyn SelectionPolicy<D::Row>>,
selection_gesture: Box<dyn SelectionGesture>,
context_menu_gesture: Box<dyn ContextMenuGesture>,
pointer_target: Option<PointerTarget<KeyOf<D>>>,
press: Option<Press<KeyOf<D>, ColumnOf<D>>>,
press_series: Option<KeyOf<D>>,
click: Option<PendingClick<KeyOf<D>, ColumnOf<D>>>,
drag_scroll: AutoScroll,
menu: Option<OpenMenu<KeyOf<D>, ColumnOf<D>>>,
tooltip: TooltipState,
#[cfg(any(test, feature = "test-support"))]
focus_visible: bool,
accessibility_label: Option<SharedString>,
#[cfg(any(test, feature = "test-support"))]
a11y_forced: bool,
#[cfg(any(test, feature = "test-support"))]
last_a11y: Option<std::rc::Rc<A11yPlan>>,
text_cache: TextCaches,
change_paint: ChangePaint,
#[cfg(any(test, feature = "test-support"))]
test_cell_lead: Option<(ColumnIx, Pixels, Option<SharedString>)>,
#[cfg(any(test, feature = "test-support"))]
test_cell_host: Option<frame::TestCellHost>,
#[cfg(any(test, feature = "test-support"))]
last_paint_order: Vec<&'static str>,
#[cfg(any(test, feature = "test-support"))]
painted_icons: Vec<(Bounds<Pixels>, SharedString, gpui_kit::Hsla)>,
#[cfg(any(test, feature = "test-support"))]
painted_images: Vec<frame::PaintedImage>,
#[cfg(any(test, feature = "test-support"))]
painted_pills: Vec<(Bounds<Pixels>, gpui_kit::Hsla)>,
fade: Option<(u32, Task<()>)>,
stats: GridStats,
focus_handle: FocusHandle,
platform: PlatformInfo,
copy: copy::CopySlot<D::Row>,
column_chooser: chooser::ChooserSlot,
group_panel: group_panel::GroupPanelState,
edit_setup: edit::EditSetup<D::Row>,
edit: edit::EditSlot<KeyOf<D>, ColumnOf<D>>,
pending_edits: pending::PendingEdits<KeyOf<D>, ColumnOf<D>>,
widgets: widgets::WidgetSlot<KeyOf<D>, ColumnOf<D>>,
links: link::LinkSlot,
images: images::CellImages,
drag: drag::DragSlot<D>,
_pull: Task<()>,
}
impl<D: LiveGridDelegate> LiveGridState<D> {
pub fn new(
schema: GridSchema<ColumnOf<D>>,
delegate: D,
store: GridStore<D::Row>,
cx: &mut Context<Self>,
) -> Self {
let subscription = store.subscribe();
let snapshot = store.snapshot();
let pull = cx.spawn(async move |this, cx| {
while subscription.changed().await {
let (snapshot, changes) = subscription.take();
let Ok(interval) = this.update(cx, |state, cx| {
state.apply_snapshot(snapshot, changes, cx);
state.tuning.pull_interval
}) else {
break;
};
cx.background_executor().timer(interval).await;
}
});
Self {
delegate,
progress: ProgressSlot::new(snapshot.progress()),
snapshot,
store,
projection: Arc::new(Projection::default()),
view: ViewSpec::new(),
engine: Arc::new(Rebuild::default()),
tuning: GridTuning::default(),
pending: PendingWork::Rebuild { expand: false },
rebuild_task: None,
rebuild_timer: None,
last_rebuild_started: None,
pending_user_action: true,
pending_scroll_reset: ScrollReset::Keep,
expansion_revision: ExpansionRevision::default(),
shown_revision: ExpansionRevision::default(),
aggregates_changed: false,
expand_anchor: None,
expand_gesture: Box::new(StandardExpandGesture),
caption_texts: CaptionTexts::default(),
totals: None,
summary_texts: SummaryTexts::default(),
reorder: Box::new(LiveReorder),
runner: Box::new(BackgroundRunner),
sort_cycle: Box::new(StandardSortCycle),
quick_filter_matcher: Arc::new(ContainsAllTerms),
quick_filter_columns: None,
quick_filter_text: SharedString::default(),
held: None,
pointer_inside: false,
last_removal_version: 0,
layout: layout::LayoutSlot::new(&schema),
columns: {
let mut columns = ColumnLayout::new(schema);
columns.normalize(&BandedMove);
columns
},
column_move: Box::new(BandedMove),
autofit: Box::new(VisibleRowsAutofit),
pending_autofit: None,
current_column: None,
header: HeaderState::default(),
scroll_row: 0,
scroll_offset: px(0.),
scroll_x: px(0.),
row_height: ComponentSize::default().table_row_height(),
body_bounds: Bounds::default(),
painted: Vec::new(),
painted_pinned: PaintedBands::default(),
coverage: Coverage::default(),
scroll_handle: GridScrollHandle::default(),
selection: SelectionModel::new(SelectionMode::default()),
selection_scope: Box::new(ProjectionScope),
selection_policy: Box::new(FocusCaptions),
selection_gesture: Box::new(StandardSelectionGesture),
context_menu_gesture: Box::new(StandardContextMenuGesture),
pointer_target: None,
press: None,
press_series: None,
click: None,
drag_scroll: AutoScroll::default(),
menu: None,
tooltip: TooltipState::default(),
#[cfg(any(test, feature = "test-support"))]
focus_visible: false,
accessibility_label: None,
#[cfg(any(test, feature = "test-support"))]
a11y_forced: false,
#[cfg(any(test, feature = "test-support"))]
last_a11y: None,
text_cache: TextCaches::default(),
change_paint: ChangePaint::default(),
#[cfg(any(test, feature = "test-support"))]
test_cell_lead: None,
#[cfg(any(test, feature = "test-support"))]
test_cell_host: None,
#[cfg(any(test, feature = "test-support"))]
last_paint_order: Vec::new(),
#[cfg(any(test, feature = "test-support"))]
painted_icons: Vec::new(),
#[cfg(any(test, feature = "test-support"))]
painted_images: Vec::new(),
#[cfg(any(test, feature = "test-support"))]
painted_pills: Vec::new(),
fade: None,
stats: GridStats::default(),
focus_handle: cx.focus_handle().tab_stop(true),
platform: cx.platform_info(),
copy: copy::CopySlot::default(),
column_chooser: chooser::ChooserSlot::default(),
group_panel: group_panel::GroupPanelState::default(),
edit_setup: edit::EditSetup::default(),
edit: edit::EditSlot::default(),
pending_edits: pending::PendingEdits::default(),
widgets: widgets::WidgetSlot::default(),
links: link::LinkSlot::default(),
images: images::CellImages::default(),
drag: drag::DragSlot::default(),
_pull: pull,
}
}
pub fn new_standalone(
schema: GridSchema<ColumnOf<D>>,
delegate: D,
options: StoreOptions,
cx: &mut Context<Self>,
) -> Self {
let store = GridStore::new(options, cx);
Self::new(schema, delegate, store, cx)
}
pub fn with_view(mut self, view: ViewSpec<D::Row>) -> Self {
let quick_filter = self.view.quick_filter().cloned();
let expansion = self.view.expansion().clone();
self.view = view
.with_quick_filter(quick_filter)
.with_expansion(expansion);
self.layout.set_view(&self.view);
self.apply_initial_layout()
}
pub fn with_engine(mut self, engine: impl ProjectionEngine<D::Row>) -> Self {
self.engine = Arc::new(engine);
self
}
pub fn with_tuning(mut self, tuning: GridTuning) -> Self {
self.tuning = tuning;
self
}
pub fn with_reorder_policy(mut self, policy: impl ReorderPolicy) -> Self {
self.reorder = Box::new(policy);
self
}
pub fn with_task_runner(mut self, runner: impl TaskRunner) -> Self {
self.runner = Box::new(runner);
self
}
pub fn with_sort_cycle(mut self, cycle: impl SortCycle) -> Self {
self.sort_cycle = Box::new(cycle);
self
}
pub fn with_quick_filter_matcher(mut self, matcher: impl QuickFilterMatcher) -> Self {
self.quick_filter_matcher = Arc::new(matcher);
self.recompile_quick_filter();
self
}
pub fn with_quick_filter_columns(
mut self,
columns: impl IntoIterator<Item = ColumnOf<D>>,
) -> Self {
let set = columns
.into_iter()
.fold(ColumnSet::EMPTY, |mut set, column| {
set.insert(column.ix());
set
});
self.quick_filter_columns = Some(set);
self.recompile_quick_filter();
self
}
pub(crate) fn set_row_height(&mut self, row_height: Pixels) {
if self.row_height != row_height {
self.row_height = row_height;
self.clamp_scroll();
}
}
pub(crate) fn set_accessibility_label(&mut self, label: Option<SharedString>) {
self.accessibility_label = label;
}
#[cfg(any(test, feature = "test-support"))]
pub fn set_a11y_forced(&mut self, forced: bool) {
self.a11y_forced = forced;
}
#[cfg(any(test, feature = "test-support"))]
pub fn a11y_focus_description(&self) -> Option<&str> {
self.last_a11y.as_ref()?.focus_description()
}
#[cfg(any(test, feature = "test-support"))]
pub fn set_test_cell_lead(
&mut self,
column: ColumnOf<D>,
indent: Pixels,
icon: Option<SharedString>,
) {
self.test_cell_lead = Some((column.ix(), indent, icon));
}
#[cfg(any(test, feature = "test-support"))]
pub fn set_test_cell_host(
&mut self,
column: Option<ColumnOf<D>>,
build: impl Fn(gpui_kit::Stateful<gpui_kit::Div>) -> gpui_kit::Stateful<gpui_kit::Div> + 'static,
) {
self.test_cell_host = column.map(|column| {
let build: std::rc::Rc<
dyn Fn(gpui_kit::Stateful<gpui_kit::Div>) -> gpui_kit::Stateful<gpui_kit::Div>,
> = std::rc::Rc::new(build);
(column.ix(), build)
});
}
#[cfg(any(test, feature = "test-support"))]
pub fn last_paint_order(&self) -> &[&'static str] {
&self.last_paint_order
}
#[cfg(any(test, feature = "test-support"))]
pub(crate) fn set_last_paint_order(&mut self, order: Vec<&'static str>) {
self.last_paint_order = order;
}
pub(crate) fn set_last_hosts_prepaint(&mut self, elapsed: std::time::Duration) {
self.stats.last_hosts_prepaint = elapsed;
}
fn is_a11y_planned(&self, window: &Window) -> bool {
#[cfg(any(test, feature = "test-support"))]
if self.a11y_forced {
return true;
}
window.is_a11y_active()
}
fn root_key_context(&self) -> KeyContext {
let mut context = KeyContext::default();
context.add(KEY_CONTEXT);
let content = self
.selection
.focus()
.filter(|focus| focus.row().is_some())
.map(|focus| self.columns.column(focus.column().ix()).content);
if self.is_link_focused() {
context.set(CELL_CONTENT_KEY, "link");
} else if let Some(content) = content {
context.set(CELL_CONTENT_KEY, content.key_value());
}
context
}
fn a11y_numbering(&self) -> RowNumbering {
RowNumbering::new(
self.snapshot.pinned_rows(PinnedEdge::Top).len(),
self.projection.len(),
self.snapshot.pinned_rows(PinnedEdge::Bottom).len(),
)
.with_totals(self.totals)
}
pub fn store(&self) -> &GridStore<D::Row> {
&self.store
}
pub fn writer(&self) -> GridWriter<D::Row> {
self.store.writer()
}
pub fn snapshot(&self) -> &Arc<StoreSnapshot<D::Row>> {
&self.snapshot
}
pub fn projection(&self) -> &Arc<Projection> {
&self.projection
}
pub fn stats(&self) -> GridStats {
self.stats.with_tree_cycles(self.projection.tree_cycles())
}
pub fn text_stats(&self) -> TextStats {
self.text_cache.stats()
}
}
impl<D: LiveGridDelegate> EventEmitter<LiveGridEvent<KeyOf<D>, ColumnOf<D>>> for LiveGridState<D> {}
impl<D: LiveGridDelegate> Focusable for LiveGridState<D> {
fn focus_handle(&self, _: &App) -> FocusHandle {
self.focus_handle.clone()
}
}
impl<D: LiveGridDelegate> Render for LiveGridState<D> {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.close_stale_menu(window, cx);
self.settle_row_drag(cx);
self.apply_scroll_request();
self.ensure_projection(cx);
let a11y = self.is_a11y_planned(window);
let header_tooltip = self.header_tooltip(window, cx);
let ghost_text = GhostTextStyle::capture(window);
let header = self.render_header(header_tooltip, &ghost_text, a11y, cx);
let group_panel = self.render_group_panel(window, cx);
let scrollbars = self.render_scrollbars();
let progress = self.render_progress_overlay(window, cx);
let menu = self.render_menu(window);
let column_chooser = self.render_column_chooser(window, cx);
let role = root_role(self.projection.is_grouped() || self.projection.is_tree());
let row_count = self.a11y_numbering().row_count();
let column_count = self.columns.visible_set().len();
let multiselectable = !self.selection.mode().is_single();
let theme = cx.theme();
let root = div()
.id("live-grid")
.test_support()
.track_focus(&self.focus_handle)
.role(role)
.when_some(self.accessibility_label.clone(), |this, label| {
this.aria_label(label)
})
.aria_row_count(row_count)
.aria_column_count(column_count)
.when(a11y && multiselectable, |this| {
this.a11y_synthetic_children(|builder| builder.parent_node().set_multiselectable())
})
.key_context(self.root_key_context())
.on_action(cx.listener(Self::on_autofit_columns))
.on_action(cx.listener(Self::on_autofit_column))
.on_action(cx.listener(Self::on_hide_column))
.on_action(cx.listener(Self::on_show_all_columns))
.on_action(cx.listener(Self::on_freeze_column_left))
.on_action(cx.listener(Self::on_freeze_column_right))
.on_action(cx.listener(Self::on_unfreeze_column))
.on_action(cx.listener(Self::on_move_column_left))
.on_action(cx.listener(Self::on_move_column_right))
.on_action(cx.listener(Self::on_reset_layout))
.on_action(cx.listener(Self::on_show_context_menu))
.on_action(cx.listener(Self::on_show_column_chooser))
.on_action(cx.listener(Self::on_sort_ascending))
.on_action(cx.listener(Self::on_sort_descending))
.on_action(cx.listener(Self::on_clear_sort))
.on_action(cx.listener(Self::on_clear_all_sorting))
.map(|this| Self::bind_selection_actions(this, cx))
.map(|this| Self::bind_disclosure_actions(this, cx))
.on_action(cx.listener(Self::on_copy))
.on_action(cx.listener(Self::on_copy_all))
.map(|this| Self::bind_group_panel(this, cx))
.map(|this| Self::bind_edit_actions(this, cx))
.map(|this| Self::bind_cell_actions(this, cx))
.map(|this| Self::bind_link_actions(this, cx))
.on_drag_move(cx.listener(Self::on_columns_drag_move))
.on_drag_move(cx.listener(Self::on_resize_drag_move))
.on_drop(cx.listener(Self::on_columns_drop))
.size_full()
.flex()
.flex_col()
.overflow_hidden()
.bg(theme.table)
.text_color(theme.foreground)
.children(group_panel)
.child(header)
.child(self.render_rows(GridBody::new(cx.entity()), ghost_text, cx))
.child(scrollbars)
.children(progress);
div()
.size_full()
.child(root)
.children(menu)
.children(column_chooser)
}
}
impl<D: LiveGridDelegate> LiveGridState<D> {
fn render_scrollbars(&self) -> impl IntoElement {
let geometry = self
.columns
.geometry(self.body_bounds.size.width, self.scroll_x);
let scrolling = geometry.zone(ColumnZone::Scrolling);
let (left, width) = (scrolling.x, scrolling.width);
let bands = self.body_bands();
let top_band = bands.band(PinnedEdge::Top).size.height;
let bottom_band = bands.band(PinnedEdge::Bottom).size.height;
div()
.absolute()
.top(self.body_top())
.left_0()
.right_0()
.bottom_0()
.child(
div()
.absolute()
.top(top_band)
.right_0()
.bottom(bottom_band)
.w(Scrollbar::width())
.child(
Scrollbar::vertical(&self.scroll_handle)
.viewport_from_layout()
.max_fps(60),
),
)
.child(
div()
.absolute()
.left(left)
.bottom(bottom_band)
.w(width)
.h(Scrollbar::width())
.child(Scrollbar::horizontal(&self.scroll_handle).viewport_from_layout()),
)
}
}