[go: up one dir, main page]

gtk4/
builder.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::path::Path;
4
5use glib::{translate::*, Object};
6
7use crate::{ffi, prelude::*, Builder};
8
9impl Builder {
10    #[doc(alias = "gtk_builder_new_from_file")]
11    #[doc(alias = "new_from_file")]
12    pub fn from_file(file_path: impl AsRef<Path>) -> Self {
13        assert_initialized_main_thread!();
14        unsafe {
15            from_glib_full(ffi::gtk_builder_new_from_file(
16                file_path.as_ref().to_glib_none().0,
17            ))
18        }
19    }
20
21    #[doc(alias = "gtk_builder_get_current_object")]
22    #[doc(alias = "get_current_object")]
23    pub fn current_object(&self) -> Option<Object> {
24        unsafe {
25            let ptr = ffi::gtk_builder_get_current_object(self.to_glib_none().0);
26            if ptr.is_null() {
27                None
28            } else {
29                glib::gobject_ffi::g_object_ref(ptr);
30                Some(from_glib_full(ptr))
31            }
32        }
33    }
34
35    #[doc(alias = "gtk_builder_get_object")]
36    #[doc(alias = "get_object")]
37    pub fn object<T: IsA<Object>>(&self, name: impl IntoGStr) -> Option<T> {
38        unsafe {
39            T::ensure_type();
40            name.run_with_gstr(|name| {
41                Option::<Object>::from_glib_none(ffi::gtk_builder_get_object(
42                    self.to_glib_none().0,
43                    name.as_ptr(),
44                ))
45                .and_then(|obj| obj.dynamic_cast::<T>().ok())
46            })
47        }
48    }
49
50    #[doc(alias = "gtk_builder_add_from_file")]
51    pub fn add_from_file(&self, file_path: impl AsRef<Path>) -> Result<(), glib::Error> {
52        unsafe {
53            let mut error = ::std::ptr::null_mut();
54            ffi::gtk_builder_add_from_file(
55                self.to_glib_none().0,
56                file_path.as_ref().to_glib_none().0,
57                &mut error,
58            );
59            if error.is_null() {
60                Ok(())
61            } else {
62                Err(from_glib_full(error))
63            }
64        }
65    }
66}