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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
// Take a look at the license at the top of the repository in the LICENSE file.

use std::mem::transmute;

use crate::{
    signal::{connect_raw, SignalHandlerId},
    translate::*,
    IsA, Object, ObjectType, RustClosure, SignalGroup, Value,
};

impl SignalGroup {
    #[doc(alias = "g_signal_group_new")]
    pub fn new<T: IsA<Object>>() -> Self {
        Self::with_type(T::static_type())
    }
    /// Connects `closure` to the signal `detailed_signal` on [`target`][struct@crate::SignalGroup#target].
    ///
    /// You cannot connect a signal handler after [`target`][struct@crate::SignalGroup#target] has been set.
    /// ## `detailed_signal`
    /// a string of the form `signal-name` with optional `::signal-detail`
    /// ## `closure`
    /// the closure to connect.
    /// ## `after`
    /// whether the handler should be called before or after the
    ///  default handler of the signal.
    #[doc(alias = "g_signal_group_connect_closure")]
    pub fn connect_closure(&self, signal_name: &str, after: bool, closure: RustClosure) {
        unsafe {
            gobject_ffi::g_signal_group_connect_closure(
                self.to_glib_none().0,
                signal_name.to_glib_none().0,
                closure.as_ref().to_glib_none().0,
                after.into_glib(),
            );
        }
    }

    /// Connects `c_handler` to the signal `detailed_signal`
    /// on the target instance of `self`.
    ///
    /// You cannot connect a signal handler after [`target`][struct@crate::SignalGroup#target] has been set.
    /// ## `detailed_signal`
    /// a string of the form "signal-name::detail"
    /// ## `c_handler`
    /// the `GCallback` to connect
    #[doc(alias = "g_signal_group_connect")]
    #[inline]
    pub fn connect<F>(&self, signal_name: &str, after: bool, callback: F)
    where
        F: Fn(&[Value]) -> Option<Value> + Send + Sync + 'static,
    {
        self.connect_closure(signal_name, after, RustClosure::new(callback));
    }

    // rustdoc-stripper-ignore-next
    /// Like [`Self::connect`] but doesn't require a `Send+Sync` closure. Signal emission will
    /// panic if the signal on the current target is emitted from a different thread from the
    /// thread that connected the signal.
    #[inline]
    pub fn connect_local<F>(&self, signal_name: &str, after: bool, callback: F)
    where
        F: Fn(&[Value]) -> Option<Value> + 'static,
    {
        self.connect_closure(signal_name, after, RustClosure::new_local(callback));
    }

    #[inline]
    pub fn connect_notify<F>(&self, name: Option<&str>, callback: F)
    where
        F: Fn(&crate::Object, &crate::ParamSpec) + Send + Sync + 'static,
    {
        let signal_name = if let Some(name) = name {
            format!("notify::{name}")
        } else {
            "notify".into()
        };

        let closure = crate::RustClosure::new(move |values| {
            let obj = values[0].get().unwrap();
            let pspec = values[1].get().unwrap();
            callback(obj, pspec);

            None
        });

        self.connect_closure(&signal_name, false, closure);
    }

    #[inline]
    pub fn connect_notify_local<F>(&self, name: Option<&str>, callback: F)
    where
        F: Fn(&crate::Object, &crate::ParamSpec) + 'static,
    {
        let signal_name = if let Some(name) = name {
            format!("notify::{name}")
        } else {
            "notify".into()
        };

        let closure = crate::RustClosure::new_local(move |values| {
            let obj = values[0].get().unwrap();
            let pspec = values[1].get().unwrap();
            callback(obj, pspec);

            None
        });

        self.connect_closure(&signal_name, false, closure);
    }

