Skip to main content

waft_winui/controls/table_view/
column.rs

1//! `TableViewColumn`, `TableViewTextColumn` and `TableViewTemplateColumn` (`controls/dev/TableView/TableViewColumn.cpp`, `TableViewTextColumn.cpp`, `TableViewTemplateColumn.cpp`): what a column shows in each cell and its header, how wide it is, whether it is frozen, and how it sorts.
2//!
3//! A column is an object the application keeps and the `TableView` writes to, as WinUI's `DependencyObject` is: the table writes `actual_width` when it resolves the widths, `sort_direction` when it sorts, and `width` when the user drags the column's gripper. Every property setter notifies with the [`ColumnChange`] it made, which the owning table reads to decide what to rebuild; a later editor who adds a property without a change kind leaves the table showing the old value.
4
5use super::source::{SortComparer, SortDirection};
6use crate::*;
7use std::cmp::Ordering;
8use std::fmt;
9use std::rc::Rc;
10use waft_foundation::{App, ChangeNotifier, ChangeNotifierData, Handle, HandleId, Ref};
11use waft_painting::{AlignmentGeometry, EdgeInsetsGeometry, TextOverflow};
12use waft_widgets::*;
13
14/// `c_widthDefault`: the width of a column whose `Width` is not set, and the provisional width of an `Auto` column before its cells are measured.
15pub(crate) const DEFAULT_WIDTH: f64 = 120.0;
16
17/// `MinWidth`'s default.
18const DEFAULT_MIN_WIDTH: f64 = 20.0;
19
20/// XAML `TableViewFrozenEdge`: `Leading` pins a column in the contiguous prefix from the first column; `Trailing` is reserved.
21#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
22pub enum TableViewFrozenEdge {
23    #[default]
24    None,
25    Leading,
26    Trailing,
27}
28
29/// XAML `TableViewSortCycle`: the directions repeated header clicks walk. The first is the direction an unsorted column opens in; the `None` variants add a step back to source order.
30#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
31pub enum TableViewSortCycle {
32    #[default]
33    AscendingDescending,
34    AscendingDescendingNone,
35    DescendingAscending,
36    DescendingAscendingNone,
37}
38
39/// Which property of a column last changed: the branch of `TableViewColumn::OnPropertyChanged` the owning table takes.
40#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
41pub(crate) enum ColumnChange {
42    #[default]
43    None,
44    /// `Width`, `MinWidth` or `MaxWidth`: `OnColumnWidthChanged`.
45    Width,
46    /// `Header`: `OnColumnHeaderChanged`.
47    Header,
48    /// `HeaderToolTip`: `OnColumnHeaderToolTipChanged`.
49    HeaderToolTip,
50    /// `FrozenEdge`: `OnColumnFrozenEdgeChanged`.
51    FrozenEdge,
52    /// `CanResize`: `QueueRebuildHeaders`.
53    CanResize,
54    /// `Visibility`: `OnColumnVisibilityChanged`.
55    Visibility,
56    /// `CanSort`: `OnColumnCanSortChanged`.
57    CanSort,
58    /// `CustomSortComparer`: the active direction is applied again with the new comparer.
59    CustomSortComparer,
60    /// `SortDirection`, written by the owning table: `RefreshSortIndicators`.
61    SortDirection,
62    /// A property the table reads when it needs it (`SortCycle`, `SortMemberPath`).
63    Other,
64}
65
66/// What a text column's cell takes from its table: `GetDensityCellPadding` and `GetCellFontSize`.
67#[derive(Clone, Copy, Debug, PartialEq)]
68pub(crate) struct TableViewCellStyle {
69    pub(crate) padding: [f64; 4],
70    pub(crate) font_size: f64,
71}
72
73/// Builds a template column's cell for an item: XAML's `CellTemplate`.
74pub type TableViewCellTemplate<T> = Rc<dyn Fn(&mut App, BuildContext, &T) -> WidgetRef>;
75
76/// The derived column's own part: a text column's `Binding`, or a template column's `CellTemplate`.
77enum ColumnCell<T> {
78    /// `TableViewTextColumn.Binding`: the text of each cell.
79    Text(Rc<dyn Fn(&T) -> String>),
80    /// `TableViewTemplateColumn.CellTemplate`.
81    Template(TableViewCellTemplate<T>),
82}
83
84/// XAML `TableViewColumn`: one column of a `TableView` over items of type `T`.
85pub struct TableViewColumn<T> {
86    notifier: ChangeNotifierData,
87    cell: ColumnCell<T>,
88    header: String,
89    header_tool_tip: Option<String>,
90    width: GridLength,
91    min_width: f64,
92    /// Whether `MinWidth` was set, which a `0*` column honours (`MinWidthForStarFactor`).
93    min_width_set: bool,
94    max_width: f64,
95    can_resize: bool,
96    actual_width: f64,
97    frozen_edge: TableViewFrozenEdge,
98    visible: bool,
99    can_sort: bool,
100    sort_cycle: TableViewSortCycle,
101    /// `SortMemberPath` as the key it names.
102    sort_key: Option<SortComparer<T>>,
103    custom_sort_comparer: Option<SortComparer<T>>,
104    sort_direction: SortDirection,
105    /// `m_owningTableView`: the table the column belongs to, at most one.
106    owner: Option<HandleId>,
107    change: ColumnChange,
108}
109
110impl<T: 'static> TableViewColumn<T> {
111    fn new(app: &mut App, header: String, cell: ColumnCell<T>) -> Ref<Self> {
112        app.create(Self {
113            notifier: ChangeNotifierData::new(),
114            cell,
115            header,
116            header_tool_tip: None,
117            width: GridLength::pixel(DEFAULT_WIDTH),
118            min_width: DEFAULT_MIN_WIDTH,
119            min_width_set: false,
120            max_width: f64::INFINITY,
121            can_resize: true,
122            actual_width: DEFAULT_WIDTH,
123            frozen_edge: TableViewFrozenEdge::None,
124            visible: true,
125            can_sort: true,
126            sort_cycle: TableViewSortCycle::AscendingDescending,
127            sort_key: None,
128            custom_sort_comparer: None,
129            sort_direction: SortDirection::None,
130            owner: None,
131            change: ColumnChange::None,
132        })
133    }
134
135    /// XAML `TableViewTextColumn` with its `Header` and `Binding`: each cell shows the text `binding` gives for the row's item, and the column sorts by that text unless given a key of its own.
136    pub fn text(
137        app: &mut App,
138        header: impl Into<String>,
139        binding: impl Fn(&T) -> String + 'static,
140    ) -> Ref<Self> {
141        Self::new(app, header.into(), ColumnCell::Text(Rc::new(binding)))
142    }
143
144    /// XAML `TableViewTemplateColumn` with its `Header` and `CellTemplate`: each cell is what `cell_template` builds for the row's item. It sorts only by a key or comparer it is given.
145    pub fn template(
146        app: &mut App,
147        header: impl Into<String>,
148        cell_template: impl Fn(&mut App, BuildContext, &T) -> WidgetRef + 'static,
149    ) -> Ref<Self> {
150        Self::new(
151            app,
152            header.into(),
153            ColumnCell::Template(Rc::new(cell_template)),
154        )
155    }
156
157    /// Releases the listeners; the column is not used after.
158    pub fn dispose(self: Handle<Self>, app: &mut App) {
159        ChangeNotifierData::dispose(app, self);
160    }
161
162    /// `Header`.
163    pub fn header(self: Handle<Self>, app: &App) -> &str {
164        &app.get(self).header
165    }
166
167    /// Sets `Header`.
168    pub fn set_header(self: Handle<Self>, app: &mut App, value: impl Into<String>) {
169        let value = value.into();
170        if app.get(self).header != value {
171            app.get_mut(self).header = value;
172            self.changed(app, ColumnChange::Header);
173        }
174    }
175
176    /// `HeaderToolTip`: the header's tooltip; `None` or empty shows none.
177    pub fn header_tool_tip(self: Handle<Self>, app: &App) -> Option<&str> {
178        app.get(self).header_tool_tip.as_deref()
179    }
180
181    /// Sets `HeaderToolTip`.
182    pub fn set_header_tool_tip(self: Handle<Self>, app: &mut App, value: Option<String>) {
183        if app.get(self).header_tool_tip != value {
184            app.get_mut(self).header_tool_tip = value;
185            self.changed(app, ColumnChange::HeaderToolTip);
186        }
187    }
188
189    /// `Width`: pixels, `Auto` (the widest realized cell) or a star share of the space the fixed columns leave.
190    pub fn width(self: Handle<Self>, app: &App) -> GridLength {
191        app.get(self).width
192    }
193
194    /// Sets `Width`.
195    pub fn set_width(self: Handle<Self>, app: &mut App, value: GridLength) {
196        if app.get(self).width != value {
197            app.get_mut(self).width = value;
198            self.width_changed(app);
199        }
200    }
201
202    /// `MinWidth`.
203    pub fn min_width(self: Handle<Self>, app: &App) -> f64 {
204        app.get(self).min_width
205    }
206
207    /// Sets `MinWidth`.
208    pub fn set_min_width(self: Handle<Self>, app: &mut App, value: f64) {
209        let column = app.get_mut(self);
210        column.min_width_set = true;
211        if column.min_width != value {
212            column.min_width = value;
213            self.width_changed(app);
214        }
215    }
216
217    /// `MaxWidth`.
218    pub fn max_width(self: Handle<Self>, app: &App) -> f64 {
219        app.get(self).max_width
220    }
221
222    /// Sets `MaxWidth`.
223    pub fn set_max_width(self: Handle<Self>, app: &mut App, value: f64) {
224        if app.get(self).max_width != value {
225            app.get_mut(self).max_width = value;
226            self.width_changed(app);
227        }
228    }
229
230    /// `CanResize`: whether this column shows a gripper; the table's `can_user_resize_columns` gates them all.
231    pub fn can_resize(self: Handle<Self>, app: &App) -> bool {
232        app.get(self).can_resize
233    }
234
235    /// Sets `CanResize`.
236    pub fn set_can_resize(self: Handle<Self>, app: &mut App, value: bool) {
237        if app.get(self).can_resize != value {
238            app.get_mut(self).can_resize = value;
239            self.changed(app, ColumnChange::CanResize);
240        }
241    }
242
243    /// `ActualWidth`: the width the table last resolved, clamped to `MinWidth` and `MaxWidth`. Read-only.
244    pub fn actual_width(self: Handle<Self>, app: &App) -> f64 {
245        app.get(self).actual_width
246    }
247
248    /// `FrozenEdge`.
249    pub fn frozen_edge(self: Handle<Self>, app: &App) -> TableViewFrozenEdge {
250        app.get(self).frozen_edge
251    }
252
253    /// Sets `FrozenEdge`.
254    pub fn set_frozen_edge(self: Handle<Self>, app: &mut App, value: TableViewFrozenEdge) {
255        if app.get(self).frozen_edge != value {
256            app.get_mut(self).frozen_edge = value;
257            self.changed(app, ColumnChange::FrozenEdge);
258        }
259    }
260
261    /// `Visibility`: whether the column and its cells are shown.
262    pub fn visible(self: Handle<Self>, app: &App) -> bool {
263        app.get(self).visible
264    }
265
266    /// Sets `Visibility`.
267    pub fn set_visible(self: Handle<Self>, app: &mut App, value: bool) {
268        if app.get(self).visible != value {
269            app.get_mut(self).visible = value;
270            self.changed(app, ColumnChange::Visibility);
271        }
272    }
273
274    /// `CanSort`: whether a header click sorts this column; sorting from code still works.
275    pub fn can_sort(self: Handle<Self>, app: &App) -> bool {
276        app.get(self).can_sort
277    }
278
279    /// Sets `CanSort`.
280    pub fn set_can_sort(self: Handle<Self>, app: &mut App, value: bool) {
281        if app.get(self).can_sort != value {
282            app.get_mut(self).can_sort = value;
283            self.changed(app, ColumnChange::CanSort);
284        }
285    }
286
287    /// `SortCycle`, read when the header is clicked.
288    pub fn sort_cycle(self: Handle<Self>, app: &App) -> TableViewSortCycle {
289        app.get(self).sort_cycle
290    }
291
292    /// Sets `SortCycle`.
293    pub fn set_sort_cycle(self: Handle<Self>, app: &mut App, value: TableViewSortCycle) {
294        app.get_mut(self).sort_cycle = value;
295    }
296
297    /// Sets `SortMemberPath`, as the key it names: the column sorts its rows by `key`. A text column without one sorts by its cells' text.
298    pub fn set_sort_key<K: Ord>(
299        self: Handle<Self>,
300        app: &mut App,
301        key: impl Fn(&T) -> K + 'static,
302    ) {
303        app.get_mut(self).sort_key = Some(Rc::new(move |a, b| key(a).cmp(&key(b))));
304        self.changed(app, ColumnChange::Other);
305    }
306
307    /// Sets `CustomSortComparer`, which takes precedence over the sort key. A column sorted at the time is sorted again with it.
308    pub fn set_custom_sort_comparer(
309        self: Handle<Self>,
310        app: &mut App,
311        comparer: impl Fn(&T, &T) -> Ordering + 'static,
312    ) {
313        app.get_mut(self).custom_sort_comparer = Some(Rc::new(comparer));
314        self.changed(app, ColumnChange::CustomSortComparer);
315    }
316
317    /// `SortDirection`: `None` unless the column is part of the active sort. Written by the owning table; read-only.
318    pub fn sort_direction(self: Handle<Self>, app: &App) -> SortDirection {
319        app.get(self).sort_direction
320    }
321}
322
323// MARK: The owning table's view of the column
324
325impl<T: 'static> TableViewColumn<T> {
326    /// `SetOwningTableViewInternal`: a column belongs to one table; a second is refused while the first holds it.
327    pub(crate) fn set_owner(self: Handle<Self>, app: &mut App, owner: Option<HandleId>) -> bool {
328        let column = app.get_mut(self);
329        if let (Some(existing), Some(new)) = (column.owner, owner)
330            && existing != new
331        {
332            debug_assert!(
333                false,
334                "TableViewColumn re-owned without removing it from the previous TableView first"
335            );
336            return false;
337        }
338        column.owner = owner;
339        true
340    }
341
342    pub(crate) fn owner(self: Handle<Self>, app: &App) -> Option<HandleId> {
343        app.get(self).owner
344    }
345
346    pub(crate) fn change(self: Handle<Self>, app: &App) -> ColumnChange {
347        app.get(self).change
348    }
349
350    pub(crate) fn min_width_set(self: Handle<Self>, app: &App) -> bool {
351        app.get(self).min_width_set
352    }
353
354    /// `SetResolvedActualWidthInternal`: the width the table resolved. It does not notify: the table writes it while laying itself out.
355    pub(crate) fn set_actual_width(self: Handle<Self>, app: &mut App, width: f64) {
356        app.get_mut(self).actual_width = width;
357    }
358
359    /// `SetSortStateInternal`.
360    pub(crate) fn set_sort_state(self: Handle<Self>, app: &mut App, direction: SortDirection) {
361        if app.get(self).sort_direction != direction {
362            app.get_mut(self).sort_direction = direction;
363            self.changed(app, ColumnChange::SortDirection);
364        }
365    }
366
367    /// `GetSortMemberPathCore` with `CustomSortComparer` ahead of it: what the column sorts by, if anything. A text column falls back to its cells' text.
368    pub(crate) fn sort_comparer(self: Handle<Self>, app: &App) -> Option<SortComparer<T>> {
369        let column = app.get(self);
370        if let Some(comparer) = &column.custom_sort_comparer {
371            return Some(comparer.clone());
372        }
373        if let Some(key) = &column.sort_key {
374            return Some(key.clone());
375        }
376        match &column.cell {
377            ColumnCell::Text(binding) => {
378                let binding = binding.clone();
379                Some(Rc::new(move |a, b| binding(a).cmp(&binding(b))))
380            }
381            ColumnCell::Template(_) => None,
382        }
383    }
384
385    /// `CanSortColumn`: the column opts in and has something to sort by.
386    pub(crate) fn is_sortable(self: Handle<Self>, app: &App) -> bool {
387        self.can_sort(app) && self.sort_comparer(app).is_some()
388    }
389
390    /// `GenerateElement`: a text column's `TextBlock`, vertically centred, ellipsized and padded by the density; a template column's content.
391    pub(crate) fn generate_element(
392        self: Handle<Self>,
393        app: &mut App,
394        context: BuildContext,
395        item: &T,
396        style: TableViewCellStyle,
397    ) -> WidgetRef {
398        match &app.get(self).cell {
399            ColumnCell::Text(binding) => {
400                let text = binding(item);
401                let r = ThemeResources::of(app, context);
402                let [left, top, right, bottom] = style.padding;
403                Align::new()
404                    .alignment(AlignmentGeometry::CENTER_LEFT)
405                    .child(
406                        Padding::new(EdgeInsetsGeometry::from_ltrb(left, top, right, bottom))
407                            .child(
408                                Text::new(text)
409                                    .style(
410                                        waft_painting::TextStyle::new()
411                                            .font_family(r.content_control_theme_font_family)
412                                            .font_size(style.font_size)
413                                            .font_weight(waft_embedder::FontWeight::NORMAL),
414                                    )
415                                    .max_lines(1)
416                                    .soft_wrap(false)
417                                    .overflow(TextOverflow::Ellipsis),
418                            ),
419                    )
420                    .into_widget()
421            }
422            ColumnCell::Template(template) => {
423                let template = template.clone();
424                template(app, context, item)
425            }
426        }
427    }
428
429    /// `UpdateActualWidth`: a pixel width clamped to the bounds, else the default, until the table resolves it.
430    fn width_changed(self: Handle<Self>, app: &mut App) {
431        let column = app.get_mut(self);
432        let pixels = if column.width.unit == GridUnitType::Pixel {
433            column.width.value
434        } else {
435            DEFAULT_WIDTH
436        };
437        let lo = column.min_width;
438        let hi = lo.max(column.max_width);
439        column.actual_width = pixels.clamp(lo, hi);
440        self.changed(app, ColumnChange::Width);
441    }
442
443    fn changed(self: Handle<Self>, app: &mut App, change: ColumnChange) {
444        app.get_mut(self).change = change;
445        self.notify_listeners(app);
446    }
447}
448
449impl<T: 'static> ChangeNotifier for TableViewColumn<T> {
450    fn change_notifier_data(&self) -> &ChangeNotifierData {
451        &self.notifier
452    }
453
454    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
455        &mut self.notifier
456    }
457}
458
459impl<T> fmt::Debug for TableViewColumn<T> {
460    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
461        f.debug_struct("TableViewColumn")
462            .field("header", &self.header)
463            .field("width", &self.width)
464            .field("actual_width", &self.actual_width)
465            .field("sort_direction", &self.sort_direction)
466            .finish_non_exhaustive()
467    }
468}