sketchbook 0.0.2

Interactive visual applications in Rust
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
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//! Mouse input.
//!
//! This aspect enables mouse input for an environment.
//!
//! ```
//! use sketchbook::aspects::mouse;
//! # sketchbook::mouse_env!();
//!
//! #[apply(derive_sketch)]
//! #[sketch(env=single_aspect, aspects=(mouse))]
//! struct App {
//!     #[page]
//!     page: single_aspect::Page,
//! }
//!
//! impl mouse::Handlers for App {
//!     fn moved(&mut self, previous: Point2<f32>) {
//!         println!("Mouse moved");
//!     }
//! }
//! ```

/// Create test environment for keyboard aspect for use in doc tests.
#[doc(hidden)]
#[macro_export]
macro_rules! mouse_env {
    {} => {
        use sketchbook::derive_sketch;
        use sketchbook::Point2;
        use macro_rules_attribute::apply;
        use sketchbook::aspects::mouse::SketchExt;
        mod single_aspect {
            use sketchbook::aspects::mouse;
            use sketchbook::aspects::mouse::*;

            sketchbook::env_for_aspect!(mouse);

            sketchbook::compose! {
                pub enum Events {
                    #[part]
                    Aspect(mouse::Event<EnvSpecificMarker>),
                }
            }

            sketchbook::compose! {
                #[derive(Default)]
                pub struct Page {
                    #[part]
                    pub aspect: mouse::EnvData<EnvSpecificMarker>,
                }
            }

            impl mouse::EnvSpecific for EnvSpecificMarker {
                type Button = u8;
                type ButtonSet = std::collections::HashSet<u8>;
                type Num = f32;
            }
        }
    }
}


use core::{borrow::Borrow, marker::PhantomData, ops::Add};

use crate::{compose::AsPart, Environment, PageOf, Point2, Sketch};

/// Event handlers for mouse aspect.
///
/// Each handler has a default implementation that does nothing.
/// Implement a method to perform actions when the associated event happens.
pub trait Handlers
where
    Self: Sketch,
    Self::Env: AssociatedEnvSpecificMarker,
{
    /// Mouse moved while any button is held.
    #[allow(unused_variables)]
    #[inline]
    fn dragged(&mut self, previous: Point2<NumFor<SpecificallyFor<Self::Env>>>) {
        // by default do nothing
    }

    /// Mouse moved with no buttons pressed.
    #[allow(unused_variables)]
    #[inline]
    fn moved(&mut self, previous: Point2<NumFor<SpecificallyFor<Self::Env>>>) {
        // by default do nothing
    }

    /// Mouse button was clicked (press followed by release).
    #[allow(unused_variables)]
    #[inline]
    fn clicked(&mut self, button: &ButtonFor<SpecificallyFor<Self::Env>>) {
        // by default do nothing
    }

    /// Handler for [`Event::Press`] event.
    #[allow(unused_variables)]
    #[inline]
    fn pressed(&mut self, button: &ButtonFor<SpecificallyFor<Self::Env>>) {
        // by default do nothing
    }

    /// Handler for [`Event::Release`] event.
    #[allow(unused_variables)]
    #[inline]
    fn released(&mut self, button: &ButtonFor<SpecificallyFor<Self::Env>>) {
        // by default do nothing
    }

    /// Handler for [`Event::Wheel`] event.
    #[allow(unused_variables)]
    #[inline]
    fn wheel(&mut self, count: &NumFor<SpecificallyFor<Self::Env>>) {
        // by default do nothing
    }
}

