Skip to main content

nrelm_macros/
lib.rs

1//! A collection of macros for gtk-rs, Relm4 and Rust in general.
2//!
3//! Docs of related crates:
4//! [nrelm](https://neorelm.gitlab.io/neorelm/nrelm)
5//! | [nrelm-macros](https://neorelm.gitlab.io/neorelm/nrelm_macros)
6//! | [nrelm-components](https://neorelm.gitlab.io/neorelm/nrelm_components)
7//! | [nrelm-css](https://neorelm.gitlab.io/neorelm/nrelm_css)
8//! | [gtk3-rs](https://gtk-rs.org/gtk3-rs/git/docs)
9//! | [gtk-rs-core](https://gtk-rs.org/gtk-rs-core/git/docs)
10//!
11//! [GitLab](https://github.com/NeoRelm/NeoRelm)
12
13#![doc(html_logo_url = "https://neorelm.gitlab.io/neorelm/assets/NeoRelm_logo_transparent.svg")]
14#![doc(html_favicon_url = "https://neorelm.gitlab.io/neorelm/assets/NeoRelm_logo_circular.svg")]
15#![warn(
16    missing_debug_implementations,
17    missing_docs,
18    rust_2018_idioms,
19    unreachable_pub,
20    unused_qualifications,
21    clippy::cargo,
22    clippy::must_use_candidate
23)]
24
25use proc_macro::TokenStream;
26use syn::{ItemImpl, parse_macro_input};
27
28mod additional_fields;
29mod args;
30mod attrs;
31mod component;
32mod factory;
33mod menu;
34mod menu_list;
35mod view;
36mod visitors;
37mod widgets;
38
39#[macro_use]
40mod util;
41mod token_streams;
42mod widget_template;
43
44use attrs::{Attrs, SyncOnlyAttrs};
45use menu::Menus;
46use menu_list::List;
47
48fn gtk_import() -> syn::Path {
49    if cfg!(feature = "nrelm") {
50        util::strings_to_path(&["nrelm", "gtk"])
51    } else {
52        util::strings_to_path(&["gtk"])
53    }
54}
55
56/// Macro that implements `nrelm::Component` or `nrelm::SimpleComponent`
57/// and generates the corresponding widgets struct.
58///
59/// # Attributes
60///
61/// To create public struct use `#[component(pub)]` or `#[component(visibility = pub)]`.
62///
63/// # Example
64///
65/// ```
66/// use nrelm::prelude::*;
67/// use nrelm::RelmContainerExt;
68/// use gtk::prelude::*;
69///
70/// #[derive(Default)]
71/// struct App {
72///     counter: u8,
73/// }
74///
75/// #[derive(Debug)]
76/// enum Msg {
77///     Increment,
78///     Decrement,
79/// }
80///
81/// #[nrelm_macros::component(pub)]
82/// impl SimpleComponent for App {
83///     type Init = u8;
84///     type Input = Msg;
85///     type Output = ();
86///
87///     view! {
88///         gtk::Window {
89///             set_title: "Simple app",
90///             set_default_size: (300, 100),
91///             gtk::Box {
92///                 set_orientation: gtk::Orientation::Vertical,
93///                 set_margin_all: 5,
94///                 set_spacing: 5,
95///
96///                 gtk::Button {
97///                     set_label: "Increment",
98///                     connect_clicked => Msg::Increment,
99///                 },
100///                 gtk::Button {
101///                     set_label: "Decrement",
102///                     connect_clicked[sender] => move |_| {
103///                         sender.input(Msg::Decrement);
104///                     },
105///                 },
106///                 gtk::Label {
107///                     set_margin_all: 5,
108///                     #[watch]
109///                     set_label: &format!("Counter: {}", model.counter),
110///                 }
111///             },
112///         }
113///     }
114///
115///     fn init(
116///         counter: Self::Init,
117///         root: Self::Root,
118///         sender: ComponentSender<Self>,
119///     ) -> ComponentParts<Self> {
120///         let model = Self { counter };
121///
122///         let widgets = view_output!();
123///
124///         ComponentParts { model, widgets }
125///     }
126///
127///     fn update(&mut self, msg: Msg, _sender: ComponentSender<Self>) {
128///         match msg {
129///             Msg::Increment => {
130///                 self.counter = self.counter.wrapping_add(1);
131///             }
132///             Msg::Decrement => {
133///                 self.counter = self.counter.wrapping_sub(1);
134///             }
135///         }
136///     }
137/// }
138/// ```
139///
140/// # Notes on `pre_view`
141///
142/// Using `return` in `pre_view` will cause a compiler warning.
143/// In general, you don't want to use `return` in `pre_view` as it will
144/// cause all following update functionality to be skipped.
145///
146/// ```compile_fail
147/// # use gtk::prelude::{BoxExt, ButtonExt, GtkWindowExt, OrientableExt};
148/// # use nrelm::{gtk, ComponentParts, ComponentSender, SimpleComponent, RelmWidgetExt};
149/// #
150/// struct App {}
151///
152/// #[nrelm_macros::component]
153/// impl SimpleComponent for App {
154///       /* Code omitted */
155/// #     type Init = ();
156/// #     type Input = ();
157/// #     type Output = ();
158/// #
159/// #     view! {
160/// #         gtk::Window {}
161/// #     }
162///
163///       fn pre_view() {
164///           return;
165///       }
166/// #
167/// #     fn init(
168/// #         counter: Self::Init,
169/// #         root: &Self::Root,
170/// #         sender: ComponentSender<Self>,
171/// #     ) -> ComponentParts<Self> {
172/// #         let model = Self {};
173/// #
174/// #         let widgets = view_output!();
175/// #
176/// #         ComponentParts { model, widgets }
177/// #     }
178/// }
179/// ```
180#[proc_macro_attribute]
181pub fn component(attributes: TokenStream, input: TokenStream) -> TokenStream {
182    let global_attributes: Attrs = parse_macro_input!(attributes);
183    let backup_input = input.clone();
184    let component_impl_res = syn::parse::<ItemImpl>(input);
185
186    match component_impl_res {
187        Ok(component_impl) => component::generate_tokens(global_attributes, component_impl).into(),
188        Err(_) => util::item_impl_error(backup_input),
189    }
190}
191
192/// Macro that implements `nrelm::factory::FactoryComponent` and generates the corresponding widgets struct.
193///
194/// # Attributes
195///
196/// To create public struct use `#[factory(pub)]` or `#[factory(visibility = pub)]`.
197///
198/// # Example
199///
200/// ```
201/// use nrelm::prelude::*;
202/// use nrelm::RelmContainerExt;
203/// use nrelm::factory::*;
204/// use gtk::prelude::*;
205///
206/// # #[derive(Debug)]
207/// # enum AppMsg {
208/// #     AddCounter,
209/// #     RemoveCounter,
210/// #     SendFront(DynamicIndex)
211/// # }
212///
213/// #[derive(Debug)]
214/// struct Counter {
215///     value: u8,
216/// }
217///
218/// #[derive(Debug)]
219/// enum CounterMsg {
220///     Increment,
221///     Decrement,
222/// }
223///
224/// #[derive(Debug)]
225/// enum CounterOutput {
226///     SendFront(DynamicIndex),
227/// }
228///
229/// #[nrelm_macros::factory(pub)]
230/// impl FactoryComponent for Counter {
231///     type CommandOutput = ();
232///     type Init = u8;
233///     type Input = CounterMsg;
234///     type Output = CounterOutput;
235///     type ParentWidget = gtk::Box;
236///
237///
238///     view! {
239///         root = gtk::Box {
240///             set_orientation: gtk::Orientation::Horizontal,
241///             set_spacing: 10,
242///
243///             #[name(label)]
244///             gtk::Label {
245///                 #[watch]
246///                 set_label: &self.value.to_string(),
247///                 set_width_chars: 3,
248///             },
249///
250///             #[name(add_button)]
251///             gtk::Button {
252///                 set_label: "+",
253///                 connect_clicked => CounterMsg::Increment,
254///             },
255///
256///             #[name(remove_button)]
257///             gtk::Button {
258///                 set_label: "-",
259///                 connect_clicked => CounterMsg::Decrement,
260///             },
261///
262///             #[name(to_front_button)]
263///             gtk::Button {
264///                 set_label: "To start",
265///                 connect_clicked[sender, index] => move |_| {
266///                     sender.output(CounterOutput::SendFront(index.clone()));
267///                 }
268///             }
269///         }
270///     }
271///
272///     fn init_model(
273///         value: Self::Init,
274///         _index: &DynamicIndex,
275///         _sender: FactorySender<Self>,
276///     ) -> Self {
277///         Self { value }
278///     }
279///
280///     fn update(&mut self, msg: Self::Input, _sender: FactorySender<Self>) {
281///         match msg {
282///             CounterMsg::Increment => {
283///                 self.value = self.value.wrapping_add(1);
284///             }
285///             CounterMsg::Decrement => {
286///                 self.value = self.value.wrapping_sub(1);
287///             }
288///         }
289///     }
290/// }
291/// ```
292///
293/// Note: the enclosing App view (which has AppMsg as its input) is responsible for adding a
294/// forward handler to the `FactoryVecDeque`, which will translate CounterOutput events into AppMsg
295/// events. For example `CounterOutput::SendFront(index) => AppMsg::SendFront(index)`
296///
297#[proc_macro_attribute]
298pub fn factory(attributes: TokenStream, input: TokenStream) -> TokenStream {
299    let attrs = parse_macro_input!(attributes);
300    let backup_input = input.clone();
301    let factory_impl_res = syn::parse::<ItemImpl>(input);
302
303    match factory_impl_res {
304        Ok(factory_impl) => factory::generate_tokens(attrs, factory_impl).into(),
305        Err(_) => util::item_impl_error(backup_input),
306    }
307}
308
309/// A macro to create menus.
310///
311/// Use
312///
313/// + `"Label text" => ActionType,` to create new entries.
314/// + `"Label text" => ActionType(value),` to create new entries with action value.
315/// + `custom: "widget_id",` to add a placeholder for custom widgets you can add later with [`set_attribute_name`](https://gtk-rs.org/gtk-rs-core/stable/0.15/docs/gio/struct.MenuItem.html#method.set_attribute_value).
316/// + `section! { ... }` to create new sections.
317///
318/// # Example
319///
320/// ```
321/// # fn gettext(string: &str) -> String {
322/// #     string.to_owned()
323/// # }
324/// #
325/// // Define some actions
326/// nrelm::new_action_group!(WindowActionGroup, "win");
327/// nrelm::new_stateless_action!(TestAction, WindowActionGroup, "test");
328/// nrelm::new_stateful_action!(TestU8Action, WindowActionGroup, "test2", u8, u8);
329///
330/// // Create a `MenuModel` called `menu_model`
331/// nrelm_macros::menu! {
332///     main_menu: {
333///         custom: "my_widget",
334///         // Translate with gettext-rs, for example.
335///         &gettext("Test") => TestAction,
336///         "Test2" => TestAction,
337///         "Test toggle" => TestU8Action(1_u8),
338///         section! {
339///             "Section test" => TestAction,
340///             "Test toggle" => TestU8Action(1_u8),
341///         },
342///         section! {
343///             "Test" => TestAction,
344///             "Test2" => TestAction,
345///             "Test Value" => TestU8Action(1_u8),
346///         }
347///     }
348/// };
349/// ```
350///
351/// # Macro expansion
352///
353/// The code generation for the example above looks like this (plus comments):
354///
355/// ```
356/// # fn gettext(string: &str) -> String {
357/// #     string.to_owned()
358/// # }
359/// #
360/// struct WindowActionGroup;
361/// impl nrelm::actions::ActionGroupName for WindowActionGroup {
362///     const NAME: &'static str = "win";
363/// }
364///
365/// struct TestAction;
366/// impl nrelm::actions::ActionName for TestAction {
367///     type Group = WindowActionGroup;
368///     type State = ();
369///     type Target = ();
370///
371///     const NAME: &'static str = "test";
372/// }
373///
374/// struct TestU8Action;
375/// impl nrelm::actions::ActionName for TestU8Action {
376///     type Group = WindowActionGroup;
377///     type State = u8;
378///     type Target = u8;
379///
380///     const NAME: &'static str = "test2";
381/// }
382///
383/// // Main menu
384/// let main_menu = nrelm::gtk::gio::Menu::new();
385///
386/// // Placeholder for custom widget
387/// let new_entry = nrelm::gtk::gio::MenuItem::new(None, None);
388/// let variant = nrelm::gtk::glib::variant::ToVariant::to_variant("my_widget");
389/// new_entry.set_attribute_value("custom", Some(&variant));
390/// main_menu.append_item(&new_entry);
391///
392/// let new_entry = nrelm::actions::RelmAction::<TestAction>::to_menu_item(&gettext("Test"));
393/// main_menu.append_item(&new_entry);
394/// let new_entry = nrelm::actions::RelmAction::<TestAction>::to_menu_item("Test2");
395/// main_menu.append_item(&new_entry);
396/// let new_entry = nrelm::actions::RelmAction::<TestU8Action>::to_menu_item_with_target_value(
397///     "Test toggle",
398///     &1_u8,
399/// );
400/// main_menu.append_item(&new_entry);
401///
402/// // Section 0
403/// let _section_0 = nrelm::gtk::gio::Menu::new();
404/// main_menu.append_section(None, &_section_0);
405/// let new_entry = nrelm::actions::RelmAction::<TestAction>::to_menu_item("Section test");
406/// _section_0.append_item(&new_entry);
407/// let new_entry = nrelm::actions::RelmAction::<TestU8Action>::to_menu_item_with_target_value(
408///     "Test toggle",
409///     &1_u8,
410/// );
411/// _section_0.append_item(&new_entry);
412///
413/// // Section 1
414/// let _section_1 = nrelm::gtk::gio::Menu::new();
415/// main_menu.append_section(None, &_section_1);
416/// let new_entry = nrelm::actions::RelmAction::<TestAction>::to_menu_item("Test");
417/// _section_1.append_item(&new_entry);
418/// let new_entry = nrelm::actions::RelmAction::<TestAction>::to_menu_item("Test2");
419/// _section_1.append_item(&new_entry);
420/// let new_entry = nrelm::actions::RelmAction::<TestU8Action>::to_menu_item_with_target_value(
421///     "Test Value",
422///     &1_u8,
423/// );
424/// _section_1.append_item(&new_entry);
425/// ```
426#[proc_macro]
427pub fn menu(input: TokenStream) -> TokenStream {
428    let menus = parse_macro_input!(input as Menus);
429    menus.menus_stream().into()
430}
431
432/// The [`menu_list!`] macro allows you to create a `gtk::ListBox` with rows
433/// that send messages to a component's sender, like a menu.
434///
435/// It works the same as inside the [`macro@component`] attribute macro,
436/// but with less features.
437///
438/// You can even use the `nrelm-macros` crate independently from Relm4 to build your GTK UI.
439///
440/// The rows are activated on a single mouse click, or with the keyboard.
441/// The macro generates a `gtk::ListBox` with a selection mode of `None`.
442///
443/// ```no_run
444/// use gtk::prelude::PopoverExt;
445/// use nrelm::{ComponentSender, Worker, gtk};
446/// use nrelm_macros::menu_list;
447///
448/// #[derive(Debug)]
449/// enum AppMsg {
450///     Add,
451///     Remove,
452/// }
453///
454/// impl Worker for AppMsg {
455///     type Input = AppMsg;
456///     type Init = ();
457///     type Output = ();
458///     fn init(_init: Self::Init, _sender: ComponentSender<Self>) -> Self { AppMsg::Add }
459///     fn update(&mut self, _msg: Self::Input, _sender: ComponentSender<Self>) {}
460/// }
461///
462/// fn build_list(sender: ComponentSender<AppMsg>) -> gtk::ListBox {
463///     menu_list! {
464///         "Add" => AppMsg::Add,
465///         "Remove" => AppMsg::Remove,
466///     }
467/// }
468/// ```
469///
470/// Rows with a block handler capture the values they use as method receivers
471/// by cloning them, so they can be used after the `menu_list!` invocation as well:
472///
473/// ```no_run
474/// use gtk::prelude::PopoverExt;
475/// use nrelm::{ComponentSender, Worker, gtk};
476/// use nrelm_macros::menu_list;
477///
478/// #[derive(Debug)]
479/// enum AppMsg {
480///     Add,
481/// }
482///
483/// impl Worker for AppMsg {
484///     type Input = AppMsg;
485///     type Init = ();
486///     type Output = ();
487///     fn init(_init: Self::Init, _sender: ComponentSender<Self>) -> Self { AppMsg::Add }
488///     fn update(&mut self, _msg: Self::Input, _sender: ComponentSender<Self>) {}
489/// }
490///
491/// fn build_list(sender: ComponentSender<AppMsg>, popover: gtk::Popover) -> gtk::ListBox {
492///     let more_btn = gtk::Button::with_label("More");
493///     let list = menu_list! {
494///         "Add" => {
495///             popover.popdown();
496///             sender.input(AppMsg::Add);
497///         },
498///         more_btn,
499///     };
500///     list
501/// }
502/// ```
503///
504/// Widget expressions are inserted into the list box as-is:
505///
506/// ```no_run
507/// use gtk::prelude::PopoverExt;
508/// use nrelm::{ComponentSender, Worker, gtk};
509/// use nrelm_macros::menu_list;
510///
511/// #[derive(Debug)]
512/// enum AppMsg {
513///     Add,
514/// }
515///
516/// impl Worker for AppMsg {
517///     type Input = AppMsg;
518///     type Init = ();
519///     type Output = ();
520///     fn init(_init: Self::Init, _sender: ComponentSender<Self>) -> Self { AppMsg::Add }
521///     fn update(&mut self, _msg: Self::Input, _sender: ComponentSender<Self>) {}
522/// }
523///
524/// fn build_list(sender: ComponentSender<AppMsg>) -> gtk::ListBox {
525///     let custom_row = gtk::Button::with_label("Custom");
526///     menu_list! {
527///         "Add" => AppMsg::Add,
528///         custom_row,
529///     }
530/// }
531/// ```
532#[proc_macro]
533pub fn menu_list(input: TokenStream) -> TokenStream {
534    let list = parse_macro_input!(input as List);
535    list.list_stream().into()
536}
537
538/// The [`view!`] macro allows you to construct your UI easily and cleanly.
539///
540/// It does the same as inside the [`macro@component`] attribute macro,
541/// but with less features.
542///
543/// You can even use the `nrelm-macros` crate independently from Relm4 to build your GTK UI.
544///
545/// ```no_run
546/// use gtk::prelude::{BoxExt, ButtonExt, LabelExt};
547/// use nrelm::gtk;
548/// use nrelm::RelmContainerExt;
549///
550/// // Creating a box with a button inside.
551/// nrelm_macros::view! {
552///     vbox = gtk::Box {
553///         gtk::Button {
554///             set_label: "Click me!",
555///             connect_clicked => |_| {
556///                 println!("Hello world!");
557///             }
558///         },
559///         gtk::Label {
560///             set_label: "The view macro works!",
561///         },
562///     }
563/// }
564///
565/// // You can simply use the vbox created in the macro.
566/// let spacing = vbox.spacing();
567/// ```
568///
569/// Also, the macro doesn't rely on any special gtk-rs features
570/// so you can even use the macro for other purposes.
571///
572/// In this example, we use it to construct a [`Command`](std::process::Command).
573///
574/// ```
575/// use std::process::Command;
576///
577/// let path = "/";
578///
579/// nrelm_macros::view! {
580///     mut process = Command::new("ls") {
581///         args: ["-la"],
582///         current_dir = mut &String {
583///             push_str: path,
584///         },
585///         env: ("HOME", "/home/nrelm"),
586///     }
587/// }
588///
589/// // Output of "ls -la" at "/"
590/// dbg!(process.output());
591/// ```
592/// # Macro expansion
593///
594/// Let's have a look the this example:
595///
596/// ```no_run
597/// # use gtk::prelude::{BoxExt, ButtonExt, LabelExt};
598/// # use nrelm::gtk;
599/// # use nrelm::RelmContainerExt;
600/// // Creating a box with a button inside.
601/// nrelm_macros::view! {
602///     vbox = gtk::Box {
603///         gtk::Button {
604///             set_label: "Click me!",
605///             connect_clicked => |_| {
606///                 println!("Hello world!");
607///             }
608///         },
609///         gtk::Label {
610///             set_label: "The view macro works!",
611///         },
612///     }
613/// }
614/// ```
615///
616/// The code generation for this example looks like this (plus comments):
617///
618/// ```no_run
619/// # use gtk::prelude::{BoxExt, ButtonExt, LabelExt};
620/// # use nrelm::gtk;
621/// # use nrelm::RelmContainerExt;
622///
623/// // We've just used `gtk::Box` so we assume it has a `default()` method
624/// let vbox = gtk::Box::default();
625/// // `vbox` was named, yet the button doesn't have an explicit name and gets a generated one instead.
626/// let _gtk_button_5 = gtk::Button::default();
627/// let _gtk_label_6 = gtk::Label::default();
628///
629/// // Connect the signal
630/// {
631///     _gtk_button_5.connect_clicked(|_| {
632///         println!("Hello world!");
633///     });
634/// }
635///
636/// // The button was added without any further instructions, so we assume `container_add()` will work.
637/// nrelm::RelmContainerExt::container_add(&vbox, &_gtk_button_5);
638/// _gtk_button_5.set_label("Click me!");
639/// nrelm::RelmContainerExt::container_add(&vbox, &_gtk_label_6);
640/// _gtk_label_6.set_label("The view macro works!");
641/// ```
642///
643/// The widgets are first initialized, then signals are connected and then
644/// properties and widgets are assigned to each other.
645///
646/// The nested structure of the UI is translated into regular Rust code.
647#[proc_macro]
648pub fn view(input: TokenStream) -> TokenStream {
649    view::generate_tokens(input)
650}
651
652/// A macro to generate widget templates.
653///
654/// This macro generates a new type that implements `nrelm::WidgetTemplate`.
655///
656/// # Example
657///
658/// ```
659/// use nrelm::prelude::*;
660/// use nrelm::RelmContainerExt;
661/// use nrelm_macros::{view, widget_template};
662/// use gtk::prelude::*;
663///
664/// #[widget_template]
665/// impl WidgetTemplate for MyBox {
666///     view! {
667///         gtk::Box {
668///             set_margin_all: 10,
669///            // Make the boxes visible
670///             inline_css: "border: 2px solid blue",
671///         }
672///     }
673/// }
674/// ```
675///
676/// The template allows you the generate deeply nested
677/// structures. All named items will be directly accessible
678/// as a child of the template, even if they are nested.
679/// In this example the "child_label" is a template child.
680///
681/// ```
682/// # use nrelm::prelude::*;
683/// # use nrelm::RelmContainerExt;
684/// # use nrelm_macros::{view, widget_template};
685/// # use gtk::prelude::*;
686/// #
687/// # #[widget_template]
688/// # impl WidgetTemplate for MyBox {
689/// #     view! {
690/// #         gtk::Box {
691/// #             set_margin_all: 10,
692/// #            // Make the boxes visible
693/// #             inline_css: "border: 2px solid blue",
694/// #         }
695/// #     }
696/// # }
697/// #
698/// #[widget_template]
699/// impl WidgetTemplate for MySpinner {
700///     view! {
701///         gtk::Spinner {
702///             set_active: true,
703///         }
704///     }
705/// }
706///
707/// #[widget_template]
708/// impl WidgetTemplate for CustomBox {
709///     view! {
710///         gtk::Box {
711///             set_orientation: gtk::Orientation::Vertical,
712///             set_margin_all: 5,
713///             set_spacing: 5,
714///
715///             #[template]
716///             MyBox {
717///                 #[template]
718///                 MySpinner,
719///
720///                 #[template]
721///                 MyBox {
722///                     #[template]
723///                     MySpinner,
724///
725///                     #[template]
726///                     MyBox {
727///                         #[template]
728///                         MySpinner,
729///
730///                         // Deeply nested!
731///                         #[name = "child_label"]
732///                         gtk::Label {
733///                             set_label: "This is a test",
734///                         }
735///                     }
736///                 }
737///             }
738///         }
739///     }
740/// }
741/// ```
742#[proc_macro_attribute]
743pub fn widget_template(attributes: TokenStream, input: TokenStream) -> TokenStream {
744    let SyncOnlyAttrs { visibility } = parse_macro_input!(attributes);
745
746    let item_impl = parse_macro_input!(input as ItemImpl);
747    widget_template::generate_tokens(visibility, item_impl).into()
748}
749
750#[cfg(test)]
751#[rustversion::all(stable, since(1.72))]
752mod test {
753    #[test]
754    fn ui() {
755        let t = trybuild::TestCases::new();
756        t.compile_fail("tests/ui/compile-fail/**/*.rs");
757    }
758}