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
//! Periodic update.
//!
//! This aspect enables a sketch's state to be update periodically.
//!
//! ```
//! use sketchbook::aspects::update;
//! # sketchbook::update_env!();
//!
//! #[apply(derive_sketch)]
//! #[sketch(env=single_aspect, aspects=(update))]
//! struct App {
//!     #[page]
//!     page: single_aspect::Page,
//! }
//!
//! impl update::Handlers for App {
//!     fn update(&mut self, delta_t: i16) {
//!         println!("Update state, time since last update: {}", delta_t);
//!     }
//! }
//! ```

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

            sketchbook::env_for_aspect!(update);

            sketchbook::compose! {
                pub enum Events {
                    #[part]
                    Aspect(update::Event),
                }
            }

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

            impl update::EnvSpecific for EnvSpecificMarker {
                type Time = i16;
                type Duration = i16;
                type Num = f32;

                fn default_update_rate() -> Self::Num {
                    30.0
                }

                fn zero_duration() -> Self::Duration {
                    0
                }

                fn duration_between(start: &Self::Time, end: &Self::Time) -> Self::Duration {
                    end - start
                }
            }

            impl update::EnvPageExt<EnvSpecificMarker> for Page {
                fn get_time(&mut self) -> update::TimeFor<EnvSpecificMarker> {
                    0
                }
            }
        }
    }
}


use core::marker::PhantomData;

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

