Skip to main content

yse_ui/widgets/
tree_view.rs

1//! Tree model and tree view wrappers for grouped, expandable rows.
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, Signal, Sink, Subscription};
10
11pub(crate) struct TreeState {
12    pub(crate) tree: *mut ffi::TreeModel,
13    bindings: RefCell<Vec<Subscription>>,
14}
15
16impl Drop for TreeState {
17    fn drop(&mut self) {
18        unsafe { ffi::tree_model_drop(self.tree) };
19    }
20}
21
22/// A tree model whose rows are supplied as flat `(parent, cells, icon)` rows;
23/// group/root rows use `parent == -1`, children point at their parent's flat
24/// row.
25pub struct TreeModel {
26    pub(crate) state: Rc<TreeState>,
27}
28
29impl Clone for TreeModel {
30    fn clone(&self) -> Self {
31        Self {
32            state: self.state.clone(),
33        }
34    }
35}
36
37impl TreeModel {
38    /// Create a tree model with `columns` columns.
39    pub fn new(columns: usize) -> Self {
40        Self {
41            state: Rc::new(TreeState {
42                tree: unsafe { ffi::tree_model_new(columns as i32) },
43                bindings: RefCell::new(Vec::new()),
44            }),
45        }
46    }
47
48    /// Bind the whole tree to a signal of flat `(parent, cells, icon)` rows.
49    /// The subscription lives as long as the model.
50    pub fn bind(&self, signal: &Signal<Vec<(i32, Vec<String>, String)>>) {
51        let state = self.state.clone();
52        let subscription = signal.observe(move |rows| {
53            let rows: Vec<ffi::TreeRow> = rows
54                .iter()
55                .map(|(parent, cells, icon)| ffi::TreeRow {
56                    parent: *parent,
57                    cells: cells.clone(),
58                    icon: icon.clone(),
59                })
60                .collect();
61            unsafe { ffi::tree_model_reset(state.tree, rows) };
62        });
63        self.state.bindings.borrow_mut().push(subscription);
64    }
65
66    /// Bind the column headers to a signal.
67    pub fn bind_headers(&self, signal: &Signal<Vec<String>>) {
68        let state = self.state.clone();
69        let subscription = signal.observe(move |headers| unsafe {
70            ffi::tree_model_set_headers(state.tree, (*headers).clone());
71        });
72        self.state.bindings.borrow_mut().push(subscription);
73    }
74
75    /// Imperatively replace the whole tree with flat `(parent, cells, icon)`
76    /// rows.
77    pub fn reset(&self, rows: impl IntoIterator<Item = (i32, Vec<String>, String)>) {
78        let rows: Vec<ffi::TreeRow> = rows
79            .into_iter()
80            .map(|(parent, cells, icon)| ffi::TreeRow {
81                parent,
82                cells,
83                icon,
84            })
85            .collect();
86        unsafe { ffi::tree_model_reset(self.state.tree, rows) };
87    }
88
89    /// Replace the column headers.
90    pub fn set_headers(&self, headers: impl IntoIterator<Item = String>) {
91        unsafe {
92            ffi::tree_model_set_headers(self.state.tree, headers.into_iter().collect());
93        }
94    }
95
96    /// Set the horizontal alignment of `column`.
97    pub fn set_column_alignment(&self, column: usize, align: TextAlign) {
98        unsafe {
99            ffi::tree_model_set_column_alignment(self.state.tree, column as i32, align.as_int())
100        };
101    }
102
103    /// Bind normalized (0..1) heat values for `column` to a signal.
104    pub fn bind_heat(&self, column: usize, signal: &Signal<Vec<f64>>) {
105        let state = self.state.clone();
106        let subscription = signal.observe(move |values| unsafe {
107            ffi::tree_model_set_heat(state.tree, column as i32, (*values).clone());
108        });
109        self.state.bindings.borrow_mut().push(subscription);
110    }
111
112    /// Number of flat rows (groups + children).
113    pub fn row_count(&self) -> usize {
114        unsafe { ffi::tree_model_flat_row_count(self.state.tree) as usize }
115    }
116}
117
118/// A `QTreeView` bound to a [`TreeModel`].
119pub struct TreeView {
120    pub(crate) inner: Rc<Component>,
121    pub(crate) selection: Rc<SelectionBridge>,
122}
123
124impl Clone for TreeView {
125    fn clone(&self) -> Self {
126        Self {
127            inner: self.inner.clone(),
128            selection: self.selection.clone(),
129        }
130    }
131}
132
133impl TreeView {
134    /// Whether the tree is currently visible on screen.
135    pub fn is_visible(&self) -> bool {
136        unsafe { ffi::widget_is_visible(self.inner.raw()) }
137    }
138
139    /// The tree's current width in pixels.
140    pub fn width(&self) -> i32 {
141        unsafe { ffi::widget_width(self.inner.raw()) }
142    }
143
144    /// The tree's current height in pixels.
145    pub fn height(&self) -> i32 {
146        unsafe { ffi::widget_height(self.inner.raw()) }
147    }
148
149    /// A stream of selection changes carrying the selected flat row indices.
150    pub fn selection_changed(&self) -> EventStream<Vec<usize>> {
151        if self.selection.sink.borrow().is_none() {
152            unsafe {
153                ffi::view_set_selection_cb(
154                    self.inner.raw(),
155                    &*self.selection as *const SelectionBridge as *mut Void,
156                );
157            }
158            *self.selection.sink.borrow_mut() = Some(Rc::new(Sink::new()));
159        }
160        self.selection.sink.borrow().as_ref().unwrap().stream()
161    }
162
163    /// Register a selection handler carrying the selected flat row indices.
164    pub fn on_selection<F>(&self, f: F) -> &Self
165    where
166        F: FnMut(&Vec<usize>) + 'static,
167    {
168        self.inner
169            .owner
170            .borrow_mut()
171            .add(self.selection_changed().observe(f));
172        self
173    }
174
175    /// Select the flat row `row`, expanding its ancestors.
176    pub fn select(&self, row: usize) {
177        if self.inner.is_alive() {
178            unsafe { ffi::tree_view_select_flat(self.inner.raw(), row as i32) };
179        }
180    }
181
182    /// The currently selected flat row indices.
183    pub fn selected_rows(&self) -> Vec<usize> {
184        unsafe { ffi::view_selected_rows(self.inner.raw()) }
185            .into_iter()
186            .map(|row| row as usize)
187            .collect()
188    }
189
190    /// A stream of header clicks carrying the clicked column index.
191    pub fn header_clicked(&self) -> EventStream<usize> {
192        if self.inner.header_sink.borrow().is_none() {
193            unsafe {
194                ffi::tree_view_set_header_clicked_cb(
195                    self.inner.raw(),
196                    &*self.inner as *const Component as *mut Void,
197                );
198            }
199            *self.inner.header_sink.borrow_mut() = Some(Rc::new(Sink::new()));
200        }
201        self.inner
202            .header_sink
203            .borrow()
204            .as_ref()
205            .unwrap()
206            .stream()
207            .map(|section| *section as usize)
208    }
209
210    /// Simulate a header click (used by tests and smoke runs).
211    pub fn click_header(&self, section: usize) {
212        if self.inner.is_alive() {
213            unsafe { ffi::tree_view_click_header(self.inner.raw(), section as i32) };
214        }
215    }
216
217    /// A stream of right-click events carrying the flat row under the cursor.
218    pub fn context_menu(&self) -> EventStream<usize> {
219        if self.inner.context_sink.borrow().is_none() {
220            unsafe {
221                ffi::view_set_context_menu_cb(
222                    self.inner.raw(),
223                    &*self.inner as *const Component as *mut Void,
224                );
225            }
226            *self.inner.context_sink.borrow_mut() = Some(Rc::new(Sink::new()));
227        }
228        self.inner
229            .context_sink
230            .borrow()
231            .as_ref()
232            .unwrap()
233            .stream()
234            .map(|row| *row as usize)
235    }
236
237    /// Simulate a right-click on flat row `row` (used by tests and smokes).
238    pub fn emit_context_menu(&self, row: usize) {
239        if self.inner.is_alive() {
240            unsafe { ffi::view_emit_context_menu(self.inner.raw(), row as i32) };
241        }
242    }
243
244    /// The current vertical scroll position in pixels.
245    pub fn scroll_value(&self) -> i32 {
246        unsafe { ffi::tree_view_scroll_value(self.inner.raw()) }
247    }
248
249    /// Restore the vertical scroll position in pixels.
250    pub fn set_scroll_value(&self, value: i32) {
251        if self.inner.is_alive() {
252            unsafe { ffi::tree_view_set_scroll_value(self.inner.raw(), value) };
253        }
254    }
255
256    /// Expand or collapse all group rows.
257    pub fn expand_all(&self, expand: bool) {
258        if self.inner.is_alive() {
259            unsafe { ffi::tree_view_expand_all(self.inner.raw(), expand) };
260        }
261    }
262
263    /// Flat rows that are currently expanded.
264    pub fn expanded_rows(&self) -> Vec<usize> {
265        unsafe { ffi::tree_view_expanded_rows(self.inner.raw()) }
266            .into_iter()
267            .map(|row| row as usize)
268            .collect()
269    }
270
271    /// Expand the given flat rows.
272    pub fn expand_rows(&self, rows: &[usize]) {
273        if self.inner.is_alive() {
274            unsafe {
275                ffi::tree_view_expand_rows(
276                    self.inner.raw(),
277                    rows.iter().map(|row| *row as i32).collect(),
278                )
279            };
280        }
281    }
282
283    /// The flat row currently scrolled to the top of the viewport, if any.
284    pub fn top_row(&self) -> Option<usize> {
285        let row = unsafe { ffi::tree_view_top_row(self.inner.raw()) };
286        (row >= 0).then_some(row as usize)
287    }
288
289    /// Scroll the viewport so `flat` is at the top.
290    pub fn scroll_to_flat(&self, flat: usize) {
291        if self.inner.is_alive() {
292            unsafe { ffi::tree_view_scroll_to_flat(self.inner.raw(), flat as i32) };
293        }
294    }
295
296    /// Set the pixel width of `column`.
297    pub fn set_column_width(&self, column: usize, width: i32) {
298        if self.inner.is_alive() {
299            unsafe { ffi::tree_view_set_column_width(self.inner.raw(), column as i32, width) };
300        }
301    }
302
303    /// Hide or show `column` without changing the model layout.
304    pub fn set_column_hidden(&self, column: usize, hidden: bool) {
305        if self.inner.is_alive() {
306            unsafe { ffi::view_set_column_hidden(self.inner.raw(), column as i32, hidden) };
307        }
308    }
309
310    /// Show the sort arrow on `column` in the given direction.
311    pub fn set_sort_indicator(&self, column: usize, ascending: bool) {
312        if self.inner.is_alive() {
313            unsafe { ffi::view_set_sort_indicator(self.inner.raw(), column as i32, ascending) };
314        }
315    }
316
317    /// Keep the sort arrow in sync with a signal of `(column, ascending)`,
318    /// so sorting state stays declarative instead of imperative.
319    pub fn bind_sort_indicator(&self, signal: &Signal<(usize, bool)>) {
320        let view = self.inner.raw();
321        self.inner
322            .owner
323            .borrow_mut()
324            .add(signal.observe(move |(column, ascending)| unsafe {
325                ffi::view_set_sort_indicator(view, *column as i32, *ascending);
326            }));
327    }
328
329    /// Let the last column fill the remaining width.
330    pub fn stretch_last_section(&self, stretch: bool) {
331        if self.inner.is_alive() {
332            unsafe { ffi::tree_view_stretch_last_section(self.inner.raw(), stretch) };
333        }
334    }
335
336    /// Select whole rows instead of individual cells.
337    pub fn select_rows(&self, on: bool) {
338        if self.inner.is_alive() {
339            unsafe { ffi::view_set_select_rows(self.inner.raw(), on) };
340        }
341    }
342
343    /// Install the heat-map delegate.
344    pub fn enable_heat(&self) {
345        if self.inner.is_alive() {
346            unsafe { ffi::view_set_heat_delegate(self.inner.raw()) };
347        }
348    }
349}
350
351impl IntoWidget for TreeView {
352    fn component(&self) -> &Rc<Component> {
353        &self.inner
354    }
355}