-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
CanvasRenderingContext2d.cc
3354 lines (2890 loc) · 96.2 KB
/
CanvasRenderingContext2d.cc
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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2010 LearnBoost <[email protected]>
#include "CanvasRenderingContext2d.h"
#include <algorithm>
#include "backend/ImageBackend.h"
#include <cairo-pdf.h>
#include "Canvas.h"
#include "CanvasGradient.h"
#include "CanvasPattern.h"
#include "InstanceData.h"
#include <cmath>
#include <cstdlib>
#include "Image.h"
#include "ImageData.h"
#include <limits>
#include <map>
#include "Point.h"
#include <string>
#include "Util.h"
#include <vector>
/*
* Rectangle arg assertions.
*/
#define RECT_ARGS \
double args[4]; \
if(!checkArgs(info, args, 4)) \
return; \
double x = args[0]; \
double y = args[1]; \
double width = args[2]; \
double height = args[3];
constexpr double twoPi = M_PI * 2.;
/*
* Simple helper macro for a rather verbose function call.
*/
#define PANGO_LAYOUT_GET_METRICS(LAYOUT) pango_context_get_metrics( \
pango_layout_get_context(LAYOUT), \
pango_layout_get_font_description(LAYOUT), \
pango_context_get_language(pango_layout_get_context(LAYOUT)))
inline static bool checkArgs(const Napi::CallbackInfo&info, double *args, int argsNum, int offset = 0){
Napi::Env env = info.Env();
int argsEnd = std::min(9, offset + argsNum);
bool areArgsValid = true;
napi_value argv[9];
size_t argc = 9;
napi_get_cb_info(env, static_cast<napi_callback_info>(info), &argc, argv, nullptr, nullptr);
for (int i = offset; i < argsEnd; i++) {
napi_valuetype type;
double val = 0;
napi_typeof(env, argv[i], &type);
if (type == napi_number) {
// fast path
napi_get_value_double(env, argv[i], &val);
} else {
napi_value num;
if (napi_coerce_to_number(env, argv[i], &num) == napi_ok) {
napi_get_value_double(env, num, &val);
}
}
if (areArgsValid) {
if (!std::isfinite(val)) {
// We should continue the loop instead of returning immediately
// See https://html.spec.whatwg.org/multipage/canvas.html
areArgsValid = false;
continue;
}
args[i - offset] = val;
}
}
return areArgsValid;
}
/*
* Initialize Context2d.
*/
void
Context2d::Initialize(Napi::Env& env, Napi::Object& exports) {
Napi::HandleScope scope(env);
InstanceData* data = env.GetInstanceData<InstanceData>();
Napi::Function ctor = DefineClass(env, "CanvasRenderingContext2D", {
InstanceMethod<&Context2d::DrawImage>("drawImage", napi_default_method),
InstanceMethod<&Context2d::PutImageData>("putImageData", napi_default_method),
InstanceMethod<&Context2d::GetImageData>("getImageData", napi_default_method),
InstanceMethod<&Context2d::CreateImageData>("createImageData", napi_default_method),
InstanceMethod<&Context2d::AddPage>("addPage", napi_default_method),
InstanceMethod<&Context2d::Save>("save", napi_default_method),
InstanceMethod<&Context2d::Restore>("restore", napi_default_method),
InstanceMethod<&Context2d::Rotate>("rotate", napi_default_method),
InstanceMethod<&Context2d::Translate>("translate", napi_default_method),
InstanceMethod<&Context2d::Transform>("transform", napi_default_method),
InstanceMethod<&Context2d::GetTransform>("getTransform", napi_default_method),
InstanceMethod<&Context2d::ResetTransform>("resetTransform", napi_default_method),
InstanceMethod<&Context2d::SetTransform>("setTransform", napi_default_method),
InstanceMethod<&Context2d::IsPointInPath>("isPointInPath", napi_default_method),
InstanceMethod<&Context2d::Scale>("scale", napi_default_method),
InstanceMethod<&Context2d::Clip>("clip", napi_default_method),
InstanceMethod<&Context2d::Fill>("fill", napi_default_method),
InstanceMethod<&Context2d::Stroke>("stroke", napi_default_method),
InstanceMethod<&Context2d::FillText>("fillText", napi_default_method),
InstanceMethod<&Context2d::StrokeText>("strokeText", napi_default_method),
InstanceMethod<&Context2d::FillRect>("fillRect", napi_default_method),
InstanceMethod<&Context2d::StrokeRect>("strokeRect", napi_default_method),
InstanceMethod<&Context2d::ClearRect>("clearRect", napi_default_method),
InstanceMethod<&Context2d::Rect>("rect", napi_default_method),
InstanceMethod<&Context2d::RoundRect>("roundRect", napi_default_method),
InstanceMethod<&Context2d::MeasureText>("measureText", napi_default_method),
InstanceMethod<&Context2d::MoveTo>("moveTo", napi_default_method),
InstanceMethod<&Context2d::LineTo>("lineTo", napi_default_method),
InstanceMethod<&Context2d::BezierCurveTo>("bezierCurveTo", napi_default_method),
InstanceMethod<&Context2d::QuadraticCurveTo>("quadraticCurveTo", napi_default_method),
InstanceMethod<&Context2d::BeginPath>("beginPath", napi_default_method),
InstanceMethod<&Context2d::ClosePath>("closePath", napi_default_method),
InstanceMethod<&Context2d::Arc>("arc", napi_default_method),
InstanceMethod<&Context2d::ArcTo>("arcTo", napi_default_method),
InstanceMethod<&Context2d::Ellipse>("ellipse", napi_default_method),
InstanceMethod<&Context2d::SetLineDash>("setLineDash", napi_default_method),
InstanceMethod<&Context2d::GetLineDash>("getLineDash", napi_default_method),
InstanceMethod<&Context2d::CreatePattern>("createPattern", napi_default_method),
InstanceMethod<&Context2d::CreateLinearGradient>("createLinearGradient", napi_default_method),
InstanceMethod<&Context2d::CreateRadialGradient>("createRadialGradient", napi_default_method),
InstanceAccessor<&Context2d::GetFormat>("pixelFormat", napi_default_jsproperty),
InstanceAccessor<&Context2d::GetPatternQuality, &Context2d::SetPatternQuality>("patternQuality", napi_default_jsproperty),
InstanceAccessor<&Context2d::GetImageSmoothingEnabled, &Context2d::SetImageSmoothingEnabled>("imageSmoothingEnabled", napi_default_jsproperty),
InstanceAccessor<&Context2d::GetGlobalCompositeOperation, &Context2d::SetGlobalCompositeOperation>("globalCompositeOperation", napi_default_jsproperty),
InstanceAccessor<&Context2d::GetGlobalAlpha, &Context2d::SetGlobalAlpha>("globalAlpha", napi_default_jsproperty),
InstanceAccessor<&Context2d::GetShadowColor, &Context2d::SetShadowColor>("shadowColor", napi_default_jsproperty),
InstanceAccessor<&Context2d::GetMiterLimit, &Context2d::SetMiterLimit>("miterLimit", napi_default_jsproperty),
InstanceAccessor<&Context2d::GetLineWidth, &Context2d::SetLineWidth>("lineWidth", napi_default_jsproperty),
InstanceAccessor<&Context2d::GetLineCap, &Context2d::SetLineCap>("lineCap", napi_default_jsproperty),
InstanceAccessor<&Context2d::GetLineJoin, &Context2d::SetLineJoin>("lineJoin", napi_default_jsproperty),
InstanceAccessor<&Context2d::GetLineDashOffset, &Context2d::SetLineDashOffset>("lineDashOffset", napi_default_jsproperty),
InstanceAccessor<&Context2d::GetShadowOffsetX, &Context2d::SetShadowOffsetX>("shadowOffsetX", napi_default_jsproperty),
InstanceAccessor<&Context2d::GetShadowOffsetY, &Context2d::SetShadowOffsetY>("shadowOffsetY", napi_default_jsproperty),
InstanceAccessor<&Context2d::GetShadowBlur, &Context2d::SetShadowBlur>("shadowBlur", napi_default_jsproperty),
InstanceAccessor<&Context2d::GetAntiAlias, &Context2d::SetAntiAlias>("antialias", napi_default_jsproperty),
InstanceAccessor<&Context2d::GetTextDrawingMode, &Context2d::SetTextDrawingMode>("textDrawingMode", napi_default_jsproperty),
InstanceAccessor<&Context2d::GetQuality, &Context2d::SetQuality>("quality", napi_default_jsproperty),
InstanceAccessor<&Context2d::GetCurrentTransform, &Context2d::SetCurrentTransform>("currentTransform", napi_default_jsproperty),
InstanceAccessor<&Context2d::GetFillStyle, &Context2d::SetFillStyle>("fillStyle", napi_default_jsproperty),
InstanceAccessor<&Context2d::GetStrokeStyle, &Context2d::SetStrokeStyle>("strokeStyle", napi_default_jsproperty),
InstanceAccessor<&Context2d::GetFont, &Context2d::SetFont>("font", napi_default_jsproperty),
InstanceAccessor<&Context2d::GetTextBaseline, &Context2d::SetTextBaseline>("textBaseline", napi_default_jsproperty),
InstanceAccessor<&Context2d::GetTextAlign, &Context2d::SetTextAlign>("textAlign", napi_default_jsproperty)
});
exports.Set("CanvasRenderingContext2d", ctor);
data->Context2dCtor = Napi::Persistent(ctor);
}
/*
* Create a cairo context.
*/
Context2d::Context2d(const Napi::CallbackInfo& info) : Napi::ObjectWrap<Context2d>(info), env(info.Env()) {
InstanceData* data = env.GetInstanceData<InstanceData>();
if (!info[0].IsObject()) {
Napi::TypeError::New(env, "Canvas expected").ThrowAsJavaScriptException();
return;
}
Napi::Object obj = info[0].As<Napi::Object>();
if (!obj.InstanceOf(data->CanvasCtor.Value()).UnwrapOr(false)) {
if (!env.IsExceptionPending()) {
Napi::TypeError::New(env, "Canvas expected").ThrowAsJavaScriptException();
}
return;
}
_canvas = Canvas::Unwrap(obj);
bool isImageBackend = _canvas->backend()->getName() == "image";
if (isImageBackend) {
cairo_format_t format = ImageBackend::DEFAULT_FORMAT;
if (info[1].IsObject()) {
Napi::Object ctxAttributes = info[1].As<Napi::Object>();
Napi::Value pixelFormat;
if (ctxAttributes.Get("pixelFormat").UnwrapTo(&pixelFormat) && pixelFormat.IsString()) {
std::string utf8PixelFormat = pixelFormat.As<Napi::String>();
if (utf8PixelFormat == "RGBA32") format = CAIRO_FORMAT_ARGB32;
else if (utf8PixelFormat == "RGB24") format = CAIRO_FORMAT_RGB24;
else if (utf8PixelFormat == "A8") format = CAIRO_FORMAT_A8;
else if (utf8PixelFormat == "RGB16_565") format = CAIRO_FORMAT_RGB16_565;
else if (utf8PixelFormat == "A1") format = CAIRO_FORMAT_A1;
#ifdef CAIRO_FORMAT_RGB30
else if (utf8PixelFormat == "RGB30") format = CAIRO_FORMAT_RGB30;
#endif
}
// alpha: false forces use of RGB24
Napi::Value alpha;
if (ctxAttributes.Get("alpha").UnwrapTo(&alpha) && alpha.IsBoolean() && !alpha.As<Napi::Boolean>().Value()) {
format = CAIRO_FORMAT_RGB24;
}
}
static_cast<ImageBackend *>(_canvas->backend())->setFormat(format);
}
_context = _canvas->createCairoContext();
_layout = pango_cairo_create_layout(_context);
// As of January 2023, Pango rounds glyph positions which renders text wider
// or narrower than the browser. See #2184 for more information
#if PANGO_VERSION_CHECK(1, 44, 0)
pango_context_set_round_glyph_positions(pango_layout_get_context(_layout), FALSE);
#endif
states.emplace();
state = &states.top();
pango_layout_set_font_description(_layout, state->fontDescription);
}
/*
* Destroy cairo context.
*/
Context2d::~Context2d() {
if (_layout) g_object_unref(_layout);
if (_context) cairo_destroy(_context);
_resetPersistentHandles();
}
/*
* Reset canvas state.
*/
void Context2d::resetState() {
states.pop();
states.emplace();
pango_layout_set_font_description(_layout, state->fontDescription);
_resetPersistentHandles();
}
void Context2d::_resetPersistentHandles() {
_fillStyle.Reset();
_strokeStyle.Reset();
}
/*
* Save cairo / canvas state.
*/
void
Context2d::save() {
cairo_save(_context);
states.emplace(states.top());
state = &states.top();
}
/*
* Restore cairo / canvas state.
*/
void
Context2d::restore() {
if (states.size() > 1) {
cairo_restore(_context);
states.pop();
state = &states.top();
pango_layout_set_font_description(_layout, state->fontDescription);
}
}
/*
* Save flat path.
*/
void
Context2d::savePath() {
_path = cairo_copy_path_flat(_context);
cairo_new_path(_context);
}
/*
* Restore flat path.
*/
void
Context2d::restorePath() {
cairo_new_path(_context);
cairo_append_path(_context, _path);
cairo_path_destroy(_path);
}
/*
* Create temporary surface for gradient or pattern transparency
*/
cairo_pattern_t*
create_transparent_gradient(cairo_pattern_t *source, float alpha) {
double x0;
double y0;
double x1;
double y1;
double r0;
double r1;
int count;
int i;
double offset;
double r;
double g;
double b;
double a;
cairo_pattern_t *newGradient;
cairo_pattern_type_t type = cairo_pattern_get_type(source);
cairo_pattern_get_color_stop_count(source, &count);
if (type == CAIRO_PATTERN_TYPE_LINEAR) {
cairo_pattern_get_linear_points (source, &x0, &y0, &x1, &y1);
newGradient = cairo_pattern_create_linear(x0, y0, x1, y1);
} else if (type == CAIRO_PATTERN_TYPE_RADIAL) {
cairo_pattern_get_radial_circles(source, &x0, &y0, &r0, &x1, &y1, &r1);
newGradient = cairo_pattern_create_radial(x0, y0, r0, x1, y1, r1);
} else {
return NULL;
}
for ( i = 0; i < count; i++ ) {
cairo_pattern_get_color_stop_rgba(source, i, &offset, &r, &g, &b, &a);
cairo_pattern_add_color_stop_rgba(newGradient, offset, r, g, b, a * alpha);
}
return newGradient;
}
cairo_pattern_t*
create_transparent_pattern(cairo_pattern_t *source, float alpha) {
cairo_surface_t *surface;
cairo_pattern_get_surface(source, &surface);
int width = cairo_image_surface_get_width(surface);
int height = cairo_image_surface_get_height(surface);
cairo_surface_t *mask_surface = cairo_image_surface_create(
CAIRO_FORMAT_ARGB32,
width,
height);
cairo_t *mask_context = cairo_create(mask_surface);
if (cairo_status(mask_context) != CAIRO_STATUS_SUCCESS) {
return NULL;
}
cairo_set_source(mask_context, source);
cairo_paint_with_alpha(mask_context, alpha);
cairo_destroy(mask_context);
cairo_pattern_t* newPattern = cairo_pattern_create_for_surface(mask_surface);
cairo_surface_destroy(mask_surface);
return newPattern;
}
/*
* Fill and apply shadow.
*/
void
Context2d::setFillRule(Napi::Value value) {
cairo_fill_rule_t rule = CAIRO_FILL_RULE_WINDING;
if (value.IsString()) {
std::string str = value.As<Napi::String>().Utf8Value();
if (str == "evenodd") {
rule = CAIRO_FILL_RULE_EVEN_ODD;
}
}
cairo_set_fill_rule(_context, rule);
}
void
Context2d::fill(bool preserve) {
cairo_pattern_t *new_pattern;
bool needsRestore = false;
if (state->fillPattern) {
if (state->globalAlpha < 1) {
new_pattern = create_transparent_pattern(state->fillPattern, state->globalAlpha);
if (new_pattern == NULL) {
Napi::Error::New(env, "Failed to initialize context").ThrowAsJavaScriptException();
// failed to allocate
return;
}
cairo_set_source(_context, new_pattern);
cairo_pattern_destroy(new_pattern);
} else {
cairo_pattern_set_filter(state->fillPattern, state->patternQuality);
cairo_set_source(_context, state->fillPattern);
}
repeat_type_t repeat = Pattern::get_repeat_type_for_cairo_pattern(state->fillPattern);
if (repeat == NO_REPEAT) {
cairo_pattern_set_extend(cairo_get_source(_context), CAIRO_EXTEND_NONE);
} else if (repeat == REPEAT) {
cairo_pattern_set_extend(cairo_get_source(_context), CAIRO_EXTEND_REPEAT);
} else {
cairo_save(_context);
cairo_path_t *savedPath = cairo_copy_path(_context);
cairo_surface_t *patternSurface = nullptr;
cairo_pattern_get_surface(cairo_get_source(_context), &patternSurface);
double width, height;
if (repeat == REPEAT_X) {
double x1, x2;
cairo_path_extents(_context, &x1, nullptr, &x2, nullptr);
width = x2 - x1;
height = cairo_image_surface_get_height(patternSurface);
} else {
double y1, y2;
cairo_path_extents(_context, nullptr, &y1, nullptr, &y2);
width = cairo_image_surface_get_width(patternSurface);
height = y2 - y1;
}
cairo_new_path(_context);
cairo_rectangle(_context, 0, 0, width, height);
cairo_clip(_context);
cairo_append_path(_context, savedPath);
cairo_path_destroy(savedPath);
cairo_pattern_set_extend(cairo_get_source(_context), CAIRO_EXTEND_REPEAT);
needsRestore = true;
}
} else if (state->fillGradient) {
if (state->globalAlpha < 1) {
new_pattern = create_transparent_gradient(state->fillGradient, state->globalAlpha);
if (new_pattern == NULL) {
Napi::Error::New(env, "Unexpected gradient type").ThrowAsJavaScriptException();
// failed to recognize gradient
return;
}
cairo_pattern_set_filter(new_pattern, state->patternQuality);
cairo_set_source(_context, new_pattern);
cairo_pattern_destroy(new_pattern);
} else {
cairo_pattern_set_filter(state->fillGradient, state->patternQuality);
cairo_set_source(_context, state->fillGradient);
}
} else {
setSourceRGBA(state->fill);
}
if (preserve) {
hasShadow()
? shadow(cairo_fill_preserve)
: cairo_fill_preserve(_context);
} else {
hasShadow()
? shadow(cairo_fill)
: cairo_fill(_context);
}
if (needsRestore) {
cairo_restore(_context);
}
}
/*
* Stroke and apply shadow.
*/
void
Context2d::stroke(bool preserve) {
cairo_pattern_t *new_pattern;
if (state->strokePattern) {
if (state->globalAlpha < 1) {
new_pattern = create_transparent_pattern(state->strokePattern, state->globalAlpha);
if (new_pattern == NULL) {
Napi::Error::New(env, "Failed to initialize context").ThrowAsJavaScriptException();
// failed to allocate
return;
}
cairo_set_source(_context, new_pattern);
cairo_pattern_destroy(new_pattern);
} else {
cairo_pattern_set_filter(state->strokePattern, state->patternQuality);
cairo_set_source(_context, state->strokePattern);
}
repeat_type_t repeat = Pattern::get_repeat_type_for_cairo_pattern(state->strokePattern);
if (NO_REPEAT == repeat) {
cairo_pattern_set_extend(cairo_get_source(_context), CAIRO_EXTEND_NONE);
} else {
cairo_pattern_set_extend(cairo_get_source(_context), CAIRO_EXTEND_REPEAT);
}
} else if (state->strokeGradient) {
if (state->globalAlpha < 1) {
new_pattern = create_transparent_gradient(state->strokeGradient, state->globalAlpha);
if (new_pattern == NULL) {
Napi::Error::New(env, "Unexpected gradient type").ThrowAsJavaScriptException();
// failed to recognize gradient
return;
}
cairo_pattern_set_filter(new_pattern, state->patternQuality);
cairo_set_source(_context, new_pattern);
cairo_pattern_destroy(new_pattern);
} else {
cairo_pattern_set_filter(state->strokeGradient, state->patternQuality);
cairo_set_source(_context, state->strokeGradient);
}
} else {
setSourceRGBA(state->stroke);
}
if (preserve) {
hasShadow()
? shadow(cairo_stroke_preserve)
: cairo_stroke_preserve(_context);
} else {
hasShadow()
? shadow(cairo_stroke)
: cairo_stroke(_context);
}
}
/*
* Apply shadow with the given draw fn.
*/
void
Context2d::shadow(void (fn)(cairo_t *cr)) {
cairo_path_t *path = cairo_copy_path_flat(_context);
cairo_save(_context);
// shadowOffset is unaffected by current transform
cairo_matrix_t path_matrix;
cairo_get_matrix(_context, &path_matrix);
cairo_identity_matrix(_context);
// Apply shadow
cairo_push_group(_context);
// No need to invoke blur if shadowBlur is 0
if (state->shadowBlur) {
// find out extent of path
double x1, y1, x2, y2;
if (fn == cairo_fill || fn == cairo_fill_preserve) {
cairo_fill_extents(_context, &x1, &y1, &x2, &y2);
} else {
cairo_stroke_extents(_context, &x1, &y1, &x2, &y2);
}
// create new image surface that size + padding for blurring
double dx = x2-x1, dy = y2-y1;
cairo_user_to_device_distance(_context, &dx, &dy);
int pad = state->shadowBlur * 2;
cairo_surface_t *shadow_surface = cairo_image_surface_create(
CAIRO_FORMAT_ARGB32,
dx + 2 * pad,
dy + 2 * pad);
cairo_t *shadow_context = cairo_create(shadow_surface);
// transform path to the right place
cairo_translate(shadow_context, pad-x1, pad-y1);
cairo_transform(shadow_context, &path_matrix);
// set lineCap lineJoin lineDash
cairo_set_line_cap(shadow_context, cairo_get_line_cap(_context));
cairo_set_line_join(shadow_context, cairo_get_line_join(_context));
double offset;
int dashes = cairo_get_dash_count(_context);
std::vector<double> a(dashes);
cairo_get_dash(_context, a.data(), &offset);
cairo_set_dash(shadow_context, a.data(), dashes, offset);
// draw the path and blur
cairo_set_line_width(shadow_context, cairo_get_line_width(_context));
cairo_new_path(shadow_context);
cairo_append_path(shadow_context, path);
setSourceRGBA(shadow_context, state->shadow);
fn(shadow_context);
blur(shadow_surface, state->shadowBlur);
// paint to original context
cairo_set_source_surface(_context, shadow_surface,
x1 - pad + state->shadowOffsetX + 1,
y1 - pad + state->shadowOffsetY + 1);
cairo_paint(_context);
cairo_destroy(shadow_context);
cairo_surface_destroy(shadow_surface);
} else {
// Offset first, then apply path's transform
cairo_translate(
_context
, state->shadowOffsetX
, state->shadowOffsetY);
cairo_transform(_context, &path_matrix);
// Apply shadow
cairo_new_path(_context);
cairo_append_path(_context, path);
setSourceRGBA(state->shadow);
fn(_context);
}
// Paint the shadow
cairo_pop_group_to_source(_context);
cairo_paint(_context);
// Restore state
cairo_restore(_context);
cairo_new_path(_context);
cairo_append_path(_context, path);
fn(_context);
cairo_path_destroy(path);
}
/*
* Set source RGBA for the current context
*/
void
Context2d::setSourceRGBA(rgba_t color) {
setSourceRGBA(_context, color);
}
/*
* Set source RGBA
*/
void
Context2d::setSourceRGBA(cairo_t *ctx, rgba_t color) {
cairo_set_source_rgba(
ctx
, color.r
, color.g
, color.b
, color.a * state->globalAlpha);
}
/*
* Check if the context has a drawable shadow.
*/
bool
Context2d::hasShadow() {
return state->shadow.a
&& (state->shadowBlur || state->shadowOffsetX || state->shadowOffsetY);
}
/*
* Blur the given surface with the given radius.
*/
void
Context2d::blur(cairo_surface_t *surface, int radius) {
// Steve Hanov, 2009
// Released into the public domain.
radius = radius * 0.57735f + 0.5f;
// get width, height
int width = cairo_image_surface_get_width( surface );
int height = cairo_image_surface_get_height( surface );
const unsigned int size = width * height * sizeof(unsigned);
unsigned* precalc = (unsigned*)malloc(size);
cairo_surface_flush( surface );
unsigned char* src = cairo_image_surface_get_data( surface );
double mul=1.f/((radius*2)*(radius*2));
int channel;
// The number of times to perform the averaging. According to wikipedia,
// three iterations is good enough to pass for a gaussian.
const int MAX_ITERATIONS = 3;
int iteration;
for ( iteration = 0; iteration < MAX_ITERATIONS; iteration++ ) {
for( channel = 0; channel < 4; channel++ ) {
int x,y;
// precomputation step.
unsigned char* pix = src;
unsigned* pre = precalc;
bool modified = false;
pix += channel;
for (y=0;y<height;y++) {
for (x=0;x<width;x++) {
int tot=pix[0];
if (x>0) tot+=pre[-1];
if (y>0) tot+=pre[-width];
if (x>0 && y>0) tot-=pre[-width-1];
*pre++=tot;
if (!modified) modified = true;
pix += 4;
}
}
if (!modified) {
memset(precalc, 0, size);
}
// blur step.
pix = src + (int)radius * width * 4 + (int)radius * 4 + channel;
for (y=radius;y<height-radius;y++) {
for (x=radius;x<width-radius;x++) {
int l = x < radius ? 0 : x - radius;
int t = y < radius ? 0 : y - radius;
int r = x + radius >= width ? width - 1 : x + radius;
int b = y + radius >= height ? height - 1 : y + radius;
int tot = precalc[r+b*width] + precalc[l+t*width] -
precalc[l+b*width] - precalc[r+t*width];
*pix=(unsigned char)(tot*mul);
pix += 4;
}
pix += (int)radius * 2 * 4;
}
}
}
cairo_surface_mark_dirty(surface);
free(precalc);
}
/*
* Get format (string).
*/
Napi::Value
Context2d::GetFormat(const Napi::CallbackInfo& info) {
std::string pixelFormatString;
switch (canvas()->backend()->getFormat()) {
case CAIRO_FORMAT_ARGB32: pixelFormatString = "RGBA32"; break;
case CAIRO_FORMAT_RGB24: pixelFormatString = "RGB24"; break;
case CAIRO_FORMAT_A8: pixelFormatString = "A8"; break;
case CAIRO_FORMAT_A1: pixelFormatString = "A1"; break;
case CAIRO_FORMAT_RGB16_565: pixelFormatString = "RGB16_565"; break;
#ifdef CAIRO_FORMAT_RGB30
case CAIRO_FORMAT_RGB30: pixelFormatString = "RGB30"; break;
#endif
default: return env.Null();
}
return Napi::String::New(env, pixelFormatString);
}
/*
* Create a new page.
*/
void
Context2d::AddPage(const Napi::CallbackInfo& info) {
if (canvas()->backend()->getName() != "pdf") {
Napi::Error::New(env, "only PDF canvases support .addPage()").ThrowAsJavaScriptException();
return;
}
cairo_show_page(context());
Napi::Number zero = Napi::Number::New(env, 0);
int width = info[0].ToNumber().UnwrapOr(zero).Int32Value();
int height = info[1].ToNumber().UnwrapOr(zero).Int32Value();
if (width < 1) width = canvas()->getWidth();
if (height < 1) height = canvas()->getHeight();
cairo_pdf_surface_set_size(canvas()->surface(), width, height);
}
/*
* Put image data.
*
* - imageData, dx, dy
* - imageData, dx, dy, sx, sy, sw, sh
*
*/
void
Context2d::PutImageData(const Napi::CallbackInfo& info) {
if (!info[0].IsObject()) {
Napi::TypeError::New(env, "ImageData expected").ThrowAsJavaScriptException();
return;
}
Napi::Object obj = info[0].As<Napi::Object>();
InstanceData* data = env.GetInstanceData<InstanceData>();
if (!obj.InstanceOf(data->ImageDataCtor.Value()).UnwrapOr(false)) {
if (!env.IsExceptionPending()) {
Napi::TypeError::New(env, "ImageData expected").ThrowAsJavaScriptException();
}
return;
}
ImageData *imageData = ImageData::Unwrap(obj);
Napi::Number zero = Napi::Number::New(env, 0);
uint8_t *src = imageData->data();
uint8_t *dst = canvas()->data();
int dstStride = canvas()->stride();
int Bpp = dstStride / canvas()->getWidth();
int srcStride = Bpp * imageData->width();
int sx = 0
, sy = 0
, sw = 0
, sh = 0
, dx = info[1].ToNumber().UnwrapOr(zero).Int32Value()
, dy = info[2].ToNumber().UnwrapOr(zero).Int32Value()
, rows
, cols;
switch (info.Length()) {
// imageData, dx, dy
case 3:
sw = imageData->width();
sh = imageData->height();
break;
// imageData, dx, dy, sx, sy, sw, sh
case 7:
sx = info[3].ToNumber().UnwrapOr(zero).Int32Value();
sy = info[4].ToNumber().UnwrapOr(zero).Int32Value();
sw = info[5].ToNumber().UnwrapOr(zero).Int32Value();
sh = info[6].ToNumber().UnwrapOr(zero).Int32Value();
// fix up negative height, width
if (sw < 0) sx += sw, sw = -sw;
if (sh < 0) sy += sh, sh = -sh;
// clamp the left edge
if (sx < 0) sw += sx, sx = 0;
if (sy < 0) sh += sy, sy = 0;
// clamp the right edge
if (sx + sw > imageData->width()) sw = imageData->width() - sx;
if (sy + sh > imageData->height()) sh = imageData->height() - sy;
// start destination at source offset
dx += sx;
dy += sy;
break;
default:
Napi::Error::New(env, "invalid arguments").ThrowAsJavaScriptException();
return;
}
// chop off outlying source data
if (dx < 0) sw += dx, sx -= dx, dx = 0;
if (dy < 0) sh += dy, sy -= dy, dy = 0;
// clamp width at canvas size
// Need to wrap std::min calls using parens to prevent macro expansion on
// windows. See http://stackoverflow.com/questions/5004858/stdmin-gives-error
cols = (std::min)(sw, canvas()->getWidth() - dx);
rows = (std::min)(sh, canvas()->getHeight() - dy);
if (cols <= 0 || rows <= 0) return;
switch (canvas()->backend()->getFormat()) {
case CAIRO_FORMAT_ARGB32: {
src += sy * srcStride + sx * 4;
dst += dstStride * dy + 4 * dx;
for (int y = 0; y < rows; ++y) {
uint8_t *dstRow = dst;
uint8_t *srcRow = src;
for (int x = 0; x < cols; ++x) {
// rgba
uint8_t r = *srcRow++;
uint8_t g = *srcRow++;
uint8_t b = *srcRow++;
uint8_t a = *srcRow++;
// argb
// performance optimization: fully transparent/opaque pixels can be
// processed more efficiently.
if (a == 0) {
*dstRow++ = 0;
*dstRow++ = 0;
*dstRow++ = 0;
*dstRow++ = 0;
} else if (a == 255) {
*dstRow++ = b;
*dstRow++ = g;
*dstRow++ = r;
*dstRow++ = a;
} else {
float alpha = (float)a / 255;
*dstRow++ = b * alpha;
*dstRow++ = g * alpha;
*dstRow++ = r * alpha;
*dstRow++ = a;
}
}
dst += dstStride;
src += srcStride;
}
break;
}
case CAIRO_FORMAT_RGB24: {
src += sy * srcStride + sx * 4;
dst += dstStride * dy + 4 * dx;
for (int y = 0; y < rows; ++y) {
uint8_t *dstRow = dst;
uint8_t *srcRow = src;
for (int x = 0; x < cols; ++x) {
// rgba
uint8_t r = *srcRow++;
uint8_t g = *srcRow++;
uint8_t b = *srcRow++;
srcRow++;
// argb
*dstRow++ = b;
*dstRow++ = g;
*dstRow++ = r;
*dstRow++ = 255;
}
dst += dstStride;
src += srcStride;
}
break;
}
case CAIRO_FORMAT_A8: {
src += sy * srcStride + sx;
dst += dstStride * dy + dx;
if (srcStride == dstStride && cols == dstStride) {
// fast path: strides are the same and doing a full-width put
memcpy(dst, src, cols * rows);
} else {
for (int y = 0; y < rows; ++y) {
memcpy(dst, src, cols);
dst += dstStride;
src += srcStride;
}
}
break;
}
case CAIRO_FORMAT_A1: {
// TODO Should this be totally packed, or maintain a stride divisible by 4?
Napi::Error::New(env, "putImageData for CANVAS_FORMAT_A1 is not yet implemented").ThrowAsJavaScriptException();
break;
}
case CAIRO_FORMAT_RGB16_565: {
src += sy * srcStride + sx * 2;
dst += dstStride * dy + 2 * dx;
for (int y = 0; y < rows; ++y) {
memcpy(dst, src, cols * 2);
dst += dstStride;
src += srcStride;
}
break;
}
#ifdef CAIRO_FORMAT_RGB30
case CAIRO_FORMAT_RGB30: {
// TODO
Napi::Error::New(env, "putImageData for CANVAS_FORMAT_RGB30 is not yet implemented").ThrowAsJavaScriptException();
break;
}
#endif
default: {
Napi::Error::New(env, "Invalid pixel format or not an image canvas").ThrowAsJavaScriptException();
return;
}
}
cairo_surface_mark_dirty_rectangle(
canvas()->surface()
, dx
, dy
, cols
, rows);
}
/*
* Get image data.
*
* - sx, sy, sw, sh
*
*/
Napi::Value
Context2d::GetImageData(const Napi::CallbackInfo& info) {
Napi::Number zero = Napi::Number::New(env, 0);
Canvas *canvas = this->canvas();
int sx = info[0].ToNumber().UnwrapOr(zero).Int32Value();
int sy = info[1].ToNumber().UnwrapOr(zero).Int32Value();
int sw = info[2].ToNumber().UnwrapOr(zero).Int32Value();
int sh = info[3].ToNumber().UnwrapOr(zero).Int32Value();
if (!sw) {
Napi::Error::New(env, "IndexSizeError: The source width is 0.").ThrowAsJavaScriptException();
return env.Undefined();
}
if (!sh) {
Napi::Error::New(env, "IndexSizeError: The source height is 0.").ThrowAsJavaScriptException();
return env.Undefined();
}
int width = canvas->getWidth();
int height = canvas->getHeight();
if (!width) {
Napi::TypeError::New(env, "Canvas width is 0").ThrowAsJavaScriptException();
return env.Undefined();
}
if (!height) {
Napi::TypeError::New(env, "Canvas height is 0").ThrowAsJavaScriptException();
return env.Undefined();
}
// WebKit and Firefox have this behavior:
// Flip the coordinates so the origin is top/left-most:
if (sw < 0) {