src/config.rs
329 lines · 9541 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 network {
142 debug_buffer: bool {
143 // Description
144 "Use a separate buffer for debug logs",
145 // Default value.
146 false,
147 },
148 },
149
150 Section input {
151 markdown_input: bool {
152 // Description
153 "Should the input be parsed as markdown",
154 // Default value.
155 true,
156 },
157 },
158
159 Section media {
160 download_prefix: String {
161 // Description.
162 "Prefix prepended to default media download filenames. The value \
163 may include a directory, and supports ~, $XDG_STATE_HOME, and \
164 ${XDG_STATE_HOME}",
165 // Default value.
166 "matrix-media-",
167 },
168 },
169);
170
171/// A wrapper for our config struct that can be cloned around.
172#[derive(Clone)]
173pub struct ConfigHandle {
174 pub inner: Rc<RefCell<Config>>,
175 servers: Servers,
176}
177
178impl ConfigHandle {
179 /// Create a new config and wrap it in our config handle.
180 pub fn new(servers: &Servers) -> ConfigHandle {
181 let config = Config::new().expect("Can't create new config");
182
183 let config = ConfigHandle {
184 inner: Rc::new(RefCell::new(config)),
185 servers: servers.clone(),
186 };
187
188 // The server section is special since it has a custom section read and
189 // write implementations to support subsections for every configured
190 // server.
191 let server_section_options = ConfigSectionSettings::new("server")
192 .set_write_callback(
193 |_weechat: &Weechat,
194 config: &Conf,
195 section: &mut ConfigSection| {
196 let mut options = section.options();
197 options.sort_by(|a, b| a.name().cmp(&b.name()));
198
199 config.write_section(section.name());
200 for option in options {
201 config.write_option(option);
202 }
203 },
204 )
205 .set_read_callback(config.clone());
206
207 {
208 let mut config_borrow = config.borrow_mut();
209
210 config_borrow
211 .new_section(server_section_options)
212 .expect("Can't create server section");
213
214 let mut look_section = config_borrow.look_mut();
215
216 let servers = servers.clone();
217
218 #[cfg(weechat410)]
219 {
220 let settings = IntegerOptionSettings::new("server_buffer")
221 .description("Should the server buffer be merged with other buffers or independent")
222 .set_change_callback(move |_, _| {
223 for server in servers.borrow().values() {
224 server.merge_server_buffers();
225 }
226 })
227 .default_value(ServerBuffer::default() as i32)
228 .string_values(
229 ServerBuffer::VARIANTS
230 .iter()
231 .map(|v| v.to_string())
232 .collect::<Vec<String>>(),
233 );
234
235 look_section
236 .new_integer_option(settings)
237 .expect("Can't create server buffers option");
238 }
239
240 #[cfg(not(weechat410))]
241 {
242 let settings = EnumOptionSettings::new("server_buffer")
243 .description("Should the server buffer be merged with other buffers or independent")
244 .set_change_callback(move |_, _| {
245 for server in servers.borrow().values() {
246 server.merge_server_buffers();
247 }
248 })
249 .default_value(ServerBuffer::default() as i32)
250 .string_values(
251 ServerBuffer::VARIANTS
252 .iter()
253 .map(|v| v.to_string())
254 .collect::<Vec<String>>(),
255 );
256
257 look_section
258 .new_enum_option(settings)
259 .expect("Can't create server buffers option");
260 }
261 }
262
263 config
264 }
265
266 pub fn borrow(&self) -> Ref<'_, Config> {
267 self.inner.borrow()
268 }
269
270 pub fn borrow_mut(&self) -> RefMut<'_, Config> {
271 self.inner.borrow_mut()
272 }
273}
274
275impl LookSection<'_> {
276 pub fn server_buffer(&self) -> ServerBuffer {
277 match self.search_option("server_buffer").unwrap() {
278 #[cfg(weechat410)]
279 ConfigOption::Integer(o) => ServerBuffer::from(o.value()),
280 #[cfg(not(weechat410))]
281 ConfigOption::Enum(o) => ServerBuffer::from(o.value()),
282 _ => panic!("Server buffer option has the wrong type"),
283 }
284 }
285}
286
287impl SectionReadCallback for ConfigHandle {
288 fn callback(
289 &mut self,
290 _: &Weechat,
291 _: &Conf,
292 section: &mut ConfigSection,
293 option_name: &str,
294 option_value: &str,
295 ) -> OptionChanged {
296 if option_name.is_empty() {
297 return OptionChanged::Error;
298 }
299
300 let option_args: Vec<&str> = option_name.splitn(2, '.').collect();
301
302 if option_args.len() != 2 {
303 return OptionChanged::Error;
304 }
305
306 let server_name = option_args[0];
307
308 // We are reading the config, if the server doesn't yet exists
309 // we need to create it before setting the option and running
310 // the option change callback.
311 if !self.servers.contains(server_name) {
312 let server = MatrixServer::new(
313 server_name,
314 self,
315 section,
316 self.servers.clone(),
317 );
318 self.servers.insert(server);
319 }
320
321 let option = section.search_option(option_name);
322
323 if let Some(o) = option {
324 o.set(option_value, true)
325 } else {
326 OptionChanged::NotFound
327 }
328 }
329}