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
use crate::{Color, DataSource, observable_value, Point, Result, Store, Time, Value};
use gdk::prelude::*;
use glib::source::Continue;
use gtk::prelude::*;
use std::{
    cell::{Cell, RefCell, RefMut},
    rc::Rc,
    time::Instant,
};

const BYTES_PER_PIXEL: usize = 4;
const BACKGROUND_COLOR: (f64, f64, f64) = (0.4, 0.4, 0.4);
const DRAWN_AREA_BACKGROUND_COLOR: (f64, f64, f64) = (0.0, 0.0, 0.0);

struct State {
    backing_surface: RefCell<cairo::Surface>,
    temp_surface: RefCell<cairo::Surface>,

    store: RefCell<Store>,

    drawing_area: gtk::DrawingArea,

    view_write: RefCell<observable_value::WriteHalf<View>>,
    view_read: RefCell<observable_value::ReadHalf<View>>,

    fps_count: Cell<u16>,
    fps_timer: Cell<Instant>,

    config: Config,

    tick_id: RefCell<TickId>,
}

enum TickId {
    IngestOnly(glib::source::SourceId),
    EveryFrame(gtk::TickCallbackId),
    None,
}

/// Describes what is currently showing on the graph.
#[derive(Clone, Debug)]
pub struct View {
    /// Zoom level, in units of t per x pixel
    pub zoom_x: f64,

    /// The most recently drawn time value.
    pub last_drawn_t: Time,

    /// The most recently drawn x pixel.
    pub last_drawn_x: u32,

    /// The longest ago time value that is still stored. Note
    /// that the oldest data is discarded to keep memory usage bounded.
    pub min_t: Time,

    /// The most recent time value.
    pub max_t: Time,

    /// The display mode.
    pub mode: ViewMode,
}

/// Describes the display mode of the graph
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ViewMode {
    /// Graph is following the latest data
    Following,

    /// Graph is scrolled to a particular point in time
    Scrolled,
}

impl View {
    fn default_from_config(c: &Config) -> View {
        View {
            zoom_x: c.base_zoom_x,
            last_drawn_t: 0,
            last_drawn_x: 0,
            min_t: 0,
            max_t: 0,
            mode: ViewMode::Following,
        }
    }
}

/// The configuration required by a `Graph` or `GraphWithControls`
///
/// Create an instance using a `ConfigBuilder`:
///
/// ```
/// use rt_graph::{Config, ConfigBuilder, TestDataGenerator};
///
/// let config: Config =
///     ConfigBuilder::default()
///         // Chain ConfigBuilder methods here
///         .data_source(TestDataGenerator::new())
///         .build()
///         .unwrap();
/// ```
#[derive(Builder, Debug)]
#[builder(pattern = "owned")]
pub struct Config {
    /// Maximum zoom out, in units of t per x pixel
    #[builder(default = "1000.0")]
    base_zoom_x: f64,

    /// Maximum zoom in, in units of t per x pixel
    #[builder(default = "1.0")]
    max_zoom_x: f64,

    /// Graph width in pixels
    #[builder(default = "800")]
    graph_width: u32,

    /// Graph height in pixels
    #[builder(default = "200")]
    graph_height: u32,

    #[builder(private, setter(name = "data_source_internal"))]
    data_source: RefCell<Box<dyn DataSource>>,

    /// How many windows width of data to store at maximum zoom out.
    #[builder(default = "100")]
    windows_to_store: u32,

    /// The style of point to draw
    #[builder(default = "PointStyle::Point")]
    point_style: PointStyle,
}

/// The style of point to draw
#[derive(Clone, Copy, Debug)]
pub enum PointStyle {
    /// A point, a single pixel.
    Point,

    /// A cross of 5 pixels in the shape of an 'x'.
    Cross,
}

impl ConfigBuilder {
    /// The data source for the graph.
    pub fn data_source<T: DataSource + 'static>(self, ds: T) -> Self {
        self.data_source_internal(RefCell::new(Box::new(ds)))
    }
}

