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
#![allow(clippy::many_single_char_names)]
#![allow(unused_imports)]
#![allow(unused_variables)]
#![cfg(not(target_arch = "wasm32"))]

use crate::{
    BaseLine, CanvasContext, Color, Direction, Gradient, GradientType, LineCap,
    LineJoin, LinearGradient, PatternExtend, Point, RadialGradient, Rect, RgbaColor, Size,
    TextAlign, TextMetrics, TextStyle, TextWeight,
};
use cairo::{self, FontFace, FontSlant, FontWeight};
use std::any::Any;

#[derive(Debug, Clone)]
pub struct Pattern {
    pub extend: PatternExtend,
    pub inner: cairo::SurfacePattern,
}

impl Pattern {
    // Create pattern
    pub fn new(extend: PatternExtend, inner: cairo::SurfacePattern) -> Self {
        Self { extend, inner }
    }
}

pub struct Canvas<'a> {
    ctx: &'a cairo::Context,
}

impl<'a> Canvas<'a> {
    #[allow(dead_code)]
    pub fn new(ctx: &'a cairo::Context) -> Self {
        Self { ctx }
    }
}

impl<'a> CanvasContext<Pattern> for Canvas<'a> {
    // fn get_current_transform(&self) -> Matrix;

    // fn set_current_transform(&self, value: Matrix<f64>) {
    //     // self.ctx.get_matrix()
    //     unimplemented!()
    // }

    fn get_direction(&self) -> Direction {
        unimplemented!()
    }

    fn set_direction(&self, value: Direction) -> String {
        info!("NOT IMPLEMENTED");
        unimplemented!()
    }

    fn set_fill_color(&self, value: Color) {
        let RgbaColor {
            red,
            green,
            blue,
            alpha,
        } = value.into();
        self.ctx.set_source_rgba(
            red as f64 / 255.,
            green as f64 / 255.,
            blue as f64 / 255.,
            alpha as f64 / 255.,
        );
    }

    fn set_fill_gradient(&self, value: &Gradient) {
        match value.kind {
            GradientType::Linear(params) => {
                let LinearGradient { x0, y0, x1, y1 } = params;
                let gradient = cairo::LinearGradient::new(x0, y0, x1, y1);
                let stops = value.stops.borrow();
                for stop in stops.iter() {
                    let RgbaColor {
                        red,
                        green,
                        blue,
                        alpha,
                    } = stop.color.into();

                    gradient.add_color_stop_rgba(
                        stop.offset,
                        red as f64 / 255.,
                        green as f64 / 255.,
                        blue as f64 / 255.,
                        alpha as f64 / 255.,
                    );
                }
                self.ctx.set_source(&gradient);
            }
            GradientType::Radial(params) => {
                let RadialGradient {
                    x0,
                    y0,
                    r0,
                    x1,
                    y1,
                    r1,
                } = params;
                let gradient = cairo::RadialGradient::new(x0, y0, r0, x1, y1, r1);
                let stops = value.stops.borrow();
                for stop in stops.iter() {
                    let RgbaColor {
                        red,
                        green,
                        blue,
                        alpha,
                    } = stop.color.into();

                    gradient.add_color_stop_rgba(
                        stop.offset,
                        red as f64 / 255.,
                        green as f64 / 255.,
                        blue as f64 / 255.,
                        alpha as f64 / 255.,
                    );
                }
                self.ctx.set_source(&gradient);
            }
        }
    }

    fn set_fill_pattern(&self, pattern: &Pattern) {
        let extend = match pattern.extend {
            PatternExtend::None => cairo::Extend::None,
            PatternExtend::Repeat => cairo::Extend::Repeat,
            PatternExtend::Reflect => cairo::Extend::Reflect,
            PatternExtend::Pad => cairo::Extend::Pad,
        };

        pattern.inner.set_extend(extend);
        self.ctx.set_source(&pattern.inner);
    }

    fn get_filter(&self) -> String {
        unimplemented!()
    }

    fn set_filter(&self, value: &str) {
        unimplemented!()
    }

    fn get_font(&self) -> String {
        // self.ctx.get_font_face(font_face)
        unimplemented!()
    }

    fn set_font(&self, family: &str, style: TextStyle, weight: TextWeight, size: f64) {
        let slant = match style {
            TextStyle::Italic => FontSlant::Italic,
            TextStyle::Normal => FontSlant::Normal,
            TextStyle::Oblique => FontSlant::Oblique,
        };

        let weight = match weight {
            TextWeight::Bold => FontWeight::Bold,
            _ => FontWeight::Normal,
        };

        self.ctx.select_font_face(family, slant, weight);
        self.ctx.set_font_size(size);
    }

    fn get_global_alpha(&self) -> f64 {
        unimplemented!()
    }

