grx_macros 0.1.2

Macros for grx
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
// SPDX-License-Identifier: GPL-3.0-or-later

use proc_macro::TokenStream;
use quote::quote;
use syn::{
    parse::{Parse, ParseStream},
    parse_macro_input,
    token::Comma,
    Attribute, Fields, Ident, Path, Result,
};

struct ComponentArgs {
    props: Ident,
    state: Ident,
}

impl Parse for ComponentArgs {
    fn parse(input: ParseStream) -> Result<Self> {
        let props: Ident = input.parse()?;
        input.parse::<Comma>()?;
        let state: Ident = input.parse()?;
        Ok(ComponentArgs { state, props })
    }
}

#[proc_macro_attribute]
pub fn component(args: TokenStream, input: TokenStream) -> TokenStream {
    let args = parse_macro_input!(args as ComponentArgs);

    let input = parse_macro_input!(input as syn::ItemStruct);
    let vis = &input.vis;
    let ident = &input.ident;
    let fields = &input.fields;
    let fields_list = match fields {
        Fields::Named(fields) => fields.named.clone(),
        Fields::Unnamed(_) => Default::default(),
        Fields::Unit => Default::default(),
    };

    let props = args.props;
    let state = args.state;

    let gen = quote! {

        #vis struct #ident {
            root: grx::Component,
            props: #props,
            annotations: grx::annotations::Annotations,
            state: std::cell::RefCell<#state>,
            __state_update_handlers: std::rc::Rc<std::cell::RefCell<Vec< (Box<dyn Fn(&#state, &#state) -> bool>, Box<dyn Fn(&#state)>) >>>,
            __store_selectors: std::cell::RefCell<Vec<std::rc::Rc<dyn Fn()>>>,
            #fields_list
        }


        impl #ident {

            /// Update the local state.
            pub fn set_state(&self, setter: impl Fn(&mut #state) + 'static) {
                let old_state = self.state.borrow().clone();
                setter(&mut self.state.borrow_mut());
                self.__state_update_handlers.borrow().iter().for_each(move |(selector, handler)| {
                    let new_state = &*self.state.borrow();
                    if selector(&old_state, new_state) {
                        handler(new_state);
                    }
                });
            }

            /// Register a handler for a state change.
            pub fn on_state(&self, handler: impl Fn(&#state) + 'static) {
                let handlers = &mut *self.__state_update_handlers.borrow_mut();
                handler(&self.state.borrow());
                handlers.push((Box::new(|_,_| true), Box::new(handler)));
            }

            /// Get a value from the local state.
            pub fn select_state(&self, selector: impl Fn(&#state, &#state) -> bool + 'static, handler: impl Fn(&#state) + 'static) {
                let handlers = &mut *self.__state_update_handlers.borrow_mut();
                handler(&self.state.borrow());
                handlers.push((Box::new(selector), Box::new(handler)));
            }

            /// Register this callback to be triggered when the component is dropped.
            pub fn later_drop(self: &std::rc::Rc<Self>, fun: Result<std::rc::Rc<dyn Fn()>, ()>) {
                if let Ok(fun) = fun {
                    self.__store_selectors.borrow_mut().push(fun);
                }
            }
            /// Drop all own selectors from the store.
            pub fn drop_selectors_from_store(&self) {
                for dropper in self.__store_selectors.borrow().iter() {
                    dropper();
                }
            }
        }

        impl #ident {
            fn new(props: #props, component: grx::Component) -> std::rc::Rc<Self> {
                let c = std::rc::Rc::new(Self {
                    root: component,
                    props,
                    annotations: Default::default(),
                    state: Default::default(),
                    __state_update_handlers: Default::default(),
                    __store_selectors: Default::default(),
                });
                grx::props::apply(c.clone());
                c
            }
        }

        impl grx::ComponentExt for #ident {
            fn visible(self: &Self) -> bool {
                self.root.visible()
            }

            fn height(self: &Self) -> i32 {
                self.root.height()
            }
            fn width(self: &Self) -> i32 {
                self.root.width()
            }

            fn set_visible(self: &Self, visible: bool) {
                self.root.set_visible(visible)
            }

            fn add_class(self: &Self, class: &str) {
                self.root.add_class(class)
            }

            fn classes<'a>(self: &Self) -> Vec<String> {
                self.root.classes()
            }

            fn remove_class(self: &Self, class: &str) {
                self.root.remove_class(class)
            }

            fn set_styles(self: &Self, styles: Vec<grx::Style>) {
                self.root.set_styles(styles)
            }

            fn inner(self: &Self) -> std::rc::Rc<dyn std::any::Any> {
                self.root.inner()
            }

            fn props(self: &Self) -> &dyn props::ExtendingProps {
                self.root.props()
            }

            fn annotations<'a>(self: &'a Self) -> std::cell::Ref<'a, grx::annotations::Annotations> {
                self.root.annotations()
            }

            fn annotations_mut<'a>(self: &'a Self) -> std::cell::RefMut<'a, grx::annotations::Annotations> {
                self.root.annotations_mut()
            }

            fn try_annotations_mut<'a>(self: &'a Self) -> Result<std::cell::RefMut<'a, grx::annotations::Annotations>, std::cell::BorrowMutError> {
                self.root.try_annotations_mut()
            }

            fn children(self: &Self) -> std::cell::Ref<Vec<crate::grx::Component>> {
                self.root.children()
            }
             fn children_mut(self: &Self) -> std::cell::RefMut<Vec<crate::grx::Component>> {
                self.root.children_mut()
            }
            fn into_any(self: std::rc::Rc<Self>) -> std::rc::Rc<dyn std::any::Any> {
                self
            }
        }
    };
    TokenStream::from(gen)
}

