src/config.rs

0e0a16c77efc019eea79a30eb91f69e5e30d1fbe
weechat-matrix-rs/src/config.rs history · blame · raw

236 lines · 6080 bytes

  1//! Configuration module
  2//!
  3//! This is the global plugin configuration.
  4//!
  5//! Configuration options should be split out into different sections:
  6//!
  7//! * network
  8//! * look
  9//! * color
 10//! * server
 11//!
 12//! The server config options are added in the server.rs file.
 13//!
 14//! The config options created here will be alive as long as the plugin is
 15//! loaded so they don't need to be freed manually. The drop implementation of
 16//! the section will do so.
 17
 18use std::{
 19    cell::{Ref, RefCell, RefMut},
 20    rc::Rc,
 21};
 22
 23use strum_macros::EnumVariantNames;
 24use weechat::{
 25    config,
 26    config::{
 27        Conf, ConfigSection, ConfigSectionSettings, OptionChanged,
 28        SectionReadCallback,
 29    },
 30    Weechat,
 31};
 32
 33use crate::{MatrixServer, Servers};
 34
 35#[derive(EnumVariantNames)]
 36#[strum(serialize_all = "kebab_case")]
 37pub enum RedactionStyle {
 38    StrikeThrough,
 39    Delete,
 40    Notice,
 41}
 42
 43impl Default for RedactionStyle {
 44    fn default() -> Self {
 45        RedactionStyle::StrikeThrough
 46    }
 47}
 48
 49impl From<i32> for RedactionStyle {
 50    fn from(value: i32) -> Self {
 51        match value {
 52            0 => RedactionStyle::StrikeThrough,
 53            1 => RedactionStyle::Delete,
 54            2 => RedactionStyle::Notice,
 55            _ => unreachable!(),
 56        }
 57    }
 58}
 59
 60#[derive(EnumVariantNames)]
 61#[strum(serialize_all = "kebab_case")]
 62pub enum ServerBuffer {
 63    MergeWithCore,
 64    MergeWithoutCore,
 65    Independent,
 66}
 67
 68impl Default for ServerBuffer {
 69    fn default() -> Self {
 70        ServerBuffer::MergeWithCore
 71    }
 72}
 73
 74impl From<i32> for ServerBuffer {
 75    fn from(value: i32) -> Self {
 76        match value {
 77            0 => ServerBuffer::MergeWithCore,
 78            1 => ServerBuffer::MergeWithoutCore,
 79            2 => ServerBuffer::Independent,
 80            _ => unreachable!(),
 81        }
 82    }
 83}
 84
 85config!(
 86    "matrix-rust",
 87    Section look {
 88        encrypted_room_sign: String {
 89            // Description.
 90            "A sign that is used to show that the current room is encrypted",
 91            // Default value.
 92            "🔒",
 93        },
 94
 95        public_room_sign: String {
 96            // Description.
 97            "A sign indicating that the current room is public",
 98            // Default value.
 99            "🌍",
100        },
101
102        busy_sign: String {
103            // Description.
104            "A sign that is used to show that the client is busy, \
105                e.g. when room history is being fetched",
106            // Default value.
107            "⏳",
108        },
109
110        local_echo: bool {
111            // Description
112            "Should the sending message be printed out before the server \
113             confirms the reception of the message",
114             // Default value
115             true,
116        },
117
118        redaction_style: Enum {
119            // Description
120            "The style that should be used when a message needs to be redacted",
121            RedactionStyle,
122        },
123
124        server_buffer: Enum {
125            // Description
126            "Should the server buffer be merged with other buffers or independent",
127            ServerBuffer,
128        },
129
130    },
131    Section network {
132        debug_buffer: bool {
133            // Description
134            "Use a separate buffer for debug logs",
135            // Default value.
136            false,
137        },
138    }
139);
140
141/// A wrapper for our config struct that can be cloned around.
142#[derive(Clone)]
143pub struct ConfigHandle {
144    pub inner: Rc<RefCell<Config>>,
145    servers: Servers,
146}
147
148impl ConfigHandle {
149    /// Create a new config and wrap it in our config handle.
150    pub fn new(servers: &Servers) -> ConfigHandle {
151        let config = Config::new().expect("Can't create new config");
152
153        let config = ConfigHandle {
154            inner: Rc::new(RefCell::new(config)),
155            servers: servers.clone(),
156        };
157
158        // The server section is special since it has a custom section read and
159        // write implementations to support subsections for every configured
160        // server.
161        let server_section_options = ConfigSectionSettings::new("server")
162            .set_write_callback(
163                |_weechat: &Weechat,
164                 config: &Conf,
165                 section: &mut ConfigSection| {
166                    config.write_section(section.name());
167                    for option in section.options() {
168                        config.write_option(option);
169                    }
170                },
171            )
172            .set_read_callback(config.clone());
173
174        {
175            let mut config_borrow = config.borrow_mut();
176
177            config_borrow
178                .new_section(server_section_options)
179                .expect("Can't create server section");
180        }
181
182        config
183    }
184
185    pub fn borrow(&self) -> Ref<'_, Config> {
186        self.inner.borrow()
187    }
188
189    pub fn borrow_mut(&self) -> RefMut<'_, Config> {
190        self.inner.borrow_mut()
191    }
192}
193
194impl SectionReadCallback for ConfigHandle {
195    fn callback(
196        &mut self,
197        _: &Weechat,
198        _: &Conf,
199        section: &mut ConfigSection,
200        option_name: &str,
201        option_value: &str,
202    ) -> OptionChanged {
203        if option_name.is_empty() {
204            return OptionChanged::Error;
205        }
206
207        let option_args: Vec<&str> = option_name.splitn(2, '.').collect();
208
209        if option_args.len() != 2 {
210            return OptionChanged::Error;
211        }
212
213        let server_name = option_args[0];
214
215        // We are reading the config, if the server doesn't yet exists
216        // we need to create it before setting the option and running
217        // the option change callback.
218        if !self.servers.contains(server_name) {
219            let server = MatrixServer::new(
220                server_name,
221                &self,
222                section,
223                self.servers.clone(),
224            );
225            self.servers.insert(server);
226        }
227
228        let option = section.search_option(option_name);
229
230        if let Some(o) = option {
231            o.set(option_value, true)
232        } else {
233            OptionChanged::NotFound
234        }
235    }
236}