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
231
// Take a look at the license at the top of the repository in the LICENSE file.

// rustdoc-stripper-ignore-next
//! `IMPL` Low level signal support.

use std::{mem, num::NonZeroU64};

use ffi::gpointer;
use gobject_ffi::GCallback;
use libc::{c_char, c_ulong, c_void};

use crate::{prelude::*, translate::*};

// rustdoc-stripper-ignore-next
/// The id of a signal that is returned by `connect`.
///
/// This type does not implement `Clone` to prevent disconnecting
/// the same signal handler multiple times.
///
/// ```ignore
/// use glib::SignalHandlerId;
/// use gtk::prelude::*;
/// use std::cell::RefCell;
///
/// struct Button {
///     widget: gtk::Button,
///     clicked_handler_id: RefCell<Option<SignalHandlerId>>,
/// }
///
/// impl Button {
///     fn new() -> Self {
///         let widget = gtk::Button::new();
///         let clicked_handler_id = RefCell::new(Some(widget.connect_clicked(|_button| {
///             // Do something.
///         })));
///         Self {
///             widget,
///             clicked_handler_id,
///         }
///     }
///
///     fn disconnect(&self) {
///         if let Some(id) = self.clicked_handler_id.take() {
///             self.widget.disconnect(id)
///         }
///     }
/// }
/// ```
#[derive(Debug, Eq, PartialEq)]
pub struct SignalHandlerId(NonZeroU64);

impl SignalHandlerId {
    // rustdoc-stripper-ignore-next
    /// Returns the internal signal handler ID.
    pub unsafe fn as_raw(&self) -> libc::c_ulong {
        self.0.get() as libc::c_ulong
    }
}

impl FromGlib<c_ulong> for SignalHandlerId {
    #[inline]
    unsafe fn from_glib(val: c_ulong) -> Self {
        debug_assert_ne!(val, 0);
        Self(NonZeroU64::new_unchecked(val as _))
    }
}

pub unsafe fn connect_raw<F>(
    receiver: *mut gobject_ffi::GObject,
    signal_name: *const c_char,
    trampoline: GCallback,
    closure: *mut F,
) -> SignalHandlerId {
    unsafe extern "C" fn destroy_closure<F>(ptr: *mut c_void, _: *mut gobject_ffi::GClosure) {
        // destroy
        let _ = Box::<F>::from_raw(ptr as *mut _);
    }
    debug_assert_eq!(mem::size_of::<*mut F>(), mem::size_of::<gpointer>());
    debug_assert!(trampoline.is_some());
    let handle = gobject_ffi::g_signal_connect_data(
        receiver,
        signal_name,
        trampoline,
        closure as *mut _,
        Some(destroy_closure::<F>),
        0,
    );
    debug_assert!(handle > 0);
    from_glib(handle)
}

#[doc(alias = "g_signal_handler_block")]
pub fn signal_handler_block<T: ObjectType>(instance: &T, handler_id: &SignalHandlerId) {
    unsafe {
        gobject_ffi::g_signal_handler_block(
            instance.as_object_ref().to_glib_none().0,
            handler_id.as_raw(),
        );
    }
}

#[doc(alias = "g_signal_handler_unblock")]
pub fn signal_handler_unblock<T: ObjectType>(instance: &T, handler_id: &SignalHandlerId) {
    unsafe {
        gobject_ffi::g_signal_handler_unblock(
            instance.as_object_ref().to_glib_none().0,
            handler_id.as_raw(),
        );
    }
}

#[allow(clippy::needless_pass_by_value)]
#[doc(alias = "g_signal_handler_disconnect")]
pub fn signal_handler_disconnect<T: ObjectType>(instance: &T, handler_id: SignalHandlerId) {
    unsafe {
        gobject_ffi::g_signal_handler_disconnect(
            instance.as_object_ref().to_glib_none().0,
            handler_id.as_raw(),
        );
    }
}

#[doc(alias = "g_signal_stop_emission_by_name")]
pub fn signal_stop_emission_by_name<T: ObjectType>(instance: &T, signal_name: &str) {
    unsafe {
        gobject_ffi::g_signal_stop_emission_by_name(
            instance.as_object_ref().to_glib_none().0,
            signal_name.to_glib_none().0,
        );
    }
}

#[doc(alias = "g_signal_has_handler_pending")]
pub fn signal_has_handler_pending<T: ObjectType>(
    instance: &T,
    signal_id: crate::subclass::SignalId,
    detail: Option<crate::Quark>,
    may_be_blocked: bool,
) -> bool {
    unsafe {
        from_glib(gobject_ffi::g_signal_has_handler_pending(
            instance.as_object_ref().to_glib_none().0,
            signal_id.into_glib(),
            detail.map_or(0, |d| d.into_glib()),
            may_be_blocked.into_glib(),
        ))
    }
}

// rustdoc-stripper-ignore-next
/// Whether to invoke the other event handlers.
///
/// `Stop` and `Proceed` map to `GDK_EVENT_STOP` (`true`) and
/// `GDK_EVENT_PROPAGATE` (`false`), respectively.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Propagation {
    // Stop other handlers from being invoked for the event.
    #[doc(alias = "GDK_EVENT_STOP")]
    Stop,
    // Propagate the event further.
    #[doc(alias = "GDK_EVENT_PROPAGATE")]
    Proceed,
}

impl Propagation {
    // rustdoc-stripper-ignore-next
    /// Returns `true` if this is a `Stop` variant.
    pub fn is_stop(&self) -> bool {
        matches!(self, Self::Stop)
    }

    // rustdoc-stripper-ignore-next
    /// Returns `true` if this is a `Proceed` variant.
    pub fn is_proceed(&self) -> bool {
        matches!(self, Self::Proceed)
    }
}

impl From<bool> for Propagation {
    fn from(value: bool) -> Self {
        if value {
            Self::Stop
        } else {
            Self::Proceed
        }
    }
}

impl From<Propagation> for bool {
    fn from(c: Propagation) -> Self {
        match c {
            Propagation::Stop => true,
            Propagation::Proceed => false,
        }
    }
}

#[doc(hidden)]
impl IntoGlib for Propagation {
    type GlibType = ffi::gboolean;

    #[inline]
    fn into_glib(self) -> ffi::gboolean {
        bool::from(self).into_glib()
    }
}

#[doc(hidden)]
impl FromGlib<ffi::gboolean> for Propagation {
    #[inline]
    unsafe fn from_glib(value: ffi::gboolean) -> Self {
        bool::from_glib(value).into()
    }
}

impl crate::value::ToValue for Propagation {
    fn to_value(&self) -> crate::Value {
        bool::from(*self).to_value()
    }

    fn value_type(&self) -> crate::Type {
        <bool as StaticType>::static_type()
    }
}

impl From<Propagation> for crate::Value {
    #[inline]
    fn from(v: Propagation) -> Self {
        bool::from(v).into()
    }
}