src/config.rs

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

264 lines · 7175 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, ConfigOption, ConfigSection, ConfigSectionSettings,
 28        IntegerOptionSettings, OptionChanged, 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    Section network {
125        debug_buffer: bool {
126            // Description
127            "Use a separate buffer for debug logs",
128            // Default value.
129            false,
130        },
131    }
132);
133
134/// A wrapper for our config struct that can be cloned around.
135#[derive(Clone)]
136pub struct ConfigHandle {
137    pub inner: Rc<RefCell<Config>>,
138    servers: Servers,
139}
140
141impl ConfigHandle {
142    /// Create a new config and wrap it in our config handle.
143    pub fn new(servers: &Servers) -> ConfigHandle {
144        let config = Config::new().expect("Can't create new config");
145
146        let config = ConfigHandle {
147            inner: Rc::new(RefCell::new(config)),
148            servers: servers.clone(),
149        };
150
151        // The server section is special since it has a custom section read and
152        // write implementations to support subsections for every configured
153        // server.
154        let server_section_options = ConfigSectionSettings::new("server")
155            .set_write_callback(
156                |_weechat: &Weechat,
157                 config: &Conf,
158                 section: &mut ConfigSection| {
159                    config.write_section(section.name());
160                    for option in section.options() {
161                        config.write_option(option);
162                    }
163                },
164            )
165            .set_read_callback(config.clone());
166
167        {
168            let mut config_borrow = config.borrow_mut();
169
170            config_borrow
171                .new_section(server_section_options)
172                .expect("Can't create server section");
173
174            let mut look_section = config_borrow.look_mut();
175
176            let servers = servers.clone();
177
178            let settings = IntegerOptionSettings::new("server_buffer")
179                .description("Should the server buffer be merged with other buffers or independent")
180                .set_change_callback(move |_, _| {
181                    for server in servers.borrow().values() {
182                        server.merge_server_buffers();
183                    }
184                })
185                .default_value(ServerBuffer::default() as i32)
186                .string_values(
187                    ServerBuffer::VARIANTS
188                        .iter()
189                        .map(|v| v.to_string())
190                        .collect::<Vec<String>>(),
191                );
192
193            look_section
194                .new_integer_option(settings)
195                .expect("Can't create server buffers option");
196        }
197
198        config
199    }
200
201    pub fn borrow(&self) -> Ref<'_, Config> {
202        self.inner.borrow()
203    }
204
205    pub fn borrow_mut(&self) -> RefMut<'_, Config> {
206        self.inner.borrow_mut()
207    }
208}
209
210impl<'a> LookSection<'a> {
211    pub fn server_buffer(&self) -> ServerBuffer {
212        if let ConfigOption::Integer(o) =
213            self.search_option("server_buffer").unwrap()
214        {
215            ServerBuffer::from(o.value())
216        } else {
217            panic!("Server buffer option has the wrong type");
218        }
219    }
220}
221
222impl SectionReadCallback for ConfigHandle {
223    fn callback(
224        &mut self,
225        _: &Weechat,
226        _: &Conf,
227        section: &mut ConfigSection,
228        option_name: &str,
229        option_value: &str,
230    ) -> OptionChanged {
231        if option_name.is_empty() {
232            return OptionChanged::Error;
233        }
234
235        let option_args: Vec<&str> = option_name.splitn(2, '.').collect();
236
237        if option_args.len() != 2 {
238            return OptionChanged::Error;
239        }
240
241        let server_name = option_args[0];
242
243        // We are reading the config, if the server doesn't yet exists
244        // we need to create it before setting the option and running
245        // the option change callback.
246        if !self.servers.contains(server_name) {
247            let server = MatrixServer::new(
248                server_name,
249                &self,
250                section,
251                self.servers.clone(),
252            );
253            self.servers.insert(server);
254        }
255
256        let option = section.search_option(option_name);
257
258        if let Some(o) = option {
259            o.set(option_value, true)
260        } else {
261            OptionChanged::NotFound
262        }
263    }
264}