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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT

use crate::{BuilderClosureFlags, BuilderScope};
use glib::{
    prelude::*,
    signal::{connect_raw, SignalHandlerId},
    translate::*,
};
use std::{boxed::Box as Box_, fmt, mem::transmute, ptr};

glib::wrapper! {
    /// A [`Builder`][crate::Builder] reads XML descriptions of a user interface and
    /// instantiates the described objects.
    ///
    /// To create a [`Builder`][crate::Builder] from a user interface description, call
    /// [`from_file()`][Self::from_file()], [`from_resource()`][Self::from_resource()]
    /// or [`from_string()`][Self::from_string()].
    ///
    /// In the (unusual) case that you want to add user interface
    /// descriptions from multiple sources to the same [`Builder`][crate::Builder] you can
    /// call [`new()`][Self::new()] to get an empty builder and populate it by
    /// (multiple) calls to [`add_from_file()`][Self::add_from_file()],
    /// [`add_from_resource()`][Self::add_from_resource()] or
    /// [`add_from_string()`][Self::add_from_string()].
    ///
    /// A [`Builder`][crate::Builder] holds a reference to all objects that it has constructed
    /// and drops these references when it is finalized. This finalization can
    /// cause the destruction of non-widget objects or widgets which are not
    /// contained in a toplevel window. For toplevel windows constructed by a
    /// builder, it is the responsibility of the user to call
    /// `Gtk::Window::destroy()` to get rid of them and all the widgets
    /// they contain.
    ///
    /// The functions [`object()`][Self::object()] and
    /// [`objects()`][Self::objects()] can be used to access the widgets in
    /// the interface by the names assigned to them inside the UI description.
    /// Toplevel windows returned by these functions will stay around until the
    /// user explicitly destroys them with `Gtk::Window::destroy()`. Other
    /// widgets will either be part of a larger hierarchy constructed by the
    /// builder (in which case you should not have to worry about their lifecycle),
    /// or without a parent, in which case they have to be added to some container
    /// to make use of them. Non-widget objects need to be reffed with
    /// g_object_ref() to keep them beyond the lifespan of the builder.
    ///
    /// # GtkBuilder UI Definitions
    ///
    /// [`Builder`][crate::Builder] parses textual descriptions of user interfaces which are
    /// specified in XML format. We refer to these descriptions as “GtkBuilder
    /// UI definitions” or just “UI definitions” if the context is clear.
    ///
    /// The toplevel element is `<interface>`. It optionally takes a “domain”
    /// attribute, which will make the builder look for translated strings
    /// using `dgettext()` in the domain specified. This can also be done by
    /// calling [`set_translation_domain()`][Self::set_translation_domain()] on the builder.
    ///
    /// Objects are described by `<object>` elements, which can contain
    /// `<property>` elements to set properties, `<signal>` elements which
    /// connect signals to handlers, and `<child>` elements, which describe
    /// child objects (most often widgets inside a container, but also e.g.
    /// actions in an action group, or columns in a tree model). A `<child>`
    /// element contains an `<object>` element which describes the child object.
    ///
    /// The target toolkit version(s) are described by `<requires>` elements,
    /// the “lib” attribute specifies the widget library in question (currently
    /// the only supported value is “gtk”) and the “version” attribute specifies
    /// the target version in the form “`<major>`.`<minor>`”. [`Builder`][crate::Builder] will
    /// error out if the version requirements are not met.
    ///
    /// Typically, the specific kind of object represented by an `<object>`
    /// element is specified by the “class” attribute. If the type has not
    /// been loaded yet, GTK tries to find the `get_type()` function from the
    /// class name by applying heuristics. This works in most cases, but if
    /// necessary, it is possible to specify the name of the `get_type()`
    /// function explicitly with the "type-func" attribute.
    ///
    /// Objects may be given a name with the “id” attribute, which allows the
    /// application to retrieve them from the builder with
    /// [`object()`][Self::object()]. An id is also necessary to use the
    /// object as property value in other parts of the UI definition. GTK
    /// reserves ids starting and ending with `___` (three consecutive
    /// underscores) for its own purposes.
    ///
    /// Setting properties of objects is pretty straightforward with the
    /// `<property>` element: the “name” attribute specifies the name of the
    /// property, and the content of the element specifies the value.
    /// If the “translatable” attribute is set to a true value, GTK uses
    /// `gettext()` (or `dgettext()` if the builder has a translation domain set)
    /// to find a translation for the value. This happens before the value
    /// is parsed, so it can be used for properties of any type, but it is
    /// probably most useful for string properties. It is also possible to
    /// specify a context to disambiguate short strings, and comments which
    /// may help the translators.
    ///
    /// [`Builder`][crate::Builder] can parse textual representations for the most common
    /// property types: characters, strings, integers, floating-point numbers,
    /// booleans (strings like “TRUE”, “t”, “yes”, “y”, “1” are interpreted
    /// as [`true`], strings like “FALSE”, “f”, “no”, “n”, “0” are interpreted
    /// as [`false`]), enumerations (can be specified by their name, nick or
    /// integer value), flags (can be specified by their name, nick, integer
    /// value, optionally combined with “|”, e.g.
    /// “GTK_INPUT_HINT_EMOJI|GTK_INPUT_HINT_LOWERCASE”)
    /// and colors (in a format understood by [`gdk::RGBA::parse()`][crate::gdk::RGBA::parse()]).
    ///
    /// `GVariant`s can be specified in the format understood by
    /// g_variant_parse(), and pixbufs can be specified as a filename of an
    /// image file to load.
    ///
    /// Objects can be referred to by their name and by default refer to
    /// objects declared in the local XML fragment and objects exposed via
    /// [`expose_object()`][Self::expose_object()]. In general, [`Builder`][crate::Builder] allows
    /// forward references to objects — declared in the local XML; an object
    /// doesn’t have to be constructed before it can be referred to. The
    /// exception to this rule is that an object has to be constructed before
    /// it can be used as the value of a construct-only property.
    ///
    /// It is also possible to bind a property value to another object's
    /// property value using the attributes "bind-source" to specify the
    /// source object of the binding, and optionally, "bind-property" and
    /// "bind-flags" to specify the source property and source binding flags
    /// respectively. Internally, [`Builder`][crate::Builder] implements this using `GBinding`
    /// objects. For more information see g_object_bind_property().
    ///
    /// Sometimes it is necessary to refer to widgets which have implicitly
    /// been constructed by GTK as part of a composite widget, to set
    /// properties on them or to add further children (e.g. the content area
    /// of a [`Dialog`][crate::Dialog]). This can be achieved by setting the “internal-child”
    /// property of the `<child>` element to a true value. Note that [`Builder`][crate::Builder]
    /// still requires an `<object>` element for the internal child, even if it
    /// has already been constructed.
    ///
    /// A number of widgets have different places where a child can be added
    /// (e.g. tabs vs. page content in notebooks). This can be reflected in
    /// a UI definition by specifying the “type” attribute on a `<child>`
    /// The possible values for the “type” attribute are described in the
    /// sections describing the widget-specific portions of UI definitions.
    ///
    /// # Signal handlers and function pointers
    ///
    /// Signal handlers are set up with the `<signal>` element. The “name”
    /// attribute specifies the name of the signal, and the “handler” attribute
    /// specifies the function to connect to the signal.
    /// The remaining attributes, “after”, “swapped” and “object”, have the
    /// same meaning as the corresponding parameters of the
    /// g_signal_connect_object() or g_signal_connect_data() functions. A
    /// “last_modification_time” attribute is also allowed, but it does not
    /// have a meaning to the builder.
    ///
    /// If you rely on `GModule` support to lookup callbacks in the symbol table,
    /// the following details should be noted:
    ///
    /// When compiling applications for Windows, you must declare signal callbacks
    /// with `G_MODULE_EXPORT`, or they will not be put in the symbol table.
    /// On Linux and Unix, this is not necessary; applications should instead
    /// be compiled with the -Wl,--export-dynamic `CFLAGS`, and linked against
    /// `gmodule-export-2.0`.
    ///
    /// # A GtkBuilder UI Definition
    ///
    /// ```xml
    /// <interface>
    ///   <object class="GtkDialog" id="dialog1">
    ///     <child internal-child="content_area">
    ///       <object class="GtkBox" id="vbox1">
    ///         <child internal-child="action_area">
    ///           <object class="GtkBox" id="hbuttonbox1">
    ///             <child>
    ///               <object class="GtkButton" id="ok_button">
    ///                 <property name="label" translatable="yes">_Ok</property>
    ///                 <property name="use-underline">True</property>
    ///                 <signal name="clicked" handler="ok_button_clicked"/>
    ///               </object>
    ///             </child>
    ///           </object>
    ///         </child>
    ///       </object>
    ///     </child>
    ///   </object>
    /// </interface>
    /// ```
    ///
    /// Beyond this general structure, several object classes define their
    /// own XML DTD fragments for filling in the ANY placeholders in the DTD
    /// above. Note that a custom element in a `<child>` element gets parsed by
    /// the custom tag handler of the parent object, while a custom element in
    /// an `<object>` element gets parsed by the custom tag handler of the object.
    ///
    /// These XML fragments are explained in the documentation of the
    /// respective objects.
    ///
    /// A `<template>` tag can be used to define a widget class’s components.
    /// See the [GtkWidget documentation](class.Widget.html#building-composite-widgets-from-template-xml) for details.
    ///
    /// ## Properties
    ///
    ///
    /// #### `current-object`
    ///  The object the builder is evaluating for.
    ///
    /// Readable | Writeable
    ///
    ///
    /// #### `scope`
    ///  The scope the builder is operating in
    ///
    /// Readable | Writeable | Construct
    ///
    ///
    /// #### `translation-domain`
    ///  The translation domain used when translating property values that
    /// have been marked as translatable.
    ///
    /// If the translation domain is [`None`], [`Builder`][crate::Builder] uses gettext(),
    /// otherwise g_dgettext().
    ///
    /// Readable | Writeable
    ///
    /// # Implements
    ///
    /// [`trait@glib::ObjectExt`]
    #[doc(alias = "GtkBuilder")]
    pub struct Builder(Object<ffi::GtkBuilder, ffi::GtkBuilderClass>);

    match fn {
        type_ => || ffi::gtk_builder_get_type(),
    }
}

