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
mod explore;
mod invite;
mod room_details;
mod room_history;

use adw::subclass::prelude::*;
use gtk::{glib, glib::clone, prelude::*, CompositeTemplate};

use self::{
    explore::Explore, invite::Invite, room_details::RoomDetails, room_history::RoomHistory,
};
use crate::{
    identity_verification_view::IdentityVerificationView,
    session::model::{
        IdentityVerification, Room, RoomType, Session, SidebarIconItem, SidebarIconItemType,
    },
};

/// A page of the content stack.
#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::EnumString, strum::AsRefStr)]
#[strum(serialize_all = "kebab-case")]
pub enum ContentPage {
    /// The placeholder page when no content is presented.
    Empty,
    /// The history of the selected room.
    RoomHistory,
    /// The selected room invite.
    Invite,
    /// The explore page.
    Explore,
    /// The selected identity verification.
    Verification,
}

mod imp {
    use std::cell::{Cell, RefCell};

    use glib::subclass::InitializingObject;

    use super::*;

    #[derive(Debug, Default, CompositeTemplate, glib::Properties)]
    #[template(resource = "/org/gnome/Fractal/ui/session/view/content/mod.ui")]
    #[properties(wrapper_type = super::Content)]
    pub struct Content {
        /// The current session.
        #[property(get, set = Self::set_session, explicit_notify, nullable)]
        pub session: glib::WeakRef<Session>,
        /// Whether this is the only visible view, i.e. there is no sidebar.
        #[property(get, set)]
        pub only_view: Cell<bool>,
        pub item_binding: RefCell<Option<glib::Binding>>,
        /// The item currently displayed.
        #[property(get, set = Self::set_item, explicit_notify, nullable)]
        pub item: RefCell<Option<glib::Object>>,
        pub signal_handler: RefCell<Option<glib::SignalHandlerId>>,
        #[template_child]
        pub stack: TemplateChild<gtk::Stack>,
        #[template_child]
        pub room_history: TemplateChild<RoomHistory>,
        #[template_child]
        pub invite: TemplateChild<Invite>,
        #[template_child]
        pub explore: TemplateChild<Explore>,
        #[template_child]
        pub empty_page: TemplateChild<adw::ToolbarView>,
        #[template_child]
        pub verification_page: TemplateChild<adw::ToolbarView>,
        #[template_child]
        pub identity_verification_widget: TemplateChild<IdentityVerificationView>,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for Content {
        const NAME: &'static str = "Content";
        type Type = super::Content;
        type ParentType = adw::NavigationPage;

        fn class_init(klass: &mut Self::Class) {
            Self::bind_template(klass);
            klass.set_accessible_role(gtk::AccessibleRole::Group);
        }

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

    #[glib::derived_properties]
    impl ObjectImpl for Content {
        fn constructed(&self) {
            self.parent_constructed();

            self.stack
                .connect_visible_child_notify(clone!(@weak self as imp => move |_| {
                    if imp.visible_page() != ContentPage::Verification {
                        imp.identity_verification_widget.set_verification(None::<IdentityVerification>);
                    }
                }));

            if let Some(binding) = self.item_binding.take() {
                binding.unbind()
            }
        }
    }

    impl WidgetImpl for Content {}

    impl NavigationPageImpl for Content {
        fn hidden(&self) {
            self.obj().set_item(None::<glib::Object>);
        }
    }

    impl Content {
        /// The visible page of the content.
        pub(super) fn visible_page(&self) -> ContentPage {
            self.stack
                .visible_child_name()
                .and_then(|s| s.as_str().try_into().ok())
                .unwrap()
        }

        /// Set the current session.
        fn set_session(&self, session: Option<Session>) {
            if session == self.session.upgrade() {
                return;
            }
            let obj = self.obj();

            if let Some(binding) = self.item_binding.take() {
                binding.unbind();
            }

            if let Some(session) = &session {
                let item_binding = session
                    .sidebar_list_model()
                    .selection_model()
                    .bind_property("selected-item", &*obj, "item")
                    .sync_create()
                    .bidirectional()
                    .build();

                self.item_binding.replace(Some(item_binding));
            }

            self.session.set(session.as_ref());
            obj.notify_session();
        }

        /// Set the item currently displayed.
        fn set_item(&self, item: Option<glib::Object>) {
            if *self.item.borrow() == item {
                return;
            }
            let obj = self.obj();

            if let Some(item) = self.item.take() {
                if let Some(signal_handler) = self.signal_handler.take() {
                    item.disconnect(signal_handler);
                }
            }

            if let Some(item) = &item {
                if let Some(room) = item.downcast_ref::<Room>() {
                    let handler_id = room.connect_category_notify(clone!(@weak obj => move |_| {
                        obj.update_visible_child();
                    }));

                    self.signal_handler.replace(Some(handler_id));
                } else if let Some(verification) = item.downcast_ref::<IdentityVerification>() {
                    let handler_id = verification.connect_dismiss(clone!(@weak obj => move |_| {
                        obj.set_item(None::<glib::Object>);
                    }));
                    self.signal_handler.replace(Some(handler_id));
                }
            }

            self.item.replace(item);
            obj.update_visible_child();
            obj.notify_item();
        }
    }
}

glib::wrapper! {
    /// A view displaying the selected content in the sidebar.
    pub struct Content(ObjectSubclass<imp::Content>)
        @extends gtk::Widget, adw::NavigationPage, @implements gtk::Accessible;
}

impl Content {
    pub fn new(session: &Session) -> Self {
        glib::Object::builder().property("session", session).build()
    }

    /// Set the visible page of the content.
    fn set_visible_page(&self, name: ContentPage) {
        self.imp().stack.set_visible_child_name(name.as_ref());
    }

    /// Handle a paste action.
    pub fn handle_paste_action(&self) {
        let imp = self.imp();
        if imp.visible_page() == ContentPage::RoomHistory {
            imp.room_history.handle_paste_action();
        }
    }

    /// Update the visible child according to the current item.
    fn update_visible_child(&self) {
        let imp = self.imp();

        match self.item() {
            None => {
                imp.stack.set_visible_child(&*imp.empty_page);
            }
            Some(o) if o.is::<Room>() => {
                if let Ok(room) = o.downcast::<Room>() {
                    if room.category() == RoomType::Invited {
                        imp.invite.set_room(Some(room));
                        self.set_visible_page(ContentPage::Invite);
                    } else {
                        imp.room_history.set_room(Some(room));
                        self.set_visible_page(ContentPage::RoomHistory);
                    }
                }
            }
            Some(o)
                if o.downcast_ref::<SidebarIconItem>()
                    .is_some_and(|i| i.item_type() == SidebarIconItemType::Explore) =>
            {
                imp.explore.init();
                self.set_visible_page(ContentPage::Explore);
            }
            Some(o) if o.is::<IdentityVerification>() => {
                if let Ok(verification) = o.downcast::<IdentityVerification>() {
                    imp.identity_verification_widget
                        .set_verification(Some(verification));
                    self.set_visible_page(ContentPage::Verification);
                }
            }
            _ => {}
        }
    }
}