gtk/
menu.rs

1// Copyright 2016, The Gtk-rs Project Developers.
2// See the COPYRIGHT file at the top-level directory of this distribution.
3// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
4
5use glib::object::Cast;
6use glib::translate::*;
7use glib_sys;
8use gtk_sys;
9use libc::c_int;
10use std::boxed::Box as Box_;
11use std::ptr;
12use IsA;
13use Menu;
14use Widget;
15
16pub trait GtkMenuExtManual: 'static {
17    fn popup<T: IsA<Widget>, U: IsA<Widget>, F: Fn(&Self, &mut i32, &mut i32) -> bool + 'static>(
18        &self,
19        parent_menu_shell: Option<&T>,
20        parent_menu_item: Option<&U>,
21        f: F,
22        button: u32,
23        activate_time: u32,
24    );
25
26    fn popup_easy(&self, button: u32, activate_time: u32);
27}
28
29impl<O: IsA<Menu>> GtkMenuExtManual for O {
30    fn popup<
31        T: IsA<Widget>,
32        U: IsA<Widget>,
33        F: FnOnce(&Self, &mut i32, &mut i32) -> bool + 'static,
34    >(
35        &self,
36        parent_menu_shell: Option<&T>,
37        parent_menu_item: Option<&U>,
38        f: F,
39        button: u32,
40        activate_time: u32,
41    ) {
42        unsafe extern "C" fn position_callback<
43            T,
44            F: FnOnce(&T, &mut i32, &mut i32) -> bool + 'static,
45        >(
46            this: *mut gtk_sys::GtkMenu,
47            x: *mut c_int,
48            y: *mut c_int,
49            push_in: *mut glib_sys::gboolean,
50            f: glib_sys::gpointer,
51        ) where
52            T: IsA<Menu>,
53        {
54            let mut f: Box<Option<F>> = Box::from_raw(f as *mut _);
55            let f = f.take().expect("No callback");
56            *push_in = f(
57                &Menu::from_glib_none(this).unsafe_cast(),
58                x.as_mut().unwrap(),
59                y.as_mut().unwrap(),
60            )
61            .to_glib();
62        }
63        unsafe {
64            let f: Box_<Option<F>> = Box_::new(Some(f));
65            gtk_sys::gtk_menu_popup(
66                self.as_ref().to_glib_none().0,
67                parent_menu_shell.map(|p| p.as_ref()).to_glib_none().0,
68                parent_menu_item.map(|p| p.as_ref()).to_glib_none().0,
69                Some(position_callback::<Self, F>),
70                Box_::into_raw(f) as *mut _,
71                button,
72                activate_time,
73            )
74        }
75    }
76
77    fn popup_easy(&self, button: u32, activate_time: u32) {
78        unsafe {
79            gtk_sys::gtk_menu_popup(
80                self.as_ref().to_glib_none().0,
81                ptr::null_mut(),
82                ptr::null_mut(),
83                None,
84                ptr::null_mut(),
85                button,
86                activate_time,
87            )
88        }
89    }
90}