1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
// Take a look at the license at the top of the repository in the LICENSE file.

use crate::Ordering;
use glib::object::{Cast, IsA};
use glib::translate::*;
use std::fmt;
use std::mem;

use crate::{SortType, TreeIter, TreeModel, TreeSortable};

#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum SortColumn {
    #[doc(alias = "GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID")]
    Default,
    Index(u32),
}

#[doc(hidden)]
impl IntoGlib for SortColumn {
    type GlibType = i32;

    #[inline]
    fn into_glib(self) -> i32 {
        match self {
            SortColumn::Default => ffi::GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID,
            SortColumn::Index(x) => {
                assert!(x <= i32::max_value() as u32, "column index is too big");
                x as i32
            }
        }
    }
}

#[doc(hidden)]
impl FromGlib<i32> for SortColumn {
    #[inline]
    unsafe fn from_glib(val: i32) -> Self {
        skip_assert_initialized!();
        match val {
            ffi::GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID => Self::Default,
            x => {
                assert!(x >= 0, "invalid column index");
                Self::Index(x as u32)
            }
        }
    }
}

impl fmt::Display for SortColumn {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "SortColumn::{}",
            match *self {
                SortColumn::Default => "Default",
                SortColumn::Index(_) => "Index",
            }
        )
    }
}

// rustdoc-stripper-ignore-next
/// Trait containing manually implemented methods of [`TreeSortable`](crate::TreeSortable).
pub trait TreeSortableExtManual: 'static {
    /// Sets the default comparison function used when sorting to be @sort_func.
    /// If the current sort column id of @self is
    /// `GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID`, then the model will sort using
    /// this function.
    ///
    /// If @sort_func is [`None`], then there will be no default comparison function.
    /// This means that once the model  has been sorted, it can’t go back to the
    /// default state. In this case, when the current sort column id of @self
    /// is `GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID`, the model will be unsorted.
    /// ## `sort_func`
    /// The comparison function
    #[doc(alias = "gtk_tree_sortable_set_default_sort_func")]
    fn set_default_sort_func<F>(&self, sort_func: F)
    where
        F: Fn(&Self, &TreeIter, &TreeIter) -> Ordering + 'static;
    /// Sets the comparison function used when sorting to be @sort_func. If the
    /// current sort column id of @self is the same as @sort_column_id, then
    /// the model will sort using this function.
    /// ## `sort_column_id`
    /// the sort column id to set the function for
    /// ## `sort_func`
    /// The comparison function
    #[doc(alias = "gtk_tree_sortable_set_sort_func")]
    fn set_sort_func<F>(&self, sort_column_id: SortColumn, sort_func: F)
    where
        F: Fn(&Self, &TreeIter, &TreeIter) -> Ordering + 'static;
    /// Fills in @sort_column_id and @order with the current sort column and the
    /// order. It returns [`true`] unless the @sort_column_id is
    /// `GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID` or
    /// `GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID`.
    ///
    /// # Returns
    ///
    /// [`true`] if the sort column is not one of the special sort
    ///   column ids.
    ///
    /// ## `sort_column_id`
    /// The sort column id to be filled in
    ///
    /// ## `order`
    /// The [`SortType`][crate::SortType] to be filled in
    #[doc(alias = "gtk_tree_sortable_get_sort_column_id")]
    #[doc(alias = "get_sort_column_id")]
    fn sort_column_id(&self) -> Option<(SortColumn, SortType)>;
    /// Sets the current sort column to be @sort_column_id. The @self will
    /// resort itself to reflect this change, after emitting a
    /// `GtkTreeSortable::sort-column-changed` signal. @sort_column_id may either be
    /// a regular column id, or one of the following special values:
    ///
    /// - `GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID`: the default sort function
    ///   will be used, if it is set
    ///
    /// - `GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID`: no sorting will occur
    /// ## `sort_column_id`
    /// the sort column id to set
    /// ## `order`
    /// The sort order of the column
    #[doc(alias = "gtk_tree_sortable_set_sort_column_id")]
    fn set_sort_column_id(&self, sort_column_id: SortColumn, order: SortType);
    #[doc(alias = "gtk_tree_sortable_set_sort_column_id")]
    fn set_unsorted(&self);
}

unsafe extern "C" fn trampoline<T, F: Fn(&T, &TreeIter, &TreeIter) -> Ordering>(
    this: *mut ffi::GtkTreeModel,
    iter: *mut ffi::GtkTreeIter,
    iter2: *mut ffi::GtkTreeIter,
    f: glib::ffi::gpointer,
) -> i32
where
    T: IsA<TreeSortable>,
{
    let f: &F = &*(f as *const F);
    f(
        &TreeModel::from_glib_none(this).unsafe_cast(),
        &from_glib_borrow(iter),
        &from_glib_borrow(iter2),
    )
    .into_glib()
}

unsafe extern "C" fn destroy_closure<T, F: Fn(&T, &TreeIter, &TreeIter) -> Ordering>(
    ptr: glib::ffi::gpointer,
) {
    Box::<F>::from_raw(ptr as *mut _);
}

fn into_raw<F, T>(func: F) -> glib::ffi::gpointer
where
    F: Fn(&T, &TreeIter, &TreeIter) -> Ordering + 'static,
{
    skip_assert_initialized!();
    let func: Box<F> = Box::new(func);
    Box::into_raw(func) as glib::ffi::gpointer
}

impl<O: IsA<TreeSortable>> TreeSortableExtManual for O {
    #[inline]
    fn sort_column_id(&self) -> Option<(SortColumn, SortType)> {
        unsafe {
            let mut sort_column_id = mem::MaybeUninit::uninit();
            let mut order = mem::MaybeUninit::uninit();
            ffi::gtk_tree_sortable_get_sort_column_id(
                self.as_ref().to_glib_none().0,
                sort_column_id.as_mut_ptr(),
                order.as_mut_ptr(),
            );
            let sort_column_id = sort_column_id.assume_init();
            if sort_column_id != ffi::GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID {
                Some((from_glib(sort_column_id), from_glib(order.assume_init())))
            } else {
                None
            }
        }
    }

    fn set_default_sort_func<F>(&self, sort_func: F)
    where
        F: Fn(&Self, &TreeIter, &TreeIter) -> Ordering + 'static,
    {
        unsafe {
            ffi::gtk_tree_sortable_set_default_sort_func(
                self.as_ref().to_glib_none().0,
                Some(trampoline::<Self, F>),
                into_raw(sort_func),
                Some(destroy_closure::<Self, F>),
            )
        }
    }

    #[inline]
    fn set_sort_column_id(&self, sort_column_id: SortColumn, order: SortType) {
        unsafe {
            ffi::gtk_tree_sortable_set_sort_column_id(
                self.as_ref().to_glib_none().0,
                sort_column_id.into_glib(),
                order.into_glib(),
            );
        }
    }

    fn set_unsorted(&self) {
        unsafe {
            ffi::gtk_tree_sortable_set_sort_column_id(
                self.as_ref().to_glib_none().0,
                ffi::GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID,
                SortType::Ascending.into_glib(),
            );
        }
    }

    fn set_sort_func<F>(&self, sort_column_id: SortColumn, sort_func: F)
    where
        F: Fn(&Self, &TreeIter, &TreeIter) -> Ordering + 'static,
    {
        unsafe {
            ffi::gtk_tree_sortable_set_sort_func(
                self.as_ref().to_glib_none().0,
                sort_column_id.into_glib(),
                Some(trampoline::<Self, F>),
                into_raw(sort_func),
                Some(destroy_closure::<Self, F>),
            )
        }
    }
}