    fn set_global_alpha(&self, value: f64) {
        unimplemented!()
    }

    fn get_global_composite_operation(&self) -> String {
        unimplemented!()
    }

    fn set_global_composite_operation(&self, value: &str) {
        unimplemented!()
    }

    // Whether images and patterns on this canvas will be smoothed when this canvas is scaled.
    // imageSmoothingEnabled
    fn is_image_smoothing_enabled(&self) -> bool {
        unimplemented!()
    }

    fn set_image_smoothing(&self, value: bool) {
        unimplemented!()
    }

    // fn get_image_smoothing_quality(&self) -> String {
    //     unimplemented!()
    // }

    // fn set_image_smoothing_quality(&self, value: &str) {
    //     unimplemented!()
    // }

    fn get_line_cap(&self) -> LineCap {
        let result = self.ctx.get_line_cap();
        // format!("{}", result)
        unimplemented!()
    }

    fn set_line_cap(&self, value: LineCap) {
        // self.ctx.set_line_cap()
        // unimplemented!()
    }

    // @SupportedBrowser(SupportedBrowser.CHROME), @SupportedBrowser(SupportedBrowser.IE, '11'), @SupportedBrowser(SupportedBrowser.SAFARI), @Unstable()
    fn get_line_dash_offset(&self) -> f64 {
        let (_, result) = self.ctx.get_dash();
        result
    }

    fn set_line_dash_offset(&self, value: f64) {
        // self.ctx.set_dash();
        unimplemented!()
    }

    fn get_line_join(&self) -> LineJoin {
        let result = self.ctx.get_line_join();
        // format!("{}", result)
        unimplemented!()
    }

    fn set_line_join(&self, value: LineJoin) {
        // self.ctx.set_line_join(arg)
        // FIXME:
    }

    fn get_line_width(&self) -> f64 {
        self.ctx.get_line_width()
    }

    fn set_line_width(&self, value: f64) {
        self.ctx.set_line_width(value);
    }

    fn get_miter_limit(&self) -> f64 {
        self.ctx.get_miter_limit()
    }

    fn set_miter_limit(&self, value: f64) {
        self.ctx.set_miter_limit(value);
    }

    fn get_shadow_blur(&self) -> f64 {
        unimplemented!()
    }

    fn set_shadow_blur(&self, value: f64) {
        unimplemented!()
    }

    fn get_shadow_color(&self) -> Color {
        unimplemented!()
    }
    fn set_shadow_color(&self, value: Color) {
        unimplemented!()
    }

    fn get_shadow_offset_x(&self) -> f64 {
        unimplemented!()
    }
    fn set_shadow_offset_x(&self, value: f64) {
        unimplemented!()
    }

    fn get_shadow_offset_y(&self) -> f64 {
        unimplemented!()
    }

    fn set_shadow_offset_y(&self, value: f64) {
        unimplemented!()
    }

    fn set_stroke_color(&self, value: Color) {
        let color: RgbaColor = value.into();
        self.ctx.set_source_rgba(
            color.red as f64 / 255.,
            color.green as f64 / 255.,
            color.blue as f64 / 255.,
            color.alpha as f64 / 255.,
        );
    }

    fn set_stroke_gradient(&self, value: &Gradient) {
        match value.kind {
            GradientType::Linear(params) => {
                let LinearGradient { x0, y0, x1, y1 } = params;
                let gradient = cairo::LinearGradient::new(x0, y0, x1, y1);
                let stops = value.stops.borrow();
                for stop in stops.iter() {
                    let RgbaColor {
                        red,
                        green,
                        blue,
                        alpha,
                    } = stop.color.into();

                    gradient.add_color_stop_rgba(
                        stop.offset,
                        red as f64 / 255.,
                        green as f64 / 255.,
                        blue as f64 / 255.,
                        alpha as f64 / 255.,
                    );
                }
                self.ctx.set_source(&gradient);
            }
            GradientType::Radial(params) => {
                let RadialGradient {
                    x0,
                    y0,
                    r0,
                    x1,
                    y1,
                    r1,
                } = params;
                let gradient = cairo::RadialGradient::new(x0, y0, r0, x1, y1, r1);
                let stops = value.stops.borrow();
                for stop in stops.iter() {
                    let RgbaColor {
                        red,
                        green,
                        blue,
                        alpha,
                    } = stop.color.into();

                    gradient.add_color_stop_rgba(
                        stop.offset,
                        red as f64 / 255.,
                        green as f64 / 255.,
                        blue as f64 / 255.,
                        alpha as f64 / 255.,
                    );
                }
                self.ctx.set_source(&gradient);
            }
        }
    }