/// A GTK widget that draws a graph.
///
/// `Graph` contains no controls to navigate it, you are expected to
/// provide your own controls using the methods and signals it provides.
/// Or you can use `GraphWithControls` that comes with a set of controls.
pub struct Graph {
    s: Rc<State>,
}

impl Graph {
    /// Build and show a `Graph` widget in the target `gtk::Container`.
    pub fn build_ui<C>(config: Config, container: &C, gdk_window: &gdk::Window) -> Graph
        where C: IsA<gtk::Container> + IsA<gtk::Widget>
    {

        let drawing_area = gtk::DrawingAreaBuilder::new()
            .height_request(config.graph_height as i32)
            .width_request(config.graph_width as i32)
            .build();
        container.add(&drawing_area);

        // Initialise State

        let backing_surface = create_backing_surface(gdk_window,
                                                     config.graph_width, config.graph_height);
        let temp_surface = create_backing_surface(gdk_window,
                                                  config.graph_width, config.graph_height);
        let store = Store::new(config.data_source.borrow().get_num_values().unwrap() as u8);
        let view = View::default_from_config(&config);
        let (view_read, view_write) =
            observable_value::ObservableValue::new(view.clone()).split();
        let s = Rc::new(State {
            backing_surface: RefCell::new(backing_surface),
            temp_surface: RefCell::new(temp_surface),

            store: RefCell::new(store),

            drawing_area: drawing_area.clone(),

            view_read: RefCell::new(view_read),
            view_write: RefCell::new(view_write),

            fps_count: Cell::new(0),
            fps_timer: Cell::new(Instant::now()),

            config,

            tick_id: RefCell::new(TickId::None),
        });
        let graph = Graph {
            s: s.clone(),
        };

        // Set signal handlers that require State
        let sc = s.clone();
        drawing_area.connect_draw(move |ctrl, ctx| {
            graph_draw(ctrl, ctx, &*sc)
        });

        graph.set_frame_tick();

        // Show everything recursively
        drawing_area.show_all();

        graph
    }

    fn set_frame_tick(&self) {
        // Take the old value.
        let old_tick_id = self.s.tick_id.replace(TickId::None);
        match old_tick_id {
            TickId::IngestOnly(id) => {
                glib::source::source_remove(id);
            },
            TickId::EveryFrame(id) => {
                // Already as desired, put old value back.
                self.s.tick_id.replace(TickId::EveryFrame(id));
                return;
            },
            TickId::None => (),
        }

        let sc = self.s.clone();
        let frame_tick_id = self.s.drawing_area.add_tick_callback(move |_ctrl, _clock| {
            tick(&*sc);
            Continue(true)
        });
        *self.s.tick_id.borrow_mut() = TickId::EveryFrame(frame_tick_id);
    }

    fn set_ingest_tick(&self) {
        // Take the old value.
        let old_tick_id = self.s.tick_id.replace(TickId::None);
        match old_tick_id {
            TickId::EveryFrame(id) => {
                id.remove();
            },
            TickId::IngestOnly(id) => {
                // Already as desired, put old value back.
                self.s.tick_id.replace(TickId::IngestOnly(id));
                return;
            }
            TickId::None => (),
        }

        let sc = self.s.clone();
        let ingest_tick_id =
            glib::source::timeout_add_seconds_local(
                1 /* seconds */,
                move || {
                    tick(&*sc);
                    Continue(true)
                });
        *self.s.tick_id.borrow_mut() = TickId::IngestOnly(ingest_tick_id);
    }

    /// Show the graph.
    pub fn show(&self) {
        self.set_frame_tick();
        self.s.drawing_area.show();
    }

    /// Hide the graph.
    pub fn hide(&self) {
        self.set_ingest_tick();
        self.s.drawing_area.hide();
    }

    /// Return the width of the graph
    pub fn width(&self) -> u32 {
        self.s.config.graph_width
    }

