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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
use adw::{prelude::*, subclass::prelude::*};
use gtk::{
    self, gdk, glib,
    glib::{clone, signal::SignalHandlerId},
    CompositeTemplate,
};
use ruma::{OwnedUserId, RoomId};
use tracing::{error, warn};

use super::{Content, CreateDmDialog, MediaViewer, RoomCreation, Sidebar};
use crate::{
    components::{JoinRoomDialog, UserProfileDialog},
    session::model::{
        Event, IdentityVerification, Room, Selection, Session, SidebarListModel, VerificationKey,
    },
    toast,
    utils::matrix::{MatrixRoomId, MatrixRoomIdUri},
    Window,
};

mod imp {
    use std::cell::RefCell;

    use glib::subclass::InitializingObject;

    use super::*;

    #[derive(Debug, Default, CompositeTemplate, glib::Properties)]
    #[template(resource = "/org/gnome/Fractal/ui/session/view/session_view.ui")]
    #[properties(wrapper_type = super::SessionView)]
    pub struct SessionView {
        #[template_child]
        pub stack: TemplateChild<gtk::Stack>,
        #[template_child]
        pub overlay: TemplateChild<gtk::Overlay>,
        #[template_child]
        pub split_view: TemplateChild<adw::NavigationSplitView>,
        #[template_child]
        pub sidebar: TemplateChild<Sidebar>,
        #[template_child]
        pub content: TemplateChild<Content>,
        #[template_child]
        pub media_viewer: TemplateChild<MediaViewer>,
        /// The current session.
        #[property(get, set = Self::set_session, explicit_notify, nullable)]
        pub session: glib::WeakRef<Session>,
        pub window_active_handler_id: RefCell<Option<SignalHandlerId>>,
    }

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

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

            klass.install_action("session.close-room", None, |obj, _, _| {
                obj.select_room(None);
            });

            klass.install_action(
                "session.show-room",
                Some(&String::static_variant_type()),
                |obj, _, parameter| {
                    if let Ok(room_id) =
                        <&RoomId>::try_from(&*parameter.unwrap().get::<String>().unwrap())
                    {
                        obj.select_room_by_id(room_id);
                    } else {
                        error!("Cannot show room with invalid ID");
                    }
                },
            );

            klass.install_action_async("session.logout", None, |obj, _, _| async move {
                if let Some(session) = obj.session() {
                    if let Err(error) = session.logout().await {
                        toast!(obj, error);
                    }
                }
            });

            klass.install_action("session.show-content", None, |obj, _, _| {
                obj.show_content();
            });

            klass.install_action("session.room-creation", None, |obj, _, _| {
                obj.show_room_creation_dialog();
            });

            klass.install_action("session.show-join-room", None, |obj, _, _| {
                obj.show_join_room_dialog(None);
            });

            klass.install_action_async("session.create-dm", None, |obj, _, _| async move {
                obj.show_create_dm_dialog().await;
            });

            klass.add_binding_action(
                gdk::Key::Escape,
                gdk::ModifierType::empty(),
                "session.close-room",
            );

            klass.install_action("session.toggle-room-search", None, |obj, _, _| {
                obj.toggle_room_search();
            });

            klass.add_binding_action(
                gdk::Key::k,
                gdk::ModifierType::CONTROL_MASK,
                "session.toggle-room-search",
            );
        }

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

    #[glib::derived_properties]
    impl ObjectImpl for SessionView {
        fn constructed(&self) {
            self.parent_constructed();
            let obj = self.obj();

            self.sidebar.property_expression("list-model").chain_property::<SidebarListModel>("selection-model").chain_property::<Selection>("selected-item").watch(glib::Object::NONE,
                clone!(@weak self as imp => move || {
                    let show_content = imp.sidebar.list_model().is_some_and(|m| m.selection_model().selected_item().is_some());
                    imp.split_view.set_show_content(show_content);
                }),
            );

            self.content
                .connect_item_notify(clone!(@weak obj => move |_| {
                    // Withdraw the notifications of the newly selected item.
                    obj.withdraw_selected_item_notifications();
                }));

            obj.connect_root_notify(|obj| {
                let Some(window) = obj.parent_window() else {
                    return;
                };

                let handler_id =
                    window.connect_is_active_notify(clone!(@weak obj => move |window| {
                        if !window.is_active() {
                            return;
                        }

                        // When the window becomes active, withdraw the notifications
                        // of the selected item.
                        obj.withdraw_selected_item_notifications();
                    }));
                obj.imp().window_active_handler_id.replace(Some(handler_id));
            });
        }

        fn dispose(&self) {
            if let Some(handler_id) = self.window_active_handler_id.take() {
                if let Some(window) = self.obj().parent_window() {
                    window.disconnect(handler_id);
                }
            }
        }
    }

    impl WidgetImpl for SessionView {}
    impl BinImpl for SessionView {}

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

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

glib::wrapper! {
    /// A view for a Matrix user session.
    pub struct SessionView(ObjectSubclass<imp::SessionView>)
        @extends gtk::Widget, adw::Bin, @implements gtk::Accessible;
}