/// # props macro
///
/// This macro generates all must-have props into your props struct:
/// ```rust,no_run
///
/// pub struct MyProps {
///     // These are generated:
///     pub id: &'static str,
///     pub styles: Vec<grx::Style>,
///     pub children: Vec<grx::Component>,
///     pub classes: &'static str,
/// }
///
/// ```
#[proc_macro_attribute]
pub fn props(_args: TokenStream, input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as syn::ItemStruct);
    let vis = &input.vis;
    let ident = &input.ident;
    let attrs: Vec<Attribute> = input
        .attrs
        .into_iter()
        .filter(|a| {
            if let Some(ident) = a.path().get_ident() {
                ident.to_string() != "props"
            } else {
                true
            }
        })
        .collect();
    let fields = &input.fields;
    let fields_list = match fields {
        Fields::Named(fields) => fields.named.clone(),
        Fields::Unnamed(_) => Default::default(),
        Fields::Unit => Default::default(),
    };
    let gen = quote! {
        #(#attrs)*
        #vis struct #ident {
            pub id: String,
            pub classes: String,
            pub styles: Vec<crate::grx::Style>,
            pub children: Vec<crate::grx::Component>,
            #fields_list
        }
        impl crate::grx::props::ExtendingProps for #ident {
            fn id(&self) -> Option<&str> {
                if self.id.len() == 0 {
                    None
                } else {
                    Some(&self.id)
                }
            }
            fn styles(&self) -> Option<&Vec<crate::grx::Style>> {
                if self.styles.len() == 0 {
                    None
                } else {
                    Some(&self.styles)
                }
            }
            fn classes(&self) -> Option<&str> {
                if self.classes.len() == 0 {
                    None
                } else {
                    Some(&self.classes)
                }
            }
        }
        impl crate::grx::props::ExtendingProps for &#ident {
            fn id(&self) -> Option<&str> {
                if self.id.len() == 0 {
                    None
                } else {
                    Some(&self.id)
                }
            }
            fn styles(&self) -> Option<&Vec<crate::grx::Style>> {
                if self.styles.len() == 0 {
                    None
                } else {
                    Some(&self.styles)
                }
            }
            fn classes(&self) -> Option<&str> {
                if self.classes.len() == 0 {
                    None
                } else {
                    Some(&self.classes)
                }
            }
        }
    };
    TokenStream::from(gen)
}

struct GtkComponentArgs {
    path: Path,
}

impl Parse for GtkComponentArgs {
    fn parse(input: ParseStream) -> Result<Self> {
        let path: Path = input.parse()?;
        Ok(GtkComponentArgs { path })
    }
}

