src/config_macros.rs

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

360 lines · 12508 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///     Section look {
241///         encrypted_room_sign: String {
242///             // Description.
243///             "A sign that is used to show that the current room is encrypted",
244///
245///             // Default value.
246///             "🔒",
247///         },
248///
249///         server_buffer: Enum {
250///             // Description.
251///             "Merge server buffers",
252///
253///             // This is an enum that needs to have the following traits
254///             // implemented:
255///             //    * Default - To define the default value of the option.
256///             //    * From<i32> - To convert the internal Weechat integer option
257///             //      to the enum.
258///             //    * VariantNames - To get the string representation of the
259///             //      enum variants. This is a trait defined in the strum library,
260///             //      a simple macro that derives an implementation is provided by
261///             //      strum.
262///             ServerBufferMerge,
263///         },
264///
265///         quote_fg: Color {
266///             // Description.
267///             "Foreground color for Matrix style blockquotes",
268///
269///             // Default value.
270///             "lightgreen",
271///         },
272///     },
273///
274///     Section network {
275///         username: EvaluatedString {
276///             // Description.
277///             "The username that will be used to log in to the server \
278///              (note: content is evaluated, see /help eval)",
279///
280///             // Default value.
281///             "",
282///         },
283///
284///         timeout: Integer {
285///             // Description.
286///             "A timeout (in seconds) that determines how long we should wait \
287///             for a request to finish before aborting.",
288///
289///             // Default value.
290///             30,
291///
292///             // The range that the value is allowed to have, note that both of
293///             // those are inclusive.
294///             0..100,
295///         },
296///
297///         autoconnect: bool {
298///             // Description.
299///             "Automatically connect to the server when Weechat is starting",
300///
301///             // Default value.
302///             false,
303///         },
304///    }
305/// );
306/// ```
307macro_rules! config {
308    ($(Section $section:ident { $($option:tt)* }), * $(,)?) => {
309        #[allow(unused_imports)]
310        use strum::VariantNames;
311        pub struct Config(weechat::config::Config);
312
313        impl Deref for Config {
314            type Target = weechat::config::Config;
315
316            fn deref(&self) -> &Self::Target {
317                &self.0
318            }
319        }
320
321        impl DerefMut for Config {
322            fn deref_mut(&mut self) -> &mut Self::Target {
323                &mut self.0
324            }
325        }
326
327        impl Config {
328            fn new(config: weechat::config::Config) -> Self {
329                let mut config = Config(config);
330                config.create_sections();
331
332                config
333            }
334
335            paste::item! {
336                fn create_sections(&mut self) {
337                    $(
338                        paste::expr! { [<$section:camel Section>]::create(self) };
339                    )*
340                }
341            }
342
343            paste::item! {
344                $(
345                    pub fn $section(&self) -> [<$section:camel Section>] {
346                        let section_name = stringify!($section);
347                        let section = self.0.search_section(section_name)
348                            .expect(&format!("Couldn't find section {}", section_name));
349
350                        paste::item! { [<$section:camel Section>](section) }
351                    }
352                )*
353            }
354        }
355
356        $(
357            section!($section { $($option)* });
358        )*
359    }
360}