gtk4/auto/builder.rs
1// This file was generated by gir (https://github.com/gtk-rs/gir)
2// from gir-files (https://github.com/gtk-rs/gir-files)
3// DO NOT EDIT
4
5use crate::{ffi, BuilderClosureFlags, BuilderScope};
6use glib::{
7 prelude::*,
8 signal::{connect_raw, SignalHandlerId},
9 translate::*,
10};
11use std::boxed::Box as Box_;
12
13glib::wrapper! {
14 /// Reads XML descriptions of a user interface and instantiates the described objects.
15 ///
16 /// To create a [`Builder`][crate::Builder] from a user interface description, call
17 /// [`from_file()`][Self::from_file()], [`from_resource()`][Self::from_resource()]
18 /// or [`from_string()`][Self::from_string()].
19 ///
20 /// In the (unusual) case that you want to add user interface
21 /// descriptions from multiple sources to the same [`Builder`][crate::Builder] you can
22 /// call [`new()`][Self::new()] to get an empty builder and populate it by
23 /// (multiple) calls to [`add_from_file()`][Self::add_from_file()],
24 /// [`add_from_resource()`][Self::add_from_resource()] or
25 /// [`add_from_string()`][Self::add_from_string()].
26 ///
27 /// A [`Builder`][crate::Builder] holds a reference to all objects that it has constructed
28 /// and drops these references when it is finalized. This finalization can
29 /// cause the destruction of non-widget objects or widgets which are not
30 /// contained in a toplevel window. For toplevel windows constructed by a
31 /// builder, it is the responsibility of the user to call
32 /// `Gtk::Window::destroy()` to get rid of them and all the widgets
33 /// they contain.
34 ///
35 /// The functions [`object()`][Self::object()] and
36 /// [`objects()`][Self::objects()] can be used to access the widgets in
37 /// the interface by the names assigned to them inside the UI description.
38 /// Toplevel windows returned by these functions will stay around until the
39 /// user explicitly destroys them with `Gtk::Window::destroy()`. Other
40 /// widgets will either be part of a larger hierarchy constructed by the
41 /// builder (in which case you should not have to worry about their lifecycle),
42 /// or without a parent, in which case they have to be added to some container
43 /// to make use of them. Non-widget objects need to be reffed with
44 /// g_object_ref() to keep them beyond the lifespan of the builder.
45 ///
46 /// ## GtkBuilder UI Definitions
47 ///
48 /// [`Builder`][crate::Builder] parses textual descriptions of user interfaces which are
49 /// specified in XML format. We refer to these descriptions as “GtkBuilder
50 /// UI definitions” or just “UI definitions” if the context is clear.
51 ///
52 /// ### Structure of UI definitions
53 ///
54 /// UI definition files are always encoded in UTF-8.
55 ///
56 /// The toplevel element is `<interface>`. It optionally takes a “domain”
57 /// attribute, which will make the builder look for translated strings
58 /// using `dgettext()` in the domain specified. This can also be done by
59 /// calling [`set_translation_domain()`][Self::set_translation_domain()] on the builder.
60 /// For example:
61 ///
62 /// ```xml
63 /// <?xml version="1.0" encoding="UTF-8">
64 /// <interface domain="your-app">
65 /// ...
66 /// </interface>
67 /// ```
68 ///
69 /// ### Requirements
70 ///
71 /// The target toolkit version(s) are described by `<requires>` elements,
72 /// the “lib” attribute specifies the widget library in question (currently
73 /// the only supported value is “gtk”) and the “version” attribute specifies
74 /// the target version in the form “`<major>`.`<minor>`”. [`Builder`][crate::Builder] will
75 /// error out if the version requirements are not met. For example:
76 ///
77 /// ```xml
78 /// <?xml version="1.0" encoding="UTF-8">
79 /// <interface domain="your-app">
80 /// <requires lib="gtk" version="4.0" />
81 /// </interface>
82 /// ```
83 ///
84 /// ### Objects
85 ///
86 /// Objects are defined as children of the `<interface>` element.
87 ///
88 /// Objects are described by `<object>` elements, which can contain
89 /// `<property>` elements to set properties, `<signal>` elements which
90 /// connect signals to handlers, and `<child>` elements, which describe
91 /// child objects.
92 ///
93 /// Typically, the specific kind of object represented by an `<object>`
94 /// element is specified by the “class” attribute. If the type has not
95 /// been loaded yet, GTK tries to find the `get_type()` function from the
96 /// class name by applying heuristics. This works in most cases, but if
97 /// necessary, it is possible to specify the name of the `get_type()`
98 /// function explicitly with the "type-func" attribute. If your UI definition
99 /// is referencing internal types, you should make sure to call
100 /// `g_type_ensure()` for each object type before parsing the UI definition.
101 ///
102 /// Objects may be given a name with the “id” attribute, which allows the
103 /// application to retrieve them from the builder with
104 /// [`object()`][Self::object()]. An id is also necessary to use the
105 /// object as property value in other parts of the UI definition. GTK
106 /// reserves ids starting and ending with `___` (three consecutive
107 /// underscores) for its own purposes.
108 ///
109 /// ### Properties
110 ///
111 /// Setting properties of objects is pretty straightforward with the
112 /// `<property>` element: the “name” attribute specifies the name of the
113 /// property, and the content of the element specifies the value:
114 ///
115 /// ```xml
116 /// <object class="GtkButton">
117 /// <property name="label">Hello, world</property>
118 /// </object>
119 /// ```
120 ///
121 /// If the “translatable” attribute is set to a true value, GTK uses
122 /// `gettext()` (or `dgettext()` if the builder has a translation domain set)
123 /// to find a translation for the value. This happens before the value
124 /// is parsed, so it can be used for properties of any type, but it is
125 /// probably most useful for string properties. It is also possible to
126 /// specify a context to disambiguate short strings, and comments which
127 /// may help the translators:
128 ///
129 /// ```xml
130 /// <object class="GtkButton">
131 /// <property name="label" translatable="yes" context="button">Hello, world</property>
132 /// </object>
133 /// ```
134 ///
135 /// [`Builder`][crate::Builder] can parse textual representations for the most common
136 /// property types:
137 ///
138 /// - characters
139 /// - strings
140 /// - integers
141 /// - floating-point numbers
142 /// - booleans (strings like “TRUE”, “t”, “yes”, “y”, “1” are interpreted
143 /// as true values, strings like “FALSE”, “f”, “no”, “n”, “0” are interpreted
144 /// as false values)
145 /// - string lists (separated by newlines)
146 /// - enumeration types (can be specified by their full C identifier their short
147 /// name used when registering the enumeration type, or their integer value)
148 /// - flag types (can be specified by their C identifier or short name,
149 /// optionally combined with “|” for bitwise OR, or a single integer value
150 /// e.g., “GTK_INPUT_HINT_EMOJI|GTK_INPUT_HINT_LOWERCASE”, or “emoji|lowercase” or 520).
151 /// - colors (in the format understood by [`gdk::RGBA::parse()`][crate::gdk::RGBA::parse()])
152 /// - transforms (in the format understood by [`gsk::Transform::parse()`][crate::gsk::Transform::parse()])
153 /// - Pango attribute lists (in the format understood by [`pango::AttrList::to_str()`][crate::pango::AttrList::to_str()])
154 /// - Pango tab arrays (in the format understood by [`pango::TabArray::to_str()`][crate::pango::TabArray::to_str()])
155 /// - Pango font descriptions (in the format understood by [`pango::FontDescription::from_string()`][crate::pango::FontDescription::from_string()])
156 /// - `GVariant` (in the format understood by `GLib::Variant::parse()`)
157 /// - textures (can be specified as an object id, a resource path or a filename of an image file to load relative to the Builder file or the CWD if [`add_from_string()`][Self::add_from_string()] was used)
158 /// - GFile (like textures, can be specified as an object id, a URI or a filename of a file to load relative to the Builder file or the CWD if [`add_from_string()`][Self::add_from_string()] was used)
159 ///
160 /// Objects can be referred to by their name and by default refer to
161 /// objects declared in the local XML fragment and objects exposed via
162 /// [`expose_object()`][Self::expose_object()]. In general, [`Builder`][crate::Builder] allows
163 /// forward references to objects declared in the local XML; an object
164 /// doesn’t have to be constructed before it can be referred to. The
165 /// exception to this rule is that an object has to be constructed before
166 /// it can be used as the value of a construct-only property.
167 ///
168 /// ### Child objects
169 ///
170 /// Many widgets have properties for child widgets, such as
171 /// [`child`][struct@crate::Expander#child]. In this case, the preferred way to
172 /// specify the child widget in a ui file is to simply set the property:
173 ///
174 /// ```xml
175 /// <object class="GtkExpander">
176 /// <property name="child">
177 /// <object class="GtkLabel">
178 /// ...
179 /// </object>
180 /// </property>
181 /// </object>
182 /// ```
183 ///
184 /// Generic containers that can contain an arbitrary number of children,
185 /// such as [`Box`][crate::Box] instead use the `<child>` element. A `<child>`
186 /// element contains an `<object>` element which describes the child object.
187 /// Most often, child objects are widgets inside a container, but they can
188 /// also be, e.g., actions in an action group, or columns in a tree model.
189 ///
190 /// Any object type that implements the [`Buildable`][crate::Buildable] interface can
191 /// specify how children may be added to it. Since many objects and widgets that
192 /// are included with GTK already implement the [`Buildable`][crate::Buildable] interface,
193 /// typically child objects can be added using the `<child>` element without
194 /// having to be concerned about the underlying implementation.
195 ///
196 /// See the [[`Widget`][crate::Widget] documentation](class.Widget.html#gtkwidget-as-gtkbuildable)
197 /// for many examples of using [`Builder`][crate::Builder] with widgets, including setting
198 /// child objects using the `<child>` element.
199 ///
200 /// A noteworthy special case to the general rule that only objects implementing
201 /// [`Buildable`][crate::Buildable] may specify how to handle the `<child>` element is that
202 /// [`Builder`][crate::Builder] provides special support for adding objects to a
203 /// `Gio::ListStore` by using the `<child>` element. For instance:
204 ///
205 /// ```xml
206 /// <object class="GListStore">
207 /// <property name="item-type">MyObject</property>
208 /// <child>
209 /// <object class="MyObject" />
210 /// </child>
211 /// ...
212 /// </object>
213 /// ```
214 ///
215 /// ### Property bindings
216 ///
217 /// It is also possible to bind a property value to another object's
218 /// property value using the attributes "bind-source" to specify the
219 /// source object of the binding, and optionally, "bind-property" and
220 /// "bind-flags" to specify the source property and source binding flags
221 /// respectively. Internally, [`Builder`][crate::Builder] implements this using
222 /// `GObject::Binding` objects.
223 ///
224 /// For instance, in the example below the “label” property of the
225 /// `bottom_label` widget is bound to the “label” property of the
226 /// `top_button` widget:
227 ///
228 /// ```xml
229 /// <object class="GtkBox">
230 /// <property name="orientation">vertical</property>
231 /// <child>
232 /// <object class="GtkButton" id="top_button">
233 /// <property name="label">Hello, world</property>
234 /// </object>
235 /// </child>
236 /// <child>
237 /// <object class="GtkLabel" id="bottom_label">
238 /// <property name="label"
239 /// bind-source="top_button"
240 /// bind-property="label"
241 /// bind-flags="sync-create" />
242 /// </object>
243 /// </child>
244 /// </object>
245 /// ```
246 ///
247 /// For more information, see the documentation of the
248 /// [`ObjectExt::bind_property()`][crate::glib::prelude::ObjectExt::bind_property()] method.
249 ///
250 /// Please note that another way to set up bindings between objects in .ui files
251 /// is to use the [`Expression`][crate::Expression] methodology. See the
252 /// [[`Expression`][crate::Expression] documentation](class.Expression.html#gtkexpression-in-ui-files)
253 /// for more information.
254 ///
255 /// ### Internal children
256 ///
257 /// Sometimes it is necessary to refer to widgets which have implicitly
258 /// been constructed by GTK as part of a composite widget, to set
259 /// properties on them or to add further children (e.g. the content area
260 /// of a [`Dialog`][crate::Dialog]). This can be achieved by setting the “internal-child”
261 /// property of the `<child>` element to a true value. Note that [`Builder`][crate::Builder]
262 /// still requires an `<object>` element for the internal child, even if it
263 /// has already been constructed.
264 ///
265 /// ### Specialized children
266 ///
267 /// A number of widgets have different places where a child can be added
268 /// (e.g. tabs vs. page content in notebooks). This can be reflected in
269 /// a UI definition by specifying the “type” attribute on a `<child>`
270 /// The possible values for the “type” attribute are described in the
271 /// sections describing the widget-specific portions of UI definitions.
272 ///
273 /// ### Signal handlers and function pointers
274 ///
275 /// Signal handlers are set up with the `<signal>` element. The “name”
276 /// attribute specifies the name of the signal, and the “handler” attribute
277 /// specifies the function to connect to the signal.
278 ///
279 /// ```xml
280 /// <object class="GtkButton" id="hello_button">
281 /// <signal name="clicked" handler="hello_button__clicked" />
282 /// </object>
283 /// ```
284 ///
285 /// The remaining attributes, “after”, “swapped” and “object”, have the
286 /// same meaning as the corresponding parameters of the
287 /// `signal_connect_object()` or `signal_connect_data()`
288 /// functions:
289 ///
290 /// - “after” matches the `G_CONNECT_AFTER` flag, and will ensure that the
291 /// handler is called after the default class closure for the signal
292 /// - “swapped” matches the `G_CONNECT_SWAPPED` flag, and will swap the
293 /// instance and closure arguments when invoking the signal handler
294 /// - “object” will bind the signal handler to the lifetime of the object
295 /// referenced by the attribute
296 ///
297 /// By default "swapped" will be set to "yes" if not specified otherwise, in
298 /// the case where "object" is set, for convenience. A “last_modification_time”
299 /// attribute is also allowed, but it does not have a meaning to the builder.
300 ///
301 /// When compiling applications for Windows, you must declare signal callbacks
302 /// with the `G_MODULE_EXPORT` decorator, or they will not be put in the symbol
303 /// table:
304 ///
305 /// **⚠️ The following code is in c ⚠️**
306 ///
307 /// ```c
308 /// G_MODULE_EXPORT void
309 /// hello_button__clicked (GtkButton *button,
310 /// gpointer data)
311 /// {
312 /// // ...
313 /// }
314 /// ```
315 ///
316 /// On Linux and Unix, this is not necessary; applications should instead
317 /// be compiled with the `-Wl,--export-dynamic` argument inside their compiler
318 /// flags, and linked against `gmodule-export-2.0`.
319 ///
320 /// ## Example UI Definition
321 ///
322 /// ```xml
323 /// <interface>
324 /// <object class="GtkDialog" id="dialog1">
325 /// <child internal-child="content_area">
326 /// <object class="GtkBox">
327 /// <child internal-child="action_area">
328 /// <object class="GtkBox">
329 /// <child>
330 /// <object class="GtkButton" id="ok_button">
331 /// <property name="label" translatable="yes">_Ok</property>
332 /// <property name="use-underline">True</property>
333 /// <signal name="clicked" handler="ok_button_clicked"/>
334 /// </object>
335 /// </child>
336 /// </object>
337 /// </child>
338 /// </object>
339 /// </child>
340 /// </object>
341 /// </interface>
342 /// ```
343 ///
344 /// ## Using GtkBuildable for extending UI definitions
345 ///
346 /// Objects can implement the [`Buildable`][crate::Buildable] interface to add custom
347 /// elements and attributes to the XML. Typically, any extension will be
348 /// documented in each type that implements the interface.
349 ///
350 /// ## Menus
351 ///
352 /// In addition to objects with properties that are created with `<object>` and
353 /// `<property>` elements, [`Builder`][crate::Builder] also allows to parse XML menu definitions
354 /// as used by [`gio::Menu`][crate::gio::Menu] when exporting menu models over D-Bus, and as
355 /// described in the [`PopoverMenu`][crate::PopoverMenu] documentation. Menus can be defined
356 /// as toplevel elements, or as property values for properties of type `GMenuModel`.
357 ///
358 /// ## Templates
359 ///
360 /// When describing a [`Widget`][crate::Widget], you can use the `<template>` tag to
361 /// describe a UI bound to a specific widget type. GTK will automatically load
362 /// the UI definition when instantiating the type, and bind children and
363 /// signal handlers to instance fields and function symbols.
364 ///
365 /// For more information, see the [[`Widget`][crate::Widget] documentation](class.Widget.html#building-composite-widgets-from-template-xml)
366 /// for details.
367 ///
368 /// ## Properties
369 ///
370 ///
371 /// #### `current-object`
372 /// The object the builder is evaluating for.
373 ///
374 /// Readable | Writeable
375 ///
376 ///
377 /// #### `scope`
378 /// The scope the builder is operating in
379 ///
380 /// Readable | Writeable | Construct
381 ///
382 ///
383 /// #### `translation-domain`
384 /// The translation domain used when translating property values that
385 /// have been marked as translatable.
386 ///
387 /// If the translation domain is [`None`], [`Builder`][crate::Builder] uses gettext(),
388 /// otherwise g_dgettext().
389 ///
390 /// Readable | Writeable
391 ///
392 /// # Implements
393 ///
394 /// [`trait@glib::ObjectExt`]
395 #[doc(alias = "GtkBuilder")]
396 pub struct Builder(Object<ffi::GtkBuilder, ffi::GtkBuilderClass>);
397
398 match fn {
399 type_ => || ffi::gtk_builder_get_type(),
400 }
401}
402
403impl Builder {
404 /// Creates a new empty builder object.
405 ///
406 /// This function is only useful if you intend to make multiple calls
407 /// to [`add_from_file()`][Self::add_from_file()], [`add_from_resource()`][Self::add_from_resource()]
408 /// or [`add_from_string()`][Self::add_from_string()] in order to merge multiple UI
409 /// descriptions into a single builder.
410 ///
411 /// # Returns
412 ///
413 /// a new (empty) [`Builder`][crate::Builder] object
414 #[doc(alias = "gtk_builder_new")]
415 pub fn new() -> Builder {
416 assert_initialized_main_thread!();
417 unsafe { from_glib_full(ffi::gtk_builder_new()) }
418 }
419
420 /// Parses the UI definition at @resource_path.
421 ///
422 /// If there is an error locating the resource or parsing the
423 /// description, then the program will be aborted.
424 /// ## `resource_path`
425 /// a `GResource` resource path
426 ///
427 /// # Returns
428 ///
429 /// a [`Builder`][crate::Builder] containing the described interface
430 #[doc(alias = "gtk_builder_new_from_resource")]
431 #[doc(alias = "new_from_resource")]
432 pub fn from_resource(resource_path: &str) -> Builder {
433 assert_initialized_main_thread!();
434 unsafe {
435 from_glib_full(ffi::gtk_builder_new_from_resource(
436 resource_path.to_glib_none().0,
437 ))
438 }
439 }
440
441 /// Parses the UI definition in @string.
442 ///
443 /// If @string is [`None`]-terminated, then @length should be -1.
444 /// If @length is not -1, then it is the length of @string.
445 ///
446 /// If there is an error parsing @string then the program will be
447 /// aborted. You should not attempt to parse user interface description
448 /// from untrusted sources.
449 /// ## `string`
450 /// a user interface (XML) description
451 /// ## `length`
452 /// the length of @string, or -1
453 ///
454 /// # Returns
455 ///
456 /// a [`Builder`][crate::Builder] containing the interface described by @string
457 #[doc(alias = "gtk_builder_new_from_string")]
458 #[doc(alias = "new_from_string")]
459 pub fn from_string(string: &str) -> Builder {
460 assert_initialized_main_thread!();
461 let length = string.len() as _;
462 unsafe {
463 from_glib_full(ffi::gtk_builder_new_from_string(
464 string.to_glib_none().0,
465 length,
466 ))
467 }
468 }
469
470 /// Parses a resource file containing a UI definition
471 /// and merges it with the current contents of @self.
472 ///
473 /// This function is useful if you need to call
474 /// [`set_current_object()`][Self::set_current_object()] to add user data to
475 /// callbacks before loading GtkBuilder UI. Otherwise, you probably
476 /// want [`from_resource()`][Self::from_resource()] instead.
477 ///
478 /// If an error occurs, 0 will be returned and @error will be assigned a
479 /// `GError` from the `GTK_BUILDER_ERROR`, `G_MARKUP_ERROR` or `G_RESOURCE_ERROR`
480 /// domain.
481 ///
482 /// It’s not really reasonable to attempt to handle failures of this
483 /// call. The only reasonable thing to do when an error is detected is
484 /// to call g_error().
485 /// ## `resource_path`
486 /// the path of the resource file to parse
487 ///
488 /// # Returns
489 ///
490 /// [`true`] on success, [`false`] if an error occurred
491 #[doc(alias = "gtk_builder_add_from_resource")]
492 pub fn add_from_resource(&self, resource_path: &str) -> Result<(), glib::Error> {
493 unsafe {
494 let mut error = std::ptr::null_mut();
495 let is_ok = ffi::gtk_builder_add_from_resource(
496 self.to_glib_none().0,
497 resource_path.to_glib_none().0,
498 &mut error,
499 );
500 debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
501 if error.is_null() {
502 Ok(())
503 } else {
504 Err(from_glib_full(error))
505 }
506 }
507 }
508
509 /// Parses a string containing a UI definition and merges it
510 /// with the current contents of @self.
511 ///
512 /// This function is useful if you need to call
513 /// [`set_current_object()`][Self::set_current_object()] to add user data to
514 /// callbacks before loading [`Builder`][crate::Builder] UI. Otherwise, you probably
515 /// want [`from_string()`][Self::from_string()] instead.
516 ///
517 /// Upon errors [`false`] will be returned and @error will be assigned a
518 /// `GError` from the `GTK_BUILDER_ERROR`, `G_MARKUP_ERROR` or
519 /// `G_VARIANT_PARSE_ERROR` domain.
520 ///
521 /// It’s not really reasonable to attempt to handle failures of this
522 /// call. The only reasonable thing to do when an error is detected is
523 /// to call g_error().
524 /// ## `buffer`
525 /// the string to parse
526 /// ## `length`
527 /// the length of @buffer (may be -1 if @buffer is nul-terminated)
528 ///
529 /// # Returns
530 ///
531 /// [`true`] on success, [`false`] if an error occurred
532 #[doc(alias = "gtk_builder_add_from_string")]
533 pub fn add_from_string(&self, buffer: &str) -> Result<(), glib::Error> {
534 let length = buffer.len() as _;
535 unsafe {
536 let mut error = std::ptr::null_mut();
537 let is_ok = ffi::gtk_builder_add_from_string(
538 self.to_glib_none().0,
539 buffer.to_glib_none().0,
540 length,
541 &mut error,
542 );
543 debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
544 if error.is_null() {
545 Ok(())
546 } else {
547 Err(from_glib_full(error))
548 }
549 }
550 }
551
552 /// Parses a file containing a UI definition building only the
553 /// requested objects and merges them with the current contents
554 /// of @self.
555 ///
556 /// Upon errors, 0 will be returned and @error will be assigned a
557 /// `GError` from the `GTK_BUILDER_ERROR`, `G_MARKUP_ERROR` or `G_FILE_ERROR`
558 /// domain.
559 ///
560 /// If you are adding an object that depends on an object that is not
561 /// its child (for instance a [`TreeView`][crate::TreeView] that depends on its
562 /// [`TreeModel`][crate::TreeModel]), you have to explicitly list all of them in @object_ids.
563 /// ## `filename`
564 /// the name of the file to parse
565 /// ## `object_ids`
566 /// nul-terminated array of objects to build
567 ///
568 /// # Returns
569 ///
570 /// [`true`] on success, [`false`] if an error occurred
571 #[doc(alias = "gtk_builder_add_objects_from_file")]
572 pub fn add_objects_from_file(
573 &self,
574 filename: impl AsRef<std::path::Path>,
575 object_ids: &[&str],
576 ) -> Result<(), glib::Error> {
577 unsafe {
578 let mut error = std::ptr::null_mut();
579 let is_ok = ffi::gtk_builder_add_objects_from_file(
580 self.to_glib_none().0,
581 filename.as_ref().to_glib_none().0,
582 object_ids.to_glib_none().0,
583 &mut error,
584 );
585 debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
586 if error.is_null() {
587 Ok(())
588 } else {
589 Err(from_glib_full(error))
590 }
591 }
592 }
593
594 /// Parses a resource file containing a UI definition, building
595 /// only the requested objects and merges them with the current
596 /// contents of @self.
597 ///
598 /// Upon errors, 0 will be returned and @error will be assigned a
599 /// `GError` from the `GTK_BUILDER_ERROR`, `G_MARKUP_ERROR` or `G_RESOURCE_ERROR`
600 /// domain.
601 ///
602 /// If you are adding an object that depends on an object that is not
603 /// its child (for instance a [`TreeView`][crate::TreeView] that depends on its
604 /// [`TreeModel`][crate::TreeModel]), you have to explicitly list all of them in @object_ids.
605 /// ## `resource_path`
606 /// the path of the resource file to parse
607 /// ## `object_ids`
608 /// nul-terminated array of objects to build
609 ///
610 /// # Returns
611 ///
612 /// [`true`] on success, [`false`] if an error occurred
613 #[doc(alias = "gtk_builder_add_objects_from_resource")]
614 pub fn add_objects_from_resource(
615 &self,
616 resource_path: &str,
617 object_ids: &[&str],
618 ) -> Result<(), glib::Error> {
619 unsafe {
620 let mut error = std::ptr::null_mut();
621 let is_ok = ffi::gtk_builder_add_objects_from_resource(
622 self.to_glib_none().0,
623 resource_path.to_glib_none().0,
624 object_ids.to_glib_none().0,
625 &mut error,
626 );
627 debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
628 if error.is_null() {
629 Ok(())
630 } else {
631 Err(from_glib_full(error))
632 }
633 }
634 }
635
636 /// Parses a string containing a UI definition, building only the
637 /// requested objects and merges them with the current contents of
638 /// @self.
639 ///
640 /// Upon errors [`false`] will be returned and @error will be assigned a
641 /// `GError` from the `GTK_BUILDER_ERROR` or `G_MARKUP_ERROR` domain.
642 ///
643 /// If you are adding an object that depends on an object that is not
644 /// its child (for instance a [`TreeView`][crate::TreeView] that depends on its
645 /// [`TreeModel`][crate::TreeModel]), you have to explicitly list all of them in @object_ids.
646 /// ## `buffer`
647 /// the string to parse
648 /// ## `length`
649 /// the length of @buffer (may be -1 if @buffer is nul-terminated)
650 /// ## `object_ids`
651 /// nul-terminated array of objects to build
652 ///
653 /// # Returns
654 ///
655 /// [`true`] on success, [`false`] if an error occurred
656 #[doc(alias = "gtk_builder_add_objects_from_string")]
657 pub fn add_objects_from_string(
658 &self,
659 buffer: &str,
660 object_ids: &[&str],
661 ) -> Result<(), glib::Error> {
662 let length = buffer.len() as _;
663 unsafe {
664 let mut error = std::ptr::null_mut();
665 let is_ok = ffi::gtk_builder_add_objects_from_string(
666 self.to_glib_none().0,
667 buffer.to_glib_none().0,
668 length,
669 object_ids.to_glib_none().0,
670 &mut error,
671 );
672 debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
673 if error.is_null() {
674 Ok(())
675 } else {
676 Err(from_glib_full(error))
677 }
678 }
679 }
680
681 /// Creates a closure to invoke the function called @function_name.
682 ///
683 /// This is using the create_closure() implementation of @self's
684 /// [`BuilderScope`][crate::BuilderScope].
685 ///
686 /// If no closure could be created, [`None`] will be returned and @error
687 /// will be set.
688 /// ## `function_name`
689 /// name of the function to look up
690 /// ## `flags`
691 /// closure creation flags
692 /// ## `object`
693 /// Object to create the closure with
694 ///
695 /// # Returns
696 ///
697 /// A new closure for invoking @function_name
698 #[doc(alias = "gtk_builder_create_closure")]
699 pub fn create_closure(
700 &self,
701 function_name: &str,
702 flags: BuilderClosureFlags,
703 object: Option<&impl IsA<glib::Object>>,
704 ) -> Result<Option<glib::Closure>, glib::Error> {
705 unsafe {
706 let mut error = std::ptr::null_mut();
707 let ret = ffi::gtk_builder_create_closure(
708 self.to_glib_none().0,
709 function_name.to_glib_none().0,
710 flags.into_glib(),
711 object.map(|p| p.as_ref()).to_glib_none().0,
712 &mut error,
713 );
714 if error.is_null() {
715 Ok(from_glib_full(ret))
716 } else {
717 Err(from_glib_full(error))
718 }
719 }
720 }
721
722 /// Add @object to the @self object pool so it can be
723 /// referenced just like any other object built by builder.
724 ///
725 /// Only a single object may be added using @name. However,
726 /// it is not an error to expose the same object under multiple
727 /// names. `gtk_builder_get_object()` may be used to determine
728 /// if an object has already been added with @name.
729 /// ## `name`
730 /// the name of the object exposed to the builder
731 /// ## `object`
732 /// the object to expose
733 #[doc(alias = "gtk_builder_expose_object")]
734 pub fn expose_object(&self, name: &str, object: &impl IsA<glib::Object>) {
735 unsafe {
736 ffi::gtk_builder_expose_object(
737 self.to_glib_none().0,
738 name.to_glib_none().0,
739 object.as_ref().to_glib_none().0,
740 );
741 }
742 }
743
744 /// Main private entry point for building composite components
745 /// from template XML.
746 ///
747 /// Most likely you do not need to call this function in applications as
748 /// templates are handled by [`Widget`][crate::Widget].
749 /// ## `object`
750 /// the object that is being extended
751 /// ## `template_type`
752 /// the type that the template is for
753 /// ## `buffer`
754 /// the string to parse
755 /// ## `length`
756 /// the length of @buffer (may be -1 if @buffer is nul-terminated)
757 ///
758 /// # Returns
759 ///
760 /// A positive value on success, 0 if an error occurred
761 #[doc(alias = "gtk_builder_extend_with_template")]
762 pub fn extend_with_template(
763 &self,
764 object: &impl IsA<glib::Object>,
765 template_type: glib::types::Type,
766 buffer: &str,
767 ) -> Result<(), glib::Error> {
768 let length = buffer.len() as _;
769 unsafe {
770 let mut error = std::ptr::null_mut();
771 let is_ok = ffi::gtk_builder_extend_with_template(
772 self.to_glib_none().0,
773 object.as_ref().to_glib_none().0,
774 template_type.into_glib(),
775 buffer.to_glib_none().0,
776 length,
777 &mut error,
778 );
779 debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
780 if error.is_null() {
781 Ok(())
782 } else {
783 Err(from_glib_full(error))
784 }
785 }
786 }
787
788 /// Gets all objects that have been constructed by @self.
789 ///
790 /// Note that this function does not increment the reference
791 /// counts of the returned objects.
792 ///
793 /// # Returns
794 ///
795 /// a
796 /// newly-allocated `GSList` containing all the objects
797 /// constructed by the `GtkBuilder instance`. It should be
798 /// freed by g_slist_free()
799 #[doc(alias = "gtk_builder_get_objects")]
800 #[doc(alias = "get_objects")]
801 pub fn objects(&self) -> Vec<glib::Object> {
802 unsafe {
803 FromGlibPtrContainer::from_glib_container(ffi::gtk_builder_get_objects(
804 self.to_glib_none().0,
805 ))
806 }
807 }
808
809 /// Gets the scope in use that was set via gtk_builder_set_scope().
810 ///
811 /// # Returns
812 ///
813 /// the current scope
814 #[doc(alias = "gtk_builder_get_scope")]
815 #[doc(alias = "get_scope")]
816 pub fn scope(&self) -> BuilderScope {
817 unsafe { from_glib_none(ffi::gtk_builder_get_scope(self.to_glib_none().0)) }
818 }
819
820 /// Gets the translation domain of @self.
821 ///
822 /// # Returns
823 ///
824 /// the translation domain
825 #[doc(alias = "gtk_builder_get_translation_domain")]
826 #[doc(alias = "get_translation_domain")]
827 #[doc(alias = "translation-domain")]
828 pub fn translation_domain(&self) -> Option<glib::GString> {
829 unsafe {
830 from_glib_none(ffi::gtk_builder_get_translation_domain(
831 self.to_glib_none().0,
832 ))
833 }
834 }
835
836 /// Looks up a type by name.
837 ///
838 /// This is using the virtual function that [`Builder`][crate::Builder] has
839 /// for that purpose. This is mainly used when implementing
840 /// the [`Buildable`][crate::Buildable] interface on a type.
841 /// ## `type_name`
842 /// type name to lookup
843 ///
844 /// # Returns
845 ///
846 /// the `GType` found for @type_name or `G_TYPE_INVALID`
847 /// if no type was found
848 #[doc(alias = "gtk_builder_get_type_from_name")]
849 #[doc(alias = "get_type_from_name")]
850 pub fn type_from_name(&self, type_name: &str) -> glib::types::Type {
851 unsafe {
852 from_glib(ffi::gtk_builder_get_type_from_name(
853 self.to_glib_none().0,
854 type_name.to_glib_none().0,
855 ))
856 }
857 }
858
859 /// Sets the current object for the @self.
860 ///
861 /// The current object can be thought of as the `this` object that the
862 /// builder is working for and will often be used as the default object
863 /// when an object is optional.
864 ///
865 /// `Gtk::Widget::init_template()` for example will set the current
866 /// object to the widget the template is inited for. For functions like
867 /// [`from_resource()`][Self::from_resource()], the current object will be [`None`].
868 /// ## `current_object`
869 /// the new current object
870 #[doc(alias = "gtk_builder_set_current_object")]
871 #[doc(alias = "current-object")]
872 pub fn set_current_object(&self, current_object: Option<&impl IsA<glib::Object>>) {
873 unsafe {
874 ffi::gtk_builder_set_current_object(
875 self.to_glib_none().0,
876 current_object.map(|p| p.as_ref()).to_glib_none().0,
877 );
878 }
879 }
880
881 /// Sets the scope the builder should operate in.
882 ///
883 /// If @scope is [`None`], a new `Gtk::BuilderCScope` will be created.
884 /// ## `scope`
885 /// the scope to use
886 #[doc(alias = "gtk_builder_set_scope")]
887 #[doc(alias = "scope")]
888 pub fn set_scope(&self, scope: Option<&impl IsA<BuilderScope>>) {
889 unsafe {
890 ffi::gtk_builder_set_scope(
891 self.to_glib_none().0,
892 scope.map(|p| p.as_ref()).to_glib_none().0,
893 );
894 }
895 }
896
897 /// Sets the translation domain of @self.
898 /// ## `domain`
899 /// the translation domain
900 #[doc(alias = "gtk_builder_set_translation_domain")]
901 #[doc(alias = "translation-domain")]
902 pub fn set_translation_domain(&self, domain: Option<&str>) {
903 unsafe {
904 ffi::gtk_builder_set_translation_domain(self.to_glib_none().0, domain.to_glib_none().0);
905 }
906 }
907
908 /// Demarshals a value from a string.
909 ///
910 /// This function calls g_value_init() on the @value argument,
911 /// so it need not be initialised beforehand.
912 ///
913 /// Can handle char, uchar, boolean, int, uint, long,
914 /// ulong, enum, flags, float, double, string, [`gdk::RGBA`][crate::gdk::RGBA] and
915 /// [`Adjustment`][crate::Adjustment] type values.
916 ///
917 /// Upon errors [`false`] will be returned and @error will be
918 /// assigned a `GError` from the `GTK_BUILDER_ERROR` domain.
919 /// ## `pspec`
920 /// the `GParamSpec` for the property
921 /// ## `string`
922 /// the string representation of the value
923 ///
924 /// # Returns
925 ///
926 /// [`true`] on success
927 ///
928 /// ## `value`
929 /// the `GValue` to store the result in
930 #[doc(alias = "gtk_builder_value_from_string")]
931 pub fn value_from_string(
932 &self,
933 pspec: impl AsRef<glib::ParamSpec>,
934 string: &str,
935 ) -> Result<glib::Value, glib::Error> {
936 unsafe {
937 let mut value = glib::Value::uninitialized();
938 let mut error = std::ptr::null_mut();
939 let is_ok = ffi::gtk_builder_value_from_string(
940 self.to_glib_none().0,
941 pspec.as_ref().to_glib_none().0,
942 string.to_glib_none().0,
943 value.to_glib_none_mut().0,
944 &mut error,
945 );
946 debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
947 if error.is_null() {
948 Ok(value)
949 } else {
950 Err(from_glib_full(error))
951 }
952 }
953 }
954
955 /// Demarshals a value from a string.
956 ///
957 /// Unlike [`value_from_string()`][Self::value_from_string()], this function
958 /// takes a `GType` instead of `GParamSpec`.
959 ///
960 /// Calls g_value_init() on the @value argument, so it
961 /// need not be initialised beforehand.
962 ///
963 /// Upon errors [`false`] will be returned and @error will be
964 /// assigned a `GError` from the `GTK_BUILDER_ERROR` domain.
965 /// ## `type_`
966 /// the `GType` of the value
967 /// ## `string`
968 /// the string representation of the value
969 ///
970 /// # Returns
971 ///
972 /// [`true`] on success
973 ///
974 /// ## `value`
975 /// the `GValue` to store the result in
976 #[doc(alias = "gtk_builder_value_from_string_type")]
977 pub fn value_from_string_type(
978 &self,
979 type_: glib::types::Type,
980 string: &str,
981 ) -> Result<glib::Value, glib::Error> {
982 unsafe {
983 let mut value = glib::Value::uninitialized();
984 let mut error = std::ptr::null_mut();
985 let is_ok = ffi::gtk_builder_value_from_string_type(
986 self.to_glib_none().0,
987 type_.into_glib(),
988 string.to_glib_none().0,
989 value.to_glib_none_mut().0,
990 &mut error,
991 );
992 debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
993 if error.is_null() {
994 Ok(value)
995 } else {
996 Err(from_glib_full(error))
997 }
998 }
999 }
1000
1001 #[doc(alias = "current-object")]
1002 pub fn connect_current_object_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
1003 unsafe extern "C" fn notify_current_object_trampoline<F: Fn(&Builder) + 'static>(
1004 this: *mut ffi::GtkBuilder,
1005 _param_spec: glib::ffi::gpointer,
1006 f: glib::ffi::gpointer,
1007 ) {
1008 let f: &F = &*(f as *const F);
1009 f(&from_glib_borrow(this))
1010 }
1011 unsafe {
1012 let f: Box_<F> = Box_::new(f);
1013 connect_raw(
1014 self.as_ptr() as *mut _,
1015 c"notify::current-object".as_ptr() as *const _,
1016 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1017 notify_current_object_trampoline::<F> as *const (),
1018 )),
1019 Box_::into_raw(f),
1020 )
1021 }
1022 }
1023
1024 #[doc(alias = "scope")]
1025 pub fn connect_scope_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
1026 unsafe extern "C" fn notify_scope_trampoline<F: Fn(&Builder) + 'static>(
1027 this: *mut ffi::GtkBuilder,
1028 _param_spec: glib::ffi::gpointer,
1029 f: glib::ffi::gpointer,
1030 ) {
1031 let f: &F = &*(f as *const F);
1032 f(&from_glib_borrow(this))
1033 }
1034 unsafe {
1035 let f: Box_<F> = Box_::new(f);
1036 connect_raw(
1037 self.as_ptr() as *mut _,
1038 c"notify::scope".as_ptr() as *const _,
1039 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1040 notify_scope_trampoline::<F> as *const (),
1041 )),
1042 Box_::into_raw(f),
1043 )
1044 }
1045 }
1046
1047 #[doc(alias = "translation-domain")]
1048 pub fn connect_translation_domain_notify<F: Fn(&Self) + 'static>(
1049 &self,
1050 f: F,
1051 ) -> SignalHandlerId {
1052 unsafe extern "C" fn notify_translation_domain_trampoline<F: Fn(&Builder) + 'static>(
1053 this: *mut ffi::GtkBuilder,
1054 _param_spec: glib::ffi::gpointer,
1055 f: glib::ffi::gpointer,
1056 ) {
1057 let f: &F = &*(f as *const F);
1058 f(&from_glib_borrow(this))
1059 }
1060 unsafe {
1061 let f: Box_<F> = Box_::new(f);
1062 connect_raw(
1063 self.as_ptr() as *mut _,
1064 c"notify::translation-domain".as_ptr() as *const _,
1065 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1066 notify_translation_domain_trampoline::<F> as *const (),
1067 )),
1068 Box_::into_raw(f),
1069 )
1070 }
1071 }
1072}
1073
1074impl Default for Builder {
1075 fn default() -> Self {
1076 Self::new()
1077 }
1078}