nrelm-macros 0.2.0

An idiomatic GUI library inspired by Elm and based on gtk3-rs
Documentation
use proc_macro2::TokenStream as TokenStream2;
use quote::{quote, quote_spanned};
use syn::Ident;

use crate::widgets::{
    ConditionalBranches, ConditionalWidget, Properties, Property, PropertyName, PropertyType,
    Widget, WidgetAttr, WidgetTemplateAttr,
};

impl Property {
    fn init_stream(&self, stream: &mut TokenStream2) {
        match &self.ty {
            PropertyType::Widget(widget) => {
                widget.init_stream(stream);
            }
            PropertyType::ConditionalWidget(cond_widget) => {
                cond_widget.init_stream(stream);
            }
            _ => (),
        }
    }
}

impl Properties {
    fn init_stream(&self, stream: &mut TokenStream2) {
        for prop in &self.properties {
            prop.init_stream(stream);
        }
    }
}

impl Widget {
    pub(crate) fn init_stream(&self, stream: &mut TokenStream2) {
        self.self_init_stream(stream);
        self.other_init_stream(stream);
    }

    pub(crate) fn init_root_init_streams(
        &self,
        init_root_stream: &mut TokenStream2,
        init_stream: &mut TokenStream2,
    ) {
        let gtk_import = crate::gtk_import();

        // Init function as return value
        let init_root = match self.template_attr {
            WidgetTemplateAttr::None | WidgetTemplateAttr::TemplateChild => {
                self.func.func_token_stream()
            }
            WidgetTemplateAttr::Template => self.func.widget_template_init(),
        };
        // Only show the root if it is a GTK widget: either a template (which
        // dereferences to a GTK widget) or a widget whose path starts with the
        // GTK import. Arbitrary types are allowed as roots and must not get a
        // show call.
        let show_root = if self.template_attr == WidgetTemplateAttr::Template
            || root_is_gtk_widget(&self.func.path, &gtk_import)
        {
            show_root_widget_stream(
                &gtk_import,
                &Ident::new("root", proc_macro2::Span::call_site()),
                self.template_attr == WidgetTemplateAttr::Template,
            )
        } else {
            TokenStream2::new()
        };
        init_root_stream.extend(quote! {
            {
                let root = #init_root;
                #show_root
                root
            }
        });

        self.other_init_stream(init_stream);
    }

    fn self_init_stream(&self, stream: &mut TokenStream2) {
        let mutability = &self.mutable;
        let name = &self.name;
        let gtk_import = crate::gtk_import();

        // Only GTK widgets need to be shown; arbitrary types are allowed as
        // widgets in the view and must not get a show call. For `local` and
        // `local_ref` widgets the widget type is the `-> Type` annotation,
        // not the (user-defined) function path.
        let is_gtk_widget = self.template_attr == WidgetTemplateAttr::Template
            || root_is_gtk_widget(
                widget_path(
                    &self.func.path,
                    self.func.ty.as_deref(),
                    self.returned_widget.as_ref(),
                ),
                &gtk_import,
            );

        let ty = self.func.ty.as_ref().map(|ty| quote! {: #ty});
        match self.attr {
            WidgetAttr::None => {
                match self.template_attr {
                    WidgetTemplateAttr::None => {
                        let func = self.func.func_token_stream();
                        let show_widget =
                            is_gtk_widget.then(|| show_widget_stream(&gtk_import, name, false));
                        stream.extend(quote! {
                            let #mutability #name #ty = #func;
                            #show_widget
                        });
                    }
                    WidgetTemplateAttr::Template => {
                        let init = self.func.widget_template_init();
                        let show_widget = show_widget_stream(&gtk_import, name, true);
                        stream.extend(quote! {
                            let #mutability #name #ty = #init;
                            #show_widget
                        });
                    }
                    // Template children are already initialized by their template.
                    WidgetTemplateAttr::TemplateChild => (),
                }
            }
            // `local` and `local_ref` widgets are created by the user before
            // the view is built. In GTK3 they must be shown explicitly, as
            // the root window is shown with `show` instead of `show_all`.
            WidgetAttr::Local | WidgetAttr::LocalRef => {
                let show_widget =
                    is_gtk_widget.then(|| show_widget_stream(&gtk_import, name, false));
                stream.extend(quote! {
                    #show_widget
                });
            }
        }
    }

    fn other_init_stream(&self, stream: &mut TokenStream2) {
        self.properties.init_stream(stream);
        self.stack_switcher_init_stream(stream);
    }

    /// In GTK3, a `StackSwitcher` creates its buttons lazily and does not show
    /// them when children are added to its stack after the switcher has been
    /// shown. Re-show the switcher whenever a child is added to its stack.
    fn stack_switcher_init_stream(&self, stream: &mut TokenStream2) {
        let gtk_import = crate::gtk_import();
        let is_stack_switcher = root_is_gtk_widget(&self.func.path, &gtk_import)
            && self
                .func
                .path
                .segments
                .last()
                .is_some_and(|segment| segment.ident == "StackSwitcher");
        if !is_stack_switcher {
            return;
        }
        let Some(set_stack) = self.properties.properties.iter().find(|prop| {
            matches!(&prop.name, PropertyName::Ident(name) if name == "set_stack")
                && matches!(&prop.ty, PropertyType::Assign(_))
        }) else {
            return;
        };
        let PropertyType::Assign(assign) = &set_stack.ty else {
            return;
        };
        let value = &assign.expr;
        let name = &self.name;
        stream.extend(quote! {
            match #value {
                Some(stack) => {
                    let switcher = #gtk_import::glib::clone::Downgrade::downgrade(&#name);
                    #gtk_import::prelude::ContainerExt::connect_add(stack, move |_, _| {
                        let switcher = switcher.clone();
                        #gtk_import::glib::idle_add_local_once(move || {
                            if let Some(switcher) = switcher.upgrade() {
                                #gtk_import::prelude::WidgetExt::show_all(&switcher);
                            }
                        });
                    });
                }
                None => {}
            }
        });
    }
}