impl Builder {
    /// Creates a new empty builder object.
    ///
    /// This function is only useful if you intend to make multiple calls
    /// to [`add_from_file()`][Self::add_from_file()], [`add_from_resource()`][Self::add_from_resource()]
    /// or [`add_from_string()`][Self::add_from_string()] in order to merge multiple UI
    /// descriptions into a single builder.
    ///
    /// # Returns
    ///
    /// a new (empty) [`Builder`][crate::Builder] object
    #[doc(alias = "gtk_builder_new")]
    pub fn new() -> Builder {
        assert_initialized_main_thread!();
        unsafe { from_glib_full(ffi::gtk_builder_new()) }
    }

    /// Parses the UI definition at @resource_path.
    ///
    /// If there is an error locating the resource or parsing the
    /// description, then the program will be aborted.
    /// ## `resource_path`
    /// a `GResource` resource path
    ///
    /// # Returns
    ///
    /// a [`Builder`][crate::Builder] containing the described interface
    #[doc(alias = "gtk_builder_new_from_resource")]
    #[doc(alias = "new_from_resource")]
    pub fn from_resource(resource_path: &str) -> Builder {
        assert_initialized_main_thread!();
        unsafe {
            from_glib_full(ffi::gtk_builder_new_from_resource(
                resource_path.to_glib_none().0,
            ))
        }
    }

