1use std::{cell::Cell, cmp::Ordering, rc::Rc};
4
5use glib::{prelude::*, translate::*, Object};
6
7use crate::{ffi, prelude::*, ListModel, ListStore};
8
9impl ListStore {
10 #[doc(alias = "g_list_store_new")]
19 pub fn new<T: IsA<Object>>() -> Self {
20 Self::with_type(T::static_type())
21 }
22
23 #[doc(alias = "g_list_store_new")]
24 pub fn with_type(type_: glib::types::Type) -> Self {
25 unsafe { from_glib_full(ffi::g_list_store_new(type_.into_glib())) }
26 }
27
28 #[doc(alias = "g_list_store_insert_sorted")]
45 pub fn insert_sorted<P: IsA<glib::Object>, F: FnMut(&Object, &Object) -> Ordering>(
46 &self,
47 item: &P,
48 compare_func: F,
49 ) -> u32 {
50 unsafe {
51 let mut func = compare_func;
52 let func_obj: &mut (dyn FnMut(&Object, &Object) -> Ordering) = &mut func;
53 let func_ptr = &func_obj as *const &mut (dyn FnMut(&Object, &Object) -> Ordering)
54 as glib::ffi::gpointer;
55
56 ffi::g_list_store_insert_sorted(
57 self.to_glib_none().0,
58 item.as_ref().to_glib_none().0,
59 Some(compare_func_trampoline),
60 func_ptr,
61 )
62 }
63 }
64
65 #[doc(alias = "g_list_store_sort")]
69 pub fn sort<F: FnMut(&Object, &Object) -> Ordering>(&self, compare_func: F) {
70 unsafe {
71 let mut func = compare_func;
72 let func_obj: &mut (dyn FnMut(&Object, &Object) -> Ordering) = &mut func;
73 let func_ptr = &func_obj as *const &mut (dyn FnMut(&Object, &Object) -> Ordering)
74 as glib::ffi::gpointer;
75
76 ffi::g_list_store_sort(
77 self.to_glib_none().0,
78 Some(compare_func_trampoline),
79 func_ptr,
80 )
81 }
82 }
83
84 #[doc(alias = "g_list_store_splice")]
104 pub fn splice(&self, position: u32, n_removals: u32, additions: &[impl IsA<glib::Object>]) {
105 let n_additions = additions.len() as u32;
106 unsafe {
107 let additions = additions.as_ptr() as *mut *mut glib::gobject_ffi::GObject;
108
109 ffi::g_list_store_splice(
110 self.to_glib_none().0,
111 position,
112 n_removals,
113 additions,
114 n_additions,
115 );
116 }
117 }
118
119 pub fn extend_from_slice(&self, additions: &[impl IsA<glib::Object>]) {
122 self.splice(self.n_items(), 0, additions)
123 }
124
125 pub fn retain(&self, mut f: impl FnMut(&glib::Object) -> bool) {
135 let mut consec_removed = 0;
136 let mut i = 0;
137 const ADDITIONS: &[glib::Object] = &[]; let changed = Rc::new(Cell::new(false));
140 let changed_clone = changed.clone();
141 let signal_id = self.connect_items_changed(move |_list, _, _, _| changed_clone.set(true));
142
143 let _signal_guard = {
144 struct Guard<'a> {
145 list_store: &'a ListStore,
146 signal_id: Option<glib::SignalHandlerId>,
147 }
148 impl Drop for Guard<'_> {
149 fn drop(&mut self) {
150 self.list_store.disconnect(self.signal_id.take().unwrap());
151 }
152 }
153 Guard {
154 list_store: self,
155 signal_id: Some(signal_id),
156 }
157 };
158
159 while i < self.n_items() {
160 let keep = f(self.item(i).unwrap().as_ref());
161 if changed.get() {
162 panic!("The closure passed to ListStore::retain() must not mutate the list store");
163 }
164 if !keep {
165 consec_removed += 1;
166 } else if consec_removed > 0 {
167 self.splice(i - consec_removed, consec_removed, ADDITIONS);
168 changed.set(false);
169 i -= consec_removed;
170 consec_removed = 0;
171 }
172 i += 1;
173 }
174 if consec_removed > 0 {
175 self.splice(i - consec_removed, consec_removed, ADDITIONS);
176 }
177 }
178
179 #[cfg(feature = "v2_74")]
200 #[cfg_attr(docsrs, doc(cfg(feature = "v2_74")))]
201 #[doc(alias = "g_list_store_find_with_equal_func_full")]
202 #[doc(alias = "g_list_store_find_with_equal_func")]
203 pub fn find_with_equal_func<F: FnMut(&glib::Object) -> bool>(
204 &self,
205 equal_func: F,
206 ) -> Option<u32> {
207 unsafe extern "C" fn equal_func_trampoline(
208 a: glib::ffi::gconstpointer,
209 _b: glib::ffi::gconstpointer,
210 func: glib::ffi::gpointer,
211 ) -> glib::ffi::gboolean {
212 let func = func as *mut &mut (dyn FnMut(&Object) -> bool);
213
214 let a = from_glib_borrow(a as *mut glib::gobject_ffi::GObject);
215
216 (*func)(&a).into_glib()
217 }
218
219 let mut func = equal_func;
220 let func_obj: &mut (dyn FnMut(&Object) -> bool) = &mut func;
221 let func_ptr = &func_obj as *const &mut (dyn FnMut(&Object) -> bool) as glib::ffi::gpointer;
222 let mut position = std::mem::MaybeUninit::uninit();
223
224 #[cfg(not(feature = "v2_76"))]
227 let result = unsafe {
228 let g_class: *mut glib::gobject_ffi::GTypeClass =
229 glib::gobject_ffi::g_type_class_peek(self.item_type().into_glib()) as *mut _;
230
231 if g_class.is_null() {
234 return None;
235 }
236
237 let item = glib::gobject_ffi::GObject {
238 g_type_instance: glib::gobject_ffi::GTypeInstance { g_class },
239 ref_count: 1,
240 qdata: std::ptr::null_mut(),
241 };
242
243 bool::from_glib(ffi::g_list_store_find_with_equal_func_full(
244 self.to_glib_none().0,
245 mut_override(&item as *const _),
246 Some(equal_func_trampoline),
247 func_ptr,
248 position.as_mut_ptr(),
249 ))
250 .then(|| position.assume_init())
251 };
252
253 #[cfg(feature = "v2_76")]
254 let result = unsafe {
255 bool::from_glib(ffi::g_list_store_find_with_equal_func_full(
256 self.to_glib_none().0,
257 std::ptr::null_mut(),
258 Some(equal_func_trampoline),
259 func_ptr,
260 position.as_mut_ptr(),
261 ))
262 .then(|| position.assume_init())
263 };
264
265 result
266 }
267}
268
269impl<P: IsA<glib::Object>> std::iter::FromIterator<P> for ListStore {
270 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> Self {
271 let store = Self::new::<P>();
272 for item in iter.into_iter() {
273 store.append(&item)
274 }
275 store
276 }
277}
278
279impl<'a> std::iter::IntoIterator for &'a ListStore {
280 type Item = <&'a ListModel as IntoIterator>::Item;
281 type IntoIter = <&'a ListModel as IntoIterator>::IntoIter;
282
283 fn into_iter(self) -> Self::IntoIter {
284 self.upcast_ref::<ListModel>().into_iter()
285 }
286}
287
288unsafe extern "C" fn compare_func_trampoline(
289 a: glib::ffi::gconstpointer,
290 b: glib::ffi::gconstpointer,
291 func: glib::ffi::gpointer,
292) -> i32 {
293 let func = func as *mut &mut (dyn FnMut(&Object, &Object) -> Ordering);
294
295 let a = from_glib_borrow(a as *mut glib::gobject_ffi::GObject);
296 let b = from_glib_borrow(b as *mut glib::gobject_ffi::GObject);
297
298 (*func)(&a, &b).into_glib()
299}
300
301impl<A: AsRef<glib::Object>> std::iter::Extend<A> for ListStore {
302 fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
303 let additions = iter
304 .into_iter()
305 .map(|o| o.as_ref().clone())
306 .collect::<Vec<_>>();
307 self.splice(self.n_items(), 0, &additions)
308 }
309}
310
311#[cfg(test)]
312mod tests {
313 use crate::{prelude::*, ListStore};
314
315 #[test]
316 fn splice() {
317 let item0 = ListStore::new::<ListStore>();
318 let item1 = ListStore::new::<ListStore>();
319 let list = ListStore::new::<ListStore>();
320 list.splice(0, 0, &[item0.clone(), item1.clone()]);
321 assert_eq!(list.item(0), Some(item0.upcast()));
322 assert_eq!(list.item(1), Some(item1.upcast()));
323 }
324
325 #[test]
326 fn extend() {
327 let item0 = ListStore::new::<ListStore>();
328 let item1 = ListStore::new::<ListStore>();
329 let mut list = ListStore::new::<ListStore>();
330 list.extend([&item0, &item1]);
331 assert_eq!(list.item(0).as_ref(), Some(item0.upcast_ref()));
332 assert_eq!(list.item(1).as_ref(), Some(item1.upcast_ref()));
333 list.extend([item0.clone(), item1.clone()]);
334 assert_eq!(list.item(2).as_ref(), Some(item0.upcast_ref()));
335 assert_eq!(list.item(3).as_ref(), Some(item1.upcast_ref()));
336
337 let list_from_slice = ListStore::new::<ListStore>();
338 list_from_slice.extend_from_slice(&[item0, item1.clone()]);
339 assert_eq!(list_from_slice.item(1).as_ref(), Some(item1.upcast_ref()));
340 }
341
342 #[test]
343 fn from_iterator() {
344 let item0 = ListStore::new::<ListStore>();
345 let item1 = ListStore::new::<ListStore>();
346 let v = vec![item0.clone(), item1.clone()];
347 let list = ListStore::from_iter(v);
348 assert_eq!(list.item(0).as_ref(), Some(item0.upcast_ref()));
349 assert_eq!(list.item(1).as_ref(), Some(item1.upcast_ref()));
350 assert_eq!(list.item(2).as_ref(), None);
351 }
352
353 #[cfg(feature = "v2_74")]
354 #[test]
355 fn find() {
356 let item0 = ListStore::new::<ListStore>();
357 let item1 = ListStore::new::<ListStore>();
358 let list = ListStore::new::<ListStore>();
359 list.append(&item0);
360 list.append(&item1);
361
362 let res = list.find_with_equal_func(|item| item == &item1);
363 assert_eq!(res, Some(1));
364 }
365
366 #[test]
367 fn retain() {
368 let list = {
369 let list = ListStore::new::<ListStore>();
370 for _ in 0..10 {
371 list.append(&ListStore::new::<ListStore>());
372 }
373 list
374 };
375
376 use std::cell::Cell;
377 use std::rc::Rc;
378
379 let signal_count = Rc::new(Cell::new(0));
380 let signal_count_clone = signal_count.clone();
381 list.connect_items_changed(move |_, _, _, _| {
382 signal_count_clone.set(signal_count_clone.get() + 1);
383 });
384
385 let to_keep = [
386 list.item(1).unwrap(),
388 list.item(3).unwrap(),
390 list.item(7).unwrap(),
394 ];
397 list.retain(|item| to_keep.contains(item));
398
399 assert_eq!(list.n_items(), 3);
401 assert_eq!(list.item(0).as_ref(), Some(&to_keep[0]));
402 assert_eq!(list.item(1).as_ref(), Some(&to_keep[1]));
403 assert_eq!(list.item(2).as_ref(), Some(&to_keep[2]));
404
405 assert_eq!(signal_count.get(), 4);
406 }
407}