Skip to main content

yse_ui/widgets/
table_view.rs

1//! Table view wrapper and its string table model.
2
3use crate::bridge as ffi;
4use crate::bridge::Void;
5use crate::component::Component;
6use crate::widgets::{IntoWidget, SelectionBridge, TextAlign};
7use std::cell::RefCell;
8use std::rc::Rc;
9use yse_model::{EventStream, ListChange, ListModel, Signal, Sink, Subscription};
10
11pub(crate) struct TableState {
12    pub(crate) table: *mut ffi::TableModel,
13    list: Rc<ListModel<Vec<String>>>,
14    subscription: RefCell<Option<Subscription>>,
15    bindings: RefCell<Vec<Subscription>>,
16}
17
18impl Drop for TableState {
19    fn drop(&mut self) {
20        self.subscription.take();
21        unsafe { ffi::table_model_drop(self.table) };
22    }
23}
24
25fn to_rows(items: &[Vec<String>]) -> Vec<ffi::Row> {
26    items
27        .iter()
28        .map(|cells| ffi::Row {
29            cells: cells.clone(),
30        })
31        .collect()
32}
33
34/// A string table model that drives a Qt `QTableView` incrementally.
35///
36/// Rows are `Vec<String>`; changes are applied to the C++ `QAbstractTableModel`
37/// with `beginInsertRows`/`beginRemoveRows`/`dataChanged`.
38pub struct StringTableModel {
39    pub(crate) state: Rc<TableState>,
40}
41
42impl Clone for StringTableModel {
43    fn clone(&self) -> Self {
44        Self {
45            state: self.state.clone(),
46        }
47    }
48}
49
50impl StringTableModel {
51    /// Create a table with `columns` columns and the given header labels.
52    pub fn new(columns: usize, headers: impl IntoIterator<Item = String>) -> Self {
53        let table = unsafe { ffi::table_model_new(columns as i32) };
54        let headers: Vec<String> = headers.into_iter().collect();
55        unsafe { ffi::table_set_headers(table, headers) };
56        let list = Rc::new(ListModel::new());
57        let table_ptr = table;
58        let subscription = list.changes().observe(move |change| match change {
59            ListChange::Insert { index, items } => {
60                let rows = to_rows(items);
61                unsafe { ffi::table_insert_rows(table_ptr, *index as i32, rows) };
62            }
63            ListChange::Remove { index, len } => {
64                unsafe { ffi::table_remove_rows(table_ptr, *index as i32, *len as i32) };
65            }
66            ListChange::Update { index, items } => {
67                let rows = to_rows(items);
68                unsafe { ffi::table_update_rows(table_ptr, *index as i32, rows) };
69            }
70            ListChange::Reset { items } => {
71                let rows = to_rows(items);
72                unsafe { ffi::table_reset(table_ptr, rows) };
73            }
74        });
75        Self {
76            state: Rc::new(TableState {
77                table,
78                list,
79                subscription: RefCell::new(Some(subscription)),
80                bindings: RefCell::new(Vec::new()),
81            }),
82        }
83    }
84
85    /// Bind the table's rows to a signal: every emission replaces all rows.
86    /// The subscription lives as long as the model.
87    pub fn bind_rows(&self, signal: &Signal<Vec<Vec<String>>>) {
88        let list = self.state.list.clone();
89        let subscription = signal.observe(move |rows| {
90            list.replace_all((*rows).clone());
91        });
92        self.state.bindings.borrow_mut().push(subscription);
93    }
94
95    /// Replace the column headers.
96    pub fn set_headers(&self, headers: impl IntoIterator<Item = String>) {
97        unsafe {
98            ffi::table_set_headers(self.state.table, headers.into_iter().collect());
99        }
100    }
101
102    /// Bind the column headers to a signal.
103    pub fn bind_headers(&self, signal: &Signal<Vec<String>>) {
104        let state = self.state.clone();
105        let subscription = signal.observe(move |headers| unsafe {
106            ffi::table_set_headers(state.table, (*headers).clone());
107        });
108        self.state.bindings.borrow_mut().push(subscription);
109    }
110
111    /// Set a per-row icon for column 0, given the file path whose icon should
112    /// be shown (e.g. an executable). Empty paths show no icon.
113    pub fn set_row_icons(&self, paths: impl IntoIterator<Item = String>) {
114        unsafe { ffi::table_model_set_row_icons(self.state.table, paths.into_iter().collect()) };
115    }
116
117    /// Bind per-row icons (file paths whose icon appears in column 0) to a
118    /// signal. The subscription lives as long as the model.
119    pub fn bind_row_icons(&self, signal: &Signal<Vec<String>>) {
120        let state = self.state.clone();
121        let subscription = signal.observe(move |paths| unsafe {
122            ffi::table_model_set_row_icons(state.table, (*paths).clone());
123        });
124        self.state.bindings.borrow_mut().push(subscription);
125    }
126
127    /// Set normalized (0..1) heat values for `column`, rendered as a
128    /// translucent intensity wash by the view's heat delegate.
129    pub fn set_heat(&self, column: usize, values: impl IntoIterator<Item = f64>) {
130        unsafe {
131            ffi::table_model_set_heat(
132                self.state.table,
133                column as i32,
134                values.into_iter().collect(),
135            )
136        };
137    }
138
139    /// Bind normalized heat values for `column` to a signal.
140    pub fn bind_heat(&self, column: usize, signal: &Signal<Vec<f64>>) {
141        let state = self.state.clone();
142        let subscription = signal.observe(move |values| unsafe {
143            ffi::table_model_set_heat(state.table, column as i32, (*values).clone());
144        });
145        self.state.bindings.borrow_mut().push(subscription);
146    }
147
148    /// Bind rows and their column-0 icons from one signal of
149    /// `(cells, icon path)` pairs. Rows and icons are applied atomically in a
150    /// single observer, so a row reset can never wipe the same-pass icons.
151    pub fn bind_table(&self, signal: &Signal<Vec<(Vec<String>, String)>>) {
152        let list = self.state.list.clone();
153        let state = self.state.clone();
154        let subscription = signal.observe(move |rows| {
155            list.replace_all(rows.iter().map(|(cells, _)| cells.clone()).collect());
156            unsafe {
157                ffi::table_model_set_row_icons(
158                    state.table,
159                    rows.iter().map(|(_, path)| path.clone()).collect(),
160                );
161            }
162        });
163        self.state.bindings.borrow_mut().push(subscription);
164    }
165
166    /// Number of rows with a non-null icon in column 0.
167    pub fn row_icon_count(&self) -> usize {
168        unsafe { ffi::table_model_row_icon_count(self.state.table) as usize }
169    }
170
171    /// Set the horizontal alignment of `column`.
172    pub fn set_column_alignment(&self, column: usize, align: TextAlign) {
173        unsafe {
174            ffi::table_model_set_column_alignment(self.state.table, column as i32, align.as_int())
175        };
176    }
177
178    /// Number of rows in the C++ mirror.
179    pub fn row_count(&self) -> usize {
180        unsafe { ffi::table_row_count(self.state.table) as usize }
181    }
182
183    /// Number of columns.
184    pub fn column_count(&self) -> usize {
185        unsafe { ffi::table_column_count(self.state.table) as usize }
186    }
187
188    /// The cell text at `(row, column)` as stored in the C++ mirror.
189    pub fn cell(&self, row: usize, column: usize) -> String {
190        unsafe { ffi::table_text(self.state.table, row as i32, column as i32) }
191    }
192
193    /// Append a row.
194    pub fn push_row(&self, row: impl IntoIterator<Item = String>) {
195        self.state.list.push(row.into_iter().collect());
196    }
197
198    /// Insert a row at `index`.
199    pub fn insert_row(&self, index: usize, row: impl IntoIterator<Item = String>) {
200        self.state.list.insert(index, row.into_iter().collect());
201    }
202
203    /// Remove the row at `index`.
204    pub fn remove_row(&self, index: usize) -> bool {
205        self.state.list.remove(index)
206    }
207
208    /// Replace the row at `index`.
209    pub fn set_row(&self, index: usize, row: impl IntoIterator<Item = String>) -> bool {
210        self.state.list.set(index, row.into_iter().collect())
211    }
212
213    /// Remove every row.
214    pub fn clear(&self) {
215        self.state.list.clear();
216    }
217
218    /// Replace the whole table.
219    pub fn replace_all(&self, rows: impl IntoIterator<Item = Vec<String>>) {
220        self.state.list.replace_all(rows.into_iter().collect());
221    }
222}
223
224/// A `QTableView` bound to a [`StringTableModel`].
225pub struct TableView {
226    pub(crate) inner: Rc<Component>,
227    pub(crate) table: Rc<TableState>,
228    pub(crate) selection: Rc<SelectionBridge>,
229}
230
231impl Clone for TableView {
232    fn clone(&self) -> Self {
233        Self {
234            inner: self.inner.clone(),
235            table: self.table.clone(),
236            selection: self.selection.clone(),
237        }
238    }
239}
240
241impl TableView {
242    /// Show or hide the table without dropping its model or selection state.
243    pub fn set_visible(&self, visible: bool) {
244        if self.inner.is_alive() {
245            unsafe { ffi::widget_set_visible(self.inner.raw(), visible) };
246        }
247    }
248
249    /// Whether the table is currently visible on screen.
250    pub fn is_visible(&self) -> bool {
251        unsafe { ffi::widget_is_visible(self.inner.raw()) }
252    }
253
254    /// The table's current width in pixels.
255    pub fn width(&self) -> i32 {
256        unsafe { ffi::widget_width(self.inner.raw()) }
257    }
258
259    /// The table's current height in pixels.
260    pub fn height(&self) -> i32 {
261        unsafe { ffi::widget_height(self.inner.raw()) }
262    }
263
264    /// A stream of header clicks, each carrying the clicked column index.
265    /// Use it to implement click-to-sort columns.
266    pub fn header_clicked(&self) -> EventStream<usize> {
267        if self.inner.header_sink.borrow().is_none() {
268            unsafe {
269                ffi::view_set_header_clicked_cb(
270                    self.inner.raw(),
271                    &*self.inner as *const Component as *mut Void,
272                );
273            }
274            *self.inner.header_sink.borrow_mut() = Some(Rc::new(Sink::new()));
275        }
276        self.inner
277            .header_sink
278            .borrow()
279            .as_ref()
280            .unwrap()
281            .stream()
282            .map(|section| *section as usize)
283    }
284
285    /// Simulate a click on the column header `section` (used by tests and
286    /// headless smoke runs).
287    pub fn click_header(&self, section: usize) {
288        if self.inner.is_alive() {
289            unsafe { ffi::view_click_header(self.inner.raw(), section as i32) };
290        }
291    }
292
293    /// A stream of right-click (context menu) events on table rows, each
294    /// carrying the row under the cursor.
295    pub fn context_menu(&self) -> EventStream<usize> {
296        if self.inner.context_sink.borrow().is_none() {
297            unsafe {
298                ffi::view_set_context_menu_cb(
299                    self.inner.raw(),
300                    &*self.inner as *const Component as *mut Void,
301                );
302            }
303            *self.inner.context_sink.borrow_mut() = Some(Rc::new(Sink::new()));
304        }
305        self.inner
306            .context_sink
307            .borrow()
308            .as_ref()
309            .unwrap()
310            .stream()
311            .map(|row| *row as usize)
312    }
313
314    /// Simulate a right-click on `row` (used by tests and headless smoke
315    /// runs); the shim shows the context menu and reports the row.
316    pub fn emit_context_menu(&self, row: usize) {
317        if self.inner.is_alive() {
318            unsafe { ffi::view_emit_context_menu(self.inner.raw(), row as i32) };
319        }
320    }
321
322    /// Set the pixel width of `column`.
323    pub fn set_column_width(&self, column: usize, width: i32) {
324        if self.inner.is_alive() {
325            unsafe { ffi::view_set_column_width(self.inner.raw(), column as i32, width) };
326        }
327    }
328
329    /// Hide or show `column` without changing the model layout.
330    pub fn set_column_hidden(&self, column: usize, hidden: bool) {
331        if self.inner.is_alive() {
332            unsafe { ffi::view_set_column_hidden(self.inner.raw(), column as i32, hidden) };
333        }
334    }
335
336    /// Show the sort arrow on `column` in the given direction.
337    pub fn set_sort_indicator(&self, column: usize, ascending: bool) {
338        if self.inner.is_alive() {
339            unsafe { ffi::view_set_sort_indicator(self.inner.raw(), column as i32, ascending) };
340        }
341    }
342
343    /// Keep the sort arrow in sync with a signal of `(column, ascending)`,
344    /// so sorting state stays declarative instead of imperative.
345    pub fn bind_sort_indicator(&self, signal: &Signal<(usize, bool)>) {
346        let view = self.inner.raw();
347        self.inner
348            .owner
349            .borrow_mut()
350            .add(signal.observe(move |(column, ascending)| unsafe {
351                ffi::view_set_sort_indicator(view, *column as i32, *ascending);
352            }));
353    }
354
355    /// Let the last column fill the remaining view width.
356    pub fn stretch_last_section(&self, stretch: bool) {
357        if self.inner.is_alive() {
358            unsafe { ffi::view_stretch_last_section(self.inner.raw(), stretch) };
359        }
360    }
361
362    /// Select whole rows instead of individual cells.
363    pub fn select_rows(&self, on: bool) {
364        if self.inner.is_alive() {
365            unsafe { ffi::view_set_select_rows(self.inner.raw(), on) };
366        }
367    }
368
369    /// Install the heat-map delegate so cells with heat values render with an
370    /// intensity wash.
371    pub fn enable_heat(&self) {
372        if self.inner.is_alive() {
373            unsafe { ffi::view_set_heat_delegate(self.inner.raw()) };
374        }
375    }
376
377    /// A stream of selection changes, each carrying the selected row indices.
378    pub fn selection_changed(&self) -> EventStream<Vec<usize>> {
379        if self.selection.sink.borrow().is_none() {
380            unsafe {
381                ffi::view_set_selection_cb(
382                    self.inner.raw(),
383                    &*self.selection as *const SelectionBridge as *mut Void,
384                );
385            }
386            *self.selection.sink.borrow_mut() = Some(Rc::new(Sink::new()));
387        }
388        self.selection.sink.borrow().as_ref().unwrap().stream()
389    }
390
391    /// Register a selection handler carrying the selected row indices.
392    pub fn on_selection<F>(&self, f: F) -> &Self
393    where
394        F: FnMut(&Vec<usize>) + 'static,
395    {
396        self.inner
397            .owner
398            .borrow_mut()
399            .add(self.selection_changed().observe(f));
400        self
401    }
402
403    /// Select `row`, replacing the current selection.
404    pub fn select(&self, row: usize) {
405        if self.inner.is_alive() {
406            unsafe { ffi::view_select_row(self.inner.raw(), row as i32) };
407        }
408    }
409
410    /// Clear the selection.
411    pub fn clear_selection(&self) {
412        if self.inner.is_alive() {
413            unsafe { ffi::view_clear_selection(self.inner.raw()) };
414        }
415    }
416
417    /// The currently selected row indices.
418    pub fn selected_rows(&self) -> Vec<usize> {
419        unsafe { ffi::view_selected_rows(self.inner.raw()) }
420            .into_iter()
421            .map(|row| row as usize)
422            .collect()
423    }
424
425    /// Escape hatch: the underlying Qt `QTableView` pointer.
426    ///
427    /// The pointer is valid only while this view's Qt object is alive. Do not
428    /// retain it after destruction or use it from a thread other than the GUI
429    /// thread. Dereferencing or passing the pointer across FFI remains unsafe.
430    pub fn qobject_ptr(&self) -> *mut Void {
431        self.inner.raw() as *mut Void
432    }
433}
434
435impl IntoWidget for TableView {
436    fn component(&self) -> &Rc<Component> {
437        &self.inner
438    }
439}