src/config_macros.rs

4538219dafb75c11e9065ae2b5144009d36d6768
weechat-matrix-rs/src/config_macros.rs history · blame · raw

364 lines · 12635 bytes

  1#[allow(unused_macros)]
  2macro_rules! string_create {
  3    ($option_name:ident, $description:literal, $default:literal) => {
  4        paste::item! {
  5            fn [<create_option_ $option_name>](section: &mut SectionHandleMut) {
  6                let option_name = stringify!($option_name);
  7                let option_settings = StringOptionSettings::new(option_name)
  8                    .description($description)
  9                    .default_value($default);
 10
 11                section.new_string_option(option_settings)
 12                    .expect(&format!("Can't create option {}", option_name));
 13            }
 14        }
 15    };
 16}
 17
 18#[allow(unused_macros)]
 19macro_rules! color_create {
 20    ($option_name:ident, $description:literal, $default:literal) => {
 21        paste::item! {
 22            fn [<create_option_ $option_name>](section: &mut SectionHandleMut) {
 23                let option_name = stringify!($option_name);
 24                let option_settings = ColorOptionSettings::new(option_name)
 25                    .description($description)
 26                    .default_value($default);
 27
 28                section.new_color_option(option_settings)
 29                    .expect(&format!("Can't create option {}", option_name));
 30            }
 31        }
 32    };
 33}
 34
 35#[allow(unused_macros)]
 36macro_rules! bool_create {
 37    ($option_name:ident, $description:literal, $default:literal) => {
 38        paste::item! {
 39            fn [<create_option_ $option_name>](section: &mut SectionHandleMut) {
 40                let option_name = stringify!($option_name);
 41                let option_settings = BooleanOptionSettings::new(option_name)
 42                    .description($description)
 43                    .default_value($default);
 44
 45                section.new_boolean_option(option_settings)
 46                    .expect(&format!("Can't create option {}", option_name));
 47            }
 48        }
 49    };
 50}
 51
 52#[allow(unused_macros)]
 53macro_rules! integer_create {
 54    ($option_name:ident, $description:literal, $default:literal, $min:literal, $max:literal) => {
 55        paste::item! {
 56            fn [<create_option_ $option_name>](section: &mut SectionHandleMut) {
 57                let option_name = stringify!($option_name);
 58
 59                let option_settings = IntegerOptionSettings::new(option_name)
 60                    .description($description)
 61                    .default_value($default)
 62                    .min($min)
 63                    .max($max);
 64
 65                section.new_integer_option(option_settings)
 66                    .expect(&format!("Can't create option {}", option_name));
 67            }
 68        }
 69    };
 70}
 71
 72#[allow(unused_macros)]
 73macro_rules! enum_create {
 74    ($option_name:ident, $description:literal, $out_type:ty) => {
 75        paste::item! {
 76            fn [<create_option_ $option_name>](section: &mut SectionHandleMut) {
 77                let mut string_values: Vec<String> = Vec::new();
 78
 79                for value in $out_type::VARIANTS {
 80                    string_values.push(value.to_string());
 81                }
 82
 83                let default_value = $out_type::default();
 84
 85                let option_name = stringify!($option_name);
 86                let option_settings = IntegerOptionSettings::new(option_name)
 87                    .description($description)
 88                    .default_value(default_value as i32)
 89                    .string_values(string_values);
 90
 91                section.new_integer_option(option_settings)
 92                    .expect(&format!("Can't create option {}", option_name));
 93            }
 94        }
 95    };
 96}
 97
 98macro_rules! option_getter {
 99    ($option_type:ident, $option_name:ident, $output_type:ty) => {
100        paste::item! {
101            pub fn [<$option_name>](&self) -> $output_type {
102                let option_name = stringify!($option_name);
103
104                if let ConfigOption::[<$option_type>](o) = self.0.search_option(option_name)
105                    .expect(&format!("Couldn't find option {} in section {}",
106                                     option_name, self.0.name()))
107                {
108                    $output_type::from(o.value())
109                } else {
110                    panic!("Incorect option type for option {} in section {}",
111                           option_name, self.0.name());
112                }
113            }
114        }
115    };
116}
117
118macro_rules! option {
119    (String, $option_name:ident, $description:literal, $default:literal $(,)?) => {
120        string_create!($option_name, $description, $default);
121        option_getter!(String, $option_name, String);
122    };
123
124    (Color, $option_name:ident, $description:literal, $default:literal $(,)?) => {
125        color_create!($option_name, $description, $default);
126        option_getter!(Color, $option_name, String);
127    };
128
129    (bool, $option_name:ident, $description:literal, $default:literal $(,)?) => {
130        bool_create!($option_name, $description, $default);
131        option_getter!(Boolean, $option_name, bool);
132    };
133
134    (Integer, $option_name:ident, $description:literal, $default:literal, $min:literal..$max:literal $(,)?) => {
135        integer_create!($option_name, $description, $default, $min, $max);
136        option_getter!(Integer, $option_name, i64);
137    };
138
139    (Enum, $option_name:ident, $description:literal, $out_type:ty $(,)?) => {
140        enum_create!($option_name, $description, $out_type);
141        option_getter!(Integer, $option_name, $out_type);
142    };
143
144    (EvaluatedString, $option_name:ident, $description:literal, $default:literal $(,)?) => {
145        string_create!($option_name, $description, $default);
146
147        paste::item! {
148            pub fn [<$option_name>](&self) -> String {
149                let option_name = stringify!($option_name);
150
151                let option = self.0.search_option(option_name)
152                    .expect(&format!("Couldn't find option {} in section {}",
153                                     option_name, self.0.name()));
154
155                if let ConfigOption::String(o) = option {
156                    Weechat::eval_string_expression(&o.value())
157                        .expect(&format!(
158                            "Can't evaluate string expression for option {} in section {}",
159                            option_name,
160                            self.0.name())
161                        )
162                } else {
163                    panic!("Incorect option type for option {} in section {}",
164                           option_name, self.0.name());
165                }
166            }
167        }
168    };
169}
170
171macro_rules! section {
172    ($section:ident { $($option_name:ident: $option_type:ident {$($option:tt)*}), * $(,)? }) => {
173        paste::item! {
174            pub struct [<$section:camel Section>]<'a>(SectionHandle<'a>);
175
176            impl<'a> [<$section:camel Section>]<'a> {
177                pub fn create(config: &mut Config) {
178                    let section_settings = ConfigSectionSettings::new(stringify!($section));
179
180                    let mut $section = config.new_section(section_settings)
181                        .expect(&format!("Can't create config section {}", stringify!($section)));
182
183                    [<$section:camel Section>]::create_options(&mut $section);
184                }
185
186                pub fn create_options(section: &mut SectionHandleMut) {
187                    $(
188                        [<$section:camel Section>]::[<create_option_ $option_name>](section);
189                    )*
190                }
191
192                $(
193                    option!($option_type, $option_name, $($option)*);
194                )*
195            }
196        }
197    }
198}
199
200/// Declare a Weechat configuration file.
201///
202/// This will generate a struct called `Config` which wraps the Weechat struct
203/// of the same name. The generated struct will have accessors for every
204/// section and option that is declared.
205///
206/// The generated struct dereferences into the Weechat `Config` struct so
207/// additional sections and options can be created the usual way as well.
208///
209/// The config still needs to be created in the `init()` method of the plugin.
210///
211/// # Example
212/// ```
213///
214/// #[derive(EnumVariantNames)]
215/// #[strum(serialize_all = "kebab_case")]
216/// pub enum ServerBufferMerge {
217///     MergeWithCore,
218///     MergeWithoutCore,
219///     Independent,
220/// }
221///
222/// impl Default for ServerBufferMerge {
223///     fn default() -> Self {
224///         ServerBufferMerge::MergeWithCore
225///     }
226/// }
227///
228/// impl From<i32> for ServerBufferMerge {
229///     fn from(value: i32) -> Self {
230///         match value {
231///             0 => ServerBufferMerge::MergeWithCore,
232///             1 => ServerBufferMerge::MergeWithoutCore,
233///             2 => ServerBufferMerge::Independent,
234///             _ => unreachable!(),
235///         }
236///     }
237/// }
238///
239/// config!(
240///     // The name of the config
241///     "my-plugin",
242///     Section look {
243///         encrypted_room_sign: String {
244///             // Description.
245///             "A sign that is used to show that the current room is encrypted",
246///
247///             // Default value.
248///             "🔒",
249///         },
250///
251///         server_buffer: Enum {
252///             // Description.
253///             "Merge server buffers",
254///
255///             // This is an enum that needs to have the following traits
256///             // implemented:
257///             //    * Default - To define the default value of the option.
258///             //    * From<i32> - To convert the internal Weechat integer option
259///             //      to the enum.
260///             //    * VariantNames - To get the string representation of the
261///             //      enum variants. This is a trait defined in the strum library,
262///             //      a simple macro that derives an implementation is provided by
263///             //      strum.
264///             ServerBufferMerge,
265///         },
266///
267///         quote_fg: Color {
268///             // Description.
269///             "Foreground color for Matrix style blockquotes",
270///
271///             // Default value.
272///             "lightgreen",
273///         },
274///     },
275///
276///     Section network {
277///         username: EvaluatedString {
278///             // Description.
279///             "The username that will be used to log in to the server \
280///              (note: content is evaluated, see /help eval)",
281///
282///             // Default value.
283///             "",
284///         },
285///
286///         timeout: Integer {
287///             // Description.
288///             "A timeout (in seconds) that determines how long we should wait \
289///             for a request to finish before aborting.",
290///
291///             // Default value.
292///             30,
293///
294///             // The range that the value is allowed to have, note that both of
295///             // those are inclusive.
296///             0..100,
297///         },
298///
299///         autoconnect: bool {
300///             // Description.
301///             "Automatically connect to the server when Weechat is starting",
302///
303///             // Default value.
304///             false,
305///         },
306///    }
307/// );
308/// ```
309macro_rules! config {
310    ($config_name:literal, $(Section $section:ident { $($option:tt)* }), * $(,)?) => {
311        #[allow(unused_imports)]
312        use strum::VariantNames;
313        pub struct Config(weechat::config::Config);
314
315        impl Deref for Config {
316            type Target = weechat::config::Config;
317
318            fn deref(&self) -> &Self::Target {
319                &self.0
320            }
321        }
322
323        impl DerefMut for Config {
324            fn deref_mut(&mut self) -> &mut Self::Target {
325                &mut self.0
326            }
327        }
328
329        impl Config {
330            fn new() -> Result<Self, ()> {
331                let config = Weechat::config_new($config_name)?;
332                let mut config = Config(config);
333
334                config.create_sections();
335
336                Ok(config)
337            }
338
339            paste::item! {
340                fn create_sections(&mut self) {
341                    $(
342                        paste::expr! { [<$section:camel Section>]::create(self) };
343                    )*
344                }
345            }
346
347            paste::item! {
348                $(
349                    pub fn $section(&self) -> [<$section:camel Section>] {
350                        let section_name = stringify!($section);
351                        let section = self.0.search_section(section_name)
352                            .expect(&format!("Couldn't find section {}", section_name));
353
354                        paste::item! { [<$section:camel Section>](section) }
355                    }
356                )*
357            }
358        }
359
360        $(
361            section!($section { $($option)* });
362        )*
363    }
364}