/// Event handlers for update 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,
{
    /// Handler for [`Event::Update`] event.
    ///
    /// Parameter `delta_t` is the time since the last call to update.
    #[allow(unused_variables)]
    #[inline]
    fn update(&mut self, delta_t: DurationFor<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,
{
    /// Stop running this sketch.
    ///
    /// This will also stop all other aspects and result in dropping the sketch.
    ///
    /// ```
    /// # use sketchbook::aspects::update;
    /// # sketchbook::update_env!();
    /// # #[apply(derive_sketch)]
    /// # #[sketch(env=single_aspect, aspects=(update))]
    /// # struct App {
    /// #     #[page]
    /// #     page: single_aspect::Page,
    /// # }
    /// #
    /// impl update::Handlers for App {
    ///     fn update(&mut self, delta_t: i16) {
    ///         self.stop();
    ///         self.page.stop();
    ///     }
    /// }
    /// ```
    #[inline]
    fn stop(&mut self) {
        self.as_part_mut().should_stop = true;
    }

    /// Pause updates for this sketch.
    ///
    /// ```
    /// # use sketchbook::aspects::update;
    /// # sketchbook::update_env!();
    /// # #[apply(derive_sketch)]
    /// # #[sketch(env=single_aspect, aspects=(update))]
    /// # struct App {
    /// #     #[page]
    /// #     page: single_aspect::Page,
    /// # }
    /// #
    /// impl update::Handlers for App {
    ///     fn update(&mut self, delta_t: i16) {
    ///         self.pause();
    ///         self.page.pause();
    ///     }
    /// }
    /// ```
    #[inline]
    fn pause(&mut self) {
        self.as_part_mut().is_paused = true;
    }

    /// Resume updates for this sketch.
    ///
    /// ```
    /// # use sketchbook::aspects::update;
    /// # sketchbook::update_env!();
    /// # #[apply(derive_sketch)]
    /// # #[sketch(env=single_aspect, aspects=(update))]
    /// # struct App {
    /// #     #[page]
    /// #     page: single_aspect::Page,
    /// # }
    /// #
    /// impl update::Handlers for App {
    ///     fn update(&mut self, delta_t: i16) {
    ///         self.resume();
    ///         self.page.resume();
    ///     }
    /// }
    /// ```
    #[inline]
    fn resume(&mut self) {
        self.as_part_mut().is_paused = false;
    }

    /// Check if sketch is paused.
    ///
    /// ```
    /// # use sketchbook::aspects::update;
    /// # sketchbook::update_env!();
    /// # #[apply(derive_sketch)]
    /// # #[sketch(env=single_aspect, aspects=(update))]
    /// # struct App {
    /// #     #[page]
    /// #     page: single_aspect::Page,
    /// # }
    /// #
    /// impl update::Handlers for App {
    ///     fn update(&mut self, delta_t: i16) {
    ///         assert_eq!(self.is_paused(), self.page.is_paused());
    ///     }
    /// }
    /// ```
    #[inline]
    fn is_paused(&self) -> bool {
        self.as_part().is_paused
    }

    /// Set the rate the update handler is called.
    ///
    /// The environment may not be able to actually call the update handler at the rate given.
    ///
    /// ```
    /// # use sketchbook::aspects::update;
    /// # sketchbook::update_env!();
    /// # #[apply(derive_sketch)]
    /// # #[sketch(env=single_aspect, aspects=(update))]
    /// # struct App {
    /// #     #[page]
    /// #     page: single_aspect::Page,
    /// # }
    /// #
    /// impl update::Handlers for App {
    ///     fn update(&mut self, delta_t: i16) {
    ///         self.update_rate(60.0);
    ///         self.page.update_rate(60.0);
    ///     }
    /// }
    /// ```
    #[inline]
    fn update_rate<R: crate::real::ToReal<M::Num>>(&mut self, rate: R) {
        self.as_part_mut().update_rate = rate.to_real();
    }
}

/// Implemented on sketches and environment pages.
impl<M, T> SketchExt<M> for T
where
    Self: AsPart<EnvData<M>>,
    M: EnvSpecific,
{
    // default impls used
}

/// 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 `update`
/// aspect is passed to the `aspects=(...)` list as seen in the
/// example below.
///
/// ```
/// use sketchbook::aspects::update;
/// # sketchbook::update_env!();
/// #[apply(derive_sketch)]
/// #[sketch(env=single_aspect, aspects=(update))]
/// struct App {
///     #[page]
///     page: single_aspect::Page,
/// }
/// 
/// impl update::Handlers for App {
///     fn update(&mut self, delta_t: i16) {
///         // This handler will now be called whenever an event happens.
///     }
/// }
/// ```
pub trait RunHandlers
where
    Self: Sketch + Handlers,
    Self::Env: AssociatedEnvSpecificMarker + Environment,
    PageOf<Self::Env>:
        EnvPageExt<SpecificallyFor<Self::Env>> + AsPart<EnvData<SpecificallyFor<Self::Env>>>,
{
    /// Run event handler for event.
    fn run_handlers(&mut self, event: &Event) {
        match event {
            Event::Update => {
                let page = self.get_page_mut();
                let now = page.get_time();
                let delta_t = if let Some(last_time) = &page.as_part().last_time {
                    SpecificallyFor::<Self::Env>::duration_between(last_time, &now)
                } else {
                    SpecificallyFor::<Self::Env>::zero_duration()
                };
                self.update(delta_t);
                self.get_page_mut().as_part_mut().last_time = Some(now);
            }
        }
    }
}

/// Possible events for update aspect.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub enum Event {
    /// Update sketch state.
    Update,
}

/// 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 {
    /// Type for times.
    type Time;

    /// Type for duration between times.
    type Duration;

    /// Type for numbers.
    type Num;

    /// Default value for update rate.
    fn default_update_rate() -> Self::Num;

    /// Value for zero duration.
    fn zero_duration() -> Self::Duration;

    /// Duration between two times.
    fn duration_between(start: &Self::Time, end: &Self::Time) -> Self::Duration;
}

/// Data for update 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::Time: serde::Serialize + serde::de::DeserializeOwned"))]
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct EnvData<M>
where
    M: EnvSpecific,
{
    marker: PhantomData<M>,
    update_rate: M::Num,
    is_paused: bool,
    should_stop: bool,
    last_time: Option<M::Time>,
}

impl<M> EnvData<M>
where
    M: EnvSpecific,
{
    /// Get should stop flag.
    #[inline]
    pub fn should_stop(&self) -> bool {
        self.should_stop
    }

    /// Get the update rate.
    #[inline]
    pub fn update_rate(&self) -> &M::Num {
        &self.update_rate
    }

    /// Single to stop executing the sketch.
    #[inline]
    pub fn stop(&mut self) {
        self.should_stop = true;
    }
}

impl<M> Default for EnvData<M>
where
    M: EnvSpecific,
{
    #[inline]
    fn default() -> Self {
        Self {
            marker: PhantomData,
            update_rate: M::default_update_rate(),
            is_paused: false,
            should_stop: false,
            last_time: None,
        }
    }
}