/// Extension methods for sketch.
///
/// These methods are automatically implemented for sketches where the 
/// environment implements the draw aspect. These methods are also available
/// on the page for the environment.
pub trait SketchExt<M>
where
    Self: AsPart<EnvData<M>>,
    M: EnvSpecific + 'static,
{
    /// Get the current x position of the mouse.
    ///
    /// ```
    /// # use sketchbook::aspects::mouse;
    /// # sketchbook::mouse_env!();
    /// # #[apply(derive_sketch)]
    /// # #[sketch(env=single_aspect, aspects=(mouse))]
    /// # struct App {
    /// #     #[page]
    /// #     page: single_aspect::Page,
    /// # }
    /// #
    /// impl mouse::Handlers for App {
    ///     fn moved(&mut self, previous: Point2<f32>) {
    ///         assert_eq!(self.mouse_x(), self.page.mouse_x());
    ///     }
    /// }
    /// ```
    #[inline]
    fn mouse_x(&self) -> &NumFor<M> {
        &self.as_part().position.x
    }

    /// Get the current y position of the mouse.
    ///
    /// ```
    /// # use sketchbook::aspects::mouse;
    /// # sketchbook::mouse_env!();
    /// # #[apply(derive_sketch)]
    /// # #[sketch(env=single_aspect, aspects=(mouse))]
    /// # struct App {
    /// #     #[page]
    /// #     page: single_aspect::Page,
    /// # }
    /// #
    /// impl mouse::Handlers for App {
    ///     fn moved(&mut self, previous: Point2<f32>) {
    ///         assert_eq!(self.mouse_y(), self.page.mouse_y());
    ///     }
    /// }
    /// ```
    #[inline]
    fn mouse_y(&self) -> &NumFor<M> {
        &self.as_part().position.y
    }

    /// Get the current position of the mouse.
    ///
    /// ```
    /// # use sketchbook::aspects::mouse;
    /// # sketchbook::mouse_env!();
    /// # #[apply(derive_sketch)]
    /// # #[sketch(env=single_aspect, aspects=(mouse))]
    /// # struct App {
    /// #     #[page]
    /// #     page: single_aspect::Page,
    /// # }
    /// #
    /// impl mouse::Handlers for App {
    ///     fn moved(&mut self, previous: Point2<f32>) {
    ///         assert_eq!(self.mouse_point(), self.page.mouse_point());
    ///     }
    /// }
    /// ```
    #[inline]
    fn mouse_point(&self) -> &Point2<NumFor<M>> {
        &self.as_part().position
    }

    /// Check if a mouse button is pressed.
    ///
    /// ```
    /// # use sketchbook::aspects::mouse;
    /// # sketchbook::mouse_env!();
    /// # #[apply(derive_sketch)]
    /// # #[sketch(env=single_aspect, aspects=(mouse))]
    /// # struct App {
    /// #     #[page]
    /// #     page: single_aspect::Page,
    /// # }
    /// #
    /// impl mouse::Handlers for App {
    ///     fn moved(&mut self, previous: Point2<f32>) {
    ///         assert_eq!(self.button_pressed(2), self.page.button_pressed(2));
    ///     }
    /// }
    /// ```
    #[inline]
    fn button_pressed<B: Borrow<ButtonFor<M>>>(&self, button: B) -> bool {
        self.as_part()
            .pressed_buttons
            .button_set_contains(button.borrow())
    }

    /// Check if any mouse buttons are pressed.
    ///
    /// ```
    /// # use sketchbook::aspects::mouse;
    /// # sketchbook::mouse_env!();
    /// # #[apply(derive_sketch)]
    /// # #[sketch(env=single_aspect, aspects=(mouse))]
    /// # struct App {
    /// #     #[page]
    /// #     page: single_aspect::Page,
    /// # }
    /// #
    /// impl mouse::Handlers for App {
    ///     fn moved(&mut self, previous: Point2<f32>) {
    ///         assert_eq!(self.any_button_pressed(), self.page.any_button_pressed());
    ///     }
    /// }
    /// ```
    #[inline]
    fn any_button_pressed(&self) -> bool {
        !self.as_part().pressed_buttons.button_set_is_empty()
    }
}

impl<M, T> SketchExt<M> for T
where
    Self: AsPart<EnvData<M>>,
    M: EnvSpecific,
{
}

