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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
// Take a look at the license at the top of the repository in the LICENSE file.

use crate::{Builder, Widget};
use glib::prelude::*;
use glib::translate::*;
use glib::GString;
use glib::Object;
use std::path::Path;
use std::ptr;

impl Builder {
    #[doc(alias = "gtk_builder_new_from_file")]
    pub fn from_file<T: AsRef<Path>>(file_path: T) -> Builder {
        assert_initialized_main_thread!();
        unsafe {
            from_glib_full(ffi::gtk_builder_new_from_file(
                file_path.as_ref().to_glib_none().0,
            ))
        }
    }
}

pub trait BuilderExtManual: 'static {
    #[doc(alias = "gtk_builder_get_object")]
    #[doc(alias = "get_object")]
    fn object<T: IsA<Object>>(&self, name: &str) -> Option<T>;

    #[doc(alias = "gtk_builder_add_from_file")]
    fn add_from_file<T: AsRef<Path>>(&self, file_path: T) -> Result<(), glib::Error>;
    /// Parses a resource file containing a [GtkBuilder UI definition][BUILDER-UI]
    /// and merges it with the current contents of `self`.
    ///
    /// Most users will probably want to use [`Builder::from_resource()`][crate::Builder::from_resource()].
    ///
    /// If an error occurs, 0 will be returned and `error` will be assigned a
    /// [`glib::Error`][crate::glib::Error] from the `GTK_BUILDER_ERROR`, `G_MARKUP_ERROR` or `G_RESOURCE_ERROR`
    /// domain.
    ///
    /// It’s not really reasonable to attempt to handle failures of this
    /// call. The only reasonable thing to do when an error is detected is
    /// to call `g_error()`.
    /// ## `resource_path`
    /// the path of the resource file to parse
    ///
    /// # Returns
    ///
    /// A positive value on success, 0 if an error occurred
    #[doc(alias = "gtk_builder_add_from_resource")]
    fn add_from_resource(&self, resource_path: &str) -> Result<(), glib::Error>;
    /// Parses a string containing a [GtkBuilder UI definition][BUILDER-UI]
    /// and merges it with the current contents of `self`.
    ///
    /// Most users will probably want to use [`Builder::from_string()`][crate::Builder::from_string()].
    ///
    /// Upon errors 0 will be returned and `error` will be assigned a
    /// [`glib::Error`][crate::glib::Error] from the `GTK_BUILDER_ERROR`, `G_MARKUP_ERROR` or
    /// `G_VARIANT_PARSE_ERROR` domain.
    ///
    /// It’s not really reasonable to attempt to handle failures of this
    /// call. The only reasonable thing to do when an error is detected is
    /// to call `g_error()`.
    /// ## `buffer`
    /// the string to parse
    /// ## `length`
    /// the length of `buffer` (may be -1 if `buffer` is nul-terminated)
    ///
    /// # Returns
    ///
    /// A positive value on success, 0 if an error occurred
    #[doc(alias = "gtk_builder_add_from_string")]
    fn add_from_string(&self, buffer: &str) -> Result<(), glib::Error>;

    /// Parses a resource file containing a [GtkBuilder UI definition][BUILDER-UI]
    /// building only the requested objects and merges
    /// them with the current contents of `self`.
    ///
    /// Upon errors 0 will be returned and `error` will be assigned a
    /// [`glib::Error`][crate::glib::Error] from the `GTK_BUILDER_ERROR`, `G_MARKUP_ERROR` or `G_RESOURCE_ERROR`
    /// domain.
    ///
    /// If you are adding an object that depends on an object that is not
    /// its child (for instance a [`TreeView`][crate::TreeView] that depends on its
    /// [`TreeModel`][crate::TreeModel]), you have to explicitly list all of them in `object_ids`.
    /// ## `resource_path`
    /// the path of the resource file to parse
    /// ## `object_ids`
    /// nul-terminated array of objects to build
    ///
    /// # Returns
    ///
    /// A positive value on success, 0 if an error occurred
    #[doc(alias = "gtk_builder_add_objects_from_resource")]
    fn add_objects_from_resource(
        &self,
        resource_path: &str,
        object_ids: &[&str],
    ) -> Result<(), glib::Error>;
    /// Parses a string containing a [GtkBuilder UI definition][BUILDER-UI]
    /// building only the requested objects and merges
    /// them with the current contents of `self`.
    ///
    /// Upon errors 0 will be returned and `error` will be assigned a
    /// [`glib::Error`][crate::glib::Error] from the `GTK_BUILDER_ERROR` or `G_MARKUP_ERROR` domain.
    ///
    /// If you are adding an object that depends on an object that is not
    /// its child (for instance a [`TreeView`][crate::TreeView] that depends on its
    /// [`TreeModel`][crate::TreeModel]), you have to explicitly list all of them in `object_ids`.
    /// ## `buffer`
    /// the string to parse
    /// ## `length`
    /// the length of `buffer` (may be -1 if `buffer` is nul-terminated)
    /// ## `object_ids`
    /// nul-terminated array of objects to build
    ///
    /// # Returns
    ///
    /// A positive value on success, 0 if an error occurred
    #[doc(alias = "gtk_builder_add_objects_from_string")]
    fn add_objects_from_string(&self, buffer: &str, object_ids: &[&str])
        -> Result<(), glib::Error>;

    #[doc(alias = "gtk_builder_connect_signals_full")]
    fn connect_signals<
        P: FnMut(&Builder, &str) -> Box<dyn Fn(&[glib::Value]) -> Option<glib::Value> + 'static>,
    >(
        &self,
        func: P,
    );

    /// Main private entry point for building composite container
    /// components from template XML.
    ///
    /// This is exported purely to let gtk-builder-tool validate
    /// templates, applications have no need to call this function.
    /// ## `widget`
    /// the widget that is being extended
    /// ## `template_type`
    /// the type that the template is for
    /// ## `buffer`
    /// the string to parse
    /// ## `length`
    /// the length of `buffer` (may be -1 if `buffer` is nul-terminated)
    ///
    /// # Returns
    ///
    /// A positive value on success, 0 if an error occurred
    #[doc(alias = "gtk_builder_extend_with_template")]
    fn extend_with_template(
        &self,
        widget: &impl IsA<Widget>,
        template_type: glib::types::Type,
        buffer: &str,
    ) -> Result<(), glib::Error>;
}

