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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
use super::gc::*;
use super::draw::*;
use super::color::*;
use super::transform2d::*;

use std::collections::vec_deque::*;
use std::sync::*;
use std::mem;

use desync::*;
use futures::task::Task;
use futures::task;
use futures::{Stream,Poll,Async};

///
/// The core structure used to store details of a canvas 
///
struct CanvasCore {
    /// What was drawn since the last clear command was sent to this canvas (and the layer that it's on)
    drawing_since_last_clear: Vec<(u32, Draw)>,

    /// The current layer that we're drawing on
    current_layer: u32,

    // Tasks to notify next time we add to the canvas
    pending_streams: Vec<Arc<CanvasStream>>,
}

///
/// A canvas is an abstract interface for drawing graphics. It doesn't actually provide a means to
/// render anything, but rather a way to describe how things should be drawn and pass those on to
/// a renderer elsewhere. 
///
pub struct Canvas {
    /// The core is shared amongst the canvas streams as well as used by the canvas itself
    core: Desync<CanvasCore>
}

impl CanvasCore {
    ///
    /// On restore, rewinds the canvas to before the last store operation
    /// 
    fn rewind_to_last_store(&mut self) {
        let mut last_store = None;

        // Search backwards in the drawing commands for the last store command
        for draw_index in (0..self.drawing_since_last_clear.len()).rev() {
            match self.drawing_since_last_clear[draw_index] {
                // Commands that might cause the store/restore to not undo perfectly break the sequence
                (_, Draw::Clip)         => break,
                (_, Draw::Unclip)       => break,
                (_, Draw::PushState)    => break,
                (_, Draw::PopState)     => break,

                // If we find no sequence breaks and a store, this is where we want to rewind to
                (_, Draw::Store)        => {
                    last_store = Some(draw_index+1);
                    break;
                },

                _               => ()
            };
        }

        // Remove everything up to the last store position
        if let Some(last_store) = last_store {
            self.drawing_since_last_clear.truncate(last_store);
        }
    }

    ///
    /// Removes all of the drawing for the specified layer
    /// 
    /// (Except for ClearCanvas)
    /// 
    fn clear_layer(&mut self, layer_id: u32) {
        // Take the old drawing from this object
        let mut old_drawing = vec![];
        mem::swap(&mut self.drawing_since_last_clear, &mut old_drawing);

        // Create a new drawing by filtering all of the actions for the current layer
        let new_drawing = old_drawing.into_iter()
            .filter(|drawing| {
                match drawing {
                    &(_, Draw::ClearCanvas)         => true,
                    &(_, Draw::LayerBlend(_, _))    => true,
                    &(layer, _)                     => layer != layer_id
                }
            })
            .collect();
        
        // This becomes the new drawing for this layer
        self.drawing_since_last_clear = new_drawing;
    }