/// Run event handler methods based on event.
///
/// A user usually doesn't need to use this directly as the
/// [`crate::derive_sketch`] macro will use it automatically.
/// This trait is implemented for the sketch when the `mouse`
/// aspect is passed to the `aspects=(...)` list as seen in the
/// example below.
///
/// ```
/// use sketchbook::aspects::mouse;
/// # sketchbook::mouse_env!();
/// #[apply(derive_sketch)]
/// #[sketch(env=single_aspect, aspects=(mouse))]
/// struct App {
///     #[page]
///     page: single_aspect::Page,
/// }
/// 
/// impl mouse::Handlers for App {
///     fn moved(&mut self, previous: Point2<f32>) {
///         // This handler will now be called whenever an event happens.
///     }
/// }
/// ```
pub trait RunHandlers
where
    Self: Sketch + Handlers,
    Self::Env: AssociatedEnvSpecificMarker + Environment,
    PageOf<Self::Env>: AsPart<EnvData<SpecificallyFor<Self::Env>>>,
{
    /// Run event handler for event.
    fn run_handlers(&mut self, event: &Event<SpecificallyFor<Self::Env>>) {
        match event {
            Event::MoveRelative(point) => {
                let data = self.get_page_mut().as_part_mut();
                let new_position = &data.position + point;
                let previous = core::mem::replace(&mut data.position, new_position);
                if data.pressed_buttons.button_set_is_empty() {
                    self.moved(previous);
                } else {
                    self.dragged(previous);
                }
            }
            Event::MoveAbsolute(point) => {
                let data = self.get_page_mut().as_part_mut();
                let previous = core::mem::replace(&mut data.position, point.clone());
                if data.pressed_buttons.button_set_is_empty() {
                    self.moved(previous);
                } else {
                    self.dragged(previous);
                }
            }
            Event::Wheel(count) => {
                self.wheel(count);
            }
            Event::Press(button) => {
                let data = self.get_page_mut().as_part_mut();
                data.pressed_buttons.button_set_insert(button.clone());
                self.pressed(button);
            }
            Event::Release(button) => {
                let data = self.get_page_mut().as_part_mut();
                let was_pressed = data.pressed_buttons.button_set_remove(button);
                self.released(button);
                if was_pressed {
                    self.clicked(button);
                }
            }
            Event::_MetaPhantom(_, _) => unreachable!(),
        }
    }
}

/// Possible events for keyboard aspect.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub enum Event<M>
where
    M: EnvSpecific,
{
    /// Needed to allow the use of `M`.
    #[doc(hidden)]
    #[cfg_attr(feature = "serde", serde(skip))]
    _MetaPhantom(core::convert::Infallible, PhantomData<M>),

    /// Mouse move relative position.
    MoveRelative(Point2<M::Num>),

    /// Mouse move absolute position.
    MoveAbsolute(Point2<M::Num>),

    /// Mouse button pressed.
    Press(M::Button),

    /// Mouse button released.
    Release(M::Button),

    /// Scroll wheel moved.
    Wheel(M::Num),
}

/// Marker trait for getting environment specific marker type.
pub trait AssociatedEnvSpecificMarker {
    /// Marker type that has environment specific implementations on it.
    type EnvSpecificMarker: EnvSpecific;
}

/// Marker trait for environment specific types.
pub trait EnvSpecific: 'static {
    /// Type used for mouse buttons.
    type Button: Clone;

    /// Type used for numbers.
    type Num: Default + Add<Output = Self::Num> + Clone;

    /// Type for set of buttons pressed.
    type ButtonSet: ButtonSet<Self::Button>;
}

/// Trait for types that can be used as a pressed button set.
pub trait ButtonSet<B> {
    /// Check if the set is empty.
    fn button_set_is_empty(&self) -> bool;

    /// Insert key into set.
    fn button_set_insert(&mut self, value: B);
    
    /// Check if set contains key.
    fn button_set_contains(&self, value: &B) -> bool;

    /// Remove key from set.
    fn button_set_remove(&mut self, value: &B) -> bool;
}

#[cfg(feature = "std")]
impl<B> ButtonSet<B> for std::collections::HashSet<B>
where
    B: std::hash::Hash + Eq,
{
    #[inline]
    fn button_set_is_empty(&self) -> bool {
        self.is_empty()
    }

    #[inline]
    fn button_set_insert(&mut self, value: B) {
        let _ = self.insert(value);
    }

    #[inline]
    fn button_set_remove(&mut self, value: &B) -> bool {
        self.remove(value)
    }

    #[inline]
    fn button_set_contains(&self, value: &B) -> bool {
        self.contains(value)
    }
}

#[cfg(feature = "alloc")]
impl<B> ButtonSet<B> for alloc::collections::BTreeSet<B>
where
    B: Ord,
{
    #[inline]
    fn button_set_is_empty(&self) -> bool {
        self.is_empty()
    }

    #[inline]
    fn button_set_insert(&mut self, value: B) {
        let _ = self.insert(value);
    }

    #[inline]
    fn button_set_remove(&mut self, value: &B) -> bool {
        self.remove(value)
    }

    #[inline]
    fn button_set_contains(&self, value: &B) -> bool {
        self.contains(value)
    }
}

/// Data for mouse aspect that the environment's page will hold.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(bound = "M::Num: serde::Serialize + serde::de::DeserializeOwned, M::ButtonSet: serde::Serialize + serde::de::DeserializeOwned"))]
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct EnvData<M>
where
    M: EnvSpecific,
{
    /// Store the marker type.
    marker: PhantomData<M>,

    /// Current position of the mouse.
    position: Point2<M::Num>,

    /// Buttons currently pressed.
    pressed_buttons: M::ButtonSet,
}