    /// Return the height of the graph
    pub fn height(&self) -> u32 {
        self.s.config.graph_height
    }

    /// Return the initial and maximally zoomed out zoom level, in
    /// units of time per x pixel.
    pub fn base_zoom_x(&self) -> f64 {
        self.s.config.base_zoom_x
    }

    /// Return the maximally zoomed in zoom level, in
    /// units of time per x pixel.
    pub fn max_zoom_x(&self) -> f64 {
        self.s.config.max_zoom_x
    }

    /// Return a description of the current view
    pub fn view(&self) -> View {
        self.s.view_read.borrow().get()
    }

    /// Return the most recent time value.
    pub fn last_t(&self) -> Time {
        self.s.store.borrow().last_t()
    }

    /// Return the longest ago time value that is still stored. Note
    /// that the oldest data is discarded to keep memory usage bounded.
    pub fn first_t(&self) -> Time {
        self.s.store.borrow().first_t()
    }

    fn _clone(&self) -> Graph {
        Graph {
            s: self.s.clone()
        }
    }

    /// Change the zoom level on the graph.
    ///
    /// Any value you pass in will be clamped between `base_zoom_x` and `max_zoom_x`.
    pub fn set_zoom_x(&self, new_zoom_x: f64) {
        debug!("set_zoom_x new_zoom_x={}", new_zoom_x);
        let new_zoom_x = new_zoom_x.min(self.s.config.base_zoom_x)
            .max(self.s.config.max_zoom_x);
        {
            // Scope the mutable borrow of view.
            let new_view = View {
                zoom_x: new_zoom_x,
                .. self.s.view_read.borrow().get()
            };
            self.s.view_write.borrow_mut().set(&new_view);
        }

        redraw_graph(&*self.s);
    }

    /// Sets the graph to follow the latest data.
    pub fn set_follow(&self) {
        debug!("set_follow");
        {
            // Scope the mutable borrow of view.
            let new_view = View {
                mode: ViewMode::Following,
                last_drawn_t: self.s.store.borrow().last_t(),
                .. self.s.view_read.borrow().get()
            };
            self.s.view_write.borrow_mut().set(&new_view);
        }
        redraw_graph(&*self.s);
    }

    /// Scrolls the graph to view a certain time value.
    pub fn scroll(&self, new_val: f64) {
        debug!("scroll new_val={}", new_val);
        {
            // Scope the borrow_mut on view
            let mut view = self.s.view_read.borrow().get();
            view.mode = ViewMode::Scrolled;
            let new_t = (new_val as u32 +
                         ((view.zoom_x * self.s.config.graph_width as f64) as u32))
                .min(self.s.store.borrow().last_t());
            // Snap new_t to a whole pixel.
            let new_t = (((new_t as f64) / view.zoom_x).floor() * view.zoom_x) as u32;
            view.last_drawn_t = new_t;
            view.last_drawn_x = 0;
            self.s.view_write.borrow_mut().set(&view);
            debug!("scroll_change, v={:?} view={:?}", new_val, view);
        }
        // TODO: Maybe keep the section of the graph that's still valid when scrolling.
        redraw_graph(&self.s);
    }

    /// Return an observable that lets you track the current `View`,
    /// which describes what is currently showing on the graph.
    pub fn view_observable(&mut self) -> RefMut<observable_value::ReadHalf<View>> {
        self.s.view_read.borrow_mut()
    }

    /// Returns the `DrawingArea` gtk widget the graph is drawn on, so
    /// you can connect to its signals.
    pub fn drawing_area(&self) -> gtk::DrawingArea {
        self.s.drawing_area.clone()
    }

