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
use adw::subclass::prelude::*;
use gtk::{glib, glib::clone, prelude::*, CompositeTemplate};
use tracing::error;

mod user_session_row;

use self::user_session_row::UserSessionRow;
use crate::{
    session::model::{User, UserSession, UserSessionsList},
    utils::{BoundObject, LoadingState},
};

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/account_settings/user_sessions_page/mod.ui"
    )]
    #[properties(wrapper_type = super::UserSessionsPage)]
    pub struct UserSessionsPage {
        #[template_child]
        pub stack: TemplateChild<gtk::Stack>,
        #[template_child]
        pub current_session_group: TemplateChild<adw::PreferencesGroup>,
        #[template_child]
        pub current_session: TemplateChild<gtk::ListBox>,
        #[template_child]
        pub other_sessions_group: TemplateChild<adw::PreferencesGroup>,
        #[template_child]
        pub other_sessions: TemplateChild<gtk::ListBox>,
        /// The list of user sessions.
        #[property(get, set = Self::set_user_sessions, explicit_notify, nullable)]
        pub user_sessions: BoundObject<UserSessionsList>,
        other_sessions_handler: RefCell<Option<glib::SignalHandlerId>>,
    }

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

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

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

    #[glib::derived_properties]
    impl ObjectImpl for UserSessionsPage {
        fn dispose(&self) {
            if let Some(user_sessions) = self.user_sessions.obj() {
                if let Some(handler) = self.other_sessions_handler.take() {
                    user_sessions.other_sessions().disconnect(handler);
                }
            }

            // AdwPreferencesPage doesn't handle children other than AdwPreferencesGroup.
            self.stack.unparent();
        }
    }

    impl WidgetImpl for UserSessionsPage {}
    impl PreferencesPageImpl for UserSessionsPage {}

    impl UserSessionsPage {
        /// Set the list of user sessions.
        fn set_user_sessions(&self, user_sessions: Option<UserSessionsList>) {
            let prev_user_sessions = self.user_sessions.obj();

            if prev_user_sessions == user_sessions {
                return;
            }

            if let Some(user_sessions) = prev_user_sessions {
                if let Some(handler) = self.other_sessions_handler.take() {
                    user_sessions.other_sessions().disconnect(handler);
                }
            }
            self.user_sessions.disconnect_signals();

            if let Some(user_sessions) = user_sessions {
                let other_sessions = user_sessions.other_sessions();

                self.other_sessions
                    .bind_model(Some(&other_sessions), |item| {
                        let Some(user_session) = item.downcast_ref::<UserSession>() else {
                            error!("Did not get a user session as an item of user session list");
                            return adw::Bin::new().upcast();
                        };

                        UserSessionRow::new(user_session).upcast()
                    });

                let other_sessions_handler = other_sessions.connect_items_changed(clone!(
                    #[weak(rename_to = imp)]
                    self,
                    move |other_sessions, _, _, _| {
                        imp.other_sessions_group
                            .set_visible(other_sessions.n_items() > 0);
                    }
                ));
                self.other_sessions_handler
                    .replace(Some(other_sessions_handler));
                self.other_sessions_group
                    .set_visible(other_sessions.n_items() > 0);

                let loading_state_handler = user_sessions.connect_loading_state_notify(clone!(
                    #[weak(rename_to = imp)]
                    self,
                    move |_| {
                        imp.update_state();
                    }
                ));
                let is_empty_handler = user_sessions.connect_is_empty_notify(clone!(
                    #[weak(rename_to = imp)]
                    self,
                    move |_| {
                        imp.update_state();
                    }
                ));
                let current_session_handler = user_sessions.connect_current_session_notify(clone!(
                    #[weak(rename_to = imp)]
                    self,
                    move |_| {
                        imp.update_current_session();
                    }
                ));

                self.user_sessions.set(
                    user_sessions,
                    vec![
                        loading_state_handler,
                        is_empty_handler,
                        current_session_handler,
                    ],
                );
            } else {
                self.other_sessions.unbind_model();
            }

            self.obj().notify_user_sessions();

            self.update_current_session();
            self.update_state();
        }

        /// Update the state of the UI according to the current state.
        fn update_state(&self) {
            let (is_empty, state) = self
                .user_sessions
                .obj()
                .map(|s| (s.is_empty(), s.loading_state()))
                .unwrap_or((true, LoadingState::Loading));

            let page = if is_empty {
                match state {
                    LoadingState::Error | LoadingState::Ready => "error",
                    _ => "loading",
                }
            } else {
                "list"
            };
            self.stack.set_visible_child_name(page);
        }

        /// Update the section about the current session.
        fn update_current_session(&self) {
            if let Some(child) = self.current_session.first_child() {
                self.current_session.remove(&child);
            }

            let current_session = self.user_sessions.obj().and_then(|s| s.current_session());
            let Some(current_session) = current_session else {
                self.current_session_group.set_visible(false);
                return;
            };

            self.current_session
                .append(&UserSessionRow::new(&current_session));
            self.current_session_group.set_visible(true);
        }
    }
}

glib::wrapper! {
    /// User sessions page.
    pub struct UserSessionsPage(ObjectSubclass<imp::UserSessionsPage>)
        @extends gtk::Widget, gtk::Window, adw::Window, adw::PreferencesWindow, @implements gtk::Accessible;
}

#[gtk::template_callbacks]
impl UserSessionsPage {
    pub fn new(user: &User) -> Self {
        glib::Object::builder().property("user", user).build()
    }

    /// Reload the user sessions list.
    #[template_callback]
    async fn reload_list(&self) {
        let Some(user_sessions) = self.user_sessions() else {
            return;
        };

        user_sessions.load().await;
    }
}