    ///
    /// Writes some drawing commands to this core
    /// 
    fn write(&mut self, to_draw: Vec<Draw>) {
        // Build up the list of new drawing commands
        let mut new_drawing     = vec![];
        let mut clear_pending   = false;

        // Process the drawing commands
        to_draw.iter().for_each(|draw| {
            match draw {
                &Draw::ClearCanvas => {
                    // Clearing the canvas empties the command list and updates the clear count
                    self.drawing_since_last_clear   = vec![];
                    self.current_layer              = 0;
                    clear_pending                   = true;

                    new_drawing = vec![];

                    // Start the new drawing with the 'clear' command
                    self.drawing_since_last_clear.push((0, *draw));
                },

                &Draw::Restore => {
                    // Have to push the restore in case it can't be cleared
                    self.drawing_since_last_clear.push((self.current_layer, *draw));

                    // On a 'restore' command we clear out everything since the 'store' if we can (so we don't build a backlog)
                    self.rewind_to_last_store();
                },

                &Draw::FreeStoredBuffer => {
                    // If the last operation was a store, pop it
                    if let Some(&(_, Draw::Store)) = self.drawing_since_last_clear.last() {
                        // Store and immediate free = just free
                        self.drawing_since_last_clear.pop();
                    } else {
                        // Something else: the free becomes part of the drawing log (this is often inefficient)
                        self.drawing_since_last_clear.push((self.current_layer, *draw));
                    }
                },

                &Draw::Layer(new_layer) => {
                    self.current_layer = new_layer;
                    self.drawing_since_last_clear.push((new_layer, *draw));
                },

                &Draw::ClearLayer => {
                    // Remove all of the commands for the current layer, replacing them with just a switch to this layer
                    let current_layer = self.current_layer;
                    self.clear_layer(current_layer);
                    self.drawing_since_last_clear.push((current_layer, Draw::Layer(current_layer)));
                },

                // Default is to add to the current drawing
                _ => self.drawing_since_last_clear.push((self.current_layer, *draw))
            }

            // Send everything to the streams
            new_drawing.push(*draw);
        });

        // Send the new drawing commands to the streams
        let mut to_remove = vec![];

        for stream_index in 0..self.pending_streams.len() {
            // Send commands to this stream
            if !self.pending_streams[stream_index].send_drawing(new_drawing.iter().map(|draw| *draw), clear_pending) {
                // If it returns false then the stream has been dropped and we should remove it from this object
                to_remove.push(stream_index);
            }
        }

        // Remove streams (in reverse order so the indexes don't get messed up)
        for remove_index in to_remove.into_iter().rev() {
            self.pending_streams.remove(remove_index);
        }
    }
}

impl Canvas {
    ///
    /// Creates a new, blank, canvas
    ///
    pub fn new() -> Canvas {
        // A canvas is initially just a clear command
        let core = CanvasCore { 
            drawing_since_last_clear:   vec![ (0, Draw::ClearCanvas) ],
            current_layer:              0,
            pending_streams:            vec![ ]
        };

        Canvas {
            core: Desync::new(core)
        }
    }

    ///
    /// Sends some new drawing commands to this canvas
    ///
    pub fn write(&self, to_draw: Vec<Draw>) {
        // Only draw if there are any drawing commands
        if to_draw.len() != 0 {
            self.core.async(move |core| core.write(to_draw));
        }
    }

    ///
    /// Provides a way to draw on this canvas via a GC
    /// 
    pub fn draw<FnAction>(&self, action: FnAction)
    where FnAction: Send+FnOnce(&mut GraphicsPrimitives) -> () {
        self.core.sync(move |core| {
            let mut graphics_context = CoreContext {
                core:       core,
                pending:    vec![]
            };

            action(&mut graphics_context);
        })
    }

    ///
    /// Creates a stream for reading the instructions from this canvas
    ///
    pub fn stream(&self) -> Box<Stream<Item=Draw,Error=()>+Send> {
        // Create a new canvas stream
        let new_stream = Arc::new(CanvasStream::new());

        // Register it and send the current set of pending commands to it
        let add_stream = Arc::clone(&new_stream);
        self.core.sync(move |core| {
            // Send the data we've received since the last clear
            add_stream.send_drawing(core.drawing_since_last_clear.iter().map(|&(_, draw)| draw), true);

            // Store the stream in the core so future notifications get sent there
            core.pending_streams.push(add_stream);
        });

        // Return the new stream
        Box::new(FragileCanvasStream::new(new_stream))
    }

    ///
    /// Retrieves the list of drawing actions in this canvas
    ///
    pub fn get_drawing(&self) -> Vec<Draw> {
        self.core.sync(|core| core.drawing_since_last_clear.iter().map(|&(_, draw)| draw.clone()).collect())
    }
}

impl Drop for Canvas {
    fn drop(&mut self) {
        self.core.async(|core| {
            // Notify any streams that are using the canvas that it has gone away
            core.pending_streams.iter_mut().for_each(|stream| stream.notify_dropped());
        });
    }
}

///
/// Graphics context built from a canvas core
///
struct CoreContext<'a> {
    core:       &'a mut CanvasCore,
    pending:    Vec<Draw>
}