    /// Parses the UI definition in @string.
    ///
    /// If @string is [`None`]-terminated, then @length should be -1.
    /// If @length is not -1, then it is the length of @string.
    ///
    /// If there is an error parsing @string then the program will be
    /// aborted. You should not attempt to parse user interface description
    /// from untrusted sources.
    /// ## `string`
    /// a user interface (XML) description
    /// ## `length`
    /// the length of @string, or -1
    ///
    /// # Returns
    ///
    /// a [`Builder`][crate::Builder] containing the interface described by @string
    #[doc(alias = "gtk_builder_new_from_string")]
    #[doc(alias = "new_from_string")]
    pub fn from_string(string: &str) -> Builder {
        assert_initialized_main_thread!();
        let length = string.len() as _;
        unsafe {
            from_glib_full(ffi::gtk_builder_new_from_string(
                string.to_glib_none().0,
                length,
            ))
        }
    }

    /// Parses a resource file containing a UI definition
    /// and merges it with the current contents of @self.
    ///
    /// This function is useful if you need to call
    /// [`set_current_object()`][Self::set_current_object()] to add user data to
    /// callbacks before loading GtkBuilder UI. Otherwise, you probably
    /// want [`from_resource()`][Self::from_resource()] instead.
    ///
    /// If an error occurs, 0 will be returned and @error will be assigned a
    /// `GError` 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
    ///
    /// [`true`] on success, [`false`] if an error occurred
    #[doc(alias = "gtk_builder_add_from_resource")]
    pub fn add_from_resource(&self, resource_path: &str) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::gtk_builder_add_from_resource(
                self.to_glib_none().0,
                resource_path.to_glib_none().0,
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Parses a string containing a UI definition and merges it
    /// with the current contents of @self.
    ///
    /// This function is useful if you need to call
    /// [`set_current_object()`][Self::set_current_object()] to add user data to
    /// callbacks before loading [`Builder`][crate::Builder] UI. Otherwise, you probably
    /// want [`from_string()`][Self::from_string()] instead.
    ///
    /// Upon errors [`false`] will be returned and @error will be assigned a
    /// `GError` 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
    ///
    /// [`true`] on success, [`false`] if an error occurred
    #[doc(alias = "gtk_builder_add_from_string")]
    pub fn add_from_string(&self, buffer: &str) -> Result<(), glib::Error> {
        let length = buffer.len() as _;
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::gtk_builder_add_from_string(
                self.to_glib_none().0,
                buffer.to_glib_none().0,
                length,
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Parses a file containing a UI definition 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
    /// `GError` from the `GTK_BUILDER_ERROR`, `G_MARKUP_ERROR` or `G_FILE_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.
    /// ## `filename`
    /// the name of the file to parse
    /// ## `object_ids`
    /// nul-terminated array of objects to build
    ///
    /// # Returns
    ///
    /// [`true`] on success, [`false`] if an error occurred
    #[doc(alias = "gtk_builder_add_objects_from_file")]
    pub fn add_objects_from_file(
        &self,
        filename: impl AsRef<std::path::Path>,
        object_ids: &[&str],
    ) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::gtk_builder_add_objects_from_file(
                self.to_glib_none().0,
                filename.as_ref().to_glib_none().0,
                object_ids.to_glib_none().0,
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Parses a resource file containing a UI definition, 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
    /// `GError` 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
    ///
    /// [`true`] on success, [`false`] if an error occurred
    #[doc(alias = "gtk_builder_add_objects_from_resource")]
    pub fn add_objects_from_resource(
        &self,
        resource_path: &str,
        object_ids: &[&str],
    ) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::gtk_builder_add_objects_from_resource(
                self.to_glib_none().0,
                resource_path.to_glib_none().0,
                object_ids.to_glib_none().0,
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Parses a string containing a UI definition, building only the
    /// requested objects and merges them with the current contents of
    /// @self.
    ///
    /// Upon errors [`false`] will be returned and @error will be assigned a
    /// `GError` 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
    ///
    /// [`true`] on success, [`false`] if an error occurred
    #[doc(alias = "gtk_builder_add_objects_from_string")]
    pub fn add_objects_from_string(
        &self,
        buffer: &str,
        object_ids: &[&str],
    ) -> Result<(), glib::Error> {
        let length = buffer.len() as _;
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::gtk_builder_add_objects_from_string(
                self.to_glib_none().0,
                buffer.to_glib_none().0,
                length,
                object_ids.to_glib_none().0,
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Creates a closure to invoke the function called @function_name.
    ///
    /// This is using the create_closure() implementation of @self's
    /// [`BuilderScope`][crate::BuilderScope].
    ///
    /// If no closure could be created, [`None`] will be returned and @error
    /// will be set.
    /// ## `function_name`
    /// name of the function to look up
    /// ## `flags`
    /// closure creation flags
    /// ## `object`
    /// Object to create the closure with
    ///
    /// # Returns
    ///
    /// A new closure for invoking @function_name
    #[doc(alias = "gtk_builder_create_closure")]
    pub fn create_closure(
        &self,
        function_name: &str,
        flags: BuilderClosureFlags,
        object: Option<&impl IsA<glib::Object>>,
    ) -> Result<Option<glib::Closure>, glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let ret = ffi::gtk_builder_create_closure(
                self.to_glib_none().0,
                function_name.to_glib_none().0,
                flags.into_glib(),
                object.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Add @object to the @self object pool so it can be
    /// referenced just like any other object built by builder.
    ///
    /// Only a single object may be added using @name. However,
    /// it is not an error to expose the same object under multiple
    /// names. `gtk_builder_get_object()` may be used to determine
    /// if an object has already been added with @name.
    /// ## `name`
    /// the name of the object exposed to the builder
    /// ## `object`
    /// the object to expose
    #[doc(alias = "gtk_builder_expose_object")]
    pub fn expose_object(&self, name: &str, object: &impl IsA<glib::Object>) {
        unsafe {
            ffi::gtk_builder_expose_object(
                self.to_glib_none().0,
                name.to_glib_none().0,
                object.as_ref().to_glib_none().0,
            );
        }
    }

    /// Main private entry point for building composite components
    /// from template XML.
    ///
    /// Most likely you do not need to call this function in applications as
    /// templates are handled by [`Widget`][crate::Widget].
    /// ## `object`
    /// the object 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")]
    pub fn extend_with_template(
        &self,
        object: &impl IsA<glib::Object>,
        template_type: glib::types::Type,
        buffer: &str,
    ) -> Result<(), glib::Error> {
        let length = buffer.len() as _;
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::gtk_builder_extend_with_template(
                self.to_glib_none().0,
                object.as_ref().to_glib_none().0,
                template_type.into_glib(),
                buffer.to_glib_none().0,
                length,
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Gets all objects that have been constructed by @self.
    ///
    /// Note that this function does not increment the reference
    /// counts of the returned objects.
    ///
    /// # Returns
    ///
    /// a
    ///   newly-allocated `GSList` containing all the objects
    ///   constructed by the `GtkBuilder instance`. It should be
    ///   freed by g_slist_free()
    #[doc(alias = "gtk_builder_get_objects")]
    #[doc(alias = "get_objects")]
    pub fn objects(&self) -> Vec<glib::Object> {
        unsafe {
            FromGlibPtrContainer::from_glib_container(ffi::gtk_builder_get_objects(
                self.to_glib_none().0,
            ))
        }
    }

    /// Gets the scope in use that was set via gtk_builder_set_scope().
    ///
    /// # Returns
    ///
    /// the current scope
    #[doc(alias = "gtk_builder_get_scope")]
    #[doc(alias = "get_scope")]
    pub fn scope(&self) -> BuilderScope {
        unsafe { from_glib_none(ffi::gtk_builder_get_scope(self.to_glib_none().0)) }
    }

    /// Gets the translation domain of @self.
    ///
    /// # Returns
    ///
    /// the translation domain
    #[doc(alias = "gtk_builder_get_translation_domain")]
    #[doc(alias = "get_translation_domain")]
    pub fn translation_domain(&self) -> Option<glib::GString> {
        unsafe {
            from_glib_none(ffi::gtk_builder_get_translation_domain(
                self.to_glib_none().0,
            ))
        }
    }

    /// Looks up a type by name.
    ///
    /// This is using the virtual function that [`Builder`][crate::Builder] has
    /// for that purpose. This is mainly used when implementing
    /// the [`Buildable`][crate::Buildable] interface on a type.
    /// ## `type_name`
    /// type name to lookup
    ///
    /// # Returns
    ///
    /// the `GType` found for @type_name or `G_TYPE_INVALID`
    ///   if no type was found
    #[doc(alias = "gtk_builder_get_type_from_name")]
    #[doc(alias = "get_type_from_name")]
    pub fn type_from_name(&self, type_name: &str) -> glib::types::Type {
        unsafe {
            from_glib(ffi::gtk_builder_get_type_from_name(
                self.to_glib_none().0,
                type_name.to_glib_none().0,
            ))
        }
    }

    /// Sets the current object for the @self.
    ///
    /// The current object can be thought of as the `this` object that the
    /// builder is working for and will often be used as the default object
    /// when an object is optional.
    ///
    /// `Gtk::Widget::init_template()` for example will set the current
    /// object to the widget the template is inited for. For functions like
    /// [`from_resource()`][Self::from_resource()], the current object will be [`None`].
    /// ## `current_object`
    /// the new current object
    #[doc(alias = "gtk_builder_set_current_object")]
    pub fn set_current_object(&self, current_object: Option<&impl IsA<glib::Object>>) {
        unsafe {
            ffi::gtk_builder_set_current_object(
                self.to_glib_none().0,
                current_object.map(|p| p.as_ref()).to_glib_none().0,
            );
        }
    }

    /// Sets the scope the builder should operate in.
    ///
    /// If @scope is [`None`], a new `Gtk::BuilderCScope` will be created.
    /// ## `scope`
    /// the scope to use
    #[doc(alias = "gtk_builder_set_scope")]
    pub fn set_scope(&self, scope: Option<&impl IsA<BuilderScope>>) {
        unsafe {
            ffi::gtk_builder_set_scope(
                self.to_glib_none().0,
                scope.map(|p| p.as_ref()).to_glib_none().0,
            );
        }
    }

    /// Sets the translation domain of @self.
    /// ## `domain`
    /// the translation domain
    #[doc(alias = "gtk_builder_set_translation_domain")]
    pub fn set_translation_domain(&self, domain: Option<&str>) {
        unsafe {
            ffi::gtk_builder_set_translation_domain(self.to_glib_none().0, domain.to_glib_none().0);
        }
    }

    /// Demarshals a value from a string.
    ///
    /// This function calls g_value_init() on the @value argument,
    /// so it need not be initialised beforehand.
    ///
    /// Can handle char, uchar, boolean, int, uint, long,
    /// ulong, enum, flags, float, double, string, [`gdk::RGBA`][crate::gdk::RGBA] and
    /// [`Adjustment`][crate::Adjustment] type values.
    ///
    /// Upon errors [`false`] will be returned and @error will be
    /// assigned a `GError` from the `GTK_BUILDER_ERROR` domain.
    /// ## `pspec`
    /// the `GParamSpec` for the property
    /// ## `string`
    /// the string representation of the value
    ///
    /// # Returns
    ///
    /// [`true`] on success
    ///
    /// ## `value`
    /// the `GValue` to store the result in
    #[doc(alias = "gtk_builder_value_from_string")]
    pub fn value_from_string(
        &self,
        pspec: impl AsRef<glib::ParamSpec>,
        string: &str,
    ) -> Result<glib::Value, glib::Error> {
        unsafe {
            let mut value = glib::Value::uninitialized();
            let mut error = ptr::null_mut();
            let is_ok = ffi::gtk_builder_value_from_string(
                self.to_glib_none().0,
                pspec.as_ref().to_glib_none().0,
                string.to_glib_none().0,
                value.to_glib_none_mut().0,
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(value)
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Demarshals a value from a string.
    ///
    /// Unlike [`value_from_string()`][Self::value_from_string()], this function
    /// takes a `GType` instead of `GParamSpec`.
    ///
    /// Calls g_value_init() on the @value argument, so it
    /// need not be initialised beforehand.
    ///
    /// Upon errors [`false`] will be returned and @error will be
    /// assigned a `GError` from the `GTK_BUILDER_ERROR` domain.
    /// ## `type_`
    /// the `GType` of the value
    /// ## `string`
    /// the string representation of the value
    ///
    /// # Returns
    ///
    /// [`true`] on success
    ///
    /// ## `value`
    /// the `GValue` to store the result in
    #[doc(alias = "gtk_builder_value_from_string_type")]
    pub fn value_from_string_type(
        &self,
        type_: glib::types::Type,
        string: &str,
    ) -> Result<glib::Value, glib::Error> {
        unsafe {
            let mut value = glib::Value::uninitialized();
            let mut error = ptr::null_mut();
            let is_ok = ffi::gtk_builder_value_from_string_type(
                self.to_glib_none().0,
                type_.into_glib(),
                string.to_glib_none().0,
                value.to_glib_none_mut().0,
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(value)
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    #[doc(alias = "current-object")]
    pub fn connect_current_object_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn notify_current_object_trampoline<F: Fn(&Builder) + 'static>(
            this: *mut ffi::GtkBuilder,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(&from_glib_borrow(this))
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::current-object\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_current_object_trampoline::<F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    #[doc(alias = "scope")]
    pub fn connect_scope_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn notify_scope_trampoline<F: Fn(&Builder) + 'static>(
            this: *mut ffi::GtkBuilder,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(&from_glib_borrow(this))
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::scope\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_scope_trampoline::<F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    #[doc(alias = "translation-domain")]
    pub fn connect_translation_domain_notify<F: Fn(&Self) + 'static>(
        &self,
        f: F,
    ) -> SignalHandlerId {
        unsafe extern "C" fn notify_translation_domain_trampoline<F: Fn(&Builder) + 'static>(
            this: *mut ffi::GtkBuilder,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(&from_glib_borrow(this))
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::translation-domain\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_translation_domain_trampoline::<F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }
}

impl Default for Builder {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Display for Builder {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("Builder")
    }
}