    /// Maps a position on `drawing_area` to the data point that is
    /// currently drawn there. Useful for handling clicks on the graph.
    ///
    /// Returns None if no appropriate point can be found, for example
    /// if the data point for a scroll position has already been
    /// discarded.
    pub fn drawing_area_pos_to_point(&self, x: f64, _y: f64) -> Option<Point> {
        let view = self.s.view_read.borrow().get();
        let t = (view.last_drawn_t as i64 +
                 ((x - (view.last_drawn_x as f64)) * view.zoom_x) as i64)
            .max(0).min(view.last_drawn_t as i64)
            as u32;
        let pt = self.s.store.borrow().query_point(t).unwrap()?;

        // If we are getting a point >= 10 pixels away, return None instead.
        // This can happen when old data has been discarded but is still on screen.
        let pt: Option<Point> = if (pt.t - t) >= (view.zoom_x * 10.0) as u32 {
            None
        } else {
            Some(pt)
        };

        pt
    }
}

/// Handle the graph's draw signal.
fn graph_draw(_ctrl: &gtk::DrawingArea, ctx: &cairo::Context, s: &State) -> Inhibit {
    trace!("graph_draw");

    // Copy from the backing_surface, which was updated elsewhere
    ctx.rectangle(0.0, 0.0, s.config.graph_width as f64, s.config.graph_height as f64);
    ctx.set_source_surface(&s.backing_surface.borrow(),
                           0.0 /* offset x */, 0.0 /* offset y */);
    ctx.fill();

    // Calculate FPS, log it once a second.
    s.fps_count.set(s.fps_count.get() + 1);
    let now = Instant::now();
    if (now - s.fps_timer.get()).as_secs() >= 1 {
        debug!("fps: {}", s.fps_count.get());
        s.fps_count.set(0);
        s.fps_timer.set(now);
    }

    Inhibit(false)
}

/// Redraw the whole graph to the backing store
fn redraw_graph(s: &State) {
    trace!("redraw_graph");
    let backing_surface = s.backing_surface.borrow();
    {
        // Clear backing_surface
        let c = cairo::Context::new(&*backing_surface);
        c.set_source_rgb(BACKGROUND_COLOR.0,
                         BACKGROUND_COLOR.1,
                         BACKGROUND_COLOR.2);
        c.rectangle(0.0, 0.0, s.config.graph_width as f64, s.config.graph_height as f64);
        c.fill();
    }

    let mut view = s.view_read.borrow().get();
    let cols = s.config.data_source.borrow().get_colors().unwrap();
    let t1: u32 = view.last_drawn_t;
    let t0: u32 = (t1 as i64 - (s.config.graph_width as f64 * view.zoom_x) as i64).max(0) as u32;
    let patch_dims = ((((t1-t0) as f64 / view.zoom_x).floor() as u32)
                          .min(s.config.graph_width) as usize,
                      s.config.graph_height as usize);
    if patch_dims.0 > 0 {
        let x = match view.mode {
            ViewMode::Following => (s.config.graph_width as usize) - patch_dims.0,
            ViewMode::Scrolled => 0,
        };
        render_patch(&*backing_surface,
                     &s.store.borrow(),
                     &cols,
                     patch_dims.0 /* w */, patch_dims.1 /* h */,
                     x /* x */, 0 /* y */,
                     t0, t1,
                     0 /* v0 */, std::u16::MAX /* v1 */,
                     s.config.point_style);
        view.last_drawn_x = (x + patch_dims.0) as u32;
        view.last_drawn_t = t1;
        s.view_write.borrow_mut().set(&view);
    }
    s.drawing_area.queue_draw();
}

