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