src/config.rs
380 lines · 11114 bytes
10 symbols in this file
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 reply_full_quote_threshold: Integer {
141 // Description
142 "Render replies to recently printed events on one line when this \
143 value is positive. The default 0 keeps the Matrix reply fallback \
144 quote when available",
145 // Default value.
146 0,
147 // Range: quote-preserving default to a large scrollback window.
148 0..100000,
149 },
150
151 nick_format: String {
152 // Description.
153 "Format for Matrix member nicks. Supported placeholders: %d for \
154 display name, %m for full MXID, %u for MXID localpart, and %h \
155 for MXID homeserver",
156 // Default value.
157 "%d",
158 },
159 },
160
161 Section color {
162 nick_prefix_admin: Color {
163 // Description.
164 "Color for the admin nick prefix (&)",
165 // Default value.
166 "lightgreen",
167 },
168
169 nick_prefix_moderator: Color {
170 // Description.
171 "Color for the moderator nick prefix (@)",
172 // Default value.
173 "lightmagenta",
174 },
175
176 nick_prefix_power: Color {
177 // Description.
178 "Color for the nick prefix (+) used by users with a non-default \
179 power level below moderator",
180 // Default value.
181 "yellow",
182 },
183 },
184
185 Section network {
186 debug_buffer: bool {
187 // Description
188 "Use a separate buffer for debug logs",
189 // Default value.
190 false,
191 },
192
193 send_read_receipts: bool {
194 // Description
195 "Send public read receipts when marking a room as read",
196 // Default value.
197 true,
198 },
199 },
200
201 Section input {
202 markdown_input: bool {
203 // Description
204 "Should the input be parsed as markdown",
205 // Default value.
206 true,
207 },
208 },
209
210 Section media {
211 download_prefix: String {
212 // Description.
213 "Prefix prepended to default media download filenames. The value \
214 may include a directory, and supports ~, $XDG_STATE_HOME, and \
215 ${XDG_STATE_HOME}",
216 // Default value.
217 "matrix-media-",
218 },
219 },
220);
221
222/// A wrapper for our config struct that can be cloned around.
223#[derive(Clone)]
224pub struct ConfigHandle {
225 pub inner: Rc<RefCell<Config>>,
226 servers: Servers,
227}
228
229impl ConfigHandle {
230 /// Create a new config and wrap it in our config handle.
231 pub fn new(servers: &Servers) -> ConfigHandle {
232 let config = Config::new().expect("Can't create new config");
233
234 let config = ConfigHandle {
235 inner: Rc::new(RefCell::new(config)),
236 servers: servers.clone(),
237 };
238
239 // The server section is special since it has a custom section read and
240 // write implementations to support subsections for every configured
241 // server.
242 let server_section_options = ConfigSectionSettings::new("server")
243 .set_write_callback(
244 |_weechat: &Weechat,
245 config: &Conf,
246 section: &mut ConfigSection| {
247 let mut options = section.options();
248 options.sort_by(|a, b| a.name().cmp(&b.name()));
249
250 config.write_section(section.name());
251 for option in options {
252 config.write_option(option);
253 }
254 },
255 )
256 .set_read_callback(config.clone());
257
258 {
259 let mut config_borrow = config.borrow_mut();
260
261 config_borrow
262 .new_section(server_section_options)
263 .expect("Can't create server section");
264
265 let mut look_section = config_borrow.look_mut();
266
267 let servers = servers.clone();
268
269 #[cfg(weechat410)]
270 {
271 let settings = IntegerOptionSettings::new("server_buffer")
272 .description("Should the server buffer be merged with other buffers or independent")
273 .set_change_callback(move |_, _| {
274 for server in servers.borrow().values() {
275 server.merge_server_buffers();
276 }
277 })
278 .default_value(ServerBuffer::default() as i32)
279 .string_values(
280 ServerBuffer::VARIANTS
281 .iter()
282 .map(|v| v.to_string())
283 .collect::<Vec<String>>(),
284 );
285
286 look_section
287 .new_integer_option(settings)
288 .expect("Can't create server buffers option");
289 }
290
291 #[cfg(not(weechat410))]
292 {
293 let settings = EnumOptionSettings::new("server_buffer")
294 .description("Should the server buffer be merged with other buffers or independent")
295 .set_change_callback(move |_, _| {
296 for server in servers.borrow().values() {
297 server.merge_server_buffers();
298 }
299 })
300 .default_value(ServerBuffer::default() as i32)
301 .string_values(
302 ServerBuffer::VARIANTS
303 .iter()
304 .map(|v| v.to_string())
305 .collect::<Vec<String>>(),
306 );
307
308 look_section
309 .new_enum_option(settings)
310 .expect("Can't create server buffers option");
311 }
312 }
313
314 config
315 }
316
317 pub fn borrow(&self) -> Ref<'_, Config> {
318 self.inner.borrow()
319 }
320
321 pub fn borrow_mut(&self) -> RefMut<'_, Config> {
322 self.inner.borrow_mut()
323 }
324}
325
326impl LookSection<'_> {
327 pub fn server_buffer(&self) -> ServerBuffer {
328 match self.search_option("server_buffer").unwrap() {
329 #[cfg(weechat410)]
330 ConfigOption::Integer(o) => ServerBuffer::from(o.value()),
331 #[cfg(not(weechat410))]
332 ConfigOption::Enum(o) => ServerBuffer::from(o.value()),
333 _ => panic!("Server buffer option has the wrong type"),
334 }
335 }
336}
337
338impl SectionReadCallback for ConfigHandle {
339 fn callback(
340 &mut self,
341 _: &Weechat,
342 _: &Conf,
343 section: &mut ConfigSection,
344 option_name: &str,
345 option_value: &str,
346 ) -> OptionChanged {
347 if option_name.is_empty() {
348 return OptionChanged::Error;
349 }
350
351 let option_args: Vec<&str> = option_name.splitn(2, '.').collect();
352
353 if option_args.len() != 2 {
354 return OptionChanged::Error;
355 }
356
357 let server_name = option_args[0];
358
359 // We are reading the config, if the server doesn't yet exists
360 // we need to create it before setting the option and running
361 // the option change callback.
362 if !self.servers.contains(server_name) {
363 let server = MatrixServer::new(
364 server_name,
365 self,
366 section,
367 self.servers.clone(),
368 );
369 self.servers.insert(server);
370 }
371
372 let option = section.search_option(option_name);
373
374 if let Some(o) = option {
375 o.set(option_value, true)
376 } else {
377 OptionChanged::NotFound
378 }
379 }
380}