#[proc_macro_attribute]
pub fn gtk_component(args: TokenStream, input: TokenStream) -> TokenStream {
    let args = parse_macro_input!(args as GtkComponentArgs);

    let input = parse_macro_input!(input as syn::ItemStruct);
    let vis = &input.vis;
    let ident = &input.ident;
    let attrs: Vec<Attribute> = input
        .attrs
        .into_iter()
        .filter(|a| {
            if let Some(ident) = a.path().get_ident() {
                ident.to_string() != "props"
            } else {
                true
            }
        })
        .collect();

    let fields = &input.fields;
    let fields_list = match fields {
        Fields::Named(fields) => fields.named.clone(),
        Fields::Unnamed(_) => Default::default(),
        Fields::Unit => Default::default(),
    };

    let wid = args.path;

    let gen = quote! {

        #(#attrs)*
        #vis struct #ident {
            widget: #wid,
            pub props: Props,
            children: std::cell::RefCell<Vec<crate::grx::Component>>,
            annotations: std::cell::RefCell<crate::annotations::Annotations>,
            #fields_list
        }

        // impl #ident {
        impl crate::components::ComponentExt for #ident {

            fn visible(self: &Self) -> bool {
                gtk::prelude::WidgetExt::is_visible(&self.widget)
            }
            fn height(self: &Self) -> i32 {
                gtk::prelude::WidgetExt::allocation(&self.widget).height()
            }
            fn width(self: &Self) -> i32 {
                gtk::prelude::WidgetExt::allocation(&self.widget).width()
            }
            fn set_visible(self: &Self, visible: bool) {
                gtk::prelude::WidgetExt::set_visible(&self.widget, visible);
            }
            fn add_class(self: &Self, class: &str) {
                gtk::prelude::WidgetExt::add_css_class(&self.widget, class);
            }
            fn classes(self: &Self) -> Vec<String> {
                gtk::prelude::WidgetExt::css_classes(&self.widget)
                    .into_iter()
                    .map(|s| s.to_string())
                    .collect()
            }
            fn set_styles(self: &Self, styles: Vec<crate::styles::Style>) {
                for style in styles.iter() {
                    crate::styles::Stylable::apply(style, self.widget.upcast_ref());
                }
            }
            fn remove_class(self: &Self, class: &str) {
                gtk::prelude::WidgetExt::remove_css_class(&self.widget, class);
            }

            // -------------------------------------------
            fn inner(self: &Self) -> std::rc::Rc<dyn std::any::Any> {
                let w: &gtk::Widget = self.widget.upcast_ref();
                Rc::new(w.clone())
            }
            fn props(&self) -> &dyn crate::props::ExtendingProps {
                &self.props
            }
            fn annotations<'a>(&'a self) -> std::cell::Ref<'a, crate::annotations::Annotations> {
                self.annotations.borrow()
            }
            fn annotations_mut<'a>(&'a self) -> std::cell::RefMut<'a, crate::annotations::Annotations> {
                use std::borrow::BorrowMut;

                self.annotations.borrow_mut()
            }
            fn try_annotations_mut<'a>(&'a self) -> Result<std::cell::RefMut<'a, crate::annotations::Annotations>, std::cell::BorrowMutError> {
                use std::borrow::BorrowMut;

                self.annotations.try_borrow_mut()
            }
            fn children(self: &Self) -> std::cell::Ref<Vec<crate::grx::Component>> {
                self.children.borrow()
            }
            fn children_mut(self: &Self) -> std::cell::RefMut<Vec<crate::grx::Component>> {
                self.children.borrow_mut()
            }
            fn into_any(self: std::rc::Rc<Self>) -> std::rc::Rc<dyn std::any::Any> {
                self
            }
        }


        // impl crate::render::Render<gtk::Widget> for #ident {
        //     fn inner(&self) -> &gtk::Widget {
        //         self.widget.upcast_ref()
        //     }
        //     fn props(&self) -> std::rc::Rc<dyn crate::props::ExtendingProps> {
        //         self.props.clone()
        //     }
        //     fn annotations(&self) -> &crate::annotations::Annotations {
        //         &self.annotations
        //     }
        //     fn any(self: Rc<Self>) -> Rc<dyn std::any::Any> {
        //         self
        //     }
        // }

    };
    TokenStream::from(gen)
}