fn tick(s: &State) {
    trace!("tick");
    // Ingest new data
    let new_data = s.config.data_source.borrow_mut().get_data().unwrap();


    if new_data.len() > 0 {
        s.store.borrow_mut().ingest(&*new_data).unwrap();
        let t_latest = s.store.borrow().last_t();

        // Discard old data if there is any
        let window_base_dt = (s.config.graph_width as f64 * s.config.base_zoom_x) as u32;
        let keep_window = s.config.windows_to_store * window_base_dt;
        let discard_start = if t_latest >= keep_window { t_latest - keep_window } else { 0 };
        if discard_start > 0 {
            s.store.borrow_mut().discard(0, discard_start).unwrap();
        }

        let mut view = s.view_read.borrow().get();

        view.min_t = s.store.borrow().first_t();
        view.max_t = t_latest;
        s.view_write.borrow_mut().set(&view);

        if view.mode == ViewMode::Following ||
            (view.mode == ViewMode::Scrolled && view.last_drawn_x < s.config.graph_width) {

            // Draw the new data.

            // Calculate the size of the latest patch to render.
            // TODO: Handle when patch_dims.0 >= s.config.graph_width.
            // TODO: Handle scrolled when new data is offscreen (don't draw)
            let patch_dims =
                ((((t_latest - view.last_drawn_t) as f64 / view.zoom_x)
                  .floor() as usize)
                 .min(s.config.graph_width as usize),
                 s.config.graph_height as usize);
            // If there is more than a pixel's worth of data to render since we last drew,
            // then draw it.
            if patch_dims.0 > 0 {
                let new_t = view.last_drawn_t + (patch_dims.0 as f64 * view.zoom_x) as u32;

                let patch_offset_x = match view.mode {
                    ViewMode::Following => s.config.graph_width - (patch_dims.0 as u32),
                    ViewMode::Scrolled => view.last_drawn_x,
                };

                if view.mode == ViewMode::Following {
                    // Copy existing graph to the temp surface, offsetting it to the left.
                    let c = cairo::Context::new(&*s.temp_surface.borrow());
                    c.set_source_surface(&*s.backing_surface.borrow(),
                                         -(patch_dims.0 as f64) /* x offset*/, 0.0 /* y offset */);
                    c.rectangle(0.0, // x offset
                                0.0, // y offset
                                patch_offset_x as f64, // width
                                s.config.graph_height as f64); // height
                    c.fill();

                    // Present new graph by swapping the surfaces.
                    s.backing_surface.swap(&s.temp_surface);
                }

                let cols = s.config.data_source.borrow().get_colors().unwrap();
                render_patch(&s.backing_surface.borrow(),
                             &s.store.borrow(),
                             &cols,
                             patch_dims.0 /* w */, patch_dims.1 /* h */,
                             patch_offset_x as usize, 0 /* y */,
                             view.last_drawn_t, new_t,
                             0 /* v0 */, std::u16::MAX /* v1 */,
                             s.config.point_style);

                view.last_drawn_t = new_t;
                view.last_drawn_x = (patch_offset_x + patch_dims.0 as u32)
                                    .min(s.config.graph_width);
                s.view_write.borrow_mut().set(&view);
            }

            // Invalidate the graph widget so we get a draw request.
            s.drawing_area.queue_draw();
        }
    }
}

fn render_patch(
    surface: &cairo::Surface,
    store: &Store, cols: &[Color],
    pw: usize, ph: usize,
    x: usize, y: usize,
    t0: Time, t1: Time, v0: Value, v1: Value,
    point_style: PointStyle,
) {
    trace!("render_patch: pw={}, ph={} x={} y={}", pw, ph, x, y);
    let mut patch_bytes = vec![0u8; pw * ph * BYTES_PER_PIXEL];
    render_patch_to_bytes(store, cols, &mut patch_bytes,
                          pw, ph,
                          t0, t1,
                          v0, v1,
                          point_func_select(point_style)
                          ).unwrap();
    copy_patch(surface, patch_bytes,
               pw, ph,
               x, y);
}

fn point_func_select(s: PointStyle) -> &'static dyn Fn(usize, usize, usize, usize, &mut [u8], Color) {
    match s {
        PointStyle::Point => &point_func_point,
        PointStyle::Cross => &point_func_cross,
    }
}

fn point_func_point(x: usize, y: usize, pbw: usize, pbh: usize, pb: &mut [u8], col: Color) {
    if x < pbw && y < pbh {
        let i = BYTES_PER_PIXEL * (pbw * y + x);
        pb[i+2] = col.0; // R
        pb[i+1] = col.1; // G
        pb[i+0] = col.2; // B
        pb[i+3] = 255;   // A
    }
}