    fn set_stroke_pattern(&self, pattern: &Pattern) {
        println!("SET STROKE PATTERN");

        let extend = match pattern.extend {
            PatternExtend::None => cairo::Extend::None,
            PatternExtend::Repeat => cairo::Extend::Repeat,
            PatternExtend::Reflect => cairo::Extend::Reflect,
            PatternExtend::Pad => cairo::Extend::Pad,
        };

        pattern.inner.set_extend(extend);
        self.ctx.set_source(&pattern.inner);
    }

    fn get_text_align(&self) -> TextAlign {
        unimplemented!()
    }

    fn set_text_align(&self, value: TextAlign) {
        //TODO: complete it
    }

    fn get_text_baseline(&self) -> BaseLine {
        unimplemented!()
    }

    fn set_text_baseline(&self, value: BaseLine) {
        //TODO: complete it
    }

    // anticlockwise: bool = false
    fn arc(
        &self,
        x: f64,
        y: f64,
        radius: f64,
        start_angle: f64,
        end_angle: f64,
        anticlockwise: bool,
    ) {
        if anticlockwise {
            self.ctx.arc_negative(x, y, radius, start_angle, end_angle);
        } else {
            self.ctx.arc(x, y, radius, start_angle, end_angle);
        }
    }

    fn arc_to(&self, x1: f64, y1: f64, x2: f64, y2: f64, radius: f64) {
        unimplemented!()
    }

    fn begin_path(&self) {
        self.ctx.new_path();
    }

    fn bezier_curve_to(&self, cp1x: f64, cp1y: f64, cp2x: f64, cp2y: f64, x: f64, y: f64) {
        self.ctx.curve_to(cp1x, cp1y, cp2x, cp2y, x, y);
    }

    // FIXME: seems code correct but it should clear with transpatency but it black (((
    fn clear_rect(&self, x: f64, y: f64, width: f64, height: f64) {
        self.ctx.save();
        self.ctx.set_source_rgba(0., 0., 0., 0.);
        self.ctx.set_operator(cairo::Operator::Clear);
        self.ctx.rectangle(x, y, width, height);
        self.ctx.fill();
        self.ctx.restore();
    }

    // [path_OR_winding: dynamic, winding: String]
    // fn clip(path_OR_winding: dynamic, winding: String); // TODO:
    fn close_path(&self) {
        self.ctx.close_path();
    }

    // @Creates('ImageData|=Object')
    // [int? sh_OR_sw, dynamic imageDataColorSettings_OR_sh, Map? imageDataColorSettings]
    // fn createImageData(data_OR_imagedata_OR_sw: dynamic, sh_OR_sw: int, imageDataColorSettings_OR_sh: dynamic, imageDataColorSettings: Map) -> ImageData; // TODO:

    // fn createImageDataFromImageData(imagedata: ImageData) -> ImageData; // TODO:

    // [Element? element]
    // fn drawFocusIfNeeded(element_OR_path: dynamic, element: Element); // TODO:

    // Draws an image from a CanvasImageSource to this canvas.
    // @JSName('drawImage')
    // fn drawImage(source: CanvasImageSource, destX: f64, destY: f64); // TODO:

    // Draws an image from a CanvasImageSource to an area of this canvas.
    // @JSName('drawImage')
    // fn drawImageScaled(source: CanvasImageSource, destX: f64, destY: f64, destWidth: f64, destHeight: f64); // TODO:

    // Draws an image from a CanvasImageSource to an area of this canvas.
    // @JSName('drawImage')
    // fn drawImageScaledFromSource(source: CanvasImageSource, sourceX: f64, sourceY: f64, sourceWidth: f64, sourceHeight: f64, destX: f64, destY: f64, destWidth: f64, destHeight: f64); // TODO:

    // Draws an image from a CanvasImageSource to an area of this canvas.
    // {Rectangle<f64>? sourceRect}
    // fn drawImageToRect(source: CanvasImageSource, destRect: Rectangle<f64>, sourceRect: Rectangle<f64>); // TODO:

    fn ellipse(
        &self,
        x: f64,
        y: f64,
        radius_x: f64,
        radius_y: f64,
        rotation: f64,
        start_angle: f64,
        end_angle: f64,
        anticlockwise: bool,
    ) {
        self.ctx.save();

        self.ctx.translate(x, y);
        self.ctx.scale(1., radius_y / radius_x);
        self.ctx.rotate(rotation);
        self.ctx.translate(-x, -y);

        self.ctx.arc(x, y, radius_x, start_angle, end_angle);

        self.ctx.restore();
        // stroke later to prevent stroke ugly transformation
    }

    // [dynamic path_OR_winding, String? winding]
    // fn fill(path_OR_winding: dynamic, winding: String); // TODO:

    fn fill(&self) {
        self.ctx.fill();
    }

