orbtk-api 0.3.1-alpha3

API crate that provides base api and elements for OrbTk like widgets basis.
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
pub use crate::{theming::prelude::*, utils::prelude::*};
pub use dces::prelude::*;

#[macro_export]
macro_rules! into_property_source {
    ($type:ty $(: $( $ex_type:ty ),*)* ) => {
        impl IntoPropertySource<$type> for $type {
            fn into_source(self) -> PropertySource<$type> {
                PropertySource::Value(self)
            }
        }

        impl IntoPropertySource<$type> for Entity {
            fn into_source(self) -> PropertySource<$type> {
                PropertySource::Source(self)
            }
        }

        impl IntoPropertySource<$type> for (String, Entity) {
            fn into_source(self) -> PropertySource<$type> {
                PropertySource::KeySource(self.0, self.1)
            }
        }

        impl IntoPropertySource<$type> for (&str, Entity) {
            fn into_source(self) -> PropertySource<$type> {
                PropertySource::KeySource(self.0.to_string(), self.1)
            }
        }

         $(
            $(
                impl IntoPropertySource<$type> for $ex_type {
                    fn into_source(self) -> PropertySource<$type> {
                        PropertySource::Value(self.into())
                    }
                }
            )*
        )*
    };
}

/// Defines a new type of `Widget` with its properties and event handlers.
/// Widgets defined by this macro can be instantiated by calling the new() method.
/// Inherits default properties from a base widget.
/// Implements the [`Widget`] trait automatically.
/// Also the struct serves as a [`builder`] of the [`builder pattern`].
///
/// Syntax:
///
/// ```
/// widget!(MyWidgetName<MyWidgetStateStruct>: Handler1, Handler2, Handler3 {
///     property_name_1: PropertyType1,
///     property_name_2: PropertyType2
/// });
/// ```
///
/// # Examples
///
/// Creates a widget named PersonWidget with three properties, without handlers, and with
/// a state struct called WidgetState.
/// ```
/// widget!(PersonWidget<WidgetState> {
///     name: String16,
///     age: usize,
///     average: f64
/// });
/// ```
///
/// [`Widget`]: ./widget/trait.Widget.html
/// [`builder`]: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html
/// [`builder pattern`]: https://en.wikipedia.org/wiki/Builder_pattern
#[macro_export]
macro_rules! widget {
    ( $(#[$widget_doc:meta])* $widget:ident $(<$state:ident>)* $(: $( $handler:ident ),*)*
            $( { $($(#[$prop_doc:meta])* $property:ident: $property_type:tt ),*
                $( attached_properties: { $($(#[$att_prop_doc:meta])* $att_property:ident: $att_property_type:tt ),* } )*
             } )* ) => {
        $(#[$widget_doc])*
        #[derive(Default, WidgetCtx)]
        #[allow(dead_code)]
        pub struct $widget {
            attached_properties: HashMap<String, ComponentBox>,
            shared_attached_properties: HashMap<(String, String), SharedComponentBox>,
            event_handlers: Vec<Rc<dyn EventHandler>>,
            #[property(Rectangle)]
            bounds: Rectangle,
            #[property(Point)]
            position: Point,
            #[property(Constraint)]
            constraint: Constraint,
            min_width: Option<f64>,
            min_height: Option<f64>,
            max_width: Option<f64>,
            max_height: Option<f64>,
            width: Option<f64>,
            height: Option<f64>,
            name: Option<String>,
            style: Option<String>,
            id: Option<String>,
            #[property(Alignment)]
            h_align: Alignment,
            #[property(Alignment)]
            v_align: Alignment,
            #[property(Thickness)]
            margin: Thickness,
            #[property(bool)]
            enabled: bool,
            #[property(bool)]
            clip: bool,
            #[property(f32)]
            opacity: f32,
            #[property(Visibility)]
            visibility: Visibility,
            #[property(Selector)]
            selector: Selector,
            #[property(Filter)]
            on_changed_filter: Filter,
            _empty: Option<RefCell<i32>>,
             $(
                $(
                    #[property($property_type)]
                    $property: Option<PropertySource<$property_type>>,
                )*
             )*
            children: Vec<Entity>,
            $(
                state: Box<$state>
            )*
        }

        impl $widget {
            // internal helper
            fn set_property<P: Component + Debug>(mut self, key: &str, property: impl IntoPropertySource<P>) -> Self {
                match property.into_source() {
                    PropertySource::Value(value) => {
                        self.attached_properties.insert(key.to_string(), ComponentBox::new(value));
                    },
                    PropertySource::Source(source) => {
                        self.shared_attached_properties.insert((key.to_string(), key.to_string()), SharedComponentBox::new(TypeId::of::<P>(), source));
                    }
                    PropertySource::KeySource(source_key, source) => {
                        self.shared_attached_properties.insert((key.to_string(), source_key), SharedComponentBox::new(TypeId::of::<P>(), source));
                    }
                }
                self
            }

            /// Sets the id selector.
            pub fn id(mut self, id: impl Into<String>) -> Self {
                if !self.id.is_none() {
                    return self;
                }
                self.id = Some(id.into());
                self
            }

            /// Sets the style selector (replaces the old selector property).
            pub fn style(mut self, style: impl Into<String>) -> Self {
                if !self.style.is_none() {
                    return self;
                }

                self.style = Some(style.into());
                self
            }

            /// Sets or shares the position of the widget. (Be careful the position could be adjusted by layouts).
            pub fn position(self, position: impl IntoPropertySource<Point>) -> Self {
                self.set_property("position", position)
            }

            /// Sets or shares the constraint property.
            pub fn constraint(self, constraint: impl IntoPropertySource<Constraint>) -> Self {
                self.set_property("constraint", constraint)
            }

             /// Sets or shares the filter for the on_changed property callback.
             pub fn on_changed_filter(self, filter: impl IntoPropertySource<Filter>) -> Self {
                self.set_property("on_changed_filter", filter)
            }

            /// Sets or shares the vertical alignment property.
            #[inline(always)]
            pub fn v_align(self, v_align: impl IntoPropertySource<Alignment>) -> Self {
                self.set_property("v_align", v_align)
            }

             /// Sets or shares the horizontal alignment property.
             #[inline(always)]
             pub fn h_align(self, h_align: impl IntoPropertySource<Alignment>) -> Self {
                 self.set_property("h_align", h_align)
             }

            /// Sets or shares the vertical alignment property.
            #[inline(always)]
            #[deprecated = "Use v_align instead"]
            pub fn vertical_alignment(self, vertical_alignment: impl IntoPropertySource<Alignment>) -> Self {
                self.v_align(vertical_alignment)
            }

            /// Sets or shares the horizontal alignment property.
            #[inline(always)]
            #[deprecated = "Use h_align instead"]
            pub fn horizontal_alignment(self, horizontal_alignment: impl IntoPropertySource<Alignment>) -> Self {
                self.h_align(horizontal_alignment)
            }

            /// Sets or shares the visibility property.
            pub fn visibility(self, visibility: impl IntoPropertySource<Visibility>) -> Self {
                self.set_property("visibility", visibility)
            }

            /// Sets or shares the margin property.
            pub fn margin(self, margin: impl IntoPropertySource<Thickness>) -> Self {
                self.set_property("margin", margin)
            }

            /// Sets or shares the enabled property.
            pub fn enabled(self, enabled: impl IntoPropertySource<bool>) -> Self {
                self.set_property("enabled", enabled)
            }

            /// Sets or shares the clip property.
            pub fn clip(self, clip: impl IntoPropertySource<bool>) -> Self {
                self.set_property("clip", clip)
            }

            /// Sets or shares the opacity property.
            pub fn opacity(self, opacity: impl IntoPropertySource<f32>) -> Self {
                self.set_property("opacity", opacity)
            }

            /// Inserts a new width.
            pub fn width(mut self, width: impl Into<f64>) -> Self {
                if !self.width.is_none() {
                    return self;
                }
                self.width = Some(width.into());
                self
            }

            /// Inserts a new height.
            pub fn height(mut self, height: impl Into<f64>) -> Self {
                if !self.height.is_none() {
                    return self;
                }
                self.height = Some(height.into());
                self
            }

            /// Inserts a new size.
            pub fn size(mut self, width: impl Into<f64>, height: impl Into<f64>) -> Self {
                if self.width.is_none() {
                    self.width = Some(width.into());
                }
                if self.height.is_none() {
                    self.height = Some(height.into());
                }
                self
            }

            /// Inserts a new min_width.
            pub fn min_width(mut self, min_width: impl Into<f64>) -> Self {
                if !self.min_width.is_none() {
                    return self;
                }
                self.min_width = Some(min_width.into());
                self
            }

            /// Inserts a new min_height.
            pub fn min_height(mut self, min_height: impl Into<f64>) -> Self {
                if !self.min_height.is_none() {
                    return self;
                }
                self.min_height = Some(min_height.into());
                self
            }

            /// Inserts a new min_size.
            pub fn min_size(mut self, min_width: impl Into<f64>, min_height: impl Into<f64>) -> Self {
                if self.min_width.is_none() {
                    self.min_width = Some(min_width.into());
                }
                if self.min_height.is_none() {
                    self.min_height = Some(min_height.into());
                }
                self
            }

            /// Inserts a new max_width.
            pub fn max_width(mut self, max_width: impl Into<f64>) -> Self {
                if !self.max_width.is_none() {
                    return self;
                }
                self.max_width = Some(max_width.into());
                self
            }

            /// Inserts a new max_height.
            pub fn max_height(mut self, max_height: impl Into<f64>) -> Self {
                if !self.max_height.is_none() {
                    return self;
                }
                self.max_height = Some(max_height.into());
                self
            }

            /// Inserts a new min_size.
            pub fn max_size(mut self, max_width: impl Into<f64>, max_height: impl Into<f64>) -> Self {
                if self.max_width.is_none() {
                    self.max_width = Some(max_width.into());
                }
                if self.max_height.is_none() {
                    self.max_height = Some(max_height.into());
                }
                self
            }

            /// Sets the debug name of the widget.
            pub fn name<P: Into<String>>(mut self, name: P) -> Self {
                self.name = Some(name.into());
                self
            }

            $(
                /// Gets a reference of the state.
                fn state(&self) -> &Box<$state> {
                    &self.state
                }

                /// Gets a mutable reference of the state.
                fn state_mut(&mut self) -> &mut Box<$state> {
                    &mut self.state
                }
            )*

            $(
                $(
                    $(#[$prop_doc])*
                    pub fn $property<P: IntoPropertySource<$property_type>>(mut self, $property: P) -> Self {
                        if !self.$property.is_none() {
                            return self;
                        }

                        self.$property = Some($property.into_source());
                        self
                    }
                )*
            )*

            $(
                $(
                    $(
                        $(#[$att_prop_doc])*
                        pub fn $att_property(property: impl IntoPropertySource<$att_property_type>) -> AttachedProperty<$att_property_type> {
                            AttachedProperty::new(stringify!($att_property), property)
                        }
                    )*
                )*
            )*
        }

        $(
            $(
                impl $handler for $widget {}
            )*
        )*

        impl ChangedHandler for $widget {}

        impl Widget for $widget {
            /// Creates a new widget.
            #[inline]
            fn new() -> Self {
                $widget {
                    event_handlers: vec![],
                    enabled: true,
                    opacity: 1.,
                    clip: false,
                    $(
                        $(
                            $property: None,
                        )*
                    )*
                    children: vec![],
                    ..Default::default()
                }
            }

            fn attach<P: Component + Debug>(mut self, property: AttachedProperty<P>) -> Self {
                match property.property_source {
                    PropertySource::Value(value) => {
                        self.attached_properties.insert(property.key, ComponentBox::new(value));
                    }
                    PropertySource::Source(source) => {
                        self.shared_attached_properties.insert((property.key.clone(), property.key), SharedComponentBox::new(TypeId::of::<P>(), source));
                    }
                    PropertySource::KeySource(source_key, source) => {
                        self.shared_attached_properties.insert((property.key, source_key), SharedComponentBox::new(TypeId::of::<P>(), source));
                    }
                }
                self
            }

            fn insert_handler(mut self, handler: impl Into<Rc<dyn EventHandler>>) -> Self {
                self.event_handlers.push(handler.into());
                self
            }

            fn child(mut self, child: Entity) -> Self {
                self.children.push(child);
                self
            }

            fn build(self, ctx: &mut BuildContext) -> Entity {
                let entity = ctx.create_entity();

                let this = self.template(entity, ctx);

                ctx.register_render_object(entity, this.render_object());
                ctx.register_layout(entity, this.layout());

                $(
                    // workaround
                    let _ = TypeId::of::<$state>();
                    ctx.register_state(entity, this.state);
                )*

                // register default set of properties
                register_property(ctx, "bounds", entity, this.bounds);
                ctx.register_property("position", entity, this.position);
                ctx.register_property("v_align", entity, this.v_align);
                ctx.register_property("h_align", entity, this.h_align);
                ctx.register_property("on_changed_filter", entity, this.on_changed_filter);
                ctx.register_property("visibility", entity, this.visibility);
                ctx.register_property("margin", entity, this.margin);
                ctx.register_property("enabled", entity, this.enabled);
                ctx.register_property("clip", entity, this.clip);
                ctx.register_property("opacity", entity, this.opacity);
                ctx.register_property("type_id", entity, TypeId::of::<$widget>());
                ctx.register_property("type_name", entity, std::any::type_name::<$widget>().to_string());
                ctx.register_property("dirty", entity, false);

                if let Some(id) = this.id {
                    ctx.register_property("id", entity, id);
                }

                if let Some(style) = this.style {
                    ctx.register_property("selector", entity, Selector::new(style));
                } else {
                    ctx.register_property("selector", entity, this.selector);
                }

                let mut constraint = this.constraint;

                if let Some(width) = this.width {
                    constraint.set_width(width);
                }
                if let Some(height) = this.height {
                    constraint.set_height(height);
                }
                if let Some(min_width) = this.min_width {
                    constraint.set_min_width(min_width);
                }
                if let Some(min_height) = this.min_height {
                    constraint.set_min_height(min_height);
                }
                if let Some(max_width) = this.max_width {
                    constraint.set_max_width(max_width);
                }
                if let Some(max_height) = this.max_height {
                    constraint.set_max_height(max_height);
                }
                ctx.register_property("constraint", entity, constraint);

                // register attached properties
                for (key, property) in this.attached_properties {
                    ctx.register_property_box(key.as_str(), entity, property);
                }

                for (key, property) in this.shared_attached_properties {
                    ctx.register_property_shared_box_by_source_key(key.0.as_str(), key.1.as_str(), entity, property);
                }

                // register properties
                $(
                    $(
                        if let Some($property) = this.$property {
                            match $property {
                                PropertySource::Value(value) => {
                                    ctx.register_property(stringify!($property), entity, value);
                                }
                                PropertySource::Source(source) => {
                                    ctx.register_shared_property::<$property_type>(stringify!($property), entity, source);
                                }
                                PropertySource::KeySource(source_key, source) => {
                                    ctx.register_shared_property_by_source_key::<$property_type>(stringify!($property), source_key.as_str(), entity, source);
                                }
                            }
                        }
                        else {
                            ctx.register_property(stringify!($property), entity, $property_type::default());
                        }
                    )*
                )*

                ctx.update_theme_by_state(entity);

                // register event handlers
                for handler in this.event_handlers {
                    ctx.register_handler(entity, handler);
                }

                // register name
                if let Some(name) = this.name {
                    ctx.register_property("name", entity, name);
                }

                for child in this.children {
                    ctx.append_child(entity, child);
                }

                entity
            }
        }
    };
}

#[macro_export]
macro_rules! trigger_event {
    ($event:ident, $event_handler:ident, $trait:ident, $method:tt) => {
        pub struct $event(pub Entity);

        impl Event for $event {}

        pub struct $event_handler(Rc<TriggerHandler>);

        impl EventHandler for $event_handler {
            fn handle_event(&self, states: &mut StatesContext, event: &EventBox) -> bool {
                if let Ok(event) = event.downcast_ref::<$event>() {
                    (self.0)(states, event.0);
                }

                false
            }

            fn handles_event(&self, event: &EventBox) -> bool {
                event.is_type::<$event>()
            }
        }

        impl From<$event_handler> for Rc<dyn EventHandler> {
            fn from(event: $event_handler) -> Self {
                Rc::new(event)
            }
        }

        pub trait $trait: Sized + Widget {
            fn $method<H: Fn(&mut StatesContext, Entity) + 'static>(self, handler: H) -> Self {
                self.insert_handler($event_handler(Rc::new(handler)))
            }
        }
    };
}