src/config.rs
116 lines · 3274 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.
17use crate::{MatrixServer, Servers};
18use weechat::config::{
19 Conf, ConfigSection, ConfigSectionSettings, OptionChanged,
20 SectionReadCallback,
21};
22use weechat::Weechat;
23
24use std::cell::{Ref, RefCell, RefMut};
25use std::rc::Rc;
26
27#[derive(Clone)]
28pub struct Config {
29 inner: Rc<RefCell<weechat::config::Config>>,
30 servers: Servers,
31}
32
33impl SectionReadCallback for Config {
34 fn callback(
35 &mut self,
36 _: &Weechat,
37 _: &Conf,
38 section: &mut ConfigSection,
39 option_name: &str,
40 option_value: &str,
41 ) -> OptionChanged {
42 if option_name.is_empty() {
43 return OptionChanged::Error;
44 }
45
46 let option_args: Vec<&str> = option_name.splitn(2, '.').collect();
47
48 if option_args.len() != 2 {
49 return OptionChanged::Error;
50 }
51
52 let server_name = option_args[0];
53
54 {
55 let mut servers_borrow = self.servers.borrow_mut();
56
57 // We are reading the config, if the server doesn't yet exists
58 // we need to create it before setting the option and running
59 // the option change callback.
60 if !servers_borrow.contains_key(server_name) {
61 let server = MatrixServer::new(server_name, &self, section);
62 servers_borrow.insert(server_name.to_owned(), server);
63 }
64 }
65
66 let option = section.search_option(option_name);
67
68 if let Some(o) = option {
69 o.set(option_value, true)
70 } else {
71 OptionChanged::NotFound
72 }
73 }
74}
75
76impl Config {
77 pub fn new(_weechat: &Weechat, servers: &Servers) -> Config {
78 let config = Weechat::config_new("matrix-rust")
79 .expect("Can't create new config");
80
81 let config = Config {
82 inner: Rc::new(RefCell::new(config)),
83 servers: servers.clone(),
84 };
85
86 let server_section_options = ConfigSectionSettings::new("server")
87 .set_write_callback(
88 |_weechat: &Weechat,
89 config: &Conf,
90 section: &mut ConfigSection| {
91 config.write_section(section.name());
92 for option in section.options() {
93 config.write_option(option);
94 }
95 },
96 )
97 .set_read_callback(config.clone());
98 {
99 let mut config_borrow = config.borrow_mut();
100
101 config_borrow
102 .new_section(server_section_options)
103 .expect("Can't create server section");
104 }
105
106 config
107 }
108
109 pub fn borrow(&self) -> Ref<'_, weechat::config::Config> {
110 self.inner.borrow()
111 }
112
113 pub fn borrow_mut(&self) -> RefMut<'_, weechat::config::Config> {
114 self.inner.borrow_mut()
115 }
116}