impl<'a> GraphicsContext for CoreContext<'a> {
    fn new_path(&mut self)                          { self.pending.push(Draw::NewPath); }
    fn move_to(&mut self, x: f32, y: f32)           { self.pending.push(Draw::Move(x, y)); }
    fn line_to(&mut self, x: f32, y: f32)           { self.pending.push(Draw::Line(x, y)); }

    fn bezier_curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x3: f32, y3: f32) {
        self.pending.push(Draw::BezierCurve((x1, y1), (x2, y2), (x3, y3)));
    }

    fn close_path(&mut self)                        { self.pending.push(Draw::ClosePath); }
    fn fill(&mut self)                              { self.pending.push(Draw::Fill); }
    fn stroke(&mut self)                            { self.pending.push(Draw::Stroke); }
    fn line_width(&mut self, width: f32)            { self.pending.push(Draw::LineWidth(width)); }
    fn line_width_pixels(&mut self, width: f32)     { self.pending.push(Draw::LineWidthPixels(width)); }
    fn line_join(&mut self, join: LineJoin)         { self.pending.push(Draw::LineJoin(join)); }
    fn line_cap(&mut self, cap: LineCap)            { self.pending.push(Draw::LineCap(cap)); }
    fn new_dash_pattern(&mut self)                  { self.pending.push(Draw::NewDashPattern); }
    fn dash_length(&mut self, length: f32)          { self.pending.push(Draw::DashLength(length)); }
    fn dash_offset(&mut self, offset: f32)          { self.pending.push(Draw::DashOffset(offset)); }
    fn fill_color(&mut self, col: Color)            { self.pending.push(Draw::FillColor(col)); }
    fn stroke_color(&mut self, col: Color)          { self.pending.push(Draw::StrokeColor(col)); }
    fn blend_mode(&mut self, mode: BlendMode)       { self.pending.push(Draw::BlendMode(mode)); }
    fn identity_transform(&mut self)                { self.pending.push(Draw::IdentityTransform); }
    fn canvas_height(&mut self, height: f32)        { self.pending.push(Draw::CanvasHeight(height)); }
    fn center_region(&mut self, minx: f32, miny: f32, maxx: f32, maxy: f32) { self.pending.push(Draw::CenterRegion((minx, miny), (maxx, maxy))); }
    fn transform(&mut self, transform: Transform2D) { self.pending.push(Draw::MultiplyTransform(transform)); }
    fn unclip(&mut self)                            { self.pending.push(Draw::Unclip); }
    fn clip(&mut self)                              { self.pending.push(Draw::Clip); }
    fn store(&mut self)                             { self.pending.push(Draw::Store); }
    fn restore(&mut self)                           { self.pending.push(Draw::Restore); }
    fn free_stored_buffer(&mut self)                { self.pending.push(Draw::FreeStoredBuffer); }
    fn push_state(&mut self)                        { self.pending.push(Draw::PushState); }
    fn pop_state(&mut self)                         { self.pending.push(Draw::PopState); }
    fn clear_canvas(&mut self)                      { self.pending.push(Draw::ClearCanvas); }
    fn layer(&mut self, layer_id: u32)              { self.pending.push(Draw::Layer(layer_id)); }
    fn layer_blend(&mut self, layer_id: u32, blend_mode: BlendMode) { self.pending.push(Draw::LayerBlend(layer_id, blend_mode)); }
    fn clear_layer(&mut self)                       { self.pending.push(Draw::ClearLayer); }

    fn draw(&mut self, d: Draw)                     { self.pending.push(d); }
    fn draw_list<'b>(&'b mut self, drawing: Box<'b+Iterator<Item=Draw>>) {
        self.pending.extend(drawing);
    }
}

impl<'a> GraphicsPrimitives for CoreContext<'a> { }

impl<'a> Drop for CoreContext<'a> {
    fn drop(&mut self) {
        let mut to_draw = vec![];
        mem::swap(&mut self.pending, &mut to_draw);
        self.core.write(to_draw);
    }
}

///
/// Internals of a canvas stream
/// 
struct CanvasStreamCore {
    /// Items waiting to be drawn for this stream
    queue: VecDeque<Draw>,

