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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
/* PluginDetails.rs
 *
 * Copyright 2020-2021 Rasmus Thomsen <oss@cogitri.dev>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

use crate::prelude::*;
use adw::subclass::prelude::*;
use gtk::glib::{self, prelude::*};

mod imp {
    use crate::prelude::*;
    use adw::{prelude::*, subclass::prelude::*};
    use gtk::{gio, glib, CompositeTemplate};
    use std::cell::Cell;

    #[repr(C)]
    pub struct PluginDetailsClass {
        pub parent_class: adw::ffi::AdwBinClass,
        pub update: fn(&super::PluginDetails) -> PinnedResultFuture<()>,
    }

    unsafe impl ClassStruct for PluginDetailsClass {
        type Type = PluginDetails;
    }

    impl std::ops::Deref for PluginDetailsClass {
        type Target = glib::Class<glib::Object>;

        fn deref(&self) -> &Self::Target {
            unsafe { &*(self as *const Self).cast::<Self::Target>() }
        }
    }

    impl std::ops::DerefMut for PluginDetailsClass {
        fn deref_mut(&mut self) -> &mut glib::Class<glib::Object> {
            unsafe { &mut *(self as *mut Self).cast::<glib::Class<glib::Object>>() }
        }
    }

    #[derive(Debug, CompositeTemplate, Default)]
    #[template(resource = "/dev/Cogitri/Health/ui/plugins/details.ui")]
    pub struct PluginDetails {
        pub is_mocked: Cell<bool>,
        #[template_child]
        pub empty_icon: TemplateChild<gtk::Image>,
        #[template_child]
        pub empty_label: TemplateChild<gtk::Label>,
        #[template_child]
        pub filled_title_label: TemplateChild<gtk::Label>,
        #[template_child]
        pub filled_subtitle_label: TemplateChild<gtk::Label>,
        #[template_child]
        pub is_mocked_label: TemplateChild<gtk::Label>,
        #[template_child]
        pub main_box: TemplateChild<gtk::Box>,
        #[template_child]
        pub stack: TemplateChild<gtk::Stack>,
    }

    // Virtual method default implementation trampolines
    fn update_default_trampoline(this: &super::PluginDetails) -> PinnedResultFuture<()> {
        PluginDetails::from_obj(this).update(this)
    }

    pub(super) fn plugin_details_update(this: &super::PluginDetails) -> PinnedResultFuture<()> {
        let klass = this.class();

        (klass.as_ref().update)(this)
    }

    impl PluginDetails {
        fn update(&self, obj: &super::PluginDetails) -> PinnedResultFuture<()> {
            Box::pin(gio::GioFuture::new(obj, move |_, _, send| {
                send.resolve(Ok(()));
            }))
        }
    }

    #[glib::object_subclass]
    impl ObjectSubclass for PluginDetails {
        const NAME: &'static str = "HealthPluginDetails";
        type ParentType = adw::Bin;
        type Type = super::PluginDetails;
        type Class = PluginDetailsClass;

        fn class_init(klass: &mut Self::Class) {
            klass.update = update_default_trampoline;
            klass.set_layout_manager_type::<gtk::BinLayout>();

            Self::bind_template(klass);
        }

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

    impl ObjectImpl for PluginDetails {
        fn properties() -> &'static [glib::ParamSpec] {
            use once_cell::sync::Lazy;
            static PROPERTIES: Lazy<Vec<glib::ParamSpec>> = Lazy::new(|| {
                vec![
                    glib::ParamSpecObject::builder::<gtk::Widget>("content-widget")
                        .write_only()
                        .build(),
                    glib::ParamSpecString::builder("empty-label").build(),
                    glib::ParamSpecString::builder("empty-icon-name").build(),
                    glib::ParamSpecString::builder("filled-title").build(),
                    glib::ParamSpecString::builder("filled-subtitle").build(),
                    glib::ParamSpecBoolean::builder("is-mocked")
                        .construct_only()
                        .readwrite()
                        .build(),
                ]
            });

            PROPERTIES.as_ref()
        }

        fn set_property(&self, _id: usize, value: &glib::Value, pspec: &glib::ParamSpec) {
            match pspec.name() {
                "content-widget" => self.main_box.append(&value.get::<gtk::Widget>().unwrap()),
                "empty-label" => self.empty_label.set_label(value.get::<&str>().unwrap()),
                "empty-icon-name" => self.empty_icon.set_icon_name(value.get().unwrap()),
                "filled-title" => self
                    .filled_title_label
                    .set_label(value.get::<&str>().unwrap()),
                "filled-subtitle" => self
                    .filled_subtitle_label
                    .set_label(value.get::<&str>().unwrap_or("")),
                "is-mocked" => {
                    self.is_mocked.set(value.get().unwrap());
                }
                _ => unimplemented!(),
            }
        }

        fn property(&self, _id: usize, pspec: &glib::ParamSpec) -> glib::Value {
            match pspec.name() {
                "empty-label" => self.empty_label.label().to_value(),
                "empty-icon-name" => self.empty_icon.icon_name().to_value(),
                "filled-title" => self.filled_title_label.label().to_value(),
                "filled-subtitle" => self.filled_subtitle_label.label().to_value(),
                "is-mocked" => self.is_mocked.get().to_value(),
                _ => unimplemented!(),
            }
        }
    }
    impl WidgetImpl for PluginDetails {}
    impl BinImpl for PluginDetails {}
}

glib::wrapper! {
    /// [PluginDetails] is a toplevel container that is implemented by all other PluginDetailss of Health. See [PluginExt] for all the methods exposed by [PluginDetails].
    pub struct PluginDetails(ObjectSubclass<imp::PluginDetails>)
        @extends gtk::Widget, adw::Bin,
        @implements gtk::Accessible, gtk::Buildable, gtk::ConstraintTarget;
}

impl PluginDetails {
    pub fn new() -> Self {
        glib::Object::new()
    }
}

pub trait PluginDetailsExt {
    /// Get the name of the icon that's displayed when the view is empty (has no data to display).
    fn empty_icon_name(&self) -> String;
    /// Get the label that's displayed when the view is empty (has to data to display).
    fn empty_label(&self) -> String;
    /// Get the subtitle that's displayed when the view is filled (has data to display).
    ///
    /// This could be a label displaying how many days in a row the user has archived their step goal.
    fn filled_subtitle(&self) -> String;
    /// Get the title that's displayed when the view is filled (has data to display).
    fn filled_title(&self) -> String;
    /// Get whether the view is mocked.
    ///
    /// This is used to show the user a demo-version of how the view looks when they activate the plugin.
    /// If this is enabled, we display some static data to the user.
    fn is_mocked(&self) -> bool;

    /// Set the name of the icon that's displayed when the view is empty (has no data to display).
    fn set_empty_icon_name(&self, val: &str);
    /// Get the label that's displayed when the view is empty (has to data to display).
    fn set_empty_label(&self, val: &str);
    /// Set the subtitle that's displayed when the view is filled (has data to display).
    ///
    /// This could be a label displaying how many days in a row the user has archived their step goal.
    fn set_filled_subtitle(&self, val: &str);
    /// Set the title that's displayed when the view is filled (has data to display).
    fn set_filled_title(&self, val: &str);

    /// Switch to the [gtk::StackPage] that shows the data.
    ///
    /// Call this if your view previously was empty and now has data to display.
    fn switch_to_data_page(&self);
    /// Switch to the [gtk::StackPage] that shows the empty-icon and empty-label
    ///
    /// Call this if your view previously was filled and is empty now.
    fn switch_to_empty_page(&self);

    /// Refresh the view's data.
    fn update(&self) -> PinnedResultFuture<()>;
}

impl<O: IsA<PluginDetails>> PluginDetailsExt for O {
    fn empty_icon_name(&self) -> String {
        self.property("empty-icon-name")
    }
    fn empty_label(&self) -> String {
        self.property("empty-label")
    }
    fn filled_subtitle(&self) -> String {
        self.property("filled-subtitle")
    }
    fn filled_title(&self) -> String {
        self.property("filled-title")
    }
    fn is_mocked(&self) -> bool {
        self.property("is-mocked")
    }

    fn set_empty_icon_name(&self, val: &str) {
        self.set_property("empty-icon-name", val);
    }
    fn set_empty_label(&self, val: &str) {
        self.set_property("empty-label", val);
    }
    fn set_filled_subtitle(&self, val: &str) {
        self.set_property("filled-subtitle", val);
    }
    fn set_filled_title(&self, val: &str) {
        self.set_property("filled-title", val);
    }
    fn switch_to_data_page(&self) {
        self.upcast_ref::<PluginDetails>()
            .imp()
            .stack
            .set_visible_child_name("data_page");
    }
    fn switch_to_empty_page(&self) {
        self.upcast_ref::<PluginDetails>()
            .imp()
            .stack
            .set_visible_child_name("empty_page");
    }

    fn update(&self) -> PinnedResultFuture<()> {
        imp::plugin_details_update(self.upcast_ref())
    }
}

pub trait PluginDetailsImpl: BinImpl + 'static {
    fn update(&self, obj: &PluginDetails) -> PinnedResultFuture<()> {
        self.parent_update(obj)
    }
}

pub trait PluginDetailsImplExt: ObjectSubclass {
    fn parent_update(&self, obj: &PluginDetails) -> PinnedResultFuture<()>;
}

impl<T: PluginDetailsImpl> PluginDetailsImplExt for T {
    fn parent_update(&self, obj: &PluginDetails) -> PinnedResultFuture<()> {
        unsafe {
            let data = Self::type_data();
            let parent_class = &*(data.as_ref().parent_class() as *mut imp::PluginDetailsClass);
            (parent_class.update)(obj)
        }
    }
}

unsafe impl<T: PluginDetailsImpl> IsSubclassable<T> for PluginDetails {
    fn class_init(class: &mut glib::Class<Self>) {
        <adw::Bin as IsSubclassable<T>>::class_init(class.upcast_ref_mut());

        let klass = class.as_mut();
        klass.update = update_trampoline::<T>;
    }

    fn instance_init(instance: &mut glib::subclass::InitializingObject<T>) {
        <adw::Bin as IsSubclassable<T>>::instance_init(instance);
    }
}

// Virtual method default implementation trampolines
fn update_trampoline<T: ObjectSubclass>(this: &PluginDetails) -> PinnedResultFuture<()>
where
    T: PluginDetailsImpl,
{
    let imp = T::from_obj(this.dynamic_cast_ref::<T::Type>().unwrap());
    imp.update(this)
}

#[cfg(test)]
mod test {
    use super::PluginDetails;
    use crate::utils::init_gtk;

    #[gtk::test]
    fn new() {
        init_gtk();
        PluginDetails::new();
    }
}