Skip to main content

gtk/
tree_sortable.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use crate::{SortType, ffi};
4use glib::object::IsA;
5use glib::translate::*;
6use std::cmp::Ordering;
7use std::fmt;
8use std::mem;
9
10use crate::{TreeIter, TreeModel, TreeSortable};
11use ffi::{GtkTreeIter, GtkTreeModel};
12use glib::ffi::gpointer;
13
14#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
15pub enum SortColumn {
16    #[doc(alias = "GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID")]
17    Default,
18    Index(u32),
19}
20
21#[doc(hidden)]
22impl IntoGlib for SortColumn {
23    type GlibType = i32;
24
25    #[inline]
26    fn into_glib(self) -> i32 {
27        match self {
28            Self::Default => ffi::GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID,
29            Self::Index(x) => {
30                assert!(x <= i32::MAX as u32, "column index is too big");
31                x as i32
32            }
33        }
34    }
35}
36
37#[doc(hidden)]
38impl FromGlib<i32> for SortColumn {
39    #[inline]
40    unsafe fn from_glib(val: i32) -> Self {
41        skip_assert_initialized!();
42        match val {
43            ffi::GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID => Self::Default,
44            x => {
45                assert!(x >= 0, "invalid column index");
46                Self::Index(x as u32)
47            }
48        }
49    }
50}
51
52impl fmt::Display for SortColumn {
53    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
54        write!(
55            f,
56            "SortColumn::{}",
57            match *self {
58                Self::Default => "Default",
59                Self::Index(_) => "Index",
60            }
61        )
62    }
63}
64
65pub trait TreeSortableExtManual: IsA<TreeSortable> + 'static {
66    /// Sets the default comparison function used when sorting to be `sort_func`.
67    /// If the current sort column id of `self` is
68    /// `GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID`, then the model will sort using
69    /// this function.
70    ///
71    /// If `sort_func` is [`None`], then there will be no default comparison function.
72    /// This means that once the model has been sorted, it can’t go back to the
73    /// default state. In this case, when the current sort column id of `self`
74    /// is `GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID`, the model will be unsorted.
75    /// ## `sort_func`
76    /// The comparison function
77    #[doc(alias = "gtk_tree_sortable_set_default_sort_func")]
78    fn set_default_sort_func<F>(&self, sort_func: F)
79    where
80        F: Fn(&TreeModel, &TreeIter, &TreeIter) -> Ordering + 'static,
81    {
82        unsafe extern "C" fn trampoline<F: Fn(&TreeModel, &TreeIter, &TreeIter) -> Ordering>(
83            this: *mut GtkTreeModel,
84            iter: *mut GtkTreeIter,
85            iter2: *mut GtkTreeIter,
86            f: gpointer,
87        ) -> i32 {
88            unsafe {
89                let f: &F = &*(f as *const F);
90                f(
91                    &TreeModel::from_glib_borrow(this),
92                    &from_glib_borrow(iter),
93                    &from_glib_borrow(iter2),
94                )
95                .into_glib()
96            }
97        }
98        unsafe extern "C" fn destroy_closure<
99            F: Fn(&TreeModel, &TreeIter, &TreeIter) -> Ordering,
100        >(
101            ptr: gpointer,
102        ) {
103            unsafe {
104                let _ = Box::<F>::from_raw(ptr as *mut _);
105            }
106        }
107        unsafe {
108            ffi::gtk_tree_sortable_set_default_sort_func(
109                self.as_ref().to_glib_none().0,
110                Some(trampoline::<F>),
111                into_raw(sort_func),
112                Some(destroy_closure::<F>),
113            )
114        }
115    }
116    /// Sets the comparison function used when sorting to be `sort_func`. If the
117    /// current sort column id of `self` is the same as `sort_column_id`, then
118    /// the model will sort using this function.
119    /// ## `sort_column_id`
120    /// the sort column id to set the function for
121    /// ## `sort_func`
122    /// The comparison function
123    #[doc(alias = "gtk_tree_sortable_set_sort_func")]
124    fn set_sort_func<F>(&self, sort_column_id: SortColumn, sort_func: F)
125    where
126        F: Fn(&TreeModel, &TreeIter, &TreeIter) -> Ordering + 'static,
127    {
128        unsafe extern "C" fn trampoline<F: Fn(&TreeModel, &TreeIter, &TreeIter) -> Ordering>(
129            this: *mut GtkTreeModel,
130            iter: *mut GtkTreeIter,
131            iter2: *mut GtkTreeIter,
132            f: gpointer,
133        ) -> i32 {
134            unsafe {
135                let f: &F = &*(f as *const F);
136                f(
137                    &TreeModel::from_glib_borrow(this),
138                    &from_glib_borrow(iter),
139                    &from_glib_borrow(iter2),
140                )
141                .into_glib()
142            }
143        }
144        unsafe extern "C" fn destroy_closure<
145            F: Fn(&TreeModel, &TreeIter, &TreeIter) -> Ordering,
146        >(
147            ptr: gpointer,
148        ) {
149            unsafe {
150                let _ = Box::<F>::from_raw(ptr as *mut _);
151            }
152        }
153        unsafe {
154            ffi::gtk_tree_sortable_set_sort_func(
155                self.as_ref().to_glib_none().0,
156                sort_column_id.into_glib(),
157                Some(trampoline::<F>),
158                into_raw(sort_func),
159                Some(destroy_closure::<F>),
160            )
161        }
162    }
163    /// Fills in `sort_column_id` and `order` with the current sort column and the
164    /// order. It returns [`true`] unless the `sort_column_id` is
165    /// `GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID` or
166    /// `GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID`.
167    ///
168    /// # Returns
169    ///
170    /// [`true`] if the sort column is not one of the special sort
171    ///  column ids.
172    ///
173    /// ## `sort_column_id`
174    /// The sort column id to be filled in
175    ///
176    /// ## `order`
177    /// The [`SortType`][crate::SortType] to be filled in
178    #[doc(alias = "get_sort_column_id")]
179    #[doc(alias = "gtk_tree_sortable_get_sort_column_id")]
180    fn sort_column_id(&self) -> Option<(SortColumn, SortType)> {
181        unsafe {
182            let mut sort_column_id = mem::MaybeUninit::uninit();
183            let mut order = mem::MaybeUninit::uninit();
184            ffi::gtk_tree_sortable_get_sort_column_id(
185                self.as_ref().to_glib_none().0,
186                sort_column_id.as_mut_ptr(),
187                order.as_mut_ptr(),
188            );
189            let sort_column_id = sort_column_id.assume_init();
190            if sort_column_id != ffi::GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID {
191                Some((from_glib(sort_column_id), from_glib(order.assume_init())))
192            } else {
193                None
194            }
195        }
196    }
197    /// Sets the current sort column to be `sort_column_id`. The `self` will
198    /// resort itself to reflect this change, after emitting a
199    /// [`sort-column-changed`][struct@crate::TreeSortable#sort-column-changed] signal. `sort_column_id` may either be
200    /// a regular column id, or one of the following special values:
201    ///
202    /// - `GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID`: the default sort function
203    ///  will be used, if it is set
204    ///
205    /// - `GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID`: no sorting will occur
206    /// ## `sort_column_id`
207    /// the sort column id to set
208    /// ## `order`
209    /// The sort order of the column
210    #[doc(alias = "gtk_tree_sortable_set_sort_column_id")]
211    fn set_sort_column_id(&self, sort_column_id: SortColumn, order: SortType) {
212        unsafe {
213            ffi::gtk_tree_sortable_set_sort_column_id(
214                self.as_ref().to_glib_none().0,
215                sort_column_id.into_glib(),
216                order.into_glib(),
217            );
218        }
219    }
220    fn set_unsorted(&self) {
221        unsafe {
222            ffi::gtk_tree_sortable_set_sort_column_id(
223                self.as_ref().to_glib_none().0,
224                ffi::GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID,
225                SortType::Ascending.into_glib(),
226            );
227        }
228    }
229}
230
231fn into_raw<F, T>(func: F) -> gpointer
232where
233    F: Fn(&T, &TreeIter, &TreeIter) -> Ordering + 'static,
234{
235    skip_assert_initialized!();
236    let func: Box<F> = Box::new(func);
237    Box::into_raw(func) as gpointer
238}
239
240impl<O: IsA<TreeSortable>> TreeSortableExtManual for O {}