src/config.rs

8454dcd1674dfb48ab4ee615134e2d4d5fc04fa7
weechat-matrix-rs/src/config.rs history · blame · raw

360 lines · 10381 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::{EnumVariantNames, VariantNames};
 24use weechat::{
 25    config,
 26    config::{
 27        Conf, ConfigOption, ConfigSection, ConfigSectionSettings,
 28        OptionChanged, SectionReadCallback,
 29    },
 30    Weechat,
 31};
 32
 33#[cfg(weechat410)]
 34use weechat::config::IntegerOptionSettings;
 35
 36#[cfg(not(weechat410))]
 37use weechat::config::EnumOptionSettings;
 38
 39use crate::{MatrixServer, Servers};
 40
 41#[derive(EnumVariantNames)]
 42#[strum(serialize_all = "kebab_case")]
 43#[derive(Default)]
 44pub enum RedactionStyle {
 45    #[default]
 46    StrikeThrough,
 47    Delete,
 48    Notice,
 49}
 50
 51impl From<i32> for RedactionStyle {
 52    fn from(value: i32) -> Self {
 53        match value {
 54            0 => RedactionStyle::StrikeThrough,
 55            1 => RedactionStyle::Delete,
 56            2 => RedactionStyle::Notice,
 57            _ => unreachable!(),
 58        }
 59    }
 60}
 61
 62#[derive(EnumVariantNames)]
 63#[strum(serialize_all = "kebab_case")]
 64#[derive(Default)]
 65pub enum ServerBuffer {
 66    #[default]
 67    MergeWithCore,
 68    MergeWithoutCore,
 69    Independent,
 70}
 71
 72impl From<i32> for ServerBuffer {
 73    fn from(value: i32) -> Self {
 74        match value {
 75            0 => ServerBuffer::MergeWithCore,
 76            1 => ServerBuffer::MergeWithoutCore,
 77            2 => ServerBuffer::Independent,
 78            _ => unreachable!(),
 79        }
 80    }
 81}
 82
 83config!(
 84    "matrix-rust",
 85
 86    Section look {
 87        encrypted_room_sign: String {
 88            // Description.
 89            "A sign that is used to show that the current room is encrypted",
 90            // Default value.
 91            "🔒",
 92        },
 93
 94        encryption_warning_sign: String {
 95            // Description.
 96            "A sign that is used to show that the current room contains unverified devices",
 97            // Default value.
 98            "❗",
 99        },
100
101        public_room_sign: String {
102            // Description.
103            "A sign indicating that the current room is public",
104            // Default value.
105            "🌍",
106        },
107
108        busy_sign: String {
109            // Description.
110            "A sign that is used to show that the client is busy, \
111                e.g. when room history is being fetched",
112            // Default value.
113            "⏳",
114        },
115
116        local_echo: bool {
117            // Description
118            "Should the sending message be printed out before the server \
119             confirms the reception of the message",
120             // Default value
121             true,
122        },
123
124        redaction_style: Enum {
125            // Description
126            "The style that should be used when a message needs to be redacted",
127            RedactionStyle,
128        },
129
130        smart_filter_delay: Integer {
131            // Description
132            "How long a room member can be inactive, in milliseconds, before \
133             membership events from them get the matrix_smart_filter tag",
134            // Default value.
135            300000,
136            // Range: 0 ms to one day.
137            0..86400000,
138        },
139    },
140
141    Section color {
142        nick_prefix_admin: Color {
143            // Description.
144            "Color for the admin nick prefix (&)",
145            // Default value.
146            "lightgreen",
147        },
148
149        nick_prefix_moderator: Color {
150            // Description.
151            "Color for the moderator nick prefix (@)",
152            // Default value.
153            "lightmagenta",
154        },
155
156        nick_prefix_power: Color {
157            // Description.
158            "Color for the nick prefix (+) used by users with a non-default \
159             power level below moderator",
160            // Default value.
161            "yellow",
162        },
163    },
164
165    Section network {
166        debug_buffer: bool {
167            // Description
168            "Use a separate buffer for debug logs",
169            // Default value.
170            false,
171        },
172
173        send_read_receipts: bool {
174            // Description
175            "Send public read receipts when marking a room as read",
176            // Default value.
177            true,
178        },
179    },
180
181    Section input {
182        markdown_input: bool {
183            // Description
184            "Should the input be parsed as markdown",
185            // Default value.
186            true,
187        },
188    },
189
190    Section media {
191        download_prefix: String {
192            // Description.
193            "Prefix prepended to default media download filenames. The value \
194             may include a directory, and supports ~, $XDG_STATE_HOME, and \
195             ${XDG_STATE_HOME}",
196            // Default value.
197            "matrix-media-",
198        },
199    },
200);
201
202/// A wrapper for our config struct that can be cloned around.
203#[derive(Clone)]
204pub struct ConfigHandle {
205    pub inner: Rc<RefCell<Config>>,
206    servers: Servers,
207}
208
209impl ConfigHandle {
210    /// Create a new config and wrap it in our config handle.
211    pub fn new(servers: &Servers) -> ConfigHandle {
212        let config = Config::new().expect("Can't create new config");
213
214        let config = ConfigHandle {
215            inner: Rc::new(RefCell::new(config)),
216            servers: servers.clone(),
217        };
218
219        // The server section is special since it has a custom section read and
220        // write implementations to support subsections for every configured
221        // server.
222        let server_section_options = ConfigSectionSettings::new("server")
223            .set_write_callback(
224                |_weechat: &Weechat,
225                 config: &Conf,
226                 section: &mut ConfigSection| {
227                    let mut options = section.options();
228                    options.sort_by(|a, b| a.name().cmp(&b.name()));
229
230                    config.write_section(section.name());
231                    for option in options {
232                        config.write_option(option);
233                    }
234                },
235            )
236            .set_read_callback(config.clone());
237
238        {
239            let mut config_borrow = config.borrow_mut();
240
241            config_borrow
242                .new_section(server_section_options)
243                .expect("Can't create server section");
244
245            let mut look_section = config_borrow.look_mut();
246
247            let servers = servers.clone();
248
249            #[cfg(weechat410)]
250            {
251                let settings = IntegerOptionSettings::new("server_buffer")
252                    .description("Should the server buffer be merged with other buffers or independent")
253                    .set_change_callback(move |_, _| {
254                        for server in servers.borrow().values() {
255                            server.merge_server_buffers();
256                        }
257                    })
258                    .default_value(ServerBuffer::default() as i32)
259                    .string_values(
260                        ServerBuffer::VARIANTS
261                            .iter()
262                            .map(|v| v.to_string())
263                            .collect::<Vec<String>>(),
264                    );
265
266                look_section
267                    .new_integer_option(settings)
268                    .expect("Can't create server buffers option");
269            }
270
271            #[cfg(not(weechat410))]
272            {
273                let settings = EnumOptionSettings::new("server_buffer")
274                    .description("Should the server buffer be merged with other buffers or independent")
275                    .set_change_callback(move |_, _| {
276                        for server in servers.borrow().values() {
277                            server.merge_server_buffers();
278                        }
279                    })
280                    .default_value(ServerBuffer::default() as i32)
281                    .string_values(
282                        ServerBuffer::VARIANTS
283                            .iter()
284                            .map(|v| v.to_string())
285                            .collect::<Vec<String>>(),
286                    );
287
288                look_section
289                    .new_enum_option(settings)
290                    .expect("Can't create server buffers option");
291            }
292        }
293
294        config
295    }
296
297    pub fn borrow(&self) -> Ref<'_, Config> {
298        self.inner.borrow()
299    }
300
301    pub fn borrow_mut(&self) -> RefMut<'_, Config> {
302        self.inner.borrow_mut()
303    }
304}
305
306impl LookSection<'_> {
307    pub fn server_buffer(&self) -> ServerBuffer {
308        match self.search_option("server_buffer").unwrap() {
309            #[cfg(weechat410)]
310            ConfigOption::Integer(o) => ServerBuffer::from(o.value()),
311            #[cfg(not(weechat410))]
312            ConfigOption::Enum(o) => ServerBuffer::from(o.value()),
313            _ => panic!("Server buffer option has the wrong type"),
314        }
315    }
316}
317
318impl SectionReadCallback for ConfigHandle {
319    fn callback(
320        &mut self,
321        _: &Weechat,
322        _: &Conf,
323        section: &mut ConfigSection,
324        option_name: &str,
325        option_value: &str,
326    ) -> OptionChanged {
327        if option_name.is_empty() {
328            return OptionChanged::Error;
329        }
330
331        let option_args: Vec<&str> = option_name.splitn(2, '.').collect();
332
333        if option_args.len() != 2 {
334            return OptionChanged::Error;
335        }
336
337        let server_name = option_args[0];
338
339        // We are reading the config, if the server doesn't yet exists
340        // we need to create it before setting the option and running
341        // the option change callback.
342        if !self.servers.contains(server_name) {
343            let server = MatrixServer::new(
344                server_name,
345                self,
346                section,
347                self.servers.clone(),
348            );
349            self.servers.insert(server);
350        }
351
352        let option = section.search_option(option_name);
353
354        if let Some(o) = option {
355            o.set(option_value, true)
356        } else {
357            OptionChanged::NotFound
358        }
359    }
360}