fn point_func_cross(x: usize, y: usize, pbw: usize, pbh: usize, pb: &mut [u8], col: Color) {
    let mut pixel = |px: usize, py: usize| {
        if px < pbw && py < pbh {
            let i = BYTES_PER_PIXEL * (pbw * py + px);
            pb[i+2] = col.0; // R
            pb[i+1] = col.1; // G
            pb[i+0] = col.2; // B
            pb[i+3] = 255;   // A
        }
    };

    pixel(x+1, y+1);
    if y >= 1 {
        pixel(x+1, y-1);
    }
    pixel(x  , y  );
    if x >= 1 {
        if y >= 1 {
            pixel(x-1, y-1);
        }
        pixel(x-1, y+1);
    }
}

fn render_patch_to_bytes(
    store: &Store, cols: &[Color],
    pb: &mut [u8], pbw: usize, pbh: usize,
    t0: Time, t1: Time, v0: Value, v1: Value,
    point_func: &dyn Fn(usize, usize, usize, usize, &mut [u8], Color),
) -> Result<()>
{
    trace!("render_patch_to_bytes: pbw={}", pbw);
    assert!(pbw >= 1);

    let points = store.query_range(t0, t1)?;
    for p in points {
        assert!(p.t >= t0 && p.t <= t1);

        let x = (((p.t-t0) as f32 / (t1-t0) as f32) * pbw as f32) as usize;
        if !(x < pbw) {
            // Should be guaranteed by store.query.
            panic!("x < pbw: x={} pbw={}", x, pbw);
        }

        for ch in 0..store.val_len() {
            let col = cols[ch as usize % cols.len()];
            let y = (((p.vals()[ch as usize]-v0) as f32 / (v1-v0) as f32) * pbh as f32) as usize;
            if y >= pbh {
                // Skip points that are outside our render patch.
                continue;
            }
            // Mirror the y-axis
            let y = pbh - y;

            point_func(x, y, pbw, pbh, pb, col);
        }
    }

    Ok(())
}

fn copy_patch(
    backing_surface: &cairo::Surface,
    bytes: Vec<u8>,
    w: usize, h: usize,
    x: usize, y: usize
) {

    trace!("copy_patch w={} x={}", w, x);

    // Create an ImageSurface from our bytes
    let patch_surface = cairo::ImageSurface::create_for_data(
        bytes,
        cairo::Format::ARgb32,
        w as i32,
        h as i32,
        (w * BYTES_PER_PIXEL) as i32 /* stride */
    ).unwrap();

    // Copy from the ImageSurface to backing_surface
    let c = cairo::Context::new(&backing_surface);
    // Fill target area with background colour.
    c.rectangle(x as f64,
                y as f64,
                w as f64, // width
                h as f64  /* height */);
    c.set_source_rgb(DRAWN_AREA_BACKGROUND_COLOR.0,
                     DRAWN_AREA_BACKGROUND_COLOR.1,
                     DRAWN_AREA_BACKGROUND_COLOR.2);
    c.fill_preserve();
    // Fill target area with patch data.
    c.set_source_surface(&patch_surface,
                         x as f64,
                         y as f64);
    c.fill();
}

fn create_backing_surface(win: &gdk::Window, w: u32, h: u32) -> cairo::Surface {
    let surface =
        win.create_similar_image_surface(
            cairo::Format::Rgb24.into(),
            w as i32 /* width */,
            h as i32 /* height */,
            1 /* scale */).unwrap();
    {
        // Clear backing_surface
        let c = cairo::Context::new(&surface);
        c.set_source_rgb(BACKGROUND_COLOR.0,
                         BACKGROUND_COLOR.1,
                         BACKGROUND_COLOR.2);
        c.rectangle(0.0, 0.0, w as f64, h as f64);
        c.fill();
    }
    surface
}