    /// The task to notify when extra data is available
    waiting_task: Option<Task>,

    /// Set to true when the canvas is dropped
    canvas_dropped: bool,

    /// Set to true if the stream is dropped
    stream_dropped: bool
}

///
/// The canvas stream can be used to read the contents of the canvas and follow new content as it arrives.
/// Unconsumed commands are cut off if the `Draw::ClearCanvas` command is issued.
///
struct CanvasStream {
    /// The core of this stream
    core: Mutex<CanvasStreamCore>
}

impl CanvasStream {
    ///
    /// Creates a new canvas stream
    /// 
    pub fn new() -> CanvasStream {
        CanvasStream {
            core: Mutex::new(CanvasStreamCore {
                queue:          VecDeque::new(),
                waiting_task:   None,
                canvas_dropped: false,
                stream_dropped: false
            })
        }
    }

    ///
    /// Wakes the stream task
    /// 
    fn notify_dropped(&self) {
        let mut core = self.core.lock().unwrap();

        core.canvas_dropped = true;

        if let Some(ref task) = core.waiting_task {
            task.notify();
        }
        core.waiting_task = None;
    }

    ///
    /// Sends some drawing commands to this stream (returning true if this stream wants more commands)
    /// 
    fn send_drawing<DrawIter: Iterator<Item=Draw>> (&self, drawing: DrawIter, clear_pending: bool) -> bool {
        let mut core = self.core.lock().unwrap();

        // Clear out any pending commands if they're hidden by a clear
        if clear_pending {
            core.queue.clear();
        }

        // Push the drawing commands
        for draw in drawing {
            core.queue.push_back(draw);
        }

        // If a task needs waking up, wake it
        if let Some(ref task) = core.waiting_task {
            task.notify();
        }
        core.waiting_task = None;

        // We want more commands if the stream is not dropped
        !core.stream_dropped
    }
}

impl CanvasStream {
    fn poll(&self) -> Poll<Option<Draw>, ()> {
        use self::Async::*;

        let mut core = self.core.lock().unwrap();

        if let Some(value) = core.queue.pop_front() {
            Ok(Ready(Some(value)))
        } else if core.canvas_dropped {
            Ok(Ready(None))
        } else {
            core.waiting_task = Some(task::current());
            Ok(NotReady)
        }
   }
}

///
/// The 'fragile' canvas stream is a variant of the canvas stream that marks the
/// stream as being dropped if this happens (so that we can remove it from the
/// list in the canvas)
/// 
struct FragileCanvasStream {
    stream: Arc<CanvasStream>
}

impl FragileCanvasStream {
    pub fn new(stream: Arc<CanvasStream>) -> FragileCanvasStream {
        FragileCanvasStream { stream: stream }
    }
}

impl Drop for FragileCanvasStream {
    fn drop(&mut self) {
        let mut core = self.stream.core.lock().unwrap();

        core.stream_dropped = true;
    }
}

impl Stream for FragileCanvasStream {
    type Item = Draw;
    type Error = ();

    fn poll(&mut self) -> Poll<Option<Draw>, ()> {
        self.stream.poll()
    }
}

#[cfg(test)]
mod test {
    use super::*;

    use futures::executor;

    use std::thread::*;
    use std::time::*;

    #[test]
    fn can_draw_to_canvas() {
        let canvas = Canvas::new();

        canvas.write(vec![Draw::NewPath]);
    }