    fn fill_rect(&self, x: f64, y: f64, width: f64, height: f64) {
        self.ctx.rectangle(x, y, width, height);
        self.ctx.fill();
    }

    // Draws text to the canvas.
    fn fill_text(&self, text: &str, x: f64, y: f64) {
        self.ctx.save();
        self.ctx.move_to(x, y);
        self.ctx.text_path(text);
        self.ctx.fill();
        self.ctx.restore();
    }

    // fn getContextAttributes() -> Map; // TODO:

    // @Creates('ImageData|=Object')
    // fn getImageData(sx: i64, sy: i64, sw: i64, sh: i64) -> ImageData; // TODO:

    // @SupportedBrowser(SupportedBrowser.CHROME), @SupportedBrowser(SupportedBrowser.IE, '11'), @SupportedBrowser(SupportedBrowser.SAFARI), @Unstable()
    fn get_line_dash(&self) -> Vec<f64> {
        let (result, _) = self.ctx.get_dash();
        result
    }

    // [dynamic winding_OR_y, String? winding]
    // fn isPointInPath(path_OR_x: dynamic, x_OR_y: f64, winding_OR_y: dynamic, winding: String) -> bool; // TODO:

    // [f64? y]
    // fn isPointInStroke(path_OR_x: dynamic, x_OR_y: f64, y: f64) -> bool; // TODO:
    fn line_to(&self, x: f64, y: f64) {
        self.ctx.line_to(x, y);
    }

    fn measure_text(&self, text: &str) -> TextMetrics {
        let ext = self.ctx.text_extents(text);
        TextMetrics {
            width: ext.width,
            height: ext.height,
        }
    }

    fn move_to(&self, x: f64, y: f64) {
        self.ctx.move_to(x, y);
    }

    // [int? dirtyX, int? dirtyY, int? dirtyWidth, int? dirtyHeight]
    // fn putImageData(imagedata: ImageData, dx: i64, dy: i64, dirtyX: i64, dirtyY: i64, dirtyWidth: i64, dirtyHeight: i64); // TODO:
    fn quadratic_curve_to(&self, cpx: f64, cpy: f64, x: f64, y: f64) {
        // A quadratic Bezier can be always represented by a cubic one by
        // applying the degree elevation algorithm. The resulted cubic representation
        // will share its anchor points with the original quadratic,
        // while the control points will be at 2/3 of the quadratic handle segments:

        // C1 = (2·C + P1)/3
        // C2 = (2·C + P2)/3

        let (x0, y0) = self.ctx.get_current_point();
        self.ctx.curve_to(
            2.0 / 3.0 * cpx + 1.0 / 3.0 * x0,
            2.0 / 3.0 * cpy + 1.0 / 3.0 * y0,
            2.0 / 3.0 * cpx + 1.0 / 3.0 * x,
            2.0 / 3.0 * cpy + 1.0 / 3.0 * y,
            x,
            y,
        );
    }

    fn rect(&self, x: f64, y: f64, width: f64, height: f64) {
        self.ctx.rectangle(x, y, width, height);
    }

    fn reset_transform(&self) {
        unimplemented!()
    }

    fn restore(&self) {
        self.ctx.restore();
    }

    fn rotate(&self, angle: f64) {
        self.ctx.rotate(angle);
    }

    fn save(&self) {
        self.ctx.save();
    }

    fn scale(&self, x: f64, y: f64) {
        self.ctx.scale(x, y);
    }

    // [Path2D? path]
    // fn scrollPathIntoView(path: Path2D); // TODO:

    // @SupportedBrowser(SupportedBrowser.CHROME), @SupportedBrowser(SupportedBrowser.IE, '11'), @SupportedBrowser(SupportedBrowser.SAFARI), @Unstable()
    fn set_line_dash(&self, dash: Vec<f64>) {
        // self.ctx.set_dash(dashes, offset)
        unimplemented!()
    }

    fn set_transform(&self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) {
        let m = cairo::Matrix::new(a, b, c, d, e, f);
        self.ctx.transform(m);
    }

    fn stroke(&self) {
        self.ctx.stroke();
    }

    fn stroke_rect(&self, x: f64, y: f64, width: f64, height: f64) {
        self.ctx.save();
        self.ctx.rectangle(x, y, width, height);
        self.ctx.fill();
        self.ctx.restore();
    }

    fn stroke_text(&self, text: &str, x: f64, y: f64) {
        self.ctx.save();
        self.ctx.move_to(x, y);
        self.ctx.text_path(text);
        self.ctx.stroke();
        self.ctx.restore();
    }

    fn transform(&self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) {
        let m = cairo::Matrix::new(a, b, c, d, e, f);
        self.ctx.transform(m);
    }

    fn translate(&self, x: f64, y: f64) {
        self.ctx.translate(x, y);
    }
}