[go: up one dir, main page]

gtk4/
custom_sorter.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::ptr;
4
5use glib::translate::*;
6
7use crate::{ffi, CustomSorter, Ordering};
8
9impl CustomSorter {
10    #[doc(alias = "gtk_custom_sorter_new")]
11    pub fn new<F>(sort_func: F) -> Self
12    where
13        F: Fn(&glib::Object, &glib::Object) -> Ordering + 'static,
14    {
15        assert_initialized_main_thread!();
16        unsafe {
17            from_glib_full(ffi::gtk_custom_sorter_new(
18                Some(trampoline::<F>),
19                Box::into_raw(Box::new(sort_func)) as *mut _,
20                Some(destroy_closure::<F>),
21            ))
22        }
23    }
24
25    #[doc(alias = "gtk_custom_sorter_set_sort_func")]
26    pub fn set_sort_func<F>(&self, sort_func: F)
27    where
28        F: Fn(&glib::Object, &glib::Object) -> Ordering + 'static,
29    {
30        unsafe {
31            ffi::gtk_custom_sorter_set_sort_func(
32                self.to_glib_none().0,
33                Some(trampoline::<F>),
34                Box::into_raw(Box::new(sort_func)) as *mut _,
35                Some(destroy_closure::<F>),
36            )
37        }
38    }
39
40    #[doc(alias = "gtk_custom_sorter_set_sort_func")]
41    #[doc(alias = "set_sort_func")]
42    pub fn unset_sort_func(&self) {
43        unsafe {
44            ffi::gtk_custom_sorter_set_sort_func(self.to_glib_none().0, None, ptr::null_mut(), None)
45        }
46    }
47}
48
49impl Default for CustomSorter {
50    fn default() -> Self {
51        assert_initialized_main_thread!();
52        unsafe { from_glib_full(ffi::gtk_custom_sorter_new(None, ptr::null_mut(), None)) }
53    }
54}
55
56unsafe extern "C" fn destroy_closure<F: Fn(&glib::Object, &glib::Object) -> Ordering + 'static>(
57    ptr: glib::ffi::gpointer,
58) {
59    let _ = Box::<F>::from_raw(ptr as *mut _);
60}
61
62unsafe extern "C" fn trampoline<F: Fn(&glib::Object, &glib::Object) -> Ordering + 'static>(
63    a: glib::ffi::gconstpointer,
64    b: glib::ffi::gconstpointer,
65    f: glib::ffi::gpointer,
66) -> i32 {
67    let f: &F = &*(f as *const F);
68    f(
69        &from_glib_borrow(a as *mut glib::gobject_ffi::GObject),
70        &from_glib_borrow(b as *mut glib::gobject_ffi::GObject),
71    )
72    .into_glib()
73}