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
use gtk::{glib, prelude::*, subclass::prelude::*};
use indexmap::{IndexMap, IndexSet};
use tracing::error;

use crate::{
    secret::SESSION_ID_LENGTH,
    session::model::{SessionSettings, StoredSessionSettings},
    Application,
};

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

    use super::*;

    #[derive(Debug, Default)]
    pub struct SessionListSettings {
        /// The settings of the sessions.
        pub sessions: RefCell<IndexMap<String, SessionSettings>>,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for SessionListSettings {
        const NAME: &'static str = "SessionListSettings";
        type Type = super::SessionListSettings;
    }

    impl ObjectImpl for SessionListSettings {}
}

glib::wrapper! {
    /// The settings of the list of sessions.
    pub struct SessionListSettings(ObjectSubclass<imp::SessionListSettings>);
}

impl SessionListSettings {
    /// Create a new `SessionListSettings`.
    pub fn new() -> Self {
        glib::Object::new()
    }

    /// Load these settings from the GSettings.
    pub fn load(&self) {
        let serialized = Application::default().settings().string("sessions");

        let stored_sessions =
            match serde_json::from_str::<Vec<(String, StoredSessionSettings)>>(&serialized) {
                Ok(stored_sessions) => stored_sessions,
                Err(error) => {
                    error!(
                        "Could not load sessions settings, fallback to default settings: {error}"
                    );
                    Default::default()
                }
            };

        // Do we need to update the settings?
        let mut needs_update = false;

        let sessions = stored_sessions
            .into_iter()
            .map(|(mut session_id, stored_session)| {
                // Session IDs have been truncated in version 6 of StoredSession.
                if session_id.len() > SESSION_ID_LENGTH {
                    session_id.truncate(SESSION_ID_LENGTH);
                    needs_update = true;
                }

                let session = SessionSettings::restore(&session_id, stored_session);
                (session_id, session)
            })
            .collect();

        self.imp().sessions.replace(sessions);

        if needs_update {
            self.save();
        }
    }

    /// Save the settings in the GSettings.
    pub fn save(&self) {
        let stored_sessions = self
            .imp()
            .sessions
            .borrow()
            .iter()
            .map(|(session_id, session)| (session_id.clone(), session.stored_settings()))
            .collect::<Vec<_>>();

        if let Err(error) = Application::default().settings().set_string(
            "sessions",
            &serde_json::to_string(&stored_sessions).unwrap(),
        ) {
            error!("Could not save sessions settings: {error}");
        }
    }

    /// Get or create the settings for the session with the given ID.
    pub fn get_or_create(&self, session_id: &str) -> SessionSettings {
        let sessions = &self.imp().sessions;

        if let Some(session) = sessions.borrow().get(session_id) {
            return session.clone();
        };

        let session = SessionSettings::new(session_id);
        sessions
            .borrow_mut()
            .insert(session_id.to_owned(), session.clone());
        self.save();

        session
    }

    /// Remove the settings of the session with the given ID.
    pub fn remove(&self, session_id: &str) {
        self.imp().sessions.borrow_mut().shift_remove(session_id);
        self.save();
    }

    /// Get the list of session IDs stored in these settings.
    pub fn session_ids(&self) -> IndexSet<String> {
        self.imp().sessions.borrow().keys().cloned().collect()
    }
}

impl Default for SessionListSettings {
    fn default() -> Self {
        Self::new()
    }
}