#[template_callbacks]
Expand description

Attribute macro for creating template callbacks from Rust methods.

Widgets with CompositeTemplate can then make use of these callbacks from within their template XML definition. The attribute must be applied to an impl statement of a struct. Functions marked as callbacks within the impl will be stored in a static array. Then, in the ObjectSubclass implementation you will need to call bind_template_callbacks in the class_init function.

Template callbacks can be specified on both a widget’s public impl or on its private impl. Template callbacks from other types can also be used. Care must be taken to call bind_template_callbacks on each type in order to use its callbacks.

These callbacks can be bound using the <signal> or <closure> tags in the template file. Note that the arguments and return type will only be checked at run time when the method is invoked.

Methods can optionally take &self as a first parameter. In this case, the attribute swapped="true" will usually have to be set on the <signal> or <closure> tag in order to invoke the function correctly.

The following options are supported on the attribute:

  • functions makes all callbacks use the function attribute by default. (see below)

The template_callback attribute is used to mark methods that will be exposed to the template scope. It can take the following options:

  • name renames the callback. Defaults to the function name if not defined.
  • function ignores the first value when calling the callback and disallows self. Useful for callbacks called from <closure> tags.
  • function = false reverts the effects of functions used on the impl, so the callback gets the first value and can take self again. Mainly useful for callbacks that are invoked with swapped="true".

The rest attribute can be placed on the last argument of a template callback. This attribute must be used on an argument of type &[glib::Value] and will pass in the remaining arguments. The first and last values will be omitted from the slice if this callback is a function.

Arguments and return types in template callbacks have some special restrictions, similar to the restrictions on glib::closure. Each argument’s type must implement glib::ToValue. The last argument can also be &[glib::Value] annotated with #[rest] as described above. The return type of a callback, if present, must implement glib::FromValue. Type-checking of inputs and outputs is done at run-time; if the argument types or return type do not match the type of the signal or closure then the callback will panic. To implement your own type checking or to use dynamic typing, an argument’s type can be left as a &glib::Value. This can also be used if you need custom unboxing, such as if the target type does not implement FromValue.

Example

use gtk::prelude::*;
use gtk::glib;
use gtk::CompositeTemplate;
use gtk::subclass::prelude::*;

mod imp {
    use super::*;

    #[derive(Debug, Default, CompositeTemplate)]
    #[template(file = "test/template_callbacks.ui")]
    pub struct MyWidget {
        #[template_child]
        pub label: TemplateChild<gtk::Label>,
        #[template_child(id = "my_button_id")]
        pub button: TemplateChild<gtk::Button>,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for MyWidget {
        const NAME: &'static str = "MyWidget";
        type Type = super::MyWidget;
        type ParentType = gtk::Box;

        fn class_init(klass: &mut Self::Class) {
            Self::bind_template(klass);
            // Bind the private callbacks
            Self::bind_template_callbacks(klass);
            // Bind the public callbacks
            Self::Type::bind_template_callbacks(klass);
            // Bind callbacks from another struct
            super::Utility::bind_template_callbacks(klass);
        }

        fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
            obj.init_template();
        }
    }

    #[gtk::template_callbacks]
    impl MyWidget {
        #[template_callback]
        fn button_clicked(&self, button: &gtk::Button) {
            button.set_label("I was clicked!");
            self.label.set_label("The button was clicked!");
        }
        #[template_callback(function, name = "strlen")]
        fn string_length(s: &str) -> u64 {
            s.len() as u64
        }
    }

    impl ObjectImpl for MyWidget {}
    impl WidgetImpl for MyWidget {}
    impl BoxImpl for MyWidget {}
}

glib::wrapper! {
    pub struct MyWidget(ObjectSubclass<imp::MyWidget>) @extends gtk::Widget, gtk::Box;
}

#[gtk::template_callbacks]
impl MyWidget {
    pub fn new() -> Self {
        glib::Object::new(&[]).expect("Failed to create an instance of MyWidget")
    }
    #[template_callback]
    pub fn print_both_labels(&self) {
        let self_ = imp::MyWidget::from_instance(self);
        println!("{} {}", self_.label.label(), self_.button.label().unwrap().as_str());
    }
}

pub struct Utility {}

#[gtk::template_callbacks(functions)]
impl Utility {
    #[template_callback]
    fn concat_strs(#[rest] values: &[glib::Value]) -> String {
        let mut res = String::new();
        for (index, value) in values.iter().enumerate() {
            res.push_str(value.get::<&str>().unwrap_or_else(|e| {
                panic!("Expected string value for argument {}: {}", index, e);
            }));
        }
        res
    }
    #[template_callback(function = false)]
    fn reset_label(label: &gtk::Label) {
        label.set_label("");
    }
}