/// Extra behavior needed on environment.
pub trait EnvPageExt<M>
where
    M: EnvSpecific,
{
    /// Get the current time.
    fn get_time(&mut self) -> M::Time;
}

/// Helper type alias to get time type for environment.
pub type TimeFor<T> = <T as EnvSpecific>::Time;

/// Helper type alias to get duration type for environment.
pub type DurationFor<T> = <T as EnvSpecific>::Duration;

/// Helper type alias to get num 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;

/// Implementation of update aspect using Instant.
#[cfg(feature = "std")]
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, Default)]
pub struct UpdateUsingInstant {
    last_update: Option<std::time::Instant>,
}

#[cfg(feature = "std")]
impl UpdateUsingInstant {
    /// Check if an update should happen. If an update should happen, then the time of calling
    /// this function is recorded to compare against the next call time.
    pub fn should_update(&mut self, update_rate: f32) -> bool {
        let now = std::time::Instant::now();
        if let Some(last_update) = self.last_update {
            if now.duration_since(last_update).as_secs_f32() >= 1. / update_rate {
                // time has expired so flag for update
                self.last_update = Some(now);
                true
            } else {
                false
            }
        } else {
            // this is the first check so flag for update
            self.last_update = Some(now);
            true
        }
    }
}

#[test]
fn test_update() {
    use crate::aspects::update;
    use crate::env::*;
    use crate::*;

    mod single_aspect {
        use crate::aspects::update;

        crate::env_for_aspect!(update);

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

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

        impl update::EnvSpecific for EnvSpecificMarker {
            type Time = i16;
            type Duration = i16;
            type Num = f32;

            fn default_update_rate() -> Self::Num {
                30.0
            }

            fn zero_duration() -> Self::Duration {
                0
            }

            fn duration_between(start: &Self::Time, end: &Self::Time) -> Self::Duration {
                end - start
            }
        }

        impl update::EnvPageExt<EnvSpecificMarker> for Page {
            fn get_time(&mut self) -> update::TimeFor<EnvSpecificMarker> {
                self.time
            }
        }
    }

    derive_sketch! {
        #[sketch(
            env = single_aspect,
            aspects = (update),
        )]
        struct App {
            #[page]
            page: single_aspect::Page,
            updated: bool,
        }
    }

    impl Setup for App {
        fn setup(page: single_aspect::Page, _: ()) -> Self {
            App {
                page,
                updated: false,
            }
        }
    }

    impl Handlers for App {
        fn update(&mut self, delta_t: i16) {
            if self.updated {
                assert_eq!(delta_t, 123);
            } else {
                assert_eq!(delta_t, 0);
                self.updated = true;
            }
        }
    }

    let mut mill = single_aspect::Mill;

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

    // send update event
    app.handle_environment_event(&single_aspect::Events::Aspect(update::Event::Update));

    assert!(app.updated);

    // change time and send update event
    app.page.time = 123;
    app.handle_environment_event(&single_aspect::Events::Aspect(update::Event::Update));

    assert_eq!(app.page.aspect.update_rate, 30.0);
    assert!(!app.page.aspect.is_paused);
    assert!(!app.page.aspect.should_stop);
    assert_eq!(app.page.aspect.last_time, Some(123));

    app.stop();
    assert!(app.page.aspect.should_stop);

    app.pause();
    assert!(app.page.aspect.is_paused);
    assert!(app.is_paused());

    app.resume();
    assert!(!app.page.aspect.is_paused);
    assert!(!app.is_paused());

    app.update_rate(10.0_f64);
    assert_eq!(app.page.aspect.update_rate, 10.0);
}

#[cfg(feature = "std")]
#[test]
fn test_update_instant_impl() {
    let mut update_impl = UpdateUsingInstant::default();

    let rate = 1_000_000.0;

    assert!(update_impl.should_update(rate));
    assert!(!update_impl.should_update(rate));
    std::thread::sleep(std::time::Duration::from_nanos(10));
    assert!(update_impl.should_update(rate));
    assert!(!update_impl.should_update(rate));
    std::thread::sleep(std::time::Duration::from_nanos(10));
    assert!(update_impl.should_update(rate));
    assert!(!update_impl.should_update(rate));
}