Commit 3969a986f5

3969a986f55b8abe6d0226186a868f552466facd

parent: 14f04e7e5c

Unsigned

Damir Jelić <poljar@termina.org.uk> · 2020-06-25 18:44 UTC

config: Add macros to declaratively define a config.

Layout: unified · split

Cargo.lock +20
@@ -1160,6 +1160,25 @@ version = "1.0.1"
1160source = "registry+https://github.com/rust-lang/crates.io-index" 1160source = "registry+https://github.com/rust-lang/crates.io-index"
1161checksum = "9a7fad362df89617628a7508b3e9d588ade1b0ac31aa25de168193ad999c2dd4" 1161checksum = "9a7fad362df89617628a7508b3e9d588ade1b0ac31aa25de168193ad999c2dd4"
1162 1162
1163[[package]]
1164name = "paste"
1165version = "0.1.18"
1166source = "registry+https://github.com/rust-lang/crates.io-index"
1167checksum = "45ca20c77d80be666aef2b45486da86238fabe33e38306bd3118fe4af33fa880"
1168dependencies = [
1169 "paste-impl",
1170 "proc-macro-hack",
1171]
1172
1173[[package]]
1174name = "paste-impl"
1175version = "0.1.18"
1176source = "registry+https://github.com/rust-lang/crates.io-index"
1177checksum = "d95a7db200b97ef370c8e6de0088252f7e0dfff7d047a28528e47456c0fc98b6"
1178dependencies = [
1179 "proc-macro-hack",
1180]
1181
1163[[package]] 1182[[package]]
1164name = "peeking_take_while" 1183name = "peeking_take_while"
1165version = "0.1.2" 1184version = "0.1.2"
@@ -2306,6 +2325,7 @@ dependencies = [
2306 "clap", 2325 "clap",
2307 "libc", 2326 "libc",
2308 "matrix-sdk", 2327 "matrix-sdk",
2328 "paste",
2309 "tokio", 2329 "tokio",
2310 "tracing", 2330 "tracing",
2311 "tracing-subscriber", 2331 "tracing-subscriber",
Cargo.toml +1
@@ -18,6 +18,7 @@ tracing-subscriber = "0.2.6"
18async-std = { version = "1.6.2", features = [ "unstable" ] } 18async-std = { version = "1.6.2", features = [ "unstable" ] }
19clap = "2.33.1" 19clap = "2.33.1"
20async-trait = "0.1.36" 20async-trait = "0.1.36"
21paste = "0.1"
21uuid = { version = "0.8.1", features = ["v4"] } 22uuid = { version = "0.8.1", features = ["v4"] }
22 23
23weechat = { git = "https://github.com/poljar/rust-weechat", features = ["async-executor"] } 24weechat = { git = "https://github.com/poljar/rust-weechat", features = ["async-executor"] }
src/commands.rs +3 −3
@@ -3,7 +3,7 @@ use clap::AppSettings as ArgParseSettings;
3use clap::{Arg, ArgMatches, SubCommand}; 3use clap::{Arg, ArgMatches, SubCommand};
4use url::Url; 4use url::Url;
5 5
6use crate::config::Config; 6use crate::config::ConfigHandle;
7use crate::PLUGIN_NAME; 7use crate::PLUGIN_NAME;
8use crate::{MatrixServer, Servers}; 8use crate::{MatrixServer, Servers};
9use weechat::buffer::Buffer; 9use weechat::buffer::Buffer;
@@ -16,7 +16,7 @@ pub struct Commands {
16 16
17struct MatrixCommand { 17struct MatrixCommand {
18 servers: Servers, 18 servers: Servers,
19 config: Config, 19 config: ConfigHandle,
20} 20}
21 21
22impl MatrixCommand { 22impl MatrixCommand {
@@ -269,7 +269,7 @@ impl Commands {
269 pub fn hook_all( 269 pub fn hook_all(
270 weechat: &Weechat, 270 weechat: &Weechat,
271 servers: &Servers, 271 servers: &Servers,
272 config: &Config, 272 config: &ConfigHandle,
273 ) -> Commands { 273 ) -> Commands {
274 let matrix_settings = CommandSettings::new("matrix") 274 let matrix_settings = CommandSettings::new("matrix")
275 .description("Matrix chat protocol command.") 275 .description("Matrix chat protocol command.")
src/config.rs +200 −37
@@ -16,69 +16,188 @@
16//! the section will do so. 16//! the section will do so.
17use crate::{MatrixServer, Servers}; 17use crate::{MatrixServer, Servers};
18use weechat::config::{ 18use weechat::config::{
19 Conf, ConfigSection, ConfigSectionSettings, OptionChanged, 19 Conf, ConfigOption, ConfigSection, ConfigSectionSettings, OptionChanged,
20 SectionReadCallback, 20 SectionHandle, SectionHandleMut, SectionReadCallback, StringOptionSettings,
21}; 21};
22use weechat::Weechat; 22use weechat::Weechat;
23 23
24use std::cell::{Ref, RefCell, RefMut}; 24use std::cell::{Ref, RefCell, RefMut};
25use std::ops::{Deref, DerefMut};
25use std::rc::Rc; 26use std::rc::Rc;
26 27
27#[derive(Clone)] 28#[derive(Clone)]
28pub struct Config { 29pub struct ConfigHandle {
29 inner: Rc<RefCell<weechat::config::Config>>, 30 inner: Rc<RefCell<Config>>,
30 servers: Servers, 31 servers: Servers,
31} 32}
32 33
33impl SectionReadCallback for Config { 34macro_rules! option {
34 fn callback( 35 (StringOption, $option_name:ident, $description:literal, $default:literal) => {
35 &mut self, 36 paste::item! {
36 _: &Weechat, 37 fn [<create_option_ $option_name>](section: &mut SectionHandleMut) {
37 _: &Conf, 38 let option_name = stringify!($option_name);
38 section: &mut ConfigSection, 39 let option_settings = StringOptionSettings::new(option_name)
39 option_name: &str, 40 .description($description)
40 option_value: &str, 41 .default_value($default);
41 ) -> OptionChanged { 42
42 if option_name.is_empty() { 43 section.new_string_option(option_settings)
43 return OptionChanged::Error; 44 .expect(&format!("Can't create option {}", option_name));
45 }
44 } 46 }
45 47
46 let option_args: Vec<&str> = option_name.splitn(2, '.').collect(); 48 paste::item! {
49 pub fn [<$option_name>](&self) -> String {
50 let option_name = stringify!($option_name);
47 51
48 if option_args.len() != 2 { 52 let option = self.0.search_option(option_name)
49 return OptionChanged::Error; 53 .expect(&format!("Couldn't find option {} in section {}",
54 option_name, self.0.name()));
55
56 if let ConfigOption::String(o) = option {
57 o.value().to_string()
58 } else {
59 panic!("Incorect option type for option {} in section {}",
60 option_name, self.0.name());
61 }
62 }
50 } 63 }
64 };
51 65
52 let server_name = option_args[0]; 66 (EvaluatedStringOption, $option_name:ident, $description:literal, $default:literal) => {
67 paste::item! {
68 fn [<create_option_ $option_name>](section: &mut SectionHandleMut) {
69 let option_name = stringify!($option_name);
70 let option_settings = StringOptionSettings::new(option_name)
71 .description(&format!("{} (note: the content is evaluated, see /help eval)", $description))
72 .default_value($default);
53 73
54 { 74 section.new_string_option(option_settings)
55 let mut servers_borrow = self.servers.borrow_mut(); 75 .expect(&format!("Can't create option {}", option_name));
76 }
77 }
56 78
57 // We are reading the config, if the server doesn't yet exists 79 paste::item! {
58 // we need to create it before setting the option and running 80 pub fn [<$option_name>](&self) -> String {
59 // the option change callback. 81 let option_name = stringify!($option_name);
60 if !servers_borrow.contains_key(server_name) { 82
61 let server = MatrixServer::new(server_name, &self, section); 83 let option = self.0.search_option(option_name)
62 servers_borrow.insert(server_name.to_owned(), server); 84 .expect(&format!("Couldn't find option {} in section {}",
85 option_name, self.0.name()));
86
87 if let ConfigOption::String(o) = option {
88 Weechat::eval_string_expression(&o.value())
89 .expect(&format!(
90 "Can't evaluate string expression for option {} in section {}",
91 option_name,
92 self.0.name())
93 )
94 } else {
95 panic!("Incorect option type for option {} in section {}",
96 option_name, self.0.name());
97 }
63 } 98 }
64 } 99 }
100 };
101}
65 102
66 let option = section.search_option(option_name); 103macro_rules! section {
104 ($section:ident { $({$option_type:ident, $option_name:ident, $($option:tt)*}), * }) => {
105 paste::item! {
106 pub struct [<$section:camel Section>]<'a>(SectionHandle<'a>);
67 107
68 if let Some(o) = option { 108 impl<'a> [<$section:camel Section>]<'a> {
69 o.set(option_value, true) 109 pub fn create(config: &mut Config) {
70 } else { 110 let section_settings = ConfigSectionSettings::new(stringify!($section));
71 OptionChanged::NotFound 111
112 let mut $section = config.new_section(section_settings)
113 .expect(&format!("Can't create config section {}", stringify!($section)));
114
115 [<$section:camel Section>]::create_options(&mut $section);
116 }
117
118 pub fn create_options(section: &mut SectionHandleMut) {
119 $(
120 [<$section:camel Section>]::[<create_option_ $option_name>](section);
121 )*
122 }
123
124 $(
125 option!($option_type, $option_name, $($option)*);
126 )*
127 }
128 }
129 }
130}
131
132macro_rules! config {
133 ($(Section $section:ident { $({$($option:tt)*}), * }), *) => {
134 pub struct Config(weechat::config::Config);
135
136 impl Deref for Config {
137 type Target = weechat::config::Config;
138
139 fn deref(&self) -> &Self::Target {
140 &self.0
141 }
142 }
143
144 impl DerefMut for Config {
145 fn deref_mut(&mut self) -> &mut Self::Target {
146 &mut self.0
147 }
148 }
149
150 impl Config {
151 fn new(config: weechat::config::Config) -> Self {
152 let mut config = Config(config);
153 config.create_sections();
154
155 config
156 }
157
158 paste::item! {
159 fn create_sections(&mut self) {
160 $(
161 paste::expr! { [<$section:camel Section>]::create(self) };
162 )*
163 }
164 }
165
166 paste::item! {
167 $(
168 pub fn $section(&self) -> [<$section:camel Section>] {
169 let section_name = stringify!($section);
170 let section = self.0.search_section(section_name)
171 .expect(&format!("Couldn't find section {}", section_name));
172
173 paste::item! { [<$section:camel Section>](section) }
174 }
175 )*
176 }
72 } 177 }
178
179 $(
180 section!($section { $({$($option)*}), * });
181 )*
73 } 182 }
74} 183}
75 184
76impl Config { 185config!(
77 pub fn new(_weechat: &Weechat, servers: &Servers) -> Config { 186 Section look {
187 {StringOption, encrypted_room_sign,
188 "A sign that is used to show that the current room is encrypted",
189 "🔒"}
190 }
191);
192
193impl ConfigHandle {
194 pub fn new(_weechat: &Weechat, servers: &Servers) -> ConfigHandle {
78 let config = Weechat::config_new("matrix-rust") 195 let config = Weechat::config_new("matrix-rust")
79 .expect("Can't create new config"); 196 .expect("Can't create new config");
80 197
81 let config = Config { 198 let config = Config::new(config);
199
200 let config = ConfigHandle {
82 inner: Rc::new(RefCell::new(config)), 201 inner: Rc::new(RefCell::new(config)),
83 servers: servers.clone(), 202 servers: servers.clone(),
84 }; 203 };
@@ -95,6 +214,7 @@ impl Config {
95 }, 214 },
96 ) 215 )
97 .set_read_callback(config.clone()); 216 .set_read_callback(config.clone());
217
98 { 218 {
99 let mut config_borrow = config.borrow_mut(); 219 let mut config_borrow = config.borrow_mut();
100 220
@@ -106,11 +226,54 @@ impl Config {
106 config 226 config
107 } 227 }
108 228
109 pub fn borrow(&self) -> Ref<'_, weechat::config::Config> { 229 pub fn borrow(&self) -> Ref<'_, Config> {
110 self.inner.borrow() 230 self.inner.borrow()
111 } 231 }
112 232
113 pub fn borrow_mut(&self) -> RefMut<'_, weechat::config::Config> { 233 pub fn borrow_mut(&self) -> RefMut<'_, Config> {
114 self.inner.borrow_mut() 234 self.inner.borrow_mut()
115 } 235 }
116} 236}
237
238impl SectionReadCallback for ConfigHandle {
239 fn callback(
240 &mut self,
241 _: &Weechat,
242 _: &Conf,
243 section: &mut ConfigSection,
244 option_name: &str,
245 option_value: &str,
246 ) -> OptionChanged {
247 if option_name.is_empty() {
248 return OptionChanged::Error;
249 }
250
251 let option_args: Vec<&str> = option_name.splitn(2, '.').collect();
252
253 if option_args.len() != 2 {
254 return OptionChanged::Error;
255 }
256
257 let server_name = option_args[0];
258
259 {
260 let mut servers_borrow = self.servers.borrow_mut();
261
262 // We are reading the config, if the server doesn't yet exists
263 // we need to create it before setting the option and running
264 // the option change callback.
265 if !servers_borrow.contains_key(server_name) {
266 let server = MatrixServer::new(server_name, &self, section);
267 servers_borrow.insert(server_name.to_owned(), server);
268 }
269 }
270
271 let option = section.search_option(option_name);
272
273 if let Some(o) = option {
274 o.set(option_value, true)
275 } else {
276 OptionChanged::NotFound
277 }
278 }
279}
src/lib.rs +34 −5
@@ -11,10 +11,14 @@ use std::collections::HashMap;
11use std::rc::Rc; 11use std::rc::Rc;
12use tracing_subscriber; 12use tracing_subscriber;
13 13
14use weechat::{weechat_plugin, ArgsWeechat, Weechat, WeechatPlugin}; 14use weechat::{
15 buffer::Buffer,
16 hooks::{BarItemCallback, BarItemHandle},
17 weechat_plugin, ArgsWeechat, Weechat, WeechatPlugin,
18};
15 19
16use crate::commands::Commands; 20use crate::commands::Commands;
17use crate::config::Config; 21use crate::config::ConfigHandle;
18use crate::server::MatrixServer; 22use crate::server::MatrixServer;
19 23
20const PLUGIN_NAME: &str = "matrix"; 24const PLUGIN_NAME: &str = "matrix";
@@ -41,7 +45,9 @@ struct Matrix {
41 #[used] 45 #[used]
42 commands: Commands, 46 commands: Commands,
43 #[used] 47 #[used]
44 config: Config, 48 config: ConfigHandle,
49 #[used]
50 status_bar: BarItemHandle,
45} 51}
46 52
47impl Matrix { 53impl Matrix {
@@ -58,7 +64,7 @@ impl Matrix {
58 64
59 fn create_default_server( 65 fn create_default_server(
60 servers: &mut HashMap<String, MatrixServer>, 66 servers: &mut HashMap<String, MatrixServer>,
61 config: &Config, 67 config: &ConfigHandle,
62 ) { 68 ) {
63 let server_name = "localhost"; 69 let server_name = "localhost";
64 let mut config_borrow = config.borrow_mut(); 70 let mut config_borrow = config.borrow_mut();
@@ -70,11 +76,33 @@ impl Matrix {
70 } 76 }
71} 77}
72 78
79impl BarItemCallback for Servers {
80 fn callback(&mut self, _: &Weechat, buffer: &Buffer) -> String {
81 let servers = self.borrow();
82
83 for server in servers.values() {
84 let server = server.inner();
85 for room in server.room_buffers().values() {
86 let room_buffer = room.weechat_buffer();
87 if &room_buffer == buffer {
88 if room.room().is_encrypted() {
89 return server.config().look().encrypted_room_sign();
90 }
91 }
92 }
93 }
94
95 "".to_owned()
96 }
97}
98
73impl WeechatPlugin for Matrix { 99impl WeechatPlugin for Matrix {
74 fn init(weechat: &Weechat, _args: ArgsWeechat) -> Result<Self, ()> { 100 fn init(weechat: &Weechat, _args: ArgsWeechat) -> Result<Self, ()> {
75 let servers = Servers::new(); 101 let servers = Servers::new();
76 let config = Config::new(weechat, &servers); 102 let config = ConfigHandle::new(weechat, &servers);
77 let commands = Commands::hook_all(weechat, &servers, &config); 103 let commands = Commands::hook_all(weechat, &servers, &config);
104 let status_bar =
105 Weechat::new_bar_item("matrix_modes", servers.clone())?;
78 106
79 tracing_subscriber::fmt().with_writer(debug::Debug).init(); 107 tracing_subscriber::fmt().with_writer(debug::Debug).init();
80 108
@@ -82,6 +110,7 @@ impl WeechatPlugin for Matrix {
82 servers: servers.clone(), 110 servers: servers.clone(),
83 commands, 111 commands,
84 config: config.clone(), 112 config: config.clone(),
113 status_bar,
85 }; 114 };
86 115
87 { 116 {
src/room_buffer.rs +1 −1
@@ -162,7 +162,7 @@ impl RoomBuffer {
162 self.inner.room.borrow() 162 self.inner.room.borrow()
163 } 163 }
164 164
165 pub fn weechat_buffer(&mut self) -> Buffer { 165 pub fn weechat_buffer(&self) -> Buffer {
166 self.buffer_handle 166 self.buffer_handle
167 .upgrade() 167 .upgrade()
168 .expect("Buffer got closed but Room is still lingering around") 168 .expect("Buffer got closed but Room is still lingering around")
src/server.rs +16 −4
@@ -52,7 +52,7 @@
52//! that processing events will not block the Weechat mainloop for too long. 52//! that processing events will not block the Weechat mainloop for too long.
53use async_std::sync::channel as async_channel; 53use async_std::sync::channel as async_channel;
54use async_std::sync::{Receiver, Sender}; 54use async_std::sync::{Receiver, Sender};
55use std::cell::RefCell; 55use std::cell::{Ref, RefCell};
56use std::collections::HashMap; 56use std::collections::HashMap;
57use std::path::PathBuf; 57use std::path::PathBuf;
58use std::rc::{Rc, Weak}; 58use std::rc::{Rc, Weak};
@@ -80,8 +80,8 @@ use weechat::JoinHandle;
80use weechat::Weechat; 80use weechat::Weechat;
81 81
82use crate::room_buffer::RoomBuffer; 82use crate::room_buffer::RoomBuffer;
83use crate::Config;
84use crate::PLUGIN_NAME; 83use crate::PLUGIN_NAME;
84use crate::{config::Config, ConfigHandle};
85 85
86const DEFAULT_SYNC_TIMEOUT: Duration = Duration::from_secs(30); 86const DEFAULT_SYNC_TIMEOUT: Duration = Duration::from_secs(30);
87 87
@@ -151,7 +151,7 @@ pub(crate) struct InnerServer {
151 server_name: Rc<String>, 151 server_name: Rc<String>,
152 room_buffers: HashMap<RoomId, RoomBuffer>, 152 room_buffers: HashMap<RoomId, RoomBuffer>,
153 settings: ServerSettings, 153 settings: ServerSettings,
154 config: Config, 154 config: ConfigHandle,
155 client: Option<Client>, 155 client: Option<Client>,
156 login_state: Option<LoginState>, 156 login_state: Option<LoginState>,
157 connected_state: Rc<RefCell<Option<Connection>>>, 157 connected_state: Rc<RefCell<Option<Connection>>>,
@@ -160,7 +160,7 @@ pub(crate) struct InnerServer {
160impl MatrixServer { 160impl MatrixServer {
161 pub fn new( 161 pub fn new(
162 name: &str, 162 name: &str,
163 config: &Config, 163 config: &ConfigHandle,
164 server_section: &mut ConfigSection, 164 server_section: &mut ConfigSection,
165 ) -> Self { 165 ) -> Self {
166 let server_name = Rc::new(name.to_owned()); 166 let server_name = Rc::new(name.to_owned());
@@ -188,6 +188,10 @@ impl MatrixServer {
188 &self.server_name 188 &self.server_name
189 } 189 }
190 190
191 pub fn inner(&self) -> Ref<'_, InnerServer> {
192 self.inner.borrow()
193 }
194
191 pub fn parse_homeserver_url(value: String) -> Result<(), String> { 195 pub fn parse_homeserver_url(value: String) -> Result<(), String> {
192 let url = Url::parse(&value); 196 let url = Url::parse(&value);
193 197
@@ -421,6 +425,14 @@ impl InnerServer {
421 self.room_buffers.get_mut(room_id).unwrap() 425 self.room_buffers.get_mut(room_id).unwrap()
422 } 426 }
423 427
428 pub fn room_buffers(&self) -> &HashMap<RoomId, RoomBuffer> {
429 &self.room_buffers
430 }
431
432 pub fn config(&self) -> Ref<Config> {
433 self.config.borrow()
434 }
435
424 fn restore_room(&mut self, room: Room) { 436 fn restore_room(&mut self, room: Room) {
425 let homeserver = self 437 let homeserver = self
426 .settings 438 .settings