impl SessionView {
    /// Create a new session view.
    pub async fn new() -> Self {
        glib::Object::new()
    }

    /// The currently selected item, if any.
    pub fn selected_item(&self) -> Option<glib::Object> {
        self.imp().content.item()
    }

    /// Select the given item.
    pub fn select_item(&self, item: Option<impl IsA<glib::Object>>) {
        let Some(session) = self.session() else {
            return;
        };

        session
            .sidebar_list_model()
            .selection_model()
            .set_selected_item(item);
    }

    /// The currently selected room, if any.
    pub fn selected_room(&self) -> Option<Room> {
        self.selected_item().and_downcast()
    }

    /// Select the given room.
    pub fn select_room(&self, room: Option<Room>) {
        self.select_item(room);
    }

    /// Select the room with the given ID in this view.
    pub fn select_room_by_id(&self, room_id: &RoomId) {
        if let Some(room) = self.session().and_then(|s| s.room_list().get(room_id)) {
            self.select_room(Some(room));
        } else {
            warn!("A room with ID {room_id} could not be found");
        }
    }

    /// Select the room with the given identifier in this view, if it exists.
    ///
    /// Returns `true` if the room was found.
    pub fn select_room_if_exists(&self, room_id: &MatrixRoomId) -> bool {
        if let Some(room) = self
            .session()
            .and_then(|s| s.room_list().joined_room(room_id))
        {
            self.select_room(Some(room));
            true
        } else {
            false
        }
    }

    /// Select the identity verification with the given key in this view.
    pub fn select_identity_verification_by_id(&self, key: &VerificationKey) {
        if let Some(verification) = self.session().and_then(|s| s.verification_list().get(key)) {
            self.select_identity_verification(verification);
        } else {
            warn!(
                "An identity verification for user {} with flow ID {} could not be found",
                key.user_id, key.flow_id
            );
        }
    }

    /// Select the given identity verification in this view.
    pub fn select_identity_verification(&self, verification: IdentityVerification) {
        self.select_item(Some(verification));
    }

    fn toggle_room_search(&self) {
        let room_search = self.imp().sidebar.room_search_bar();
        room_search.set_search_mode(!room_search.is_search_mode());
    }

    /// Returns the parent GtkWindow containing this widget.
    fn parent_window(&self) -> Option<Window> {
        self.root().and_downcast()
    }

    fn show_room_creation_dialog(&self) {
        let Some(session) = self.session() else {
            return;
        };

        let dialog = RoomCreation::new(&session);
        dialog.present(self);
    }

    async fn show_create_dm_dialog(&self) {
        let Some(session) = self.session() else {
            return;
        };

        let dialog = CreateDmDialog::new(&session);
        dialog.start_direct_chat(self).await;
    }

    /// Offer to the user to join a room.
    ///
    /// If no room URI is provided, the user will have to enter one.
    pub fn show_join_room_dialog(&self, room_uri: Option<MatrixRoomIdUri>) {
        let Some(session) = self.session() else {
            return;
        };

        if let Some(room_uri) = &room_uri {
            if self.select_room_if_exists(&room_uri.id) {
                return;
            }
        }

        let dialog = JoinRoomDialog::new(&session);

        if let Some(uri) = room_uri {
            dialog.set_uri(uri);
        }

        dialog.present(self);
    }

    pub fn handle_paste_action(&self) {
        self.imp().content.handle_paste_action();
    }

    /// Show the content of the session
    pub fn show_content(&self) {
        let imp = self.imp();

        imp.stack.set_visible_child(&*imp.overlay);

        if let Some(window) = self.parent_window() {
            window.show_selected_session();
        }
    }

    /// Show a media event.
    pub fn show_media(&self, event: &Event, source_widget: &impl IsA<gtk::Widget>) {
        let Some(message) = event.message() else {
            error!("Trying to open the media viewer with an event that is not a message");
            return;
        };

        let imp = self.imp();
        imp.media_viewer
            .set_message(&event.room(), event.event_id().unwrap(), message);
        imp.media_viewer.reveal(source_widget);
    }

    /// Show the profile of the given user.
    pub fn show_user_profile_dialog(&self, user_id: OwnedUserId) {
        let Some(session) = self.session() else {
            return;
        };

        let dialog = UserProfileDialog::new();
        dialog.load_user(&session, user_id);
        dialog.present(self);
    }

    /// Withdraw the notifications for the currently selected item.
    fn withdraw_selected_item_notifications(&self) {
        let Some(session) = self.session() else {
            return;
        };
        let Some(item) = self.selected_item() else {
            return;
        };

        let notifications = session.notifications();

        if let Some(room) = item.downcast_ref::<Room>() {
            notifications.withdraw_all_for_room(room.room_id());
        } else if let Some(verification) = item.downcast_ref::<IdentityVerification>() {
            notifications.withdraw_identity_verification(&verification.key());
        }
    }
}