    #[test]
    fn can_follow_canvas_stream() {
        let canvas  = Canvas::new();
        let mut stream  = executor::spawn(canvas.stream());
        
        // Thread to draw some stuff to the canvas
        spawn(move || {
            sleep(Duration::from_millis(50));

            canvas.write(vec![
                Draw::NewPath,
                Draw::Move(0.0, 0.0),
                Draw::Line(10.0, 0.0),
                Draw::Line(10.0, 10.0),
                Draw::Line(0.0, 10.0)
            ]);
        });

        // TODO: if the canvas fails to notify, this will block forever :-/

        // Check we can get the results via the stream
        assert!(stream.wait_stream() == Some(Ok(Draw::ClearCanvas)));
        assert!(stream.wait_stream() == Some(Ok(Draw::NewPath)));
        assert!(stream.wait_stream() == Some(Ok(Draw::Move(0.0, 0.0))));
        assert!(stream.wait_stream() == Some(Ok(Draw::Line(10.0, 0.0))));
        assert!(stream.wait_stream() == Some(Ok(Draw::Line(10.0, 10.0))));
        assert!(stream.wait_stream() == Some(Ok(Draw::Line(0.0, 10.0))));

        // When the thread goes away, it'll drop the canvas, so we should get the 'None' request here too
        assert!(stream.wait_stream() == None);
    }

    #[test]
    fn can_draw_using_gc() {
        let canvas      = Canvas::new();
        let mut stream  = executor::spawn(canvas.stream());
        
        // Draw using a graphics context
        canvas.draw(|gc| {
            gc.new_path();
            gc.move_to(0.0, 0.0);
            gc.line_to(10.0, 0.0);
            gc.line_to(10.0, 10.0);
            gc.line_to(0.0, 10.0);
        });

        // Check we can get the results via the stream
        assert!(stream.wait_stream() == Some(Ok(Draw::ClearCanvas)));
        assert!(stream.wait_stream() == Some(Ok(Draw::NewPath)));
        assert!(stream.wait_stream() == Some(Ok(Draw::Move(0.0, 0.0))));
        assert!(stream.wait_stream() == Some(Ok(Draw::Line(10.0, 0.0))));
        assert!(stream.wait_stream() == Some(Ok(Draw::Line(10.0, 10.0))));
        assert!(stream.wait_stream() == Some(Ok(Draw::Line(0.0, 10.0))));
    }

    #[test]
    fn restore_rewinds_canvas() {
        let canvas      = Canvas::new();
        
        // Draw using a graphics context
        canvas.draw(|gc| {
            gc.new_path();
            gc.move_to(0.0, 0.0);
            gc.line_to(10.0, 0.0);
            gc.line_to(10.0, 10.0);
            gc.line_to(0.0, 10.0);

            gc.store();
            gc.new_path();
            gc.rect(0.0,0.0, 100.0,100.0);
            gc.restore();

            gc.stroke();
        });

        // Only the commands before the 'store' should be present
        let mut stream  = executor::spawn(canvas.stream());

        assert!(stream.wait_stream() == Some(Ok(Draw::ClearCanvas)));
        assert!(stream.wait_stream() == Some(Ok(Draw::NewPath)));
        assert!(stream.wait_stream() == Some(Ok(Draw::Move(0.0, 0.0))));
        assert!(stream.wait_stream() == Some(Ok(Draw::Line(10.0, 0.0))));
        assert!(stream.wait_stream() == Some(Ok(Draw::Line(10.0, 10.0))));
        assert!(stream.wait_stream() == Some(Ok(Draw::Line(0.0, 10.0))));

        // 'Store' is still present as we can restore the same thing repeatedly
        assert!(stream.wait_stream() == Some(Ok(Draw::Store)));

        assert!(stream.wait_stream() == Some(Ok(Draw::Stroke)));
    }

    #[test]
    fn free_store_rewinds_canvas_further() {
        let canvas      = Canvas::new();
        
        // Draw using a graphics context
        canvas.draw(|gc| {
            gc.new_path();
            gc.move_to(0.0, 0.0);
            gc.line_to(10.0, 0.0);
            gc.line_to(10.0, 10.0);
            gc.line_to(0.0, 10.0);

            gc.store();
            gc.new_path();
            gc.rect(0.0,0.0, 100.0,100.0);
            gc.restore();
            gc.free_stored_buffer();

            gc.stroke();
        });

        // Only the commands before the 'store' should be present
        let mut stream  = executor::spawn(canvas.stream());

        assert!(stream.wait_stream() == Some(Ok(Draw::ClearCanvas)));
        assert!(stream.wait_stream() == Some(Ok(Draw::NewPath)));
        assert!(stream.wait_stream() == Some(Ok(Draw::Move(0.0, 0.0))));
        assert!(stream.wait_stream() == Some(Ok(Draw::Line(10.0, 0.0))));
        assert!(stream.wait_stream() == Some(Ok(Draw::Line(10.0, 10.0))));
        assert!(stream.wait_stream() == Some(Ok(Draw::Line(0.0, 10.0))));

        assert!(stream.wait_stream() == Some(Ok(Draw::Stroke)));
    }

