Repository navigation
Expand file tree
/
Copy pathtests.javaScript.all.ts
More file actions
2393 lines (2188 loc) · 89.2 KB
/
Copy pathtests.javaScript.all.ts
File metadata and controls
2393 lines (2188 loc) · 89.2 KB
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
import * as Mocha from "mocha";
import { expect } from "chai";
import { Buffer } from "buffer";
import {
RequestFile,
NativeEngine,
RawTexture,
DynamicTexture,
MeshBuilder,
DefaultRenderingPipeline,
RefractionPostProcess,
ImageProcessingPostProcess,
HighlightsPostProcess,
PassPostProcess,
TonemapPostProcess,
TonemappingOperator,
Color3,
ConvolutionPostProcess,
BlackAndWhitePostProcess,
ShaderMaterial,
Scene,
Vector2,
BlurPostProcess
} from "@babylonjs/core";
import { GradientMaterial } from "@babylonjs/materials";
import { registerPngTests } from "./tests.nativeEngine.png";
declare var describe: typeof Mocha.describe;
declare var it: typeof Mocha.it;
Mocha.setup("bdd");
// @ts-ignore
Mocha.reporter("spec");
declare const hostPlatform: string;
declare const hasGpuRendering: boolean;
declare const hasNativeImageLoading: boolean;
declare const setExitCode: (code: number) => void;
declare const setImageReloadTestResponse: (bytes: Uint8Array) => void;
declare const skipCanvasGpuTests: boolean;
declare const _native: any;
registerPngTests(describe, it, hasGpuRendering && hasNativeImageLoading);
describe("Native texture readback", function () {
this.timeout(10000);
// Native LoadRawTexture is also disabled when native image loading is off.
const itWithRawTexture = hasGpuRendering && hasNativeImageLoading ? it : it.skip;
itWithRawTexture("returns bottom-origin RGBA8 crops and preserves destination offsets", async function () {
const engine = new NativeEngine();
const scene = new Scene(engine);
try {
for (const invertY of [false, true]) {
const width = 5;
const height = 7;
const data = new Uint8Array(width * height * 4);
for (let y = 0; y < height; ++y) {
for (let x = 0; x < width; ++x) {
data.set([x * 40, y * 30, 128, 255], (y * width + x) * 4);
}
}
const texture = RawTexture.CreateRGBATexture(data, width, height, scene, false, invertY);
try {
for (const [x, y, readWidth, readHeight] of [
[0, 0, width, height], [0, 0, 1, 1], [4, 6, 1, 1],
[1, 0, 3, 2], [1, 2, 2, 3], [0, 5, 5, 2]
]) {
const storage = new Uint8Array(readWidth * readHeight * 4 + 12).fill(91);
const destination = storage.subarray(4, storage.length - 8);
const result = await texture.readPixels(0, 0, destination, true, false, x, y, readWidth, readHeight);
expect(result).to.equal(destination);
expect(Array.from(storage.subarray(0, 4))).to.deep.equal([91, 91, 91, 91]);
expect(Array.from(storage.subarray(storage.length - 8))).to.deep.equal(Array(8).fill(91));
for (let row = 0; row < readHeight; ++row) {
const sourceY = invertY ? height - 1 - (y + row) : y + row;
for (let column = 0; column < readWidth; ++column) {
const offset = (row * readWidth + column) * 4;
expect(Array.from(destination.subarray(offset, offset + 4)),
`invertY=${invertY}, crop=${x},${y},${readWidth},${readHeight}, pixel=${column},${row}`)
.to.deep.equal([(x + column) * 40, sourceY * 30, 128, 255]);
}
}
}
} finally {
texture.dispose();
}
}
} finally {
scene.dispose();
engine.dispose();
}
});
itWithRawTexture("returns wide odd-height readbacks without changing the middle row", async function () {
const engine = new NativeEngine();
const scene = new Scene(engine);
try {
const width = 2049;
const height = 3;
const rowPitch = width * 4;
const data = new Uint8Array(rowPitch * height);
for (let y = 0; y < height; ++y) {
for (let x = 0; x < width; ++x) {
data.set([x % 251, y * 70, Math.floor(x / 256) * 23, 255], y * rowPitch + x * 4);
}
}
for (const invertY of [false, true]) {
const texture = RawTexture.CreateRGBATexture(data, width, height, scene, false, invertY);
try {
const result = await texture.readPixels();
if (!(result instanceof Uint8Array)) {
throw new Error("Expected RGBA8 wide readback");
}
expect(result.length).to.equal(data.length);
for (let row = 0; row < height; ++row) {
const sourceY = invertY ? height - 1 - row : row;
expect(Array.from(result.subarray(row * rowPitch, (row + 1) * rowPitch)))
.to.deep.equal(Array.from(data.subarray(sourceY * rowPitch, (sourceY + 1) * rowPitch)));
}
} finally {
texture.dispose();
}
}
} finally {
scene.dispose();
engine.dispose();
}
});
itWithRawTexture("uses mip extents for cropped readback", async function () {
const engine = new NativeEngine();
const scene = new Scene(engine);
try {
const data = new Uint8Array(4 * 8 * 4);
for (let y = 0; y < 8; ++y) {
for (let x = 0; x < 4; ++x) {
data.set([x < 2 ? 255 : 0, y < 4 ? 255 : 0, 0, 255], (y * 4 + x) * 4);
}
}
const texture = RawTexture.CreateRGBATexture(data, 4, 8, scene, true, false);
for (const [y, green] of [[0, 255], [3, 0]]) {
const result = await texture.readPixels(0, 1, null, true, false, 1, y, 1, 1);
if (!(result instanceof Uint8Array)) {
throw new Error("Expected RGBA8 mip readback");
}
expect(result.length).to.equal(4);
expect(result[0]).to.equal(0);
// Mip generation can round a solid 255 channel down by one.
expect(result[1]).to.be.closeTo(green, 1);
expect(result[2]).to.equal(0);
expect(result[3]).to.equal(255);
}
const internalTexture = texture.getInternalTexture();
if (!internalTexture) {
throw new Error("Expected an initialized raw texture");
}
for (const [x, y, width, height] of [
[2, 0, 1, 1], [0, 4, 1, 1], [0, 3, 1, 2], [0, 0, 0, 1],
[0, 0, 65535, 65535]
]) {
let error: unknown;
try {
await engine._readTexturePixels(internalTexture, width, height, -1, 1, null, true, false, x, y);
} catch (caught) {
error = caught;
}
if (!(error instanceof Error)) {
throw new Error("Expected out-of-range mip readback to reject");
}
expect(error.message).to.contain("rectangle is out of range");
}
for (const invalid of [65536, 65537, 256, 2 ** 32, 2 ** 32 + 1, -1, 0.5, NaN, Infinity]) {
for (const component of [1, 2, 3, 4, 0]) {
const request = [0, 0, 0, 1, 1];
request[component] = invalid;
const [mip, x, y, width, height] = request;
const destination = new Uint8Array(4).fill(91);
let error: unknown;
try {
await engine._readTexturePixels(internalTexture, width, height, -1, mip, destination, true, false, x, y);
} catch (caught) {
error = caught;
}
if (!(error instanceof Error)) {
throw new Error(`Expected invalid readback component ${component}=${invalid} to reject`);
}
const maximum = component === 0 ? 255 : 65535;
if (!Number.isInteger(invalid) || invalid < 0 || invalid > maximum) {
const parameter = ["mip level", "x", "y", "width", "height"][component];
expect(error.message).to.equal(`readTexture ${parameter} must be a finite integer between 0 and ${maximum}.`);
} else {
expect(error.message).to.contain("rectangle is out of range");
}
expect(Array.from(destination)).to.deep.equal([91, 91, 91, 91]);
}
}
} finally {
scene.dispose();
engine.dispose();
}
});
});
describe("RequestFile", function () {
this.timeout(0);
it("should throw when requesting a URL with no protocol", function () {
function requestFile() {
RequestFile("noprotocol.gltf", () => {});
}
expect(requestFile).to.throw();
});
});
describe("ColorParsing", function () {
expect(_native.Canvas.parseColor("")).to.equal(0);
expect(_native.Canvas.parseColor("transparent")).to.equal(0);
expect(_native.Canvas.parseColor("#123")).to.equal(0xff332211);
expect(_native.Canvas.parseColor("#1234")).to.equal(0x44332211);
expect(_native.Canvas.parseColor("#123456")).to.equal(0xff563412);
expect(_native.Canvas.parseColor("#12345678")).to.equal(0x78563412);
expect(_native.Canvas.parseColor("snow")).to.equal(0xfffafaff);
expect(_native.Canvas.parseColor("rgb(16,32,48)")).to.equal(0xff302010);
// Alpha is a 0-1 number (or a percentage) per CSS Color, so any value above
// 1 clamps to fully opaque. It is not a 0-255 channel like r/g/b.
expect(_native.Canvas.parseColor("rgba(16,32,48,64)")).to.equal(0xff302010);
expect(_native.Canvas.parseColor("rgb(16, 32 , 48 )")).to.equal(
0xff302010
);
expect(
_native.Canvas.parseColor("rgba( 16, 32 , 48 , 64 )")
).to.equal(0xff302010);
expect(_native.Canvas.parseColor("rgba(16,32,48,1)")).to.equal(0xff302010);
expect(_native.Canvas.parseColor("rgba(16,32,48,0)")).to.equal(0x00302010);
// Fractional and percentage alpha, whitespace-separated components and the
// "/ alpha" form all used to fall through to the "unable to parse" throw.
expect(_native.Canvas.parseColor("rgba(16,32,48,0.5)")).to.equal(0x80302010);
expect(_native.Canvas.parseColor("rgba(16 32 48 / 50%)")).to.equal(
0x80302010
);
expect(_native.Canvas.parseColor("rgb(16 32 48)")).to.equal(0xff302010);
expect(_native.Canvas.parseColor("rgb(100%,0%,0%)")).to.equal(0xff0000ff);
expect(_native.Canvas.parseColor("hsl(0,100%,50%)")).to.equal(0xff0000ff);
expect(_native.Canvas.parseColor("hsla(0,100%,50%,0.5)")).to.equal(
0x800000ff
);
it("should throw", function () {
function incorrectColor() {
_native.Canvas.parseColor("unknownColor");
}
expect(incorrectColor).to.throw();
});
it("should throw", function () {
function incorrectColor() {
_native.Canvas.parseColor("#");
}
expect(incorrectColor).to.throw();
});
it("should throw", function () {
function incorrectColor() {
_native.Canvas.parseColor("#12345");
}
expect(incorrectColor).to.throw();
});
it("should throw", function () {
function incorrectColor() {
_native.Canvas.parseColor("rgb(11)");
}
expect(incorrectColor).to.throw();
});
it("should throw", function () {
function incorrectColor() {
_native.Canvas.parseColor("rgb(11,22,33");
}
expect(incorrectColor).to.throw();
});
it("should throw", function () {
function incorrectColor() {
_native.Canvas.parseColor("rgb(11,22,33,");
}
expect(incorrectColor).to.throw();
});
it("should throw", function () {
function incorrectColor() {
_native.Canvas.parseColor("rgba(11, 22, 33, )");
}
expect(incorrectColor).to.throw();
});
it("should throw", function () {
function incorrectColor() {
_native.Canvas.parseColor("rgba(11, 22, 33, 44, 55, 66 )");
}
expect(incorrectColor).to.throw();
});
it("should throw", function () {
function incorrectColor() {
_native.Canvas.parseColor("rgb");
}
expect(incorrectColor).to.throw();
});
it("should throw", function () {
function incorrectColor() {
_native.Canvas.parseColor("rgba");
}
expect(incorrectColor).to.throw();
});
});
describe("Canvas2D", function () {
// No-op renderers accept GPU commands but cannot produce pixels for readback.
const itWithGpu = hasGpuRendering ? it : it.skip;
function createContext(): any {
const canvas = new _native.Canvas();
canvas.width = 64;
canvas.height = 64;
return canvas.getContext("2d");
}
function createCanvas(width: number, height: number): any {
const canvas = new _native.Canvas();
canvas.width = width;
canvas.height = height;
return { canvas, context: canvas.getContext("2d") };
}
function disposeCanvas(resource: any): void {
resource.context.dispose();
resource.canvas.dispose();
}
function captureGpuPixels(canvas: any): any {
return canvas.getContext("2d").getImageData(
0,
0,
canvas.width,
canvas.height
).data;
}
function pixelAt(
pixels: any,
width: number,
x: number,
y: number
): number[] {
const offset = (y * width + x) * 4;
return [
pixels[offset],
pixels[offset + 1],
pixels[offset + 2],
pixels[offset + 3],
];
}
(skipCanvasGpuTests ? it.skip : it)(
"intersects nested clips and restores parent clips on the GPU",
async function () {
this.timeout(10000);
for (const translated of [false, true]) {
const engine = new NativeEngine();
const scene = new Scene(engine);
try {
const texture = new DynamicTexture("nested clips", 64, scene, false);
const ctx = texture.getContext();
ctx.fillStyle = "white";
ctx.fillRect(0, 0, 64, 64);
ctx.save();
ctx.beginPath();
ctx.rect(8, 0, 24, 64);
ctx.clip();
ctx.save();
if (translated) {
ctx.translate(16, 0);
}
ctx.beginPath();
ctx.rect(0, 0, 64, 64);
ctx.clip();
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 64, 64);
ctx.restore();
ctx.fillStyle = "#00ff00";
ctx.fillRect(24, 0, 16, 64);
ctx.save();
ctx.beginPath();
ctx.rect(40, 0, 16, 64);
ctx.clip();
ctx.fillStyle = "magenta";
ctx.fillRect(0, 0, 64, 64);
ctx.restore();
ctx.restore();
ctx.fillStyle = "blue";
ctx.fillRect(40, 0, 8, 64);
texture.update(false);
const pixels = await texture.readPixels();
if (!(pixels instanceof Uint8Array)) {
throw new Error("Expected RGBA8 GPU readback for the canvas texture");
}
const pixel = (x: number) =>
Array.from(
pixels.subarray(
(32 * 64 + x) * 4,
(32 * 64 + x + 1) * 4
)
);
expect(pixel(4), "outside parent").to.deep.equal([
255, 255, 255, 255
]);
expect(pixel(12), "translated child boundary").to.deep.equal(
translated ? [255, 255, 255, 255] : [255, 0, 0, 255]
);
expect(pixel(20), "inside intersection").to.deep.equal([
255, 0, 0, 255
]);
expect(pixel(28), "restored parent").to.deep.equal([
0, 255, 0, 255
]);
expect(pixel(36), "outside restored parent").to.deep.equal([
255, 255, 255, 255
]);
expect(pixel(44), "restored unclipped state").to.deep.equal([
0, 0, 255, 255
]);
expect(pixel(52), "disjoint clip").to.deep.equal([
255, 255, 255, 255
]);
expect(pixel(60), "outside every fill").to.deep.equal([
255, 255, 255, 255
]);
} finally {
scene.dispose();
engine.dispose();
}
}
}
);
(skipCanvasGpuTests ? it.skip : it)(
"normalizes negative rectangle dimensions before intersecting GPU clips",
async function () {
this.timeout(10000);
const engine = new NativeEngine();
const scene = new Scene(engine);
try {
const texture = new DynamicTexture("signed clips", 64, scene, false);
const ctx = texture.getContext();
for (const rotated of [false, true]) {
let expected: Uint8Array | undefined;
for (const flips of [
[false, false], [true, false], [false, true], [true, true]
]) {
const flipX = flips[0];
const flipY = flips[1];
ctx.fillStyle = "white";
ctx.fillRect(0, 0, 64, 64);
ctx.save();
ctx.beginPath();
ctx.rect(18, 12, 36, 44);
ctx.clip();
ctx.save();
if (rotated) {
ctx.translate(32, 32);
ctx.rotate(0.3);
ctx.translate(-32, -32);
}
ctx.beginPath();
ctx.rect(
flipX ? 40 : 16, flipY ? 40 : 20,
flipX ? -24 : 24, flipY ? -20 : 20
);
ctx.clip();
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, 64, 64);
ctx.restore();
ctx.restore();
texture.update(false);
const pixels = await texture.readPixels();
if (!(pixels instanceof Uint8Array)) {
throw new Error("Expected RGBA8 GPU readback for signed clips");
}
const description =
`rotated=${rotated}, flipX=${flipX}, flipY=${flipY}`;
expect(pixelAt(pixels, 64, 28, 30), `inside clip, ${description}`)
.to.deep.equal([0, 0, 255, 255]);
expect(pixelAt(pixels, 64, 0, 0), "outside parent clip")
.to.deep.equal([255, 255, 255, 255]);
if (expected) {
let changed = 0;
for (let index = 0; index < pixels.length; ++index) {
if (pixels[index] !== expected[index]) {
++changed;
}
}
expect(changed, `signed clip equivalence, ${description}`)
.to.equal(0);
} else {
expected = pixels.slice();
}
}
}
} finally {
scene.dispose();
engine.dispose();
}
}
);
(skipCanvasGpuTests ? it.skip : it)(
"clears only the clipped GPU region and ignores globalAlpha and filters",
async function () {
this.timeout(10000);
const engine = new NativeEngine();
const scene = new Scene(engine);
try {
const texture = new DynamicTexture("clipped clear", 64, scene, false);
const ctx = texture.getContext();
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 64, 64);
texture.update(false);
ctx.filter = "blur(2px)";
ctx.fillRect(0, 0, 64, 64);
ctx.save();
ctx.beginPath();
ctx.rect(8, 0, 24, 64);
ctx.clip();
ctx.globalAlpha = 0.25;
ctx.clearRect(0, 0, 64, 64);
ctx.restore();
texture.update(false);
const pixels = await texture.readPixels();
if (!(pixels instanceof Uint8Array)) {
throw new Error("Expected RGBA8 GPU readback for the canvas texture");
}
const pixel = (x: number) =>
Array.from(
pixels.subarray((32 * 64 + x) * 4, (32 * 64 + x + 1) * 4)
);
expect(pixel(36), "preserved near clip").to.deep.equal([
255, 0, 0, 255
]);
expect(pixel(16), "fully cleared inside clip").to.deep.equal([
0, 0, 0, 0
]);
expect(pixel(44), "preserved after clip").to.deep.equal([
255, 0, 0, 255
]);
} finally {
scene.dispose();
engine.dispose();
}
}
);
it("round-trips a string fillStyle and strokeStyle", function () {
const ctx = createContext();
ctx.fillStyle = "#ff0000";
ctx.strokeStyle = "#00ff00";
expect(ctx.fillStyle).to.equal("#ff0000");
expect(ctx.strokeStyle).to.equal("#00ff00");
});
it("rejects a prototype-spoofed object in place of a Path2D", function () {
// instanceof only walks the prototype chain, and a prototype is assignable, so an
// InstanceOf gate accepted any object wearing Path2D.prototype and then unwrapped it.
// Handing fill() a CanvasGradient this way was an access violation, not a wrong answer.
// Object.create(Path2D.prototype) is the same hole with no native wrap behind it at all.
const ctx = createContext();
const spoofedGradient: any = ctx.createLinearGradient(0, 0, 10, 10);
Object.setPrototypeOf(spoofedGradient, Path2D.prototype);
expect(spoofedGradient instanceof Path2D).to.equal(true);
const bare: any = Object.create(Path2D.prototype);
expect(bare instanceof Path2D).to.equal(true);
const realPath = new Path2D();
for (const impostor of [spoofedGradient, bare]) {
expect(function () { ctx.fill(impostor); }).to.throw();
expect(function () { ctx.stroke(impostor); }).to.throw();
expect(function () { realPath.addPath(impostor); }).to.throw();
// The Path2D() argument is a (Path2D or DOMString) union, so a non-Path2D is string
// data rather than an error. It must not be unwrapped on the way there.
expect(function () { new Path2D(impostor); }).to.not.throw();
}
});
it("ignores a prototype-spoofed object assigned to fillStyle or strokeStyle", function () {
// Same defect on the gradient side: the assignment gate accepted anything wearing the
// gradient prototype and stored it, and the next fill unwrapped it as a CanvasGradient.
const ctx = createContext();
const gradient = ctx.createLinearGradient(0, 0, 10, 10);
const spoofedPath: any = new Path2D();
Object.setPrototypeOf(spoofedPath, Object.getPrototypeOf(gradient));
ctx.fillStyle = "#ff0000";
ctx.strokeStyle = "#00ff00";
ctx.fillStyle = spoofedPath;
ctx.strokeStyle = spoofedPath;
// Per spec an unusable assignment leaves the previous value in place.
expect(ctx.fillStyle).to.equal("#ff0000");
expect(ctx.strokeStyle).to.equal("#00ff00");
// The drawing path must stay usable rather than unwrapping the impostor.
expect(function () { ctx.fillRect(0, 0, 10, 10); }).to.not.throw();
expect(function () { ctx.strokeRect(0, 0, 10, 10); }).to.not.throw();
});
it("rejects a non-Path2D argument to fill and stroke", function () {
// Neither call type-checked the argument before handing it to ObjectWrap::Unwrap,
// which does no checking of its own, so an unrelated object was reinterpreted as a
// NativeCanvasPath2D. stroke() was the worse of the two: it had no gate at all, so
// even a string got there.
// The thrown type is deliberately not asserted: a C++ Napi::TypeError surfaces as a
// JS TypeError on some engines and as an InternalError on the QuickJS Node-API port,
// so only the fact that it throws is portable. Every other throw test here does the same.
const ctx = createContext();
expect(function () { ctx.stroke("x"); }).to.throw();
expect(function () { ctx.stroke({}); }).to.throw();
expect(function () { ctx.stroke(5); }).to.throw();
expect(function () { ctx.fill({}); }).to.throw();
expect(function () { ctx.fill(5); }).to.throw();
});
it("still accepts the valid fill and stroke argument forms", function () {
const ctx = createContext();
const path = new Path2D("M0 0 L10 10");
expect(function () { ctx.fill(); }).to.not.throw();
expect(function () { ctx.stroke(); }).to.not.throw();
// undefined selects the no-argument overload rather than being a bad Path2D.
expect(function () { ctx.fill(undefined); }).to.not.throw();
expect(function () { ctx.stroke(undefined); }).to.not.throw();
// fill() also takes a fill rule string.
expect(function () { ctx.fill("evenodd"); }).to.not.throw();
expect(function () { ctx.fill(new String("evenodd") as any); }).to.not.throw();
expect(function () {
ctx.fill({ toString: function () { return "nonzero"; } } as any);
}).to.not.throw();
expect(function () { ctx.fill(path); }).to.not.throw();
expect(function () { ctx.fill(path, "nonzero"); }).to.not.throw();
expect(function () { ctx.fill(path, new String("evenodd") as any); }).to.not.throw();
expect(function () { ctx.stroke(path); }).to.not.throw();
expect(function () { ctx.fill("invalid"); }).to.throw();
expect(function () { ctx.fill(path, "invalid"); }).to.throw();
});
it("rejects a non-Path2D argument to Path2D.addPath", function () {
// addPath had neither a type check nor an arity check, so addPath() unwrapped a
// missing argument and addPath("x") unwrapped a string. See above for why the
// thrown type is not asserted.
const path = new Path2D();
expect(function () { path.addPath(); }).to.throw();
expect(function () { path.addPath("x"); }).to.throw();
expect(function () { path.addPath({}); }).to.throw();
expect(function () { path.addPath(new Path2D("M0 0 L5 5")); }).to.not.throw();
});
it("rejects an invalid native source argument to drawImage", function () {
// Native-looking impostors must throw, not AV via an unchecked Unwrap.
const ctx = createContext();
const realCanvas = new _native.Canvas();
const spoofedCanvas = Object.create(Object.getPrototypeOf(realCanvas));
expect(spoofedCanvas instanceof _native.Canvas).to.equal(true);
expect(function () { ctx.drawImage({}, 0, 0); }).to.throw();
expect(function () { ctx.drawImage(new Path2D(), 0, 0); }).to.throw();
expect(function () { ctx.drawImage(spoofedCanvas, 0, 0); }).to.throw();
realCanvas.dispose();
});
it("treats a non-Path2D Path2D() argument as path data", function () {
// The constructor routed on IsObject(), so any object was unwrapped as a Path2D.
// Per the (Path2D or DOMString) union a non-Path2D is stringified instead.
expect(function () { new Path2D({}); }).to.not.throw();
expect(function () { new Path2D(5); }).to.not.throw();
expect(function () { new Path2D(); }).to.not.throw();
// A copy of a real Path2D still copies, and an object that stringifies to path
// data is still parsed as such.
const source = new Path2D("M0 0 L10 10");
const ctx = createContext();
expect(function () { ctx.fill(new Path2D(source)); }).to.not.throw();
expect(function () {
ctx.fill(new Path2D({ toString: function () { return "M0 0 L10 10"; } }));
}).to.not.throw();
});
it("accepts a CanvasGradient as fillStyle", function () {
const ctx = createContext();
const gradient = ctx.createLinearGradient(0, 0, 64, 64);
gradient.addColorStop(0, "red");
gradient.addColorStop(1, "blue");
expect(function () {
ctx.fillStyle = gradient;
}).to.not.throw();
expect(ctx.fillStyle).to.not.equal("#ff0000");
});
it("accepts a CanvasGradient as strokeStyle", function () {
// strokeStyle used to be string-only and threw "A string was expected",
// which broke every GUI control that strokes with a gradient (Line, Button border).
const ctx = createContext();
const gradient = ctx.createLinearGradient(0, 0, 64, 64);
gradient.addColorStop(0, "red");
gradient.addColorStop(1, "blue");
expect(function () {
ctx.strokeStyle = gradient;
}).to.not.throw();
});
it("accepts a radial CanvasGradient defined by two independent circles", function () {
const ctx = createContext();
// Neither concentric nor r0 == 0: both circles have to be honored.
const gradient = ctx.createRadialGradient(10, 10, 5, 40, 32, 30);
gradient.addColorStop(0, "yellow");
gradient.addColorStop(0.5, "pink");
gradient.addColorStop(1, "green");
expect(function () {
ctx.fillStyle = gradient;
ctx.strokeStyle = gradient;
}).to.not.throw();
});
it("restores a gradient strokeStyle across save/restore", function () {
const ctx = createContext();
const gradient = ctx.createLinearGradient(0, 0, 64, 64);
gradient.addColorStop(0, "red");
ctx.strokeStyle = "#0000ff";
ctx.save();
ctx.strokeStyle = gradient;
ctx.restore();
expect(ctx.strokeStyle).to.equal("#0000ff");
});
it("restores the shadow attributes across save/restore", function () {
// These have no nanovg counterpart, so nvgRestore() never rewound them and a
// value assigned after save() survived restore().
const ctx = createContext();
ctx.shadowColor = "#00ff00";
ctx.shadowBlur = 1;
ctx.shadowOffsetX = 2;
ctx.shadowOffsetY = 3;
ctx.save();
ctx.shadowColor = "#ff0000";
ctx.shadowBlur = 40;
ctx.shadowOffsetX = 50;
ctx.shadowOffsetY = 60;
ctx.restore();
expect(ctx.shadowColor).to.equal("#00ff00");
expect(ctx.shadowBlur).to.equal(1);
expect(ctx.shadowOffsetX).to.equal(2);
expect(ctx.shadowOffsetY).to.equal(3);
});
it("restores the remaining drawing state across save/restore", function () {
// nvgRestore() rewinds nanovg's copy of these, but the wrapper kept its own
// mirror, so the getters reported the post-save() value forever after.
const ctx = createContext();
ctx.lineWidth = 1;
ctx.globalAlpha = 1;
ctx.lineCap = "butt";
ctx.lineJoin = "miter";
ctx.miterLimit = 10;
ctx.setLineDash([1, 2]);
ctx.save();
ctx.lineWidth = 9;
ctx.globalAlpha = 0.25;
ctx.lineCap = "round";
ctx.lineJoin = "bevel";
ctx.miterLimit = 3;
ctx.setLineDash([7, 8, 9]);
ctx.restore();
expect(ctx.lineWidth).to.equal(1);
expect(ctx.globalAlpha).to.equal(1);
expect(ctx.lineCap).to.equal("butt");
expect(ctx.lineJoin).to.equal("miter");
expect(ctx.miterLimit).to.equal(10);
expect(ctx.getLineDash()).to.deep.equal([1, 2]);
});
it("reads back globalAlpha", function () {
// globalAlpha was registered with a nullptr getter, so it was write-only and
// reading it gave undefined. The value was never mirrored either, so the
// save/restore stack carried a field nothing could observe.
const ctx = createContext();
expect(ctx.globalAlpha).to.equal(1);
ctx.globalAlpha = 0.5;
expect(ctx.globalAlpha).to.equal(0.5);
});
it("ignores an out-of-range or non-finite globalAlpha", function () {
// The spec says values outside [0, 1] and non-finite values are ignored,
// leaving the previous value in place, rather than clamped or thrown.
const ctx = createContext();
ctx.globalAlpha = 0.5;
ctx.globalAlpha = -1;
expect(ctx.globalAlpha).to.equal(0.5);
ctx.globalAlpha = 2;
expect(ctx.globalAlpha).to.equal(0.5);
ctx.globalAlpha = Infinity;
expect(ctx.globalAlpha).to.equal(0.5);
ctx.globalAlpha = NaN;
expect(ctx.globalAlpha).to.equal(0.5);
ctx.globalAlpha = 0;
expect(ctx.globalAlpha).to.equal(0);
});
it("reports the spec defaults on a fresh context", function () {
// These four mirror state nanovg also keeps, and nvgReset installs butt/miter/1/10.
// The C++ mirrors were value-initialized to ""/""/0/0 instead, so a fresh context
// reported a default it was not actually drawing with.
const ctx = createContext();
expect(ctx.lineCap).to.equal("butt");
expect(ctx.lineJoin).to.equal("miter");
expect(ctx.lineWidth).to.equal(1);
expect(ctx.miterLimit).to.equal(10);
});
it("keeps the previous dash list when a new one is rejected", function () {
// The list was cleared before validation, so a rejected argument -- which the
// spec says must leave the previous list untouched -- wiped it instead.
const ctx = createContext();
ctx.setLineDash([5, 10]);
ctx.setLineDash([-1]);
expect(ctx.getLineDash()).to.deep.equal([5, 10]);
ctx.setLineDash([2, "x"]);
expect(ctx.getLineDash()).to.deep.equal([5, 10]);
ctx.setLineDash([Number.NaN]);
expect(ctx.getLineDash()).to.deep.equal([5, 10]);
// A valid list still replaces it, and an empty list still means "solid".
ctx.setLineDash([3, 4]);
expect(ctx.getLineDash()).to.deep.equal([3, 4]);
ctx.setLineDash([]);
expect(ctx.getLineDash()).to.deep.equal([]);
});
it("keeps a gradient assigned to fillStyle alive across a collection", function () {
const ctx = createContext();
const global: any = Function("return this")();
// Create and assign the gradient inside a scope that keeps no reference to it, so
// the only thing left pointing at it is whatever fillStyle stored. CanvasGradient is
// an ObjectWrap, so if the style does not root the JavaScript wrapper the finalizer
// deletes the native gradient and the next fill dereferences freed memory.
(function () {
const gradient: any = ctx.createLinearGradient(0, 0, 64, 0);
gradient.addColorStop(0, "red");
gradient.addColorStop(1, "blue");
gradient.tag = "kept";
ctx.fillStyle = gradient;
})();
// Not every engine the polyfill runs on exposes a collection hook; the assertions
// below are worth making either way.
if (typeof global.CollectGarbage === "function") {
global.CollectGarbage();
}
// The getter has to hand back the object that was assigned. The expando proves it is
// that same JavaScript object rather than a fresh wrapper.
expect(ctx.fillStyle.tag).to.equal("kept");
// ...and the native gradient behind it has to still be there.
ctx.fillStyle.addColorStop(0.5, "green");
ctx.fillRect(0, 0, 64, 64);
});
it("keeps a gradient assigned to strokeStyle alive across a collection", function () {
const ctx = createContext();
const global: any = Function("return this")();
(function () {
const gradient: any = ctx.createRadialGradient(32, 32, 0, 32, 32, 32);
gradient.addColorStop(0, "red");
gradient.addColorStop(1, "blue");
gradient.tag = "kept";
ctx.strokeStyle = gradient;
})();
if (typeof global.CollectGarbage === "function") {
global.CollectGarbage();
}
expect(ctx.strokeStyle.tag).to.equal("kept");
ctx.strokeStyle.addColorStop(0.5, "green");
ctx.strokeRect(0, 0, 64, 64);
});
it("keeps the previous dash list when the argument is not a list", function () {
// A present-but-rejected argument skipped the parse loop and then committed the
// empty temporary, so setLineDash("x") cleared the list where setLineDash([-1])
// correctly kept it. An absent argument still means "solid".
const ctx = createContext();
ctx.setLineDash([5, 10]);
ctx.setLineDash("x" as any);
expect(ctx.getLineDash()).to.deep.equal([5, 10]);
ctx.setLineDash(null as any);
expect(ctx.getLineDash()).to.deep.equal([5, 10]);
ctx.setLineDash(7 as any);
expect(ctx.getLineDash()).to.deep.equal([5, 10]);
(ctx.setLineDash as any)();
expect(ctx.getLineDash()).to.deep.equal([]);
});
it("restores font", function () {
// font was the one exposed attribute left out of the saved state. It is worse than
// the getter-only cases: the font id resolved here is what the text draw path binds,
// so the wrong face actually rendered after a restore().
const ctx = createContext();
ctx.font = "18px Arial";
// The getter reports a normalized serialization, so compare against the round-tripped
// value rather than the literal that was assigned.
const saved = ctx.font;
ctx.save();
ctx.font = "40px Times";
expect(ctx.font).to.not.equal(saved);
ctx.restore();
expect(ctx.font).to.equal(saved);
expect(function () {
ctx.fillText("after restore", 0, 20);
}).to.not.throw();
});
it("ignores a fillStyle or strokeStyle that is neither a color string nor a gradient", function () {
// Both setters reached napi_unwrap for any object, so `ctx.strokeStyle = {}` unwrapped
// an object that was never wrapped and dereferenced whatever the slot held. Per spec
// an unusable value leaves the attribute unchanged.
const ctx = createContext();
ctx.fillStyle = "#ff0000";
ctx.strokeStyle = "#00ff00";
expect(function () {
ctx.fillStyle = {} as any;
ctx.strokeStyle = {} as any;
ctx.fillStyle = [] as any;
ctx.strokeStyle = (function () {}) as any;
}).to.not.throw();
expect(ctx.fillStyle).to.equal("#ff0000");
expect(ctx.strokeStyle).to.equal("#00ff00");
// A real gradient is still accepted.
const gradient = ctx.createLinearGradient(0, 0, 64, 0);
gradient.addColorStop(0, "red");
gradient.addColorStop(1, "blue");
ctx.fillStyle = gradient;
expect(ctx.fillStyle).to.not.equal("#ff0000");
});
it("accepts two color stops at the same offset", function () {
// Only checks that the insertion path accepts the duplicate offset the spec allows;
// std::map::insert() dropped it by returning {it, false} rather than throwing, so this
// does not by itself prove the stop survives. That needs a separate rendered-ramp assertion.
const ctx = createContext();
const gradient = ctx.createLinearGradient(0, 0, 64, 0);
gradient.addColorStop(0, "red");
gradient.addColorStop(0.5, "red");
gradient.addColorStop(0.5, "blue");
gradient.addColorStop(1, "blue");
expect(function () {
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 64, 64);
}).to.not.throw();
});
// The three parsers below all used to reach std::stof/std::stoi with a value the regex
// admits but the target type cannot hold. The resulting std::out_of_range is not a
// Napi::Error, so it escaped the N-API callback and terminated the host process outright
// rather than surfacing as a JS exception. Reaching the assertion at all is the test.
it("survives an out-of-range rgb() component", function () {
const ctx = createContext();
const huge = "9".repeat(400);
expect(function () {
ctx.fillStyle = `rgb(${huge}, 0, 0)`;
}).to.not.throw();
expect(function () {
ctx.fillStyle = `rgba(0, 0, 0, ${huge})`;
}).to.not.throw();
});
it("survives an out-of-range font size and weight", function () {
const ctx = createContext();
ctx.font = "18px Arial";
// The size regex accepts an exponent, so this parses but does not fit a float.
expect(function () {
ctx.font = "18e999px Arial";
}).to.not.throw();
expect(function () {
ctx.font = `${"9".repeat(400)} 18px Arial`;
}).to.not.throw();
// An unparseable font is ignored, so the previous one stays in effect.
expect(ctx.font).to.contain("18px");
});
it("survives an out-of-range letterSpacing", function () {