impl ConditionalWidget {
    pub(crate) fn init_root_init_streams(
        &self,
        init_root_stream: &mut TokenStream2,
        init_stream: &mut TokenStream2,
    ) {
        let gtk_import = crate::gtk_import();

        let show_root = show_root_widget_stream(
            &gtk_import,
            &Ident::new("root", proc_macro2::Span::call_site()),
            false,
        );
        init_root_stream.extend(quote! {
            {
                let root = #gtk_import::Stack::default();
                #show_root
                root
            }
        });

        self.other_init_stream(init_stream)
    }

    pub(crate) fn init_stream(&self, stream: &mut TokenStream2) {
        let name = &self.name;
        let gtk_import = crate::gtk_import();

        let show_widget = show_widget_stream(&gtk_import, name, false);
        stream.extend(quote_spanned! {
            name.span() =>
                let #name = #gtk_import::Stack::default();
                #show_widget
        });

        self.other_init_stream(stream);
    }

    fn other_init_stream(&self, stream: &mut TokenStream2) {
        let name = &self.name;
        let gtk_import = crate::gtk_import();

        if let Some(transition) = &self.transition {
            stream.extend(quote_spanned! {
                // emit deprecation warning
                transition.span() =>
                    const _: () = ::nrelm::macro_helper::transition();
                    #name.set_transition_type(#gtk_import::StackTransitionType:: #transition);
            });
        }

        match &self.branches {
            ConditionalBranches::If(if_branches) => {
                for branch in if_branches {
                    branch.widget.init_stream(stream);
                }
            }
            ConditionalBranches::Match((_, _, match_arms)) => {
                for arm in match_arms {
                    arm.widget.init_stream(stream);
                }
            }
        }

        if let Some(properties) = &self.properties {
            properties.init_stream(stream);
        }
    }
}

fn show_widget_stream(gtk_import: &syn::Path, widget: &Ident, template: bool) -> TokenStream2 {
    show_widget_stream_with_root(gtk_import, widget, template, false)
}

/// Whether the given widget path is a GTK widget, i.e. its first segment
/// matches the GTK import (for example `gtk::Window`, where the import may
/// be `gtk` or `nrelm::gtk`).
fn root_is_gtk_widget(path: &syn::Path, gtk_import: &syn::Path) -> bool {
    match (path.segments.first(), gtk_import.segments.last()) {
        (Some(path_segment), Some(gtk_segment)) => path_segment.ident == gtk_segment.ident,
        _ => false,
    }
}

/// The path of a widget's type: the `-> Type` annotation if present (used by
/// `local` and `local_ref` widgets), otherwise the return type of a returned
/// widget, otherwise the function path.
fn widget_path<'a>(
    func_path: &'a syn::Path,
    func_ty: Option<&'a syn::Type>,
    returned_widget: Option<&'a crate::widgets::ReturnedWidget>,
) -> &'a syn::Path {
    if let Some(syn::Type::Path(type_path)) = func_ty {
        return &type_path.path;
    }
    returned_widget
        .and_then(|ret_widget| ret_widget.ty.as_ref())
        .unwrap_or(func_path)
}

fn show_root_widget_stream(gtk_import: &syn::Path, widget: &Ident, template: bool) -> TokenStream2 {
    show_widget_stream_with_root(gtk_import, widget, template, true)
}

fn show_widget_stream_with_root(
    gtk_import: &syn::Path,
    widget: &Ident,
    template: bool,
    root: bool,
) -> TokenStream2 {
    #[cfg(feature = "nrelm")]
    {
        let _ = gtk_import;
        let show_fn = if root {
            Ident::new("show_root_widget", proc_macro2::Span::call_site())
        } else {
            Ident::new("show_widget", proc_macro2::Span::call_site())
        };
        if template {
            quote! {
                ::nrelm::macro_helper::#show_fn(&::std::ops::Deref::deref(&#widget));
            }
        } else {
            quote! {
                ::nrelm::macro_helper::#show_fn(&#widget);
            }
        }
    }
    #[cfg(not(feature = "nrelm"))]
    {
        if root {
            let deref = if template {
                quote! { ::std::ops::Deref::deref(&#widget) }
            } else {
                quote! { &#widget }
            };
            quote! {
                let widget = #gtk_import::prelude::Cast::upcast_ref::<#gtk_import::Widget>(#deref);
                if widget.downcast_ref::<#gtk_import::Window>().is_none() {
                    #gtk_import::prelude::WidgetExt::show(widget);
                }
            }
        } else if template {
            quote! {
                #gtk_import::prelude::WidgetExt::show(::std::ops::Deref::deref(&#widget));
            }
        } else {
            quote! {
                #gtk_import::prelude::WidgetExt::show(&#widget);
            }
        }
    }
}