    #[test]
    fn clip_interrupts_rewind() {
        let canvas      = Canvas::new();
        
        // Draw using a graphics context
        canvas.draw(|gc| {
            gc.new_path();
            gc.move_to(0.0, 0.0);
            gc.line_to(10.0, 0.0);
            gc.line_to(10.0, 10.0);
            gc.line_to(0.0, 10.0);

            gc.store();
            gc.clip();
            gc.new_path();
            gc.restore();
        });

        // Only the commands before the 'store' should be present
        let mut stream  = executor::spawn(canvas.stream());

        assert!(stream.wait_stream() == Some(Ok(Draw::ClearCanvas)));
        assert!(stream.wait_stream() == Some(Ok(Draw::NewPath)));
        assert!(stream.wait_stream() == Some(Ok(Draw::Move(0.0, 0.0))));
        assert!(stream.wait_stream() == Some(Ok(Draw::Line(10.0, 0.0))));
        assert!(stream.wait_stream() == Some(Ok(Draw::Line(10.0, 10.0))));
        assert!(stream.wait_stream() == Some(Ok(Draw::Line(0.0, 10.0))));

        assert!(stream.wait_stream() == Some(Ok(Draw::Store)));
        assert!(stream.wait_stream() == Some(Ok(Draw::Clip)));
        assert!(stream.wait_stream() == Some(Ok(Draw::NewPath)));
        assert!(stream.wait_stream() == Some(Ok(Draw::Restore)));
    }

    #[test]
    fn can_follow_many_streams() {
        let canvas  = Canvas::new();
        let mut stream  = executor::spawn(canvas.stream());
        let mut stream2  = executor::spawn(canvas.stream());
        
        // Thread to draw some stuff to the canvas
        spawn(move || {
            sleep(Duration::from_millis(50));

            canvas.write(vec![
                Draw::NewPath,
                Draw::Move(0.0, 0.0),
                Draw::Line(10.0, 0.0),
                Draw::Line(10.0, 10.0),
                Draw::Line(0.0, 10.0)
            ]);
        });

        // TODO: if the canvas fails to notify, this will block forever :-/

        // Check we can get the results via the stream
        assert!(stream.wait_stream() == Some(Ok(Draw::ClearCanvas)));
        assert!(stream.wait_stream() == Some(Ok(Draw::NewPath)));
        assert!(stream.wait_stream() == Some(Ok(Draw::Move(0.0, 0.0))));

        assert!(stream2.wait_stream() == Some(Ok(Draw::ClearCanvas)));
        assert!(stream2.wait_stream() == Some(Ok(Draw::NewPath)));
        assert!(stream2.wait_stream() == Some(Ok(Draw::Move(0.0, 0.0))));

        assert!(stream.wait_stream() == Some(Ok(Draw::Line(10.0, 0.0))));
        assert!(stream.wait_stream() == Some(Ok(Draw::Line(10.0, 10.0))));
        assert!(stream.wait_stream() == Some(Ok(Draw::Line(0.0, 10.0))));

        assert!(stream2.wait_stream() == Some(Ok(Draw::Line(10.0, 0.0))));
        assert!(stream2.wait_stream() == Some(Ok(Draw::Line(10.0, 10.0))));
        assert!(stream2.wait_stream() == Some(Ok(Draw::Line(0.0, 10.0))));

        // When the thread goes away, it'll drop the canvas, so we should get the 'None' request here too
        assert!(stream.wait_stream() == None);
        assert!(stream2.wait_stream() == None);
    }

