aboutsummaryrefslogtreecommitdiffstats
path: root/components/canvas/canvas_paint_thread.rs
blob: 1bcf294d3b6e3d5ed4d79772c9a9a6326d291028 (plain) (blame)
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
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use azure::azure::{AzColor, AzFloat};
use azure::azure_hl::{AntialiasMode, CapStyle, CompositionOp, JoinStyle};
use azure::azure_hl::{BackendType, DrawOptions, DrawTarget, Pattern, StrokeOptions, SurfaceFormat};
use azure::azure_hl::{ColorPattern, DrawSurfaceOptions, Filter, PathBuilder};
use canvas_traits::*;
use euclid::matrix2d::Matrix2D;
use euclid::point::Point2D;
use euclid::rect::Rect;
use euclid::size::Size2D;
use gfx_traits::color;
use ipc_channel::ipc::IpcSharedMemory;
use ipc_channel::ipc::{self, IpcSender};
use ipc_channel::router::ROUTER;
use layers::platform::surface::NativeSurface;
use num::ToPrimitive;
use premultiplytable::PREMULTIPLY_TABLE;
use std::borrow::ToOwned;
use std::mem;
use std::sync::mpsc::{Sender, channel};
use util::opts;
use util::thread::spawn_named;
use util::vec::byte_swap;
use webrender_traits;

impl<'a> CanvasPaintThread<'a> {
    /// It reads image data from the canvas
    /// canvas_size: The size of the canvas we're reading from
    /// read_rect: The area of the canvas we want to read from
    fn read_pixels(&self, read_rect: Rect<i32>, canvas_size: Size2D<f64>) -> Vec<u8>{
        let canvas_size = canvas_size.to_i32();
        let canvas_rect = Rect::new(Point2D::new(0i32, 0i32), canvas_size);
        let src_read_rect = canvas_rect.intersection(&read_rect).unwrap_or(Rect::zero());

        let mut image_data = Vec::new();
        if src_read_rect.is_empty() || canvas_size.width <= 0 && canvas_size.height <= 0 {
          return image_data;
        }

        let data_surface = self.drawtarget.snapshot().get_data_surface();
        let mut src_data = Vec::new();
        data_surface.with_data(|element| { src_data = element.to_vec(); });
        let stride = data_surface.stride();

        //start offset of the copyable rectangle
        let mut src = (src_read_rect.origin.y * stride + src_read_rect.origin.x * 4) as usize;
        //copy the data to the destination vector
        for _ in 0..src_read_rect.size.height {
            let row = &src_data[src .. src + (4 * src_read_rect.size.width) as usize];
            image_data.extend_from_slice(row);
            src += stride as usize;
        }

        image_data
    }
}

pub struct CanvasPaintThread<'a> {
    drawtarget: DrawTarget,
    /// TODO(pcwalton): Support multiple paths.
    path_builder: PathBuilder,
    state: CanvasPaintState<'a>,
    saved_states: Vec<CanvasPaintState<'a>>,
    webrender_api: Option<webrender_traits::RenderApi>,
    webrender_image_key: Option<webrender_traits::ImageKey>,
}

#[derive(Clone)]
struct CanvasPaintState<'a> {
    draw_options: DrawOptions,
    fill_style: Pattern,
    stroke_style: Pattern,
    stroke_opts: StrokeOptions<'a>,
    /// The current 2D transform matrix.
    transform: Matrix2D<f32>,
    shadow_offset_x: f64,
    shadow_offset_y: f64,
    shadow_blur: f64,
    shadow_color: AzColor,
}

impl<'a> CanvasPaintState<'a> {
    fn new() -> CanvasPaintState<'a> {
        let antialias = if opts::get().enable_canvas_antialiasing {
            AntialiasMode::Default
        } else {
            AntialiasMode::None
        };

        CanvasPaintState {
            draw_options: DrawOptions::new(1.0, CompositionOp::Over, antialias),
            fill_style: Pattern::Color(ColorPattern::new(color::black())),
            stroke_style: Pattern::Color(ColorPattern::new(color::black())),
            stroke_opts: StrokeOptions::new(1.0, JoinStyle::MiterOrBevel, CapStyle::Butt, 10.0, &[]),
            transform: Matrix2D::identity(),
            shadow_offset_x: 0.0,
            shadow_offset_y: 0.0,
            shadow_blur: 0.0,
            shadow_color: color::transparent(),
        }
    }
}