impl<O: IsA<Builder>> BuilderExtManual for O {
    fn object<T: IsA<Object>>(&self, name: &str) -> Option<T> {
        unsafe {
            Option::<Object>::from_glib_none(ffi::gtk_builder_get_object(
                self.upcast_ref().to_glib_none().0,
                name.to_glib_none().0,
            ))
            .and_then(|obj| obj.dynamic_cast::<T>().ok())
        }
    }

    fn add_from_file<T: AsRef<Path>>(&self, file_path: T) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ::std::ptr::null_mut();
            let exit_code = ffi::gtk_builder_add_from_file(
                self.upcast_ref().to_glib_none().0,
                file_path.as_ref().to_glib_none().0,
                &mut error,
            );
            assert_eq!(exit_code == 0, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    fn add_from_resource(&self, resource_path: &str) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let exit_code = ffi::gtk_builder_add_from_resource(
                self.as_ref().to_glib_none().0,
                resource_path.to_glib_none().0,
                &mut error,
            );
            assert_eq!(exit_code == 0, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    fn add_from_string(&self, buffer: &str) -> Result<(), glib::Error> {
        let length = buffer.len() as usize;
        unsafe {
            let mut error = ptr::null_mut();
            let exit_code = ffi::gtk_builder_add_from_string(
                self.as_ref().to_glib_none().0,
                buffer.to_glib_none().0,
                length,
                &mut error,
            );
            assert_eq!(exit_code == 0, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    fn add_objects_from_resource(
        &self,
        resource_path: &str,
        object_ids: &[&str],
    ) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let exit_code = ffi::gtk_builder_add_objects_from_resource(
                self.as_ref().to_glib_none().0,
                resource_path.to_glib_none().0,
                object_ids.to_glib_none().0,
                &mut error,
            );
            assert_eq!(exit_code == 0, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    fn add_objects_from_string(
        &self,
        buffer: &str,
        object_ids: &[&str],
    ) -> Result<(), glib::Error> {
        let length = buffer.len() as usize;
        unsafe {
            let mut error = ptr::null_mut();
            let exit_code = ffi::gtk_builder_add_objects_from_string(
                self.as_ref().to_glib_none().0,
                buffer.to_glib_none().0,
                length,
                object_ids.to_glib_none().0,
                &mut error,
            );
            assert_eq!(exit_code == 0, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    fn connect_signals<
        P: FnMut(&Builder, &str) -> Box<dyn Fn(&[glib::Value]) -> Option<glib::Value> + 'static>,
    >(
        &self,
        func: P,
    ) {
        let func_data: P = func;
        unsafe extern "C" fn func_func<
            P: FnMut(&Builder, &str) -> Box<dyn Fn(&[glib::Value]) -> Option<glib::Value> + 'static>,
        >(
            builder: *mut ffi::GtkBuilder,
            object: *mut glib::gobject_ffi::GObject,
            signal_name: *const libc::c_char,
            handler_name: *const libc::c_char,
            connect_object: *mut glib::gobject_ffi::GObject,
            flags: glib::gobject_ffi::GConnectFlags,
            user_data: glib::ffi::gpointer,
        ) {
            assert!(connect_object.is_null(), "Connect object is not supported");
            assert!(
                flags & glib::gobject_ffi::G_CONNECT_SWAPPED == 0,
                "Swapped signal handler is not supported"
            );

            let builder = from_glib_borrow(builder);
            let object: Borrowed<glib::Object> = from_glib_borrow(object);
            let signal_name: Borrowed<GString> = from_glib_borrow(signal_name);
            let handler_name: Borrowed<GString> = from_glib_borrow(handler_name);
            let callback: *mut P = user_data as *const _ as usize as *mut P;
            let func = (*callback)(&builder, handler_name.as_str());
            object
                .try_connect_unsafe(
                    signal_name.as_str(),
                    flags & glib::gobject_ffi::G_CONNECT_AFTER != 0,
                    move |args| func(args),
                )
                .expect("Failed to connect to builder signal");
        }
        let func = Some(func_func::<P> as _);
        let super_callback0: &P = &func_data;
        unsafe {
            ffi::gtk_builder_connect_signals_full(
                self.as_ref().to_glib_none().0,
                func,
                super_callback0 as *const _ as usize as *mut _,
            );
        }
    }

    fn extend_with_template(
        &self,
        widget: &impl IsA<Widget>,
        template_type: glib::types::Type,
        buffer: &str,
    ) -> Result<(), glib::Error> {
        let length = buffer.len() as usize;
        unsafe {
            let mut error = ptr::null_mut();
            let exit_code = ffi::gtk_builder_extend_with_template(
                self.as_ref().to_glib_none().0,
                widget.as_ref().to_glib_none().0,
                template_type.into_glib(),
                buffer.to_glib_none().0,
                length,
                &mut error,
            );
            assert_eq!(exit_code == 0, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }
}