Skip to main content

waft_winui/controls/table_view/
mod.rs

1//! `TableView` (`controls/dev/TableView`: `TableView.xaml`, `TableView.cpp`, `TableView_Layout.cpp`, `TableView_Columns.cpp`, `TableView_Selection.cpp`, `TableView_Sort.cpp` and `TableView_Keyboard.cpp`): items an application gives as a [`TableViewSource`], shown as rows of cells under a header band, in columns the user can resize and sort, with one row selected.
2//!
3//! WinUI makes the rows through an `ItemsRepeater` in a `ScrollViewer` that scrolls both ways. Here the rows are Waft's lazy `ListView`, which builds only what is in sight, inside a horizontal viewport as wide as the columns; the vertical bar stays at the table's edge. The header band and every row lay their cells out in a `TableViewCellsPanel` at the widths the table resolves into the columns while it lays itself out, so they share each column's width; an `Auto` column's width comes from the cells measured so far, and is resolved again after the frame in which a measured cell changed. The table keeps the built rows' focus nodes by index, and a later editor must keep that registry exact: keyboard navigation reads it.
4
5mod cells_panel;
6mod column;
7mod keyboard;
8mod layout;
9mod row;
10mod selection;
11mod sort;
12mod source;
13
14pub use column::{TableViewCellTemplate, TableViewColumn, TableViewFrozenEdge, TableViewSortCycle};
15pub use selection::TableViewSelection;
16pub use sort::TableViewSort;
17pub use source::{SortDirection, TableViewSource};
18
19use cells_panel::{CellsPanelColumn, CellsPanelPlacement, ColumnMeasurements, TableViewCellsPanel};
20use column::{ColumnChange, TableViewCellStyle};
21use row::{TableViewRow, TableViewRowEvents, cell_wrapper, row_background};
22
23use crate::FocusState;
24use crate::*;
25use std::cell::Cell;
26use std::collections::HashMap;
27use std::fmt;
28use std::rc::Rc;
29use waft_embedder::{Clip, Color, FontWeight, Offset, Radius, Rect};
30use waft_foundation::{App, Handle, HandleId, ListenableObject, Listener, OptionRetained, Ref};
31use waft_painting::{AlignmentGeometry, Axis, BorderRadius, EdgeInsetsGeometry};
32use waft_scheduler::FrameCallback;
33use waft_services::{HardwareKeyboard, KeyEvent, LogicalKeyboardKey};
34use waft_widgets::*;
35
36/// XAML `TableViewHeadersVisibility`.
37#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
38pub enum TableViewHeadersVisibility {
39    None,
40    #[default]
41    Column,
42}
43
44/// XAML `TableViewGridLinesVisibility`.
45#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
46pub enum TableViewGridLinesVisibility {
47    #[default]
48    All,
49    Horizontal,
50    None,
51    Vertical,
52}
53
54impl TableViewGridLinesVisibility {
55    /// `WantsHorizontalLines`.
56    fn horizontal(self) -> bool {
57        matches!(self, Self::All | Self::Horizontal)
58    }
59
60    /// `WantsVerticalLines`.
61    fn vertical(self) -> bool {
62        matches!(self, Self::All | Self::Vertical)
63    }
64}
65
66/// XAML `TableViewDensity`: the row height and the built-in cell and header padding.
67#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
68pub enum TableViewDensity {
69    Compact,
70    #[default]
71    Standard,
72    Comfortable,
73}
74
75/// XAML `TableViewSelectionMode`.
76#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
77pub enum TableViewSelectionMode {
78    None,
79    #[default]
80    Single,
81}
82
83/// XAML `SelectionChangedEventArgs` of a `TableView`: the items, as their indices in the source's items, that left and joined the selection.
84#[derive(Clone, Debug, Default, PartialEq, Eq)]
85pub struct TableViewSelectionChangedEventArgs {
86    /// `RemovedItems`.
87    pub removed_items: Vec<usize>,
88    /// `AddedItems`.
89    pub added_items: Vec<usize>,
90}
91
92/// XAML `TableViewSortingEventArgs`, raised before a sort is applied.
93pub struct TableViewSortingEventArgs<T> {
94    column: Option<Handle<TableViewColumn<T>>>,
95    direction: SortDirection,
96    cancel: Cell<bool>,
97}
98
99impl<T> TableViewSortingEventArgs<T> {
100    /// `Column`: the column to sort; `None` when every sort is being cleared.
101    pub fn column(&self) -> Option<Handle<TableViewColumn<T>>> {
102        self.column
103    }
104
105    /// `Direction`: the direction about to be applied.
106    pub fn direction(&self) -> SortDirection {
107        self.direction
108    }
109
110    /// `Cancel`: whether the table leaves its sort as it is, the application ordering the rows itself.
111    pub fn cancel(&self) -> bool {
112        self.cancel.get()
113    }
114
115    /// Sets `Cancel`.
116    pub fn set_cancel(&self, cancel: bool) {
117        self.cancel.set(cancel);
118    }
119}
120
121impl<T> fmt::Debug for TableViewSortingEventArgs<T> {
122    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123        f.debug_struct("TableViewSortingEventArgs")
124            .field("column", &self.column)
125            .field("direction", &self.direction)
126            .field("cancel", &self.cancel.get())
127            .finish()
128    }
129}
130
131/// XAML `TableViewSortedEventArgs`, raised after a sort was applied.
132pub struct TableViewSortedEventArgs<T> {
133    column: Option<Handle<TableViewColumn<T>>>,
134    direction: SortDirection,
135}
136
137impl<T> TableViewSortedEventArgs<T> {
138    /// `Column`: the column sorted; `None` when every sort was cleared.
139    pub fn column(&self) -> Option<Handle<TableViewColumn<T>>> {
140        self.column
141    }
142
143    /// `Direction`: the direction now applied to the column.
144    pub fn direction(&self) -> SortDirection {
145        self.direction
146    }
147}
148
149impl<T> fmt::Debug for TableViewSortedEventArgs<T> {
150    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151        f.debug_struct("TableViewSortedEventArgs")
152            .field("column", &self.column)
153            .field("direction", &self.direction)
154            .finish()
155    }
156}
157
158/// Builds what an empty table shows: XAML's `EmptyTemplate`.
159pub type TableViewEmptyTemplate = Rc<dyn Fn(&mut App, BuildContext) -> WidgetRef>;
160
161/// Receives XAML `SelectionChanged`.
162pub type TableViewSelectionChangedHandler =
163    Rc<dyn Fn(&mut App, &TableViewSelectionChangedEventArgs)>;
164
165/// Receives XAML `Sorting`.
166pub type TableViewSortingHandler<T> = Rc<dyn Fn(&mut App, &TableViewSortingEventArgs<T>)>;
167
168/// Receives XAML `Sorted`.
169pub type TableViewSortedHandler<T> = Rc<dyn Fn(&mut App, &TableViewSortedEventArgs<T>)>;
170
171/// XAML `TableView`.
172pub struct TableView<T> {
173    /// `ItemsSource`: the items and the shape they are shown in.
174    pub items_source: Ref<TableViewSource<T>>,
175    /// `Columns`.
176    pub columns: Vec<Ref<TableViewColumn<T>>>,
177    /// `HeadersVisibility`.
178    pub headers_visibility: TableViewHeadersVisibility,
179    /// `GridLinesVisibility`.
180    pub grid_lines_visibility: TableViewGridLinesVisibility,
181    /// `CanUserResizeColumns`.
182    pub can_user_resize_columns: bool,
183    /// `CanUserSortColumns`.
184    pub can_user_sort_columns: bool,
185    /// `Density`.
186    pub density: TableViewDensity,
187    /// `RowBackground`.
188    pub row_background: Option<Brush>,
189    /// `AlternatingRowBackground`.
190    pub alternating_row_background: Option<Brush>,
191    /// `EmptyTemplate`.
192    pub empty_template: Option<TableViewEmptyTemplate>,
193    /// `SelectionMode`; selection needs a [`selection`](Self::selection) as well.
194    pub selection_mode: TableViewSelectionMode,
195    /// The selection, which holds `SelectedIndex` and `SelectedItem`; a table given none selects nothing.
196    pub selection: Option<Ref<TableViewSelection>>,
197    /// Sorting from code; a header sorts without it.
198    pub sort: Option<Ref<TableViewSort>>,
199    /// `SelectionChanged`.
200    pub selection_changed: Option<TableViewSelectionChangedHandler>,
201    /// `Sorting`.
202    pub sorting: Option<TableViewSortingHandler<T>>,
203    /// `Sorted`.
204    pub sorted: Option<TableViewSortedHandler<T>>,
205    /// Identity retained across parent rebuilds.
206    pub key: Option<KeyRef>,
207}
208
209impl<T> Clone for TableView<T> {
210    fn clone(&self) -> Self {
211        Self {
212            items_source: self.items_source.clone(),
213            columns: self.columns.clone(),
214            headers_visibility: self.headers_visibility,
215            grid_lines_visibility: self.grid_lines_visibility,
216            can_user_resize_columns: self.can_user_resize_columns,
217            can_user_sort_columns: self.can_user_sort_columns,
218            density: self.density,
219            row_background: self.row_background,
220            alternating_row_background: self.alternating_row_background,
221            empty_template: self.empty_template.clone(),
222            selection_mode: self.selection_mode,
223            selection: self.selection.clone(),
224            sort: self.sort.clone(),
225            selection_changed: self.selection_changed.clone(),
226            sorting: self.sorting.clone(),
227            sorted: self.sorted.clone(),
228            key: self.key.clone(),
229        }
230    }
231}
232
233impl<T: 'static> TableView<T> {
234    /// Creates a table of the items of `items_source` in `columns`.
235    pub fn new(
236        items_source: Ref<TableViewSource<T>>,
237        columns: Vec<Ref<TableViewColumn<T>>>,
238    ) -> Self {
239        Self {
240            items_source,
241            columns,
242            headers_visibility: TableViewHeadersVisibility::Column,
243            grid_lines_visibility: TableViewGridLinesVisibility::All,
244            can_user_resize_columns: true,
245            can_user_sort_columns: true,
246            density: TableViewDensity::Standard,
247            row_background: None,
248            alternating_row_background: None,
249            empty_template: None,
250            selection_mode: TableViewSelectionMode::Single,
251            selection: None,
252            sort: None,
253            selection_changed: None,
254            sorting: None,
255            sorted: None,
256            key: None,
257        }
258    }
259
260    /// Sets the XAML `HeadersVisibility`.
261    pub fn headers_visibility(mut self, value: TableViewHeadersVisibility) -> Self {
262        self.headers_visibility = value;
263        self
264    }
265
266    /// Sets the XAML `GridLinesVisibility`.
267    pub fn grid_lines_visibility(mut self, value: TableViewGridLinesVisibility) -> Self {
268        self.grid_lines_visibility = value;
269        self
270    }
271
272    /// Sets the XAML `CanUserResizeColumns`.
273    pub fn can_user_resize_columns(mut self, value: bool) -> Self {
274        self.can_user_resize_columns = value;
275        self
276    }
277
278    /// Sets the XAML `CanUserSortColumns`.
279    pub fn can_user_sort_columns(mut self, value: bool) -> Self {
280        self.can_user_sort_columns = value;
281        self
282    }
283
284    /// Sets the XAML `Density`.
285    pub fn density(mut self, value: TableViewDensity) -> Self {
286        self.density = value;
287        self
288    }
289
290    /// Sets the XAML `RowBackground`.
291    pub fn row_background(mut self, value: Brush) -> Self {
292        self.row_background = Some(value);
293        self
294    }
295
296    /// Sets the XAML `AlternatingRowBackground`.
297    pub fn alternating_row_background(mut self, value: Brush) -> Self {
298        self.alternating_row_background = Some(value);
299        self
300    }
301
302    /// Sets the XAML `EmptyTemplate`.
303    pub fn empty_template(
304        mut self,
305        template: impl Fn(&mut App, BuildContext) -> WidgetRef + 'static,
306    ) -> Self {
307        self.empty_template = Some(Rc::new(template));
308        self
309    }
310
311    /// Sets the XAML `SelectionMode`.
312    pub fn selection_mode(mut self, value: TableViewSelectionMode) -> Self {
313        self.selection_mode = value;
314        self
315    }
316
317    /// Gives the table the application's selection.
318    pub fn selection(mut self, value: Ref<TableViewSelection>) -> Self {
319        self.selection = Some(value);
320        self
321    }
322
323    /// Gives the table the application's sorting from code.
324    pub fn sort(mut self, value: Ref<TableViewSort>) -> Self {
325        self.sort = Some(value);
326        self
327    }
328
329    /// Sets the XAML `SelectionChanged` handler.
330    pub fn selection_changed(
331        mut self,
332        handler: impl Fn(&mut App, &TableViewSelectionChangedEventArgs) + 'static,
333    ) -> Self {
334        self.selection_changed = Some(Rc::new(handler));
335        self
336    }
337
338    /// Sets the XAML `Sorting` handler.
339    pub fn sorting(
340        mut self,
341        handler: impl Fn(&mut App, &TableViewSortingEventArgs<T>) + 'static,
342    ) -> Self {
343        self.sorting = Some(Rc::new(handler));
344        self
345    }
346
347    /// Sets the XAML `Sorted` handler.
348    pub fn sorted(
349        mut self,
350        handler: impl Fn(&mut App, &TableViewSortedEventArgs<T>) + 'static,
351    ) -> Self {
352        self.sorted = Some(Rc::new(handler));
353        self
354    }
355
356    /// Sets the identity retained across rebuilds.
357    pub fn key(mut self, key: KeyRef) -> Self {
358        self.key = Some(key);
359        self
360    }
361}
362
363impl<T> fmt::Debug for TableView<T> {
364    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
365        f.debug_struct("TableView")
366            .field("columns", &self.columns.len())
367            .field("headers_visibility", &self.headers_visibility)
368            .field("grid_lines_visibility", &self.grid_lines_visibility)
369            .field("density", &self.density)
370            .field("selection_mode", &self.selection_mode)
371            .finish_non_exhaustive()
372    }
373}
374
375impl<T: 'static> StatefulWidget for TableView<T> {
376    type State = TableViewState<T>;
377
378    fn key(&self) -> Option<&KeyRef> {
379        self.key.as_ref()
380    }
381
382    fn create_state(&self) -> TableViewState<T> {
383        TableViewState {
384            state: StateData::new(),
385            vertical: None,
386            horizontal: None,
387            measurements: None,
388            resolve_queued: false,
389            viewport: None,
390            scale: 1.0,
391            source: None,
392            selection: None,
393            sort: None,
394            columns: Vec::new(),
395            sorted_column: None,
396            source_sort_token: None,
397            grippers: HashMap::new(),
398            active_resize: None,
399            rows: HashMap::new(),
400            focus_epoch: 0,
401            body_key: GlobalKey::new(),
402        }
403    }
404}
405
406/// `ColumnResizeDragState`: the drag in flight, which Escape can cancel.
407struct ColumnResizeDrag<T> {
408    column: Handle<TableViewColumn<T>>,
409    /// `startValue`: the column's width when the drag began.
410    start_value: f64,
411    /// `startWidth`: its `Width` as authored, which a canceled drag restores.
412    start_width: GridLength,
413    /// `didWrite`: the drag has written `Width`.
414    did_write: bool,
415}
416
417impl<T> Clone for ColumnResizeDrag<T> {
418    fn clone(&self) -> Self {
419        *self
420    }
421}
422
423impl<T> Copy for ColumnResizeDrag<T> {}
424
425/// The table's view of its source, selection, sort and columns, its scrolling, the grippers and the built rows.
426pub struct TableViewState<T: 'static> {
427    state: StateData<TableView<T>>,
428    vertical: Option<Ref<ScrollViewportController>>,
429    horizontal: Option<Ref<ScrollViewportController>>,
430    measurements: Option<Rc<ColumnMeasurements>>,
431    /// A width resolution is waiting for the end of the frame.
432    resolve_queued: bool,
433    /// The body's width at the last layout.
434    viewport: Option<f64>,
435    /// The device pixel ratio widths are rounded to.
436    scale: f64,
437    source: Option<(Ref<TableViewSource<T>>, Listener)>,
438    selection: Option<(Ref<TableViewSelection>, Listener)>,
439    sort: Option<Ref<TableViewSort>>,
440    /// The columns listened to, with their listeners.
441    columns: Vec<(Ref<TableViewColumn<T>>, Listener)>,
442    /// `m_sortedColumns`: the one column sorted, if any.
443    sorted_column: Option<Handle<TableViewColumn<T>>>,
444    /// `m_tableViewSourceSort.AxisToken`: the source axis the table installed.
445    source_sort_token: Option<HandleId>,
446    /// Each column's gripper gesture.
447    grippers: HashMap<HandleId, Ref<ResizeGripperDrag>>,
448    /// `m_activeColumnResizeDrag`.
449    active_resize: Option<ColumnResizeDrag<T>>,
450    /// The built rows' focus nodes by index.
451    rows: HashMap<usize, Handle<FocusNode>>,
452    /// Counts focus requests, so a request waiting for its row to be built gives way to a later one.
453    focus_epoch: u64,
454    /// The body viewport, whose rectangle keyboard navigation scrolls rows into.
455    body_key: GlobalKey,
456}
457
458/// What every row of one build shares.
459struct RowLayout {
460    columns: Vec<CellsPanelColumn>,
461    frozen: usize,
462    vertical_lines: bool,
463    horizontal_lines: bool,
464    min_height: f64,
465    cell_style: TableViewCellStyle,
466    row_background: Option<Brush>,
467    alternating_row_background: Option<Brush>,
468}
469
470/// The density's metrics: `GetDensityRowMinHeight`, `GetDensityCellPadding` and `GetDensityHeaderCellPadding`.
471fn density_metrics(r: &ThemeResources, density: TableViewDensity) -> (f64, [f64; 4], [f64; 4]) {
472    match density {
473        TableViewDensity::Compact => (
474            r.table_view_row_min_height_compact,
475            r.table_view_cell_padding_compact,
476            r.table_view_header_cell_padding_compact,
477        ),
478        TableViewDensity::Standard => (
479            r.table_view_row_min_height,
480            r.table_view_cell_padding,
481            r.table_view_header_cell_padding,
482        ),
483        TableViewDensity::Comfortable => (
484            r.table_view_row_min_height_comfortable,
485            r.table_view_cell_padding_comfortable,
486            r.table_view_header_cell_padding_comfortable,
487        ),
488    }
489}
490
491// MARK: Source and columns
492
493impl<T: 'static> TableViewState<T> {
494    fn id_of(self: Handle<Self>) -> HandleId {
495        self.id()
496    }
497
498    fn source_handle(self: Handle<Self>, app: &App) -> Handle<TableViewSource<T>> {
499        self.widget(app).items_source.handle()
500    }
501
502    fn row_count(self: Handle<Self>, app: &App) -> usize {
503        self.source_handle(app).view(app).len()
504    }
505
506    fn selection_handle(self: Handle<Self>, app: &App) -> Option<Handle<TableViewSelection>> {
507        self.widget(app).selection.handle()
508    }
509
510    /// The columns the table owns, in order; a column another table holds is skipped, as `IsColumnOwnedBy` skips it.
511    fn owned_columns(self: Handle<Self>, app: &App) -> Vec<Handle<TableViewColumn<T>>> {
512        let id = self.id_of();
513        self.widget(app)
514            .columns
515            .iter()
516            .map(|column| column.handle())
517            .filter(|column| column.owner(app) == Some(id))
518            .collect()
519    }
520
521    fn alive(self: Handle<Self>, app: &App) -> bool {
522        app.contains(self) && self.mounted(app)
523    }
524
525    /// Runs `work` once the frame is over, if the table is still mounted.
526    fn after_frame(self: Handle<Self>, app: &mut App, work: impl Fn(&mut App) + 'static) {
527        let view = View::maybe_id_of(app, self.context(app));
528        after_next_frame(
529            app,
530            view,
531            FrameCallback::new(move |app, _| {
532                if self.alive(app) {
533                    work(app);
534                }
535            }),
536        );
537    }
538
539    fn sync(self: Handle<Self>, app: &mut App) {
540        self.sync_source(app);
541        self.sync_columns(app);
542        self.sync_selection(app);
543        self.sync_sort(app);
544    }
545
546    /// `AdoptItemsSource`: listens to the source and owns it; a different source drops the sort the old one carried (`ResetSortStateForNewItemsSource`).
547    fn sync_source(self: Handle<Self>, app: &mut App) {
548        let source = self.widget(app).items_source.clone();
549        let held = app.get(self).source.as_ref().map(|(held, _)| held.handle());
550        if held == Some(source.handle()) {
551            return;
552        }
553        if let Some((old, listener)) = app.get_mut(self).source.take() {
554            old.remove_listener(app, &listener);
555            old.set_owner(app, None);
556            self.reset_sort_state_for_new_items_source(app);
557        }
558        source.set_owner(app, Some(self.id_of()));
559        let listener = Listener::new(move |app| self.source_changed(app));
560        source.add_listener(app, listener.clone());
561        app.get_mut(self).source = Some((source, listener));
562    }
563
564    /// The source changed its view: the rows are rebuilt. The selection follows its source itself,
565    /// so rows that change while no table holds it still move it.
566    fn source_changed(self: Handle<Self>, app: &mut App) {
567        if !self.alive(app) {
568            return;
569        }
570        self.set_state(app, |_| {});
571    }
572
573    /// `TrackColumnsFromVector` and `DetachAllColumnOwners`: the table owns and listens to its columns; a column that left gives up its sort (`PurgeColumnFromSortState`).
574    fn sync_columns(self: Handle<Self>, app: &mut App) {
575        let id = self.id_of();
576        let columns = self.widget(app).columns.clone();
577        let held = std::mem::take(&mut app.get_mut(self).columns);
578        let mut kept = Vec::with_capacity(columns.len());
579        let mut purged = false;
580        for (column, listener) in held {
581            if columns
582                .iter()
583                .any(|current| current.handle() == column.handle())
584            {
585                kept.push((column, listener));
586                continue;
587            }
588            column.remove_listener(app, &listener);
589            column.set_owner(app, None);
590            column.set_sort_state(app, SortDirection::None);
591            if app.get(self).sorted_column == Some(column.handle()) {
592                app.get_mut(self).sorted_column = None;
593                purged = true;
594            }
595            if let Some(gripper) = app.get_mut(self).grippers.remove(&column.handle().id()) {
596                gripper.dispose(app);
597            }
598        }
599        for column in columns {
600            if kept
601                .iter()
602                .any(|(held, _)| held.handle() == column.handle())
603            {
604                continue;
605            }
606            if !column.set_owner(app, Some(id)) {
607                continue;
608            }
609            let handle = column.handle();
610            let listener = Listener::new(move |app| self.column_changed(app, handle));
611            column.add_listener(app, listener.clone());
612            kept.push((column, listener));
613        }
614        app.get_mut(self).columns = kept;
615        if purged {
616            // `QueueClearSortAfterColumnRemoval`: the reshape waits until the columns settle.
617            self.after_frame(app, move |app| self.recompute_sort_and_raise(app, None));
618        }
619    }
620
621    /// `TableViewColumn::OnPropertyChanged`'s calls into the table.
622    fn column_changed(self: Handle<Self>, app: &mut App, column: Handle<TableViewColumn<T>>) {
623        if !self.alive(app) || !app.contains(column) {
624            return;
625        }
626        match column.change(app) {
627            ColumnChange::None | ColumnChange::Other => return,
628            // `OnColumnCanSortChanged`: a column that opted out drops the sort it holds.
629            ColumnChange::CanSort => {
630                if !column.can_sort(app) && column.sort_direction(app) != SortDirection::None {
631                    self.sort_by_column(app, column, SortDirection::None);
632                }
633            }
634            // The order the column is sorted in belongs to the comparer it was sorted with.
635            ColumnChange::CustomSortComparer => {
636                let direction = column.sort_direction(app);
637                if direction != SortDirection::None {
638                    self.sort_by_column(app, column, SortDirection::None);
639                    self.sort_by_column(app, column, direction);
640                }
641            }
642            _ => {}
643        }
644        self.set_state(app, |_| {});
645    }
646}
647
648// MARK: Resizing a column
649
650impl<T: 'static> TableViewState<T> {
651    /// The gripper gesture of `column`, made the first time its header shows one.
652    fn gripper(
653        self: Handle<Self>,
654        app: &mut App,
655        column: Handle<TableViewColumn<T>>,
656    ) -> Ref<ResizeGripperDrag> {
657        if let Some(gripper) = app.get(self).grippers.get(&column.id()) {
658            return gripper.clone();
659        }
660        let gripper = ResizeGripperDrag::new(
661            app,
662            Axis::Horizontal,
663            ResizeGripperEvents {
664                drag_started: Rc::new(move |app| self.resize_started(app, column)),
665                drag_delta: Rc::new(move |app, _, total| self.resize_delta(app, column, total)),
666                drag_completed: Rc::new(move |app, _, canceled| {
667                    self.resize_completed(app, column, canceled)
668                }),
669            },
670        );
671        app.get_mut(self)
672            .grippers
673            .insert(column.id(), gripper.clone());
674        gripper
675    }
676
677    /// `DragStarted`: one resize at a time; the column's width and authored `Width` are the anchor.
678    fn resize_started(self: Handle<Self>, app: &mut App, column: Handle<TableViewColumn<T>>) {
679        if !app.contains(self) || !app.contains(column) {
680            return;
681        }
682        if let Some(active) = app.get(self).active_resize
683            && active.column != column
684            && let Some(other) = app.get(self).grippers.get(&active.column.id()).cloned()
685            && other.is_dragging(app)
686        {
687            if let Some(own) = app.get(self).grippers.get(&column.id()).cloned() {
688                own.end_drag(app, true);
689            }
690            return;
691        }
692        app.get_mut(self).active_resize = Some(ColumnResizeDrag {
693            column,
694            start_value: column.actual_width(app),
695            start_width: column.width(app),
696            did_write: false,
697        });
698    }
699
700    /// `DragDelta`: the anchor plus the offset, clamped to the column's bounds, written as a pixel `Width`.
701    fn resize_delta(
702        self: Handle<Self>,
703        app: &mut App,
704        column: Handle<TableViewColumn<T>>,
705        total: f64,
706    ) {
707        if !app.contains(self) || !app.contains(column) {
708            return;
709        }
710        let Some(active) = app
711            .get(self)
712            .active_resize
713            .filter(|active| active.column == column)
714        else {
715            return;
716        };
717        let min = column.min_width(app);
718        let lo = if min.is_finite() && min >= 0.0 {
719            min
720        } else {
721            0.0
722        };
723        let max = column.max_width(app);
724        let hi = if max.is_finite() && max >= 0.0 {
725            lo.max(max)
726        } else {
727            f64::INFINITY
728        };
729        let next = (active.start_value + total).clamp(lo, hi);
730        let current = column.width(app);
731        if current.unit == GridUnitType::Pixel && (current.value - next).abs() < 0.0001 {
732            return;
733        }
734        column.set_width(app, GridLength::pixel(next));
735        if let Some(active) = &mut app.get_mut(self).active_resize {
736            active.did_write = true;
737        }
738    }
739
740    /// `DragCompleted`: a canceled drag restores the authored `Width`.
741    fn resize_completed(
742        self: Handle<Self>,
743        app: &mut App,
744        column: Handle<TableViewColumn<T>>,
745        canceled: bool,
746    ) {
747        if !app.contains(self) {
748            return;
749        }
750        let Some(active) = app
751            .get(self)
752            .active_resize
753            .filter(|active| active.column == column)
754        else {
755            return;
756        };
757        app.get_mut(self).active_resize = None;
758        if canceled && active.did_write && app.contains(column) {
759            column.set_width(app, active.start_width);
760        }
761    }
762
763    /// `CancelColumnResizeDrag`: Escape ends the drag in flight. Answers whether there was one.
764    fn cancel_column_resize_drag(self: Handle<Self>, app: &mut App) -> bool {
765        let Some(active) = app.get(self).active_resize else {
766            return false;
767        };
768        match app.get(self).grippers.get(&active.column.id()).cloned() {
769            Some(gripper) if gripper.is_dragging(app) => gripper.end_drag(app, true),
770            _ => app.get_mut(self).active_resize = None,
771        }
772        true
773    }
774
775    /// `TryHandleHeaderColumnResizeKey`: Left and Right resize the column whose header has the focus, Shift the larger step; Alt is reserved.
776    fn header_key(
777        self: Handle<Self>,
778        app: &mut App,
779        column: Handle<TableViewColumn<T>>,
780        event: &KeyEvent,
781    ) -> KeyEventResult {
782        if matches!(event, KeyEvent::Up(_)) {
783            return KeyEventResult::Ignored;
784        }
785        let key = event.logical_key();
786        if key != LogicalKeyboardKey::ARROW_LEFT && key != LogicalKeyboardKey::ARROW_RIGHT {
787            return KeyEventResult::Ignored;
788        }
789        let keyboard = HardwareKeyboard::instance(app);
790        if keyboard.is_alt_pressed(app) {
791            return KeyEventResult::Ignored;
792        }
793        if !self.widget(app).can_user_resize_columns || !column.can_resize(app) {
794            return KeyEventResult::Ignored;
795        }
796        let shift = keyboard.is_shift_pressed(app);
797        let gripper = self.gripper(app, column);
798        if gripper.try_keyboard_step(app, key, false, shift) {
799            KeyEventResult::Handled
800        } else {
801            KeyEventResult::Ignored
802        }
803    }
804}
805
806// MARK: Building
807
808impl<T: 'static> TableViewState<T> {
809    fn vertical(self: Handle<Self>, app: &App) -> Handle<ScrollViewportController> {
810        app.get(self)
811            .vertical
812            .handle()
813            .expect("made in `init_state`")
814    }
815
816    fn horizontal(self: Handle<Self>, app: &App) -> Handle<ScrollViewportController> {
817        app.get(self)
818            .horizontal
819            .handle()
820            .expect("made in `init_state`")
821    }
822
823    /// The template inside the border, at the width the table is given: the widths are resolved here, then `PART_HeaderRow` over `PART_BodyScroller`.
824    fn template(self: Handle<Self>, app: &mut App, context: BuildContext, width: f64) -> WidgetRef {
825        let r = ThemeResources::of(app, context);
826        let widget = self.widget(app).clone();
827        let scale = MediaQuery::maybe_device_pixel_ratio_of(app, context).unwrap_or(1.0);
828        {
829            let state = app.get_mut(self);
830            state.viewport = Some(width).filter(|width| width.is_finite());
831            state.scale = scale;
832        }
833        let columns = self.owned_columns(app);
834        self.resolve_column_widths(app, &columns);
835        let (min_height, cell_padding, header_padding) = density_metrics(&r, widget.density);
836        let panel_columns: Vec<CellsPanelColumn> = columns
837            .iter()
838            .map(|&column| CellsPanelColumn {
839                id: column.id(),
840                auto: column.width(app).unit == GridUnitType::Auto,
841                width: column.actual_width(app),
842                visible: column.visible(app),
843            })
844            .collect();
845        // Only the contiguous prefix from the first column is frozen.
846        let frozen = columns
847            .iter()
848            .take_while(|column| column.frozen_edge(app) == TableViewFrozenEdge::Leading)
849            .count();
850        let content_width: f64 = panel_columns
851            .iter()
852            .filter(|column| column.visible)
853            .map(|column| column.width)
854            .sum();
855        let layout = Rc::new(RowLayout {
856            columns: panel_columns,
857            frozen,
858            vertical_lines: widget.grid_lines_visibility.vertical(),
859            horizontal_lines: widget.grid_lines_visibility.horizontal(),
860            min_height,
861            cell_style: TableViewCellStyle {
862                padding: cell_padding,
863                font_size: r.table_view_cell_font_size,
864            },
865            row_background: widget.row_background,
866            alternating_row_background: widget.alternating_row_background,
867        });
868        let mut children = Vec::new();
869        if widget.headers_visibility == TableViewHeadersVisibility::Column {
870            children.push(self.header_row(app, &r, &layout, &columns, header_padding));
871        }
872        children.push(
873            Expanded::new(self.body(app, context, &layout, content_width.max(width))).into_widget(),
874        );
875        Column::new().children(children).into_widget()
876    }
877
878    /// PART_HeaderRow > PART_HeaderScroller > PART_HeaderHost.
879    fn header_row(
880        self: Handle<Self>,
881        app: &mut App,
882        r: &ThemeResources,
883        layout: &RowLayout,
884        columns: &[Handle<TableViewColumn<T>>],
885        header_padding: [f64; 4],
886    ) -> WidgetRef {
887        let cells: Vec<WidgetRef> = columns
888            .iter()
889            .map(|&column| self.header_cell(app, r, layout, column, header_padding))
890            .collect();
891        let host = TableViewCellsPanel {
892            columns: layout.columns.clone(),
893            frozen: layout.frozen,
894            placement: CellsPanelPlacement::Header,
895            horizontal: self.horizontal(app).native_controller(app),
896            measurements: self.measurements(app),
897            children: cells,
898        };
899        ControlBorder::new(
900            Brush::Solid(r.tabular_surface_header_background_brush),
901            Brush::Solid(r.tabular_surface_grid_line_brush),
902        )
903        .border_thickness_ltrb(if layout.horizontal_lines {
904            [0.0, 0.0, 0.0, 1.0]
905        } else {
906            [0.0; 4]
907        })
908        .child(host)
909        .into_widget()
910    }
911
912    /// One header cell (`RebuildHeaders`): the header content, the vertical grid line, the sort chevron and the gripper, on the cell's trailing edge in that order.
913    fn header_cell(
914        self: Handle<Self>,
915        app: &mut App,
916        r: &ThemeResources,
917        layout: &RowLayout,
918        column: Handle<TableViewColumn<T>>,
919        header_padding: [f64; 4],
920    ) -> WidgetRef {
921        let widget = self.widget(app).clone();
922        let [left, top, right, bottom] = header_padding;
923        let content = Padding::new(EdgeInsetsGeometry::from_ltrb(left, top, right, bottom)).child(
924            Align::new()
925                .alignment(AlignmentGeometry::CENTER_LEFT)
926                .child(
927                    Text::new(column.header(app).to_string())
928                        .style(control_text_style(
929                            r,
930                            r.table_view_header_font_size,
931                            FontWeight::W600,
932                            r.tabular_surface_row_foreground_brush,
933                        ))
934                        .max_lines(1)
935                        .soft_wrap(false),
936                ),
937        );
938        let mut children = vec![content.into_widget()];
939        if layout.vertical_lines {
940            // TableViewHeaderGridLine
941            children.push(
942                Positioned::new(
943                    IgnorePointer::new().child(ColoredBox::new(r.tabular_surface_grid_line_brush)),
944                )
945                .right(0.0)
946                .top(0.0)
947                .bottom(0.0)
948                .width(1.0)
949                .into_widget(),
950            );
951        }
952        let sortable = widget.can_user_sort_columns && column.can_sort(app);
953        if sortable {
954            let direction = match column.sort_direction(app) {
955                SortDirection::Ascending => SortIndicatorDirection::Ascending,
956                SortDirection::Descending => SortIndicatorDirection::Descending,
957                SortDirection::None => SortIndicatorDirection::None,
958            };
959            // TableViewSortIndicator in its host, centred on the trailing edge.
960            children.push(
961                Positioned::new(Center::new().child(SortIndicator::new(direction)))
962                    .right(0.0)
963                    .top(0.0)
964                    .bottom(0.0)
965                    .into_widget(),
966            );
967        }
968        let resizable = widget.can_user_resize_columns && column.can_resize(app);
969        if resizable {
970            let gripper_width = Some(r.table_view_resize_gripper_width)
971                .filter(|width| width.is_finite() && *width > 0.0)
972                .unwrap_or(8.0);
973            let gripper = self.gripper(app, column);
974            children.push(
975                Positioned::new(ResizeGripper::new(gripper))
976                    .right(0.0)
977                    .top(0.0)
978                    .bottom(0.0)
979                    .width(gripper_width)
980                    .into_widget(),
981            );
982        }
983        let mut cell: WidgetRef =
984            ConstrainedBox::new(BoxConstraints::new().min_height(layout.min_height))
985                .child(ColoredBox::new(Color::new(0)).child(Stack::new().children(children)))
986                .into_widget();
987        if sortable {
988            cell = GestureDetector::new()
989                .behavior(waft_rendering::HitTestBehavior::Opaque)
990                .on_tap(Listener::new(move |app| {
991                    if self.alive(app) && app.contains(column) {
992                        self.toggle_sort_direction(app, column);
993                    }
994                }))
995                .child(cell)
996                .into_widget();
997        }
998        if let Some(tip) = column.header_tool_tip(app).filter(|tip| !tip.is_empty()) {
999            cell =
1000                ToolTipService::new(cell, ToolTip::new(Text::new(tip.to_string()))).into_widget();
1001        }
1002        HeaderCell {
1003            child: cell,
1004            is_tab_stop: resizable,
1005            key_handler: Rc::new(move |app, event| {
1006                if self.alive(app) && app.contains(column) {
1007                    self.header_key(app, column, event)
1008                } else {
1009                    KeyEventResult::Ignored
1010                }
1011            }),
1012        }
1013        .into_widget()
1014    }
1015
1016    /// PART_BodyScroller > PART_BodyContent: PART_RowsRepeater, or PART_EmptyStatePresenter when there are no rows and an `EmptyTemplate`.
1017    fn body(
1018        self: Handle<Self>,
1019        app: &mut App,
1020        context: BuildContext,
1021        layout: &Rc<RowLayout>,
1022        rows_width: f64,
1023    ) -> WidgetRef {
1024        let widget = self.widget(app).clone();
1025        let count = self.row_count(app);
1026        if count == 0
1027            && let Some(template) = widget.empty_template.clone()
1028        {
1029            return Center::new().child(template(app, context)).into_widget();
1030        }
1031        let layout = layout.clone();
1032        let list = ListView::builder(move |app, context, index| {
1033            Some(self.row(app, context, index as usize, &layout))
1034        })
1035        .item_count(count as i32)
1036        .build()
1037        .controller(self.vertical(app).native_controller(app));
1038        let rows = SizedBox::new().width(rows_width).child(list);
1039        let horizontal = ScrollBarViewport::new(
1040            app.get(self)
1041                .horizontal
1042                .clone()
1043                .expect("made in `init_state`"),
1044            rows,
1045        )
1046        .axis(Axis::Horizontal);
1047        let vertical = ScrollBarViewport::scroller(
1048            app.get(self)
1049                .vertical
1050                .clone()
1051                .expect("made in `init_state`"),
1052            horizontal,
1053        )
1054        .depth(1);
1055        KeyedSubtree::new(vertical.into_widget())
1056            .key(app.get(self).body_key.clone().into())
1057            .into_widget()
1058    }
1059
1060    /// One `TableViewRow`: a cell wrapper per column, from `GenerateElement` for the row's item.
1061    fn row(
1062        self: Handle<Self>,
1063        app: &mut App,
1064        context: BuildContext,
1065        index: usize,
1066        layout: &RowLayout,
1067    ) -> WidgetRef {
1068        let r = ThemeResources::of(app, context);
1069        let widget = self.widget(app).clone();
1070        let source = self.source_handle(app);
1071        let Some(&item) = source.view(app).get(index) else {
1072            return SizedBox::new().into_widget();
1073        };
1074        let item = source.shared_item(app, item);
1075        let columns = self.owned_columns(app);
1076        let cells: Vec<WidgetRef> = columns
1077            .iter()
1078            .map(|&column| {
1079                let element = column.generate_element(app, context, &item, layout.cell_style);
1080                cell_wrapper(&r, layout.vertical_lines, layout.min_height, element)
1081            })
1082            .collect();
1083        let panel = TableViewCellsPanel {
1084            columns: layout.columns.clone(),
1085            frozen: layout.frozen,
1086            placement: CellsPanelPlacement::Row,
1087            horizontal: self.horizontal(app).native_controller(app),
1088            measurements: self.measurements(app),
1089            children: cells,
1090        };
1091        TableViewRow {
1092            index,
1093            cells: panel.into_widget(),
1094            background: row_background(
1095                &r,
1096                index,
1097                layout.row_background,
1098                layout.alternating_row_background,
1099            ),
1100            horizontal_lines: layout.horizontal_lines,
1101            min_height: layout.min_height,
1102            selection: widget.selection.clone(),
1103            events: Rc::new(TableViewRowEvents {
1104                pointer_select: Rc::new(move |app, index| {
1105                    if self.alive(app) {
1106                        self.select_row_from_interaction(app, index);
1107                    }
1108                }),
1109                register: Rc::new(move |app, index, node| self.register_row(app, index, node)),
1110                unregister: Rc::new(move |app, index, node| self.unregister_row(app, index, node)),
1111            }),
1112        }
1113        .into_widget()
1114    }
1115}
1116
1117impl<T: 'static> State for TableViewState<T> {
1118    type Widget = TableView<T>;
1119    waft_widgets::state_accessors!();
1120
1121    fn init_state(self: Handle<Self>, app: &mut App) {
1122        InputDevice::initialize(app);
1123        let vertical = ScrollViewportController::new(app);
1124        let horizontal = ScrollViewportController::new(app);
1125        let measurements = ColumnMeasurements::new(Rc::new(move |app| self.request_resolve(app)));
1126        let state = app.get_mut(self);
1127        state.vertical = Some(vertical);
1128        state.horizontal = Some(horizontal);
1129        state.measurements = Some(measurements);
1130        self.sync(app);
1131    }
1132
1133    fn did_update_widget(self: Handle<Self>, app: &mut App, old: &TableView<T>) {
1134        self.sync(app);
1135        // `OnCanUserSortColumnsPropertyChanged`: turning sorting off drops the sort it made.
1136        if old.can_user_sort_columns && !self.widget(app).can_user_sort_columns {
1137            self.clear_sort(app);
1138        }
1139    }
1140
1141    fn dispose(self: Handle<Self>, app: &mut App) {
1142        let id = self.id_of();
1143        if let Some((source, listener)) = app.get_mut(self).source.take() {
1144            source.remove_listener(app, &listener);
1145            source.set_owner(app, None);
1146        }
1147        if let Some((selection, listener)) = app.get_mut(self).selection.take() {
1148            selection.remove_listener(app, &listener);
1149            selection.unbind(app, id);
1150        }
1151        if let Some(sort) = app.get_mut(self).sort.take() {
1152            sort.unbind(app, id);
1153        }
1154        for (column, listener) in std::mem::take(&mut app.get_mut(self).columns) {
1155            column.remove_listener(app, &listener);
1156            column.set_owner(app, None);
1157        }
1158        for (_, gripper) in std::mem::take(&mut app.get_mut(self).grippers) {
1159            gripper.dispose(app);
1160        }
1161        for controller in [
1162            app.get_mut(self).vertical.take(),
1163            app.get_mut(self).horizontal.take(),
1164        ]
1165        .into_iter()
1166        .flatten()
1167        {
1168            controller.dispose(app);
1169        }
1170    }
1171
1172    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1173        let r = ThemeResources::of(app, context);
1174        let corner = r.control_corner_radius;
1175        let template = LayoutBuilder::new(move |app, context, constraints| {
1176            // The border's 1 pixel on each side is outside the template.
1177            self.template(app, context, constraints.constraints().max_width)
1178        });
1179        let [top_left, top_right, bottom_right, bottom_left] =
1180            corner.map(|radius| Radius::circular((radius - 1.0).max(0.0)));
1181        let clipped = ClipRRect::new()
1182            .border_radius(
1183                BorderRadius::only(top_left, top_right, bottom_left, bottom_right).into(),
1184            )
1185            .clip_behavior(Clip::AntiAlias)
1186            .child(template.into_widget());
1187        let border = ControlBorder::new(
1188            Brush::Solid(r.tabular_surface_row_background_brush),
1189            Brush::Solid(r.tabular_surface_grid_line_brush),
1190        )
1191        .border_thickness(1.0)
1192        .corner_radius_corners(corner)
1193        .child(DefaultTextStyle::new(
1194            control_text_style(
1195                &r,
1196                r.table_view_cell_font_size,
1197                FontWeight::NORMAL,
1198                r.tabular_surface_row_foreground_brush,
1199            ),
1200            clipped,
1201        ));
1202        Focus::new(border)
1203            .can_request_focus(false)
1204            .skip_traversal(true)
1205            .on_key_event(Rc::new(move |app, _, event| self.key(app, event)))
1206            .into_widget()
1207    }
1208}
1209
1210/// A header cell's key handler.
1211type HeaderKeyHandler = Rc<dyn Fn(&mut App, &KeyEvent) -> KeyEventResult>;
1212
1213/// A header cell's focus: a tab stop with the system focus visual only when it can resize, and its Left and Right keys.
1214#[derive(Clone)]
1215struct HeaderCell {
1216    child: WidgetRef,
1217    is_tab_stop: bool,
1218    key_handler: HeaderKeyHandler,
1219}
1220
1221impl fmt::Debug for HeaderCell {
1222    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1223        f.debug_struct("HeaderCell")
1224            .field("is_tab_stop", &self.is_tab_stop)
1225            .finish_non_exhaustive()
1226    }
1227}
1228
1229impl StatefulWidget for HeaderCell {
1230    type State = HeaderCellState;
1231
1232    fn create_state(&self) -> HeaderCellState {
1233        HeaderCellState {
1234            state: StateData::new(),
1235            focused: false,
1236        }
1237    }
1238}
1239
1240struct HeaderCellState {
1241    state: StateData<HeaderCell>,
1242    focused: bool,
1243}
1244
1245impl State for HeaderCellState {
1246    type Widget = HeaderCell;
1247    waft_widgets::state_accessors!();
1248
1249    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1250        let r = ThemeResources::of(app, context);
1251        let widget = self.widget(app).clone();
1252        let focused = app.get(self).focused && FocusState::current(app).shows_focus_visual();
1253        let visual = FocusVisual::new(widget.child.clone(), r.theme)
1254            .visible(focused && widget.is_tab_stop)
1255            .corner_radius(0.0);
1256        let handler = widget.key_handler.clone();
1257        Focus::new(visual)
1258            .can_request_focus(widget.is_tab_stop)
1259            .skip_traversal(!widget.is_tab_stop)
1260            .on_focus_change(move |app, focused| {
1261                self.set_state(app, |state| state.focused = focused)
1262            })
1263            .on_key_event(Rc::new(move |app, _, event| handler(app, event)))
1264            .into_widget()
1265    }
1266}