impl<M> Default for EnvData<M>
where
    M: EnvSpecific,
    M::ButtonSet: Default,
{
    #[inline]
    fn default() -> Self {
        Self {
            marker: PhantomData,
            pressed_buttons: M::ButtonSet::default(),
            position: Point2 {
                x: M::Num::default(),
                y: M::Num::default(),
            },
        }
    }
}

/// Helper type alias to get button type for environment.
pub type ButtonFor<T> = <T as EnvSpecific>::Button;

/// Helper type alias to get number type for environment.
pub type NumFor<T> = <T as EnvSpecific>::Num;

/// Helper type alias to get type specifically for environment.
pub type SpecificallyFor<T> = <T as AssociatedEnvSpecificMarker>::EnvSpecificMarker;

#[test]
fn test_mouse() {
    use crate::aspects::mouse;
    use crate::env::*;
    use crate::*;

    mod single_aspect {
        use std::collections::HashSet;

        use crate::aspects::mouse;

        crate::env_for_aspect!(mouse);

        crate::compose! {
            pub enum Events {
                #[part]
                Aspect(super::Event<EnvSpecificMarker>),
            }
        }

        crate::compose! {
            #[derive(Default)]
            pub struct Page {
                #[part]
                pub aspect: super::EnvData<EnvSpecificMarker>,
            }
        }

        impl mouse::EnvSpecific for EnvSpecificMarker {
            type Button = u8;
            type ButtonSet = HashSet<u8>;
            type Num = f32;
        }
    }

    derive_sketch! {
        #[sketch(
            env = single_aspect,
            aspects = (mouse),
        )]
        struct App {
            #[page] page: single_aspect::Page,
            dragged: bool,
            moved: bool,
            clicked: bool,
            pressed: bool,
            released: bool,
            wheel: bool,
        }
    }

    impl Setup for App {
        fn setup(page: single_aspect::Page, _: ()) -> Self {
            App {
                page,
                dragged: false,
                moved: false,
                clicked: false,
                pressed: false,
                released: false,
                wheel: false,
            }
        }
    }

    impl Handlers for App {
        fn dragged(&mut self, previous: Point2<f32>) {
            assert_eq!(previous, Point2 { x: 1.0, y: -2.0 });
            assert_eq!(*self.mouse_x(), -2.0);
            assert_eq!(*self.mouse_y(), 1.0);
            assert_eq!(*self.mouse_point(), Point2 { x: -2.0, y: 1.0 });
            self.dragged = true;
        }

        fn moved(&mut self, previous: Point2<f32>) {
            assert_eq!(previous, Point2 { x: 0.0, y: 0.0 });
            assert_eq!(*self.mouse_x(), 1.0);
            assert_eq!(*self.mouse_y(), -2.0);
            assert_eq!(*self.mouse_point(), Point2 { x: 1.0, y: -2.0 });
            self.moved = true;
        }

        fn clicked(&mut self, &button: &u8) {
            assert_eq!(button, 4);
            self.clicked = true;
        }

        fn pressed(&mut self, &button: &u8) {
            assert_eq!(button, 4);
            self.pressed = true;
        }

        fn released(&mut self, &button: &u8) {
            assert_eq!(button, 4);
            self.released = true;
        }

        fn wheel(&mut self, count: &f32) {
            assert_eq!(*count, -20.0);
            self.wheel = true;
        }
    }

    let mut mill = single_aspect::Mill;

    let mut app = App::setup(mill.new_page(), ());

    // move mouse
    app.handle_environment_event(&single_aspect::Events::Aspect(mouse::Event::MoveAbsolute(
        Point2 { x: 1.0, y: -2.0 },
    )));

    // press button
    app.handle_environment_event(&single_aspect::Events::Aspect(mouse::Event::Press(4)));

    // move mouse (this becomes a drag event)
    app.handle_environment_event(&single_aspect::Events::Aspect(mouse::Event::MoveRelative(
        Point2 { x: -3.0, y: 3.0 },
    )));

    // release button
    app.handle_environment_event(&single_aspect::Events::Aspect(mouse::Event::Release(4)));

    // move wheel
    app.handle_environment_event(&single_aspect::Events::Aspect(mouse::Event::Wheel(-20.0)));

    assert!(app.moved);
    assert!(app.pressed);
    assert!(app.dragged);
    assert!(app.released);
    assert!(app.clicked);
    assert!(app.wheel);
}