fractal/components/
action_button.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
use adw::{prelude::*, subclass::prelude::*};
use gtk::{glib, glib::closure_local, CompositeTemplate};

#[derive(Debug, Default, Hash, Eq, PartialEq, Clone, Copy, glib::Enum)]
#[repr(u32)]
#[enum_type(name = "ActionState")]
pub enum ActionState {
    #[default]
    Default = 0,
    Confirm = 1,
    Retry = 2,
    Loading = 3,
    Success = 4,
    Warning = 5,
    Error = 6,
}

impl AsRef<str> for ActionState {
    fn as_ref(&self) -> &str {
        match self {
            ActionState::Default => "default",
            ActionState::Confirm => "confirm",
            ActionState::Retry => "retry",
            ActionState::Loading => "loading",
            ActionState::Success => "success",
            ActionState::Warning => "warning",
            ActionState::Error => "error",
        }
    }
}

mod imp {
    use std::{
        cell::{Cell, RefCell},
        marker::PhantomData,
        sync::LazyLock,
    };

    use glib::subclass::{InitializingObject, Signal};

    use super::*;

    #[derive(Debug, Default, CompositeTemplate, glib::Properties)]
    #[template(resource = "/org/gnome/Fractal/ui/components/action_button.ui")]
    #[properties(wrapper_type = super::ActionButton)]
    pub struct ActionButton {
        #[template_child]
        stack: TemplateChild<gtk::Stack>,
        #[template_child]
        button_default: TemplateChild<gtk::Button>,
        /// The icon used in the default state.
        #[property(get, set = Self::set_icon_name, explicit_notify)]
        icon_name: RefCell<String>,
        /// The extra CSS classes applied to the button in the default state.
        extra_classes: RefCell<Vec<&'static str>>,
        /// The action emitted by the button.
        #[property(get = Self::action_name, set = Self::set_action_name, override_interface = gtk::Actionable)]
        action_name: RefCell<Option<glib::GString>>,
        /// The target value of the action of the button.
        #[property(get = Self::action_target_value, set = Self::set_action_target, override_interface = gtk::Actionable)]
        action_target: RefCell<Option<glib::Variant>>,
        /// The state of the button.
        #[property(get, set = Self::set_state, explicit_notify, builder(ActionState::default()))]
        state: Cell<ActionState>,
        /// The tooltip text of the button of the default state.
        #[property(set = Self::set_default_state_tooltip_text)]
        default_state_tooltip_text: PhantomData<Option<String>>,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for ActionButton {
        const NAME: &'static str = "ActionButton";
        type Type = super::ActionButton;
        type ParentType = adw::Bin;
        type Interfaces = (gtk::Actionable,);

        fn class_init(klass: &mut Self::Class) {
            Self::bind_template(klass);
            Self::bind_template_callbacks(klass);

            klass.set_css_name("action-button");
        }

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

    #[glib::derived_properties]
    impl ObjectImpl for ActionButton {
        fn signals() -> &'static [Signal] {
            static SIGNALS: LazyLock<Vec<Signal>> =
                LazyLock::new(|| vec![Signal::builder("clicked").build()]);
            SIGNALS.as_ref()
        }
    }

    impl WidgetImpl for ActionButton {}
    impl BinImpl for ActionButton {}

    impl ActionableImpl for ActionButton {
        fn action_name(&self) -> Option<glib::GString> {
            self.action_name.borrow().clone()
        }

        fn action_target_value(&self) -> Option<glib::Variant> {
            self.action_target.borrow().clone()
        }

        fn set_action_name(&self, name: Option<&str>) {
            self.action_name.replace(name.map(Into::into));
        }

        fn set_action_target_value(&self, value: Option<&glib::Variant>) {
            self.set_action_target(value.cloned());
        }
    }

    #[gtk::template_callbacks]
    impl ActionButton {
        /// Set the icon used in the default state.
        fn set_icon_name(&self, icon_name: &str) {
            if self.icon_name.borrow().as_str() == icon_name {
                return;
            }

            self.icon_name.replace(icon_name.to_owned());
            self.obj().notify_icon_name();
        }

        /// Set the extra CSS classes applied to the button in the default
        /// state.
        pub(super) fn set_extra_classes(&self, classes: &[&'static str]) {
            let mut extra_classes = self.extra_classes.borrow_mut();

            if *extra_classes == classes {
                // Nothing to do.
                return;
            }

            for class in extra_classes.drain(..) {
                self.button_default.remove_css_class(class);
            }

            for class in classes {
                self.button_default.add_css_class(class);
            }

            extra_classes.extend(classes);
        }

        /// Set the state of the button.
        fn set_state(&self, state: ActionState) {
            if self.state.get() == state {
                return;
            }

            self.stack.set_visible_child_name(state.as_ref());
            self.state.replace(state);
            self.obj().notify_state();
        }

        /// Set the target value of the action of the button.
        fn set_action_target(&self, value: Option<glib::Variant>) {
            self.action_target.replace(value);
        }

        /// Set the tooltip text of the button of the default state.
        fn set_default_state_tooltip_text(&self, text: Option<&str>) {
            self.button_default.set_tooltip_text(text);
        }

        #[template_callback]
        fn button_clicked(&self) {
            self.obj().emit_by_name::<()>("clicked", &[]);
        }
    }
}

glib::wrapper! {
    /// A button to emit an action and handle its different states.
    pub struct ActionButton(ObjectSubclass<imp::ActionButton>)
        @extends gtk::Widget, adw::Bin, @implements gtk::Actionable, gtk::Accessible;
}

#[gtk::template_callbacks]
impl ActionButton {
    pub fn new() -> Self {
        glib::Object::new()
    }

    /// Set the extra CSS classes applied to the button in the default state.
    pub(crate) fn set_extra_classes(&self, classes: &[&'static str]) {
        self.imp().set_extra_classes(classes);
    }

    /// Connect to the signal emitted when the button is clicked.
    pub fn connect_clicked<F: Fn(&Self) + 'static>(&self, f: F) -> glib::SignalHandlerId {
        self.connect_closure(
            "clicked",
            true,
            closure_local!(move |obj: Self| {
                f(&obj);
            }),
        )
    }
}