gtk/
builder.rs

1// Copyright 2013-2015, The Gtk-rs Project Developers.
2// See the COPYRIGHT file at the top-level directory of this distribution.
3// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
4
5use glib::object::{Cast, IsA};
6use glib::translate::*;
7use glib::Object;
8use gtk_sys;
9use std::path::Path;
10use Builder;
11use Error;
12
13impl Builder {
14    pub fn new_from_file<T: AsRef<Path>>(file_path: T) -> Builder {
15        assert_initialized_main_thread!();
16        unsafe {
17            from_glib_full(gtk_sys::gtk_builder_new_from_file(
18                file_path.as_ref().to_glib_none().0,
19            ))
20        }
21    }
22}
23
24pub trait BuilderExtManual: 'static {
25    fn get_object<T: IsA<Object>>(&self, name: &str) -> Option<T>;
26    fn add_from_file<T: AsRef<Path>>(&self, file_path: T) -> Result<(), Error>;
27}
28
29impl<O: IsA<Builder>> BuilderExtManual for O {
30    fn get_object<T: IsA<Object>>(&self, name: &str) -> Option<T> {
31        unsafe {
32            Option::<Object>::from_glib_none(gtk_sys::gtk_builder_get_object(
33                self.upcast_ref().to_glib_none().0,
34                name.to_glib_none().0,
35            ))
36            .and_then(|obj| obj.dynamic_cast::<T>().ok())
37        }
38    }
39
40    fn add_from_file<T: AsRef<Path>>(&self, file_path: T) -> Result<(), Error> {
41        unsafe {
42            let mut error = ::std::ptr::null_mut();
43            gtk_sys::gtk_builder_add_from_file(
44                self.upcast_ref().to_glib_none().0,
45                file_path.as_ref().to_glib_none().0,
46                &mut error,
47            );
48            if error.is_null() {
49                Ok(())
50            } else {
51                Err(from_glib_full(error))
52            }
53        }
54    }
55}