    unsafe fn connect_bind_unsafe<F: Fn(&Self, &Object)>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn bind_trampoline<F: Fn(&SignalGroup, &Object)>(
            this: *mut crate::gobject_ffi::GSignalGroup,
            instance: *mut crate::gobject_ffi::GObject,
            f: ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(&from_glib_borrow(this), &from_glib_borrow(instance))
        }
        let f: Box<F> = Box::new(f);
        connect_raw(
            self.as_ptr() as *mut _,
            b"bind\0".as_ptr() as *const _,
            Some(transmute::<_, unsafe extern "C" fn()>(
                bind_trampoline::<F> as *const (),
            )),
            Box::into_raw(f),
        )
    }

    unsafe fn connect_unbind_unsafe<F: Fn(&Self)>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn unbind_trampoline<F: Fn(&SignalGroup)>(
            this: *mut crate::gobject_ffi::GSignalGroup,
            f: ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(&from_glib_borrow(this))
        }
        let f: Box<F> = Box::new(f);
        connect_raw(
            self.as_ptr() as *mut _,
            b"unbind\0".as_ptr() as *const _,
            Some(transmute::<_, unsafe extern "C" fn()>(
                unbind_trampoline::<F> as *const (),
            )),
            Box::into_raw(f),
        )
    }

    /// This signal is emitted when [`target`][struct@crate::SignalGroup#target] is set to a new value
    /// other than [`None`]. It is similar to [`notify`][struct@crate::Object#notify] on `target` except it
    /// will not emit when [`target`][struct@crate::SignalGroup#target] is [`None`] and also allows for
    /// receiving the [`Object`][crate::Object] without a data-race.
    /// ## `instance`
    /// a [`Object`][crate::Object] containing the new value for [`target`][struct@crate::SignalGroup#target]
    #[doc(alias = "bind")]
    pub fn connect_bind<F: Fn(&Self, &Object) + Send + Sync + 'static>(
        &self,
        f: F,
    ) -> SignalHandlerId {
        unsafe { self.connect_bind_unsafe(f) }
    }

    // rustdoc-stripper-ignore-next
    /// Like [`Self::connect_bind`] but doesn't require a `Send+Sync` closure. Signal emission will
    /// panic if the signal is emitted from a different thread from the thread that connected the
    /// signal.
    pub fn connect_bind_local<F: Fn(&Self, &Object) + 'static>(&self, f: F) -> SignalHandlerId {
        let f = crate::thread_guard::ThreadGuard::new(f);

        unsafe {
            self.connect_bind_unsafe(move |s, o| {
                (f.get_ref())(s, o);
            })
        }
    }

    /// This signal is emitted when the target instance of `self_` is set to a
    /// new [`Object`][crate::Object].
    ///
    /// This signal will only be emitted if the previous target of `self_` is
    /// non-[`None`].
    #[doc(alias = "unbind")]
    pub fn connect_unbind<F: Fn(&Self) + Send + Sync + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe { self.connect_unbind_unsafe(f) }
    }

    // rustdoc-stripper-ignore-next
    /// Like [`Self::connect_unbind`] but doesn't require a `Send+Sync` closure. Signal emission
    /// will panic if the signal is emitted from a different thread from the thread that connected
    /// the signal.
    pub fn connect_unbind_local<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        let f = crate::thread_guard::ThreadGuard::new(f);

        unsafe {
            self.connect_unbind_unsafe(move |s| {
                (f.get_ref())(s);
            })
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{cell::RefCell, rc::Rc};

    use super::*;
    use crate as glib;
    use crate::{ObjectExt, StaticType};

    mod imp {
        use super::*;
        use crate::subclass::{prelude::*, Signal};

        #[derive(Default)]
        pub struct SignalObject {}

        #[glib::object_subclass]
        impl ObjectSubclass for SignalObject {
            const NAME: &'static str = "SignalObject";
            type Type = super::SignalObject;
        }

        impl ObjectImpl for SignalObject {
            fn signals() -> &'static [Signal] {
                use once_cell::sync::Lazy;
                static SIGNALS: Lazy<Vec<Signal>> = Lazy::new(|| {
                    vec![
                        Signal::builder("sig-with-args")
                            .param_types([u32::static_type(), String::static_type()])
                            .build(),
                        Signal::builder("sig-with-ret")
                            .return_type::<String>()
                            .build(),
                    ]
                });
                SIGNALS.as_ref()
            }
        }
    }

    wrapper! {
        pub struct SignalObject(ObjectSubclass<imp::SignalObject>);
    }

    #[test]
    fn group_emit() {
        let group = SignalGroup::new::<SignalObject>();

        let obj = Object::new::<SignalObject>();
        let store = Rc::new(RefCell::new(String::new()));
        group.connect_closure(
            "sig-with-args",
            false,
            glib::closure_local!(@watch obj, @strong store => move |o: &SignalObject, a: u32, b: &str| {
                assert_eq!(o, obj);
                store.replace(format!("a {a} b {b}"));
            })
        );
        group.connect_closure(
            "sig-with-ret",
            false,
            glib::closure_local!(@watch obj => move |o: &SignalObject| -> &'static crate::GStr {
                assert_eq!(o, obj);
                crate::gstr!("Hello")
            }),
        );
        group.set_target(Some(&obj));
        obj.emit_by_name::<()>("sig-with-args", &[&5u32, &"World"]);
        assert_eq!(*store.borrow(), "a 5 b World");
        let ret = obj.emit_by_name::<crate::GString>("sig-with-ret", &[]);
        assert_eq!(ret, "Hello");
        group.set_target(Object::NONE);
        let ret = obj.emit_by_name::<Option<String>>("sig-with-ret", &[]);
        assert_eq!(ret, None);
    }
}