impl<'a> CanvasPaintThread<'a> {
    fn new(size: Size2D<i32>,
           webrender_api_sender: Option<webrender_traits::RenderApiSender>) -> CanvasPaintThread<'a> {
        let draw_target = CanvasPaintThread::create(size);
        let path_builder = draw_target.create_path_builder();
        let webrender_api = webrender_api_sender.map(|wr| wr.create_api());
        let webrender_image_key = webrender_api.as_ref().map(|wr| wr.alloc_image());
        CanvasPaintThread {
            drawtarget: draw_target,
            path_builder: path_builder,
            state: CanvasPaintState::new(),
            saved_states: Vec::new(),
            webrender_api: webrender_api,
            webrender_image_key: webrender_image_key,
        }
    }

    /// Creates a new `CanvasPaintThread` and returns the out-of-process sender and the in-process
    /// sender for it.
    pub fn start(size: Size2D<i32>,
                 webrender_api_sender: Option<webrender_traits::RenderApiSender>)
                    -> (IpcSender<CanvasMsg>, Sender<CanvasMsg>) {
        // TODO(pcwalton): Ask the pipeline to create this for us instead of spawning it directly.
        // This will be needed for multiprocess Servo.
        let (out_of_process_chan, out_of_process_port) = ipc::channel::<CanvasMsg>().unwrap();
        let (in_process_chan, in_process_port) = channel();
        ROUTER.route_ipc_receiver_to_mpsc_sender(out_of_process_port, in_process_chan.clone());
        spawn_named("CanvasThread".to_owned(), move || {
            let mut painter = CanvasPaintThread::new(size, webrender_api_sender);
            loop {
                let msg = in_process_port.recv();
                match msg.unwrap() {
                    CanvasMsg::Canvas2d(message) => {
                        match message {
                            Canvas2dMsg::FillRect(ref rect) => painter.fill_rect(rect),
                            Canvas2dMsg::StrokeRect(ref rect) => painter.stroke_rect(rect),
                            Canvas2dMsg::ClearRect(ref rect) => painter.clear_rect(rect),
                            Canvas2dMsg::BeginPath => painter.begin_path(),
                            Canvas2dMsg::ClosePath => painter.close_path(),
                            Canvas2dMsg::Fill => painter.fill(),
                            Canvas2dMsg::Stroke => painter.stroke(),
                            Canvas2dMsg::Clip => painter.clip(),
                            Canvas2dMsg::IsPointInPath(x, y, fill_rule, chan) => {
                                painter.is_point_in_path(x, y, fill_rule, chan)
                            },
                            Canvas2dMsg::DrawImage(imagedata, image_size, dest_rect, source_rect,
                                                   smoothing_enabled) => {
                                painter.draw_image(imagedata, image_size, dest_rect, source_rect, smoothing_enabled)
                            }
                            Canvas2dMsg::DrawImageSelf(image_size, dest_rect, source_rect, smoothing_enabled) => {
                                painter.draw_image_self(image_size, dest_rect, source_rect, smoothing_enabled)
                            }
                            Canvas2dMsg::MoveTo(ref point) => painter.move_to(point),
                            Canvas2dMsg::LineTo(ref point) => painter.line_to(point),
                            Canvas2dMsg::Rect(ref rect) => painter.rect(rect),
                            Canvas2dMsg::QuadraticCurveTo(ref cp, ref pt) => {
                                painter.quadratic_curve_to(cp, pt)
                            }
                            Canvas2dMsg::BezierCurveTo(ref cp1, ref cp2, ref pt) => {
                                painter.bezier_curve_to(cp1, cp2, pt)
                            }
                            Canvas2dMsg::Arc(ref center, radius, start, end, ccw) => {
                                painter.arc(center, radius, start, end, ccw)
                            }
                            Canvas2dMsg::ArcTo(ref cp1, ref cp2, radius) => {
                                painter.arc_to(cp1, cp2, radius)
                            }
                            Canvas2dMsg::RestoreContext => painter.restore_context_state(),
                            Canvas2dMsg::SaveContext => painter.save_context_state(),
                            Canvas2dMsg::SetFillStyle(style) => painter.set_fill_style(style),
                            Canvas2dMsg::SetStrokeStyle(style) => painter.set_stroke_style(style),
                            Canvas2dMsg::SetLineWidth(width) => painter.set_line_width(width),
                            Canvas2dMsg::SetLineCap(cap) => painter.set_line_cap(cap),
                            Canvas2dMsg::SetLineJoin(join) => painter.set_line_join(join),
                            Canvas2dMsg::SetMiterLimit(limit) => painter.set_miter_limit(limit),
                            Canvas2dMsg::SetTransform(ref matrix) => painter.set_transform(matrix),
                            Canvas2dMsg::SetGlobalAlpha(alpha) => painter.set_global_alpha(alpha),
                            Canvas2dMsg::SetGlobalComposition(op) => painter.set_global_composition(op),
                            Canvas2dMsg::GetImageData(dest_rect, canvas_size, chan)
                                => painter.image_data(dest_rect, canvas_size, chan),
                            Canvas2dMsg::PutImageData(imagedata, offset, image_data_size, dirty_rect)
                                => painter.put_image_data(imagedata, offset, image_data_size, dirty_rect),
                            Canvas2dMsg::SetShadowOffsetX(value) => painter.set_shadow_offset_x(value),
                            Canvas2dMsg::SetShadowOffsetY(value) => painter.set_shadow_offset_y(value),
                            Canvas2dMsg::SetShadowBlur(value) => painter.set_shadow_blur(value),
                            Canvas2dMsg::SetShadowColor(ref color) => painter.set_shadow_color(color.to_azcolor()),
                        }
                    },
                    CanvasMsg::Common(message) => {
                        match message {
                            CanvasCommonMsg::Close => break,
                            CanvasCommonMsg::Recreate(size) => painter.recreate(size),
                        }
                    },
                    CanvasMsg::FromLayout(message) => {
                        match message {
                            FromLayoutMsg::SendData(chan) => {
                                painter.send_data(chan)
                            }
                        }
                    }
                    CanvasMsg::FromPaint(message) => {
                        match message {
                            FromPaintMsg::SendNativeSurface(chan) => {
                                painter.send_native_surface(chan)
                            }
                        }
                    }
                    CanvasMsg::WebGL(_) => panic!("Wrong message sent to Canvas2D thread"),
                }
            }
        });

        (out_of_process_chan, in_process_chan)
    }

    fn save_context_state(&mut self) {
        self.saved_states.push(self.state.clone());
    }

    fn restore_context_state(&mut self) {
        if let Some(state) = self.saved_states.pop() {
            mem::replace(&mut self.state, state);
            self.drawtarget.set_transform(&self.state.transform);
            self.drawtarget.pop_clip();
        }
    }

    fn fill_rect(&self, rect: &Rect<f32>) {
        if is_zero_size_gradient(&self.state.fill_style) {
            return; // Paint nothing if gradient size is zero.
        }

        let draw_rect = Rect::new(rect.origin,
            match self.state.fill_style {
                Pattern::Surface(ref surface) => {
                    let surface_size = surface.size();
                    match (surface.repeat_x, surface.repeat_y) {
                        (true, true) => rect.size,
                        (true, false) => Size2D::new(rect.size.width, surface_size.height as f32),
                        (false, true) => Size2D::new(surface_size.width as f32, rect.size.height),
                        (false, false) => Size2D::new(surface_size.width as f32, surface_size.height as f32),
                    }
                },
                _ => rect.size,
            }
        );

        if self.need_to_draw_shadow() {
            self.draw_with_shadow(&draw_rect, |new_draw_target: &DrawTarget| {
                new_draw_target.fill_rect(&draw_rect, self.state.fill_style.to_pattern_ref(),
                                          Some(&self.state.draw_options));
            });
        } else {
            self.drawtarget.fill_rect(&draw_rect, self.state.fill_style.to_pattern_ref(),
                                      Some(&self.state.draw_options));
        }
    }

    fn clear_rect(&self, rect: &Rect<f32>) {
        self.drawtarget.clear_rect(rect);
    }

    fn stroke_rect(&self, rect: &Rect<f32>) {
        if is_zero_size_gradient(&self.state.stroke_style) {
            return; // Paint nothing if gradient size is zero.
        }

        if self.need_to_draw_shadow() {
            self.draw_with_shadow(&rect, |new_draw_target: &DrawTarget| {
                new_draw_target.stroke_rect(rect, self.state.stroke_style.to_pattern_ref(),
                                            &self.state.stroke_opts, &self.state.draw_options);
            });
        } else if rect.size.width == 0. || rect.size.height == 0. {
            let cap = match self.state.stroke_opts.line_join {
                JoinStyle::Round => CapStyle::Round,
                _ => CapStyle::Butt
            };

            let stroke_opts =
                StrokeOptions::new(self.state.stroke_opts.line_width,
                                   self.state.stroke_opts.line_join,
                                   cap,
                                   self.state.stroke_opts.miter_limit,
                                   self.state.stroke_opts.mDashPattern);
            self.drawtarget.stroke_line(rect.origin, rect.bottom_right(),
                                        self.state.stroke_style.to_pattern_ref(),
                                        &stroke_opts, &self.state.draw_options);
        } else {
            self.drawtarget.stroke_rect(rect, self.state.stroke_style.to_pattern_ref(),
                                        &self.state.stroke_opts, &self.state.draw_options);
        }
    }

    fn begin_path(&mut self) {
        self.path_builder = self.drawtarget.create_path_builder()
    }

    fn close_path(&self) {
        self.path_builder.close()
    }

    fn fill(&self) {
        if is_zero_size_gradient(&self.state.fill_style) {
            return; // Paint nothing if gradient size is zero.
        }

        self.drawtarget.fill(&self.path_builder.finish(),
                             self.state.fill_style.to_pattern_ref(),
                             &self.state.draw_options);
    }

    fn stroke(&self) {
        if is_zero_size_gradient(&self.state.stroke_style) {
            return; // Paint nothing if gradient size is zero.
        }

        self.drawtarget.stroke(&self.path_builder.finish(),
                               self.state.stroke_style.to_pattern_ref(),
                               &self.state.stroke_opts,
                               &self.state.draw_options);
    }

    fn clip(&self) {
        self.drawtarget.push_clip(&self.path_builder.finish());
    }

    fn is_point_in_path(&mut self, x: f64, y: f64,
                        _fill_rule: FillRule, chan: IpcSender<bool>) {
        let path = self.path_builder.finish();
        let result = path.contains_point(x, y, &self.state.transform);
        self.path_builder = path.copy_to_builder();
        chan.send(result).unwrap();
    }

    fn draw_image(&self, image_data: Vec<u8>, image_size: Size2D<f64>,
                  dest_rect: Rect<f64>, source_rect: Rect<f64>, smoothing_enabled: bool) {
        // We round up the floating pixel values to draw the pixels
        let source_rect = source_rect.ceil();
        // It discards the extra pixels (if any) that won't be painted
        let image_data = crop_image(image_data, image_size, source_rect);

        if self.need_to_draw_shadow() {
            let rect = Rect::new(Point2D::new(dest_rect.origin.x as f32, dest_rect.origin.y as f32),
                                 Size2D::new(dest_rect.size.width as f32, dest_rect.size.height as f32));

            self.draw_with_shadow(&rect, |new_draw_target: &DrawTarget| {
                write_image(&new_draw_target, image_data, source_rect.size, dest_rect,
                            smoothing_enabled, self.state.draw_options.composition,
                            self.state.draw_options.alpha);
            });
        } else {
            write_image(&self.drawtarget, image_data, source_rect.size, dest_rect,
                        smoothing_enabled, self.state.draw_options.composition,
                        self.state.draw_options.alpha);
        }
    }

    fn draw_image_self(&self, image_size: Size2D<f64>,
                       dest_rect: Rect<f64>, source_rect: Rect<f64>,
                       smoothing_enabled: bool) {
        // Reads pixels from source image
        // In this case source and target are the same canvas
        let image_data = self.read_pixels(source_rect.to_i32(), image_size);

        if self.need_to_draw_shadow() {
            let rect = Rect::new(Point2D::new(dest_rect.origin.x as f32, dest_rect.origin.y as f32),
                                 Size2D::new(dest_rect.size.width as f32, dest_rect.size.height as f32));

            self.draw_with_shadow(&rect, |new_draw_target: &DrawTarget| {
                write_image(&new_draw_target, image_data, source_rect.size, dest_rect,
                            smoothing_enabled, self.state.draw_options.composition,
                            self.state.draw_options.alpha);
            });
        } else {
            // Writes on target canvas
            write_image(&self.drawtarget, image_data, image_size, dest_rect,
                        smoothing_enabled, self.state.draw_options.composition,
                        self.state.draw_options.alpha);
        }
    }

    fn move_to(&self, point: &Point2D<AzFloat>) {
        self.path_builder.move_to(*point)
    }

    fn line_to(&self, point: &Point2D<AzFloat>) {
        self.path_builder.line_to(*point)
    }

    fn rect(&self, rect: &Rect<f32>) {
        self.path_builder.move_to(Point2D::new(rect.origin.x, rect.origin.y));
        self.path_builder.line_to(Point2D::new(rect.origin.x + rect.size.width, rect.origin.y));
        self.path_builder.line_to(Point2D::new(rect.origin.x + rect.size.width,
                                               rect.origin.y + rect.size.height));
        self.path_builder.line_to(Point2D::new(rect.origin.x, rect.origin.y + rect.size.height));
        self.path_builder.close();
    }

    fn quadratic_curve_to(&self,
                          cp: &Point2D<AzFloat>,
                          endpoint: &Point2D<AzFloat>) {
        self.path_builder.quadratic_curve_to(cp, endpoint)
    }

    fn bezier_curve_to(&self,
                       cp1: &Point2D<AzFloat>,
                       cp2: &Point2D<AzFloat>,
                       endpoint: &Point2D<AzFloat>) {
        self.path_builder.bezier_curve_to(cp1, cp2, endpoint)
    }

    fn arc(&self,
           center: &Point2D<AzFloat>,
           radius: AzFloat,
           start_angle: AzFloat,
           end_angle: AzFloat,
           ccw: bool) {
        self.path_builder.arc(*center, radius, start_angle, end_angle, ccw)
    }

    fn arc_to(&self,
              cp1: &Point2D<AzFloat>,
              cp2: &Point2D<AzFloat>,
              radius: AzFloat) {
        let cp0 = self.path_builder.get_current_point();
        let cp1 = *cp1;
        let cp2 = *cp2;

        if (cp0.x == cp1.x && cp0.y == cp1.y) || cp1 == cp2 || radius == 0.0 {
            self.line_to(&cp1);
            return;
        }

        // if all three control points lie on a single straight line,
        // connect the first two by a straight line
        let direction = (cp2.x - cp1.x) * (cp0.y - cp1.y) + (cp2.y - cp1.y) * (cp1.x - cp0.x);
        if direction == 0.0 {
            self.line_to(&cp1);
            return;
        }

        // otherwise, draw the Arc
        let a2 = (cp0.x - cp1.x).powi(2) + (cp0.y - cp1.y).powi(2);
        let b2 = (cp1.x - cp2.x).powi(2) + (cp1.y - cp2.y).powi(2);
        let d = {
            let c2 = (cp0.x - cp2.x).powi(2) + (cp0.y - cp2.y).powi(2);
            let cosx = (a2 + b2 - c2) / (2.0 * (a2 * b2).sqrt());
            let sinx = (1.0 - cosx.powi(2)).sqrt();
            radius / ((1.0 - cosx) / sinx)
        };

        // first tangent point
        let anx = (cp1.x - cp0.x) / a2.sqrt();
        let any = (cp1.y - cp0.y) / a2.sqrt();
        let tp1 = Point2D::new(cp1.x - anx * d, cp1.y - any * d);

        // second tangent point
        let bnx = (cp1.x - cp2.x) / b2.sqrt();
        let bny = (cp1.y - cp2.y) / b2.sqrt();
        let tp2 = Point2D::new(cp1.x - bnx * d, cp1.y - bny * d);

        // arc center and angles
        let anticlockwise = direction < 0.0;
        let cx = tp1.x + any * radius * if anticlockwise { 1.0 } else { -1.0 };
        let cy = tp1.y - anx * radius * if anticlockwise { 1.0 } else { -1.0 };
        let angle_start = (tp1.y - cy).atan2(tp1.x - cx);
        let angle_end = (tp2.y - cy).atan2(tp2.x - cx);

        self.line_to(&tp1);
        if [cx, cy, angle_start, angle_end].iter().all(|x| x.is_finite()) {
            self.arc(&Point2D::new(cx, cy), radius,
                     angle_start, angle_end, anticlockwise);
        }
    }

    fn set_fill_style(&mut self, style: FillOrStrokeStyle) {
        if let Some(pattern) = style.to_azure_pattern(&self.drawtarget) {
            self.state.fill_style = pattern
        }
    }

    fn set_stroke_style(&mut self, style: FillOrStrokeStyle) {
        if let Some(pattern) = style.to_azure_pattern(&self.drawtarget) {
            self.state.stroke_style = pattern
        }
    }

    fn set_line_width(&mut self, width: f32) {
        self.state.stroke_opts.line_width = width;
    }

    fn set_line_cap(&mut self, cap: LineCapStyle) {
        self.state.stroke_opts.line_cap = cap.to_azure_style();
    }

    fn set_line_join(&mut self, join: LineJoinStyle) {
        self.state.stroke_opts.line_join = join.to_azure_style();
    }

    fn set_miter_limit(&mut self, limit: f32) {
        self.state.stroke_opts.miter_limit = limit;
    }

    fn set_transform(&mut self, transform: &Matrix2D<f32>) {
        self.state.transform = *transform;
        self.drawtarget.set_transform(transform)
    }

    fn set_global_alpha(&mut self, alpha: f32) {
        self.state.draw_options.alpha = alpha;
    }

    fn set_global_composition(&mut self, op: CompositionOrBlending) {
        self.state.draw_options.set_composition_op(op.to_azure_style());
    }

    fn create(size: Size2D<i32>) -> DrawTarget {
        DrawTarget::new(BackendType::Skia, size, SurfaceFormat::B8G8R8A8)
    }

    fn recreate(&mut self, size: Size2D<i32>) {
        self.drawtarget = CanvasPaintThread::create(size);
    }

    fn send_data(&mut self, chan: IpcSender<CanvasData>) {
        self.drawtarget.snapshot().get_data_surface().with_data(|element| {
            if let Some(ref webrender_api) = self.webrender_api {
                let size = self.drawtarget.get_size();
                let mut bytes = Vec::new();
                bytes.extend_from_slice(element);
                webrender_api.update_image(self.webrender_image_key.unwrap(),
                                           size.width as u32,
                                           size.height as u32,
                                           webrender_traits::ImageFormat::RGBA8,
                                           bytes);
            }

            let pixel_data = CanvasPixelData {
                image_data: IpcSharedMemory::from_bytes(element),
                image_key: self.webrender_image_key,
            };
            chan.send(CanvasData::Pixels(pixel_data)).unwrap();
        })
    }

    fn send_native_surface(&self, _chan: Sender<NativeSurface>) {
        // FIXME(mrobinson): We need a handle on the NativeDisplay to create compatible
        // NativeSurfaces for the compositor.
        unimplemented!()
    }

    fn image_data(&self,
                      dest_rect: Rect<i32>,
                      canvas_size: Size2D<f64>,
                      chan: IpcSender<Vec<u8>>) {
        let mut dest_data = self.read_pixels(dest_rect, canvas_size);

        // bgra -> rgba
        byte_swap(&mut dest_data);
        chan.send(dest_data).unwrap();
    }

    // https://html.spec.whatwg.org/multipage/#dom-context-2d-putimagedata
    fn put_image_data(&mut self, imagedata: Vec<u8>,
                      offset: Point2D<f64>,
                      image_data_size: Size2D<f64>,
                      mut dirty_rect: Rect<f64>) {

        if image_data_size.width <= 0.0 || image_data_size.height <= 0.0 {
            return
        }

        assert!(image_data_size.width * image_data_size.height * 4.0 == imagedata.len() as f64);

        // Step 1. TODO (neutered data)

        // Step 2.
        if dirty_rect.size.width < 0.0f64 {
            dirty_rect.origin.x += dirty_rect.size.width;
            dirty_rect.size.width = -dirty_rect.size.width;
        }

        if dirty_rect.size.height < 0.0f64 {
            dirty_rect.origin.y += dirty_rect.size.height;
            dirty_rect.size.height = -dirty_rect.size.height;
        }

        // Step 3.
        if dirty_rect.origin.x < 0.0f64 {
            dirty_rect.size.width += dirty_rect.origin.x;
            dirty_rect.origin.x = 0.0f64;
        }

        if dirty_rect.origin.y < 0.0f64 {
            dirty_rect.size.height += dirty_rect.origin.y;
            dirty_rect.origin.y = 0.0f64;
        }

        // Step 4.
        if dirty_rect.max_x() > image_data_size.width {
            dirty_rect.size.width = image_data_size.width - dirty_rect.origin.x;
        }

        if dirty_rect.max_y() > image_data_size.height {
            dirty_rect.size.height = image_data_size.height - dirty_rect.origin.y;
        }

        // 5) If either dirtyWidth or dirtyHeight is negative or zero,
        // stop without affecting any bitmaps
        if dirty_rect.size.width <= 0.0 || dirty_rect.size.height <= 0.0 {
            return
        }

        // Step 6.
        let dest_rect = dirty_rect.translate(&offset).to_i32();

        // azure_hl operates with integers. We need to cast the image size
        let image_size = image_data_size.to_i32();

        let first_pixel = dest_rect.origin - offset.to_i32();
        let mut src_line = (first_pixel.y * (image_size.width * 4) + first_pixel.x * 4) as usize;

        let mut dest =
            Vec::with_capacity((dest_rect.size.width * dest_rect.size.height * 4) as usize);

        for _ in 0 .. dest_rect.size.height {
            let mut src_offset = src_line;
            for _ in 0 .. dest_rect.size.width {
                // Premultiply alpha and swap RGBA -> BGRA.
                let alpha = imagedata[src_offset + 3] as usize;
                dest.push(PREMULTIPLY_TABLE[256 * alpha + imagedata[src_offset + 2] as usize]);
                dest.push(PREMULTIPLY_TABLE[256 * alpha + imagedata[src_offset + 1] as usize]);
                dest.push(PREMULTIPLY_TABLE[256 * alpha + imagedata[src_offset + 0] as usize]);
                dest.push(imagedata[src_offset + 3]);
                src_offset += 4;
            }
            src_line += (image_size.width * 4) as usize;
        }

        if let Some(source_surface) = self.drawtarget.create_source_surface_from_data(
                &dest,
                dest_rect.size,
                dest_rect.size.width * 4,
                SurfaceFormat::B8G8R8A8) {
            self.drawtarget.copy_surface(source_surface,
                                         Rect::new(Point2D::new(0, 0), dest_rect.size),
                                         dest_rect.origin);
        }
    }

    fn set_shadow_offset_x(&mut self, value: f64) {
        self.state.shadow_offset_x = value;
    }

    fn set_shadow_offset_y(&mut self, value: f64) {
        self.state.shadow_offset_y = value;
    }

    fn set_shadow_blur(&mut self, value: f64) {
        self.state.shadow_blur = value;
    }

    fn set_shadow_color(&mut self, value: AzColor) {
        self.state.shadow_color = value;
    }

    // https://html.spec.whatwg.org/multipage/#when-shadows-are-drawn
    fn need_to_draw_shadow(&self) -> bool {
        self.state.shadow_color.a != 0.0f32 &&
        (self.state.shadow_offset_x != 0.0f64 ||
         self.state.shadow_offset_y != 0.0f64 ||
         self.state.shadow_blur != 0.0f64)
    }

    fn create_draw_target_for_shadow(&self, source_rect: &Rect<f32>) -> DrawTarget {
        let draw_target = self.drawtarget.create_similar_draw_target(&Size2D::new(source_rect.size.width as i32,
                                                                                  source_rect.size.height as i32),
                                                                     self.drawtarget.get_format());
        let matrix = Matrix2D::identity().translate(-source_rect.origin.x as AzFloat,
                                                    -source_rect.origin.y as AzFloat)
                                         .mul(&self.state.transform);
        draw_target.set_transform(&matrix);
        draw_target
    }

    fn draw_with_shadow<F>(&self, rect: &Rect<f32>, draw_shadow_source: F)
        where F: FnOnce(&DrawTarget)
    {
        let shadow_src_rect = self.state.transform.transform_rect(rect);
        let new_draw_target = self.create_draw_target_for_shadow(&shadow_src_rect);
        draw_shadow_source(&new_draw_target);
        self.drawtarget.draw_surface_with_shadow(new_draw_target.snapshot(),
                                                 &Point2D::new(shadow_src_rect.origin.x as AzFloat,
                                                               shadow_src_rect.origin.y as AzFloat),
                                                 &self.state.shadow_color,
                                                 &Point2D::new(self.state.shadow_offset_x as AzFloat,
                                                               self.state.shadow_offset_y as AzFloat),
                                                 (self.state.shadow_blur / 2.0f64) as AzFloat,
                                                 self.state.draw_options.composition);
    }
}

