Adding buildtime checks to Builder::get_object()
I'm using a python script to generate a function for each object with id in my .ui-files. Those functions call get_object() for the id. This way I get compile time errors if I am trying to use an id that does not exist. Also, I get the type of the object for free (also from .ui-file).
I will certainly continue using something like this because I'm so happy about having this solution. My question is if there is interest to adapting this to other projects. It would also be an option to rewrite this in rust and use it via build.rs.
The generated code currently looks like this
// class name is derived from file name
impl DialogDeviceMissing {
pub fn new() -> Self {
Self {
builder: gtk::Builder::from_string(include_str!(concat!(
data_dir!(),
"/ui/dialog_device_missing.ui"
))),
}
}
fn get<T: glib::IsA<glib::object::Object>>(&self, id: &str) -> T {
gtk::prelude::BuilderExtManual::get_object(&self.builder, id).unwrap_or_else(|| {
panic!(
"Object with id '{}' not found in 'ui/dialog_device_missing.ui'",
id
)
})
}
pub fn cancel(&self) -> gtk::Button {
self.get("cancel")
}
pub fn device(&self) -> gtk::Label {
self.get("device")
}
}
Edited by Sophie Herold