    #[test]
    fn commands_after_clear_are_suppressed() {
        let canvas  = Canvas::new();
        let mut stream  = executor::spawn(canvas.stream());
        
        // Thread to draw some stuff to the canvas
        spawn(move || {
            sleep(Duration::from_millis(50));

            canvas.write(vec![
                Draw::NewPath,
                Draw::Move(0.0, 0.0),
                Draw::Line(10.0, 0.0),
                Draw::Line(10.0, 10.0),
                Draw::Line(0.0, 10.0)
            ]);

            // Enough time that we read the first few commands
            sleep(Duration::from_millis(100));

            canvas.write(vec![
                Draw::ClearCanvas,
                Draw::Move(200.0, 200.0),
            ]);
        });

        // TODO: if the canvas fails to notify, this will block forever :-/

        // Check we can get the results via the stream
        assert!(stream.wait_stream() == Some(Ok(Draw::ClearCanvas)));
        assert!(stream.wait_stream() == Some(Ok(Draw::NewPath)));

        // Give the thread some time to clear the canvas
        sleep(Duration::from_millis(120));

        // Commands we sent before the flush are gone
        assert!(stream.wait_stream() == Some(Ok(Draw::ClearCanvas)));
        assert!(stream.wait_stream() == Some(Ok(Draw::Move(200.0, 200.0))));

        // When the thread goes away, it'll drop the canvas, so we should get the 'None' request here too
        assert!(stream.wait_stream() == None);
    }

    #[test]
    fn clear_layer_0_removes_commands() {
        let canvas      = Canvas::new();
        
        // Draw using a graphics context
        canvas.draw(|gc| {
            gc.new_path();
            gc.move_to(0.0, 0.0);
            gc.line_to(10.0, 0.0);
            gc.line_to(10.0, 10.0);
            gc.line_to(0.0, 10.0);

            gc.stroke();
            gc.clear_layer();

            gc.new_path();
            gc.move_to(10.0, 10.0);
            gc.fill();
        });

        // Only the commands after clear_layer should be present
        let mut stream  = executor::spawn(canvas.stream());

        assert!(stream.wait_stream() == Some(Ok(Draw::ClearCanvas)));
        assert!(stream.wait_stream() == Some(Ok(Draw::Layer(0))));
        assert!(stream.wait_stream() == Some(Ok(Draw::NewPath)));
        assert!(stream.wait_stream() == Some(Ok(Draw::Move(10.0, 10.0))));
        assert!(stream.wait_stream() == Some(Ok(Draw::Fill)));
    }

    #[test]
    fn clear_layer_only_removes_commands_for_the_current_layer() {
        let canvas      = Canvas::new();
        
        // Draw using a graphics context
        canvas.draw(|gc| {
            gc.new_path();
            gc.move_to(20.0, 20.0);

            gc.stroke();

            gc.layer(1);
            gc.new_path();
            gc.move_to(0.0, 0.0);
            gc.line_to(10.0, 0.0);
            gc.line_to(10.0, 10.0);
            gc.line_to(0.0, 10.0);

            gc.clear_layer();

            gc.new_path();
            gc.move_to(10.0, 10.0);
            gc.fill();
        });

        // Only the commands after clear_layer should be present
        let mut stream  = executor::spawn(canvas.stream());

        assert!(stream.wait_stream() == Some(Ok(Draw::ClearCanvas)));
        assert!(stream.wait_stream() == Some(Ok(Draw::NewPath)));
        assert!(stream.wait_stream() == Some(Ok(Draw::Move(20.0, 20.0))));
        assert!(stream.wait_stream() == Some(Ok(Draw::Stroke)));

        assert!(stream.wait_stream() == Some(Ok(Draw::Layer(1))));
        assert!(stream.wait_stream() == Some(Ok(Draw::NewPath)));
        assert!(stream.wait_stream() == Some(Ok(Draw::Move(10.0, 10.0))));
        assert!(stream.wait_stream() == Some(Ok(Draw::Fill)));
    }
}