/// Used by drawImage to get rid of the extra pixels of the image data that
/// won't be copied to the canvas
/// image_data: Color pixel data of the image
/// image_size: Image dimensions
/// crop_rect: It determines the area of the image we want to keep
fn crop_image(image_data: Vec<u8>,
              image_size: Size2D<f64>,
              crop_rect: Rect<f64>) -> Vec<u8>{
    // We're going to iterate over a pixel values array so we need integers
    let crop_rect = crop_rect.to_i32();
    let image_size = image_size.to_i32();
    // Assuming 4 bytes per pixel and row-major order for storage
    // (consecutive elements in a pixel row of the image are contiguous in memory)
    let stride = image_size.width * 4;
    let image_bytes_length = image_size.height * image_size.width * 4;
    let crop_area_bytes_length = crop_rect.size.height * crop_rect.size.height * 4;
    // If the image size is less or equal than the crop area we do nothing
    if image_bytes_length <= crop_area_bytes_length {
        return image_data;
    }

    let mut new_image_data = Vec::new();
    let mut src = (crop_rect.origin.y * stride + crop_rect.origin.x * 4) as usize;
    for _ in 0..crop_rect.size.height {
        let row = &image_data[src .. src + (4 * crop_rect.size.width) as usize];
        new_image_data.extend_from_slice(row);
        src += stride as usize;
    }
    new_image_data
}

/// It writes an image to the destination target
/// draw_target: the destination target where the image_data will be copied
/// image_data: Pixel information of the image to be written. It takes RGBA8
/// image_size: The size of the image to be written
/// dest_rect: Area of the destination target where the pixels will be copied
/// smoothing_enabled: It determines if smoothing is applied to the image result
fn write_image(draw_target: &DrawTarget,
               mut image_data: Vec<u8>,
               image_size: Size2D<f64>,
               dest_rect: Rect<f64>,
               smoothing_enabled: bool,
               composition_op: CompositionOp,
               global_alpha: f32) {
    if image_data.is_empty() {
        return
    }
    let image_rect = Rect::new(Point2D::zero(), image_size);
    // rgba -> bgra
    byte_swap(&mut image_data);

    // From spec https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage
    // When scaling up, if the imageSmoothingEnabled attribute is set to true, the user agent should attempt
    // to apply a smoothing algorithm to the image data when it is scaled.
    // Otherwise, the image must be rendered using nearest-neighbor interpolation.
    let filter = if smoothing_enabled {
        Filter::Linear
    } else {
        Filter::Point
    };
    // azure_hl operates with integers. We need to cast the image size
    let image_size = image_size.to_i32();

    if let Some(source_surface) =
            draw_target.create_source_surface_from_data(&image_data,
                                                        image_size,
                                                        image_size.width * 4,
                                                        SurfaceFormat::B8G8R8A8) {
        let draw_surface_options = DrawSurfaceOptions::new(filter, true);
        let draw_options = DrawOptions::new(global_alpha, composition_op, AntialiasMode::None);

        draw_target.draw_surface(source_surface,
                                 dest_rect.to_azfloat(),
                                 image_rect.to_azfloat(),
                                 draw_surface_options,
                                 draw_options);
    }
}

fn is_zero_size_gradient(pattern: &Pattern) -> bool {
    if let &Pattern::LinearGradient(ref gradient) = pattern {
        if gradient.is_zero_size() {
            return true;
        }
    }
    false
}

pub trait PointToi32 {
    fn to_i32(&self) -> Point2D<i32>;
}

impl PointToi32 for Point2D<f64> {
    fn to_i32(&self) -> Point2D<i32> {
        Point2D::new(self.x.to_i32().unwrap(),
                     self.y.to_i32().unwrap())
    }
}

pub trait SizeToi32 {
    fn to_i32(&self) -> Size2D<i32>;
}

impl SizeToi32 for Size2D<f64> {
    fn to_i32(&self) -> Size2D<i32> {
        Size2D::new(self.width.to_i32().unwrap(),
                    self.height.to_i32().unwrap())
    }
}

pub trait RectToi32 {
    fn to_i32(&self) -> Rect<i32>;
    fn ceil(&self) -> Rect<f64>;
}

impl RectToi32 for Rect<f64> {
    fn to_i32(&self) -> Rect<i32> {
        Rect::new(Point2D::new(self.origin.x.to_i32().unwrap(),
                               self.origin.y.to_i32().unwrap()),
                  Size2D::new(self.size.width.to_i32().unwrap(),
                              self.size.height.to_i32().unwrap()))
    }

    fn ceil(&self) -> Rect<f64> {
        Rect::new(Point2D::new(self.origin.x.ceil(),
                               self.origin.y.ceil()),
                  Size2D::new(self.size.width.ceil(),
                              self.size.height.ceil()))
    }

}

pub trait ToAzFloat {
    fn to_azfloat(&self) -> Rect<AzFloat>;
}

impl ToAzFloat for Rect<f64> {
    fn to_azfloat(&self) -> Rect<AzFloat> {
        Rect::new(Point2D::new(self.origin.x as AzFloat, self.origin.y as AzFloat),
                  Size2D::new(self.size.width as AzFloat, self.size.height as AzFloat))
    }
}