Skip to main content

yse_ui/widgets/
list_view.rs

1//! List view wrapper and its string list model.
2
3use crate::bridge as ffi;
4use crate::bridge::Void;
5use crate::component::Component;
6use crate::widgets::{IntoWidget, SelectionBridge};
7use std::cell::RefCell;
8use std::rc::Rc;
9use yse_model::{EventStream, ListChange, ListModel, Sink, Subscription};
10
11/// A retained list view backed by a [`StringListModel`].
12pub struct ListView {
13    pub(crate) inner: Rc<Component>,
14    pub(crate) model: Rc<ModelState>,
15    pub(crate) selection: Rc<SelectionBridge>,
16}
17
18impl Clone for ListView {
19    fn clone(&self) -> Self {
20        Self {
21            inner: self.inner.clone(),
22            model: self.model.clone(),
23            selection: self.selection.clone(),
24        }
25    }
26}
27
28impl ListView {
29    /// A stream of selection changes, each carrying the selected row indices.
30    pub fn selection_changed(&self) -> EventStream<Vec<usize>> {
31        if self.selection.sink.borrow().is_none() {
32            unsafe {
33                ffi::view_set_selection_cb(
34                    self.inner.raw(),
35                    &*self.selection as *const SelectionBridge as *mut Void,
36                );
37            }
38            *self.selection.sink.borrow_mut() = Some(Rc::new(Sink::new()));
39        }
40        self.selection.sink.borrow().as_ref().unwrap().stream()
41    }
42
43    /// Register a selection handler carrying the selected row indices.
44    pub fn on_selection<F>(&self, f: F) -> &Self
45    where
46        F: FnMut(&Vec<usize>) + 'static,
47    {
48        self.inner
49            .owner
50            .borrow_mut()
51            .add(self.selection_changed().observe(f));
52        self
53    }
54
55    /// Select `row`, replacing the current selection.
56    pub fn select(&self, row: usize) {
57        if self.inner.is_alive() {
58            unsafe { ffi::view_select_row(self.inner.raw(), row as i32) };
59        }
60    }
61
62    /// Clear the selection.
63    pub fn clear_selection(&self) {
64        if self.inner.is_alive() {
65            unsafe { ffi::view_clear_selection(self.inner.raw()) };
66        }
67    }
68
69    /// The currently selected row indices.
70    pub fn selected_rows(&self) -> Vec<usize> {
71        unsafe { ffi::view_selected_rows(self.inner.raw()) }
72            .into_iter()
73            .map(|row| row as usize)
74            .collect()
75    }
76
77    /// Escape hatch: the underlying Qt `QListView` pointer.
78    ///
79    /// The pointer is valid only while this view's Qt object is alive. Do not
80    /// retain it after destruction or use it from a thread other than the GUI
81    /// thread. Dereferencing or passing the pointer across FFI remains unsafe.
82    pub fn qobject_ptr(&self) -> *mut Void {
83        self.inner.raw() as *mut Void
84    }
85}
86
87impl IntoWidget for ListView {
88    fn component(&self) -> &Rc<Component> {
89        &self.inner
90    }
91}
92
93pub(crate) struct ModelState {
94    pub(crate) model: *mut ffi::Model,
95    list: Rc<ListModel<String>>,
96    subscription: RefCell<Option<Subscription>>,
97}
98
99impl Drop for ModelState {
100    fn drop(&mut self) {
101        // Unsubscribe before freeing the C++ model so no change event can
102        // touch a freed pointer.
103        self.subscription.take();
104        unsafe { ffi::model_drop(self.model) };
105    }
106}
107
108/// A string list model that drives a Qt `QListView` incrementally.
109///
110/// Mutations update a [`yse_model::ListModel`] and are applied to the C++
111/// `QAbstractListModel` through `beginInsertRows`/`beginRemoveRows`/
112/// `dataChanged`, so the view never resets for ordinary edits.
113pub struct StringListModel {
114    pub(crate) state: Rc<ModelState>,
115}
116
117impl Clone for StringListModel {
118    fn clone(&self) -> Self {
119        Self {
120            state: self.state.clone(),
121        }
122    }
123}
124
125impl StringListModel {
126    /// Create an empty model.
127    pub fn new() -> Self {
128        let model = unsafe { ffi::model_new() };
129        let list = Rc::new(ListModel::new());
130        let model_ptr = model;
131        let subscription = list.changes().observe(move |change| match change {
132            ListChange::Insert { index, items } => {
133                unsafe { ffi::model_insert_rows(model_ptr, *index as i32, items.clone()) };
134            }
135            ListChange::Remove { index, len } => {
136                unsafe { ffi::model_remove_rows(model_ptr, *index as i32, *len as i32) };
137            }
138            ListChange::Update { index, items } => {
139                unsafe { ffi::model_update_rows(model_ptr, *index as i32, items.clone()) };
140            }
141            ListChange::Reset { items } => {
142                unsafe { ffi::model_reset(model_ptr, items.clone()) };
143            }
144        });
145        Self {
146            state: Rc::new(ModelState {
147                model,
148                list,
149                subscription: RefCell::new(Some(subscription)),
150            }),
151        }
152    }
153
154    /// Number of rows in the C++ mirror (equal to the list length).
155    pub fn row_count(&self) -> usize {
156        unsafe { ffi::model_row_count(self.state.model) as usize }
157    }
158
159    /// The text of a row as stored in the C++ mirror.
160    pub fn row_text(&self, row: usize) -> String {
161        unsafe { ffi::model_text(self.state.model, row as i32) }
162    }
163
164    /// The underlying pure-Rust list.
165    pub fn list(&self) -> &Rc<ListModel<String>> {
166        &self.state.list
167    }
168
169    /// Append `item`.
170    pub fn push(&self, item: impl Into<String>) {
171        self.state.list.push(item.into());
172    }
173
174    /// Append every item in `items`.
175    pub fn extend(&self, items: impl IntoIterator<Item = String>) {
176        self.state.list.extend(items.into_iter().collect());
177    }
178
179    /// Insert `item` at `index`.
180    pub fn insert(&self, index: usize, item: impl Into<String>) {
181        self.state.list.insert(index, item.into());
182    }
183
184    /// Remove the row at `index`.
185    pub fn remove(&self, index: usize) -> bool {
186        self.state.list.remove(index)
187    }
188
189    /// Replace the row at `index`.
190    pub fn set(&self, index: usize, item: impl Into<String>) -> bool {
191        self.state.list.set(index, item.into())
192    }
193
194    /// Remove every row.
195    pub fn clear(&self) {
196        self.state.list.clear();
197    }
198
199    /// Replace the whole list.
200    pub fn replace_all(&self, items: impl IntoIterator<Item = String>) {
201        self.state.list.replace_all(items.into_iter().collect());
202    }
203}
204
205impl Default for StringListModel {
206    fn default() -> Self {
207        Self::new()
208    }
209}