@xterm/addon-webgl 0.20.0-beta.2 → 0.20.0-beta.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,712 @@
1
+ /**
2
+ * Copyright (c) 2021 The xterm.js authors. All rights reserved.
3
+ * @license MIT
4
+ */
5
+
6
+ import { throwIfFalsy } from 'browser/renderer/shared/RendererUtils';
7
+ import { customGlyphDefinitions } from './CustomGlyphDefinitions';
8
+ import { CustomGlyphDefinitionType, CustomGlyphScaleType, CustomGlyphVectorType, type CustomGlyphDefinitionPart, type CustomGlyphPathDrawFunctionDefinition, type CustomGlyphPatternDefinition, type ICustomGlyphSolidOctantBlockVector, type ICustomGlyphVectorShape } from './Types';
9
+
10
+ /**
11
+ * Try drawing a custom block element or box drawing character, returning whether it was
12
+ * successfully drawn.
13
+ */
14
+ export function tryDrawCustomGlyph(
15
+ ctx: CanvasRenderingContext2D,
16
+ c: string,
17
+ xOffset: number,
18
+ yOffset: number,
19
+ deviceCellWidth: number,
20
+ deviceCellHeight: number,
21
+ deviceCharWidth: number,
22
+ deviceCharHeight: number,
23
+ fontSize: number,
24
+ devicePixelRatio: number,
25
+ backgroundColor?: string
26
+ ): boolean {
27
+ const unifiedCharDefinition = customGlyphDefinitions[c];
28
+ if (unifiedCharDefinition) {
29
+ // Normalize to array for uniform handling
30
+ const parts = Array.isArray(unifiedCharDefinition) ? unifiedCharDefinition : [unifiedCharDefinition];
31
+ for (const part of parts) {
32
+ drawDefinitionPart(ctx, part, xOffset, yOffset, deviceCellWidth, deviceCellHeight, deviceCharWidth, deviceCharHeight, fontSize, devicePixelRatio, backgroundColor);
33
+ }
34
+ return true;
35
+ }
36
+
37
+ return false;
38
+ }
39
+
40
+ function drawDefinitionPart(
41
+ ctx: CanvasRenderingContext2D,
42
+ part: CustomGlyphDefinitionPart,
43
+ xOffset: number,
44
+ yOffset: number,
45
+ deviceCellWidth: number,
46
+ deviceCellHeight: number,
47
+ deviceCharWidth: number,
48
+ deviceCharHeight: number,
49
+ fontSize: number,
50
+ devicePixelRatio: number,
51
+ backgroundColor?: string
52
+ ): void {
53
+ // Handle scaleType - adjust dimensions and offset when scaling to character area
54
+ let drawWidth = deviceCellWidth;
55
+ let drawHeight = deviceCellHeight;
56
+ let drawXOffset = xOffset;
57
+ let drawYOffset = yOffset;
58
+ if (part.scaleType === CustomGlyphScaleType.CHAR) {
59
+ drawWidth = deviceCharWidth;
60
+ drawHeight = deviceCharHeight;
61
+ // Center the character within the cell
62
+ drawXOffset = xOffset + (deviceCellWidth - deviceCharWidth) / 2;
63
+ drawYOffset = yOffset + (deviceCellHeight - deviceCharHeight) / 2;
64
+ }
65
+
66
+ // Handle clipPath generically for any definition type
67
+ if (part.clipPath) {
68
+ ctx.save();
69
+ applyClipPath(ctx, part.clipPath, drawXOffset, drawYOffset, drawWidth, drawHeight);
70
+ }
71
+
72
+ switch (part.type) {
73
+ case CustomGlyphDefinitionType.SOLID_OCTANT_BLOCK_VECTOR:
74
+ drawBlockVectorChar(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight);
75
+ break;
76
+ case CustomGlyphDefinitionType.BLOCK_PATTERN:
77
+ drawPatternChar(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight);
78
+ break;
79
+ case CustomGlyphDefinitionType.PATH_FUNCTION:
80
+ drawPathFunctionCharacter(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight, devicePixelRatio, part.strokeWidth);
81
+ break;
82
+ case CustomGlyphDefinitionType.PATH:
83
+ drawPathDefinitionCharacter(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight);
84
+ break;
85
+ case CustomGlyphDefinitionType.PATH_NEGATIVE:
86
+ drawPathNegativeDefinitionCharacter(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight, devicePixelRatio, backgroundColor);
87
+ break;
88
+ case CustomGlyphDefinitionType.VECTOR_SHAPE:
89
+ drawVectorShape(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight, fontSize, devicePixelRatio);
90
+ break;
91
+ case CustomGlyphDefinitionType.BRAILLE:
92
+ drawBrailleCharacter(ctx, part.data, drawXOffset, drawYOffset, drawWidth, drawHeight);
93
+ break;
94
+ }
95
+
96
+ if (part.clipPath) {
97
+ ctx.restore();
98
+ }
99
+ }
100
+
101
+ function drawBlockVectorChar(
102
+ ctx: CanvasRenderingContext2D,
103
+ charDefinition: ICustomGlyphSolidOctantBlockVector[],
104
+ xOffset: number,
105
+ yOffset: number,
106
+ deviceCellWidth: number,
107
+ deviceCellHeight: number
108
+ ): void {
109
+ for (let i = 0; i < charDefinition.length; i++) {
110
+ const box = charDefinition[i];
111
+ const xEighth = deviceCellWidth / 8;
112
+ const yEighth = deviceCellHeight / 8;
113
+ ctx.fillRect(
114
+ xOffset + box.x * xEighth,
115
+ yOffset + box.y * yEighth,
116
+ box.w * xEighth,
117
+ box.h * yEighth
118
+ );
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Braille dot positions in octant coordinates (x, y for center of each dot area)
124
+ * Columns: left=1-2, right=5-6 (leaving 0 and 7 as margins, 3-4 as gap)
125
+ * Rows: 0-1, 2-3, 4-5, 6-7 for the 4 rows
126
+ */
127
+ const brailleDotPositions = new Uint8Array([
128
+ 1, 0, // dot 1 - bit 0
129
+ 1, 2, // dot 2 - bit 1
130
+ 1, 4, // dot 3 - bit 2
131
+ 5, 0, // dot 4 - bit 3
132
+ 5, 2, // dot 5 - bit 4
133
+ 5, 4, // dot 6 - bit 5
134
+ 1, 6, // dot 7 - bit 6
135
+ 5, 6, // dot 8 - bit 7
136
+ ]);
137
+
138
+ /**
139
+ * Draws a braille pattern
140
+ */
141
+ function drawBrailleCharacter(
142
+ ctx: CanvasRenderingContext2D,
143
+ pattern: number,
144
+ xOffset: number,
145
+ yOffset: number,
146
+ deviceCellWidth: number,
147
+ deviceCellHeight: number
148
+ ): void {
149
+ const xEighth = deviceCellWidth / 8;
150
+ const paddingY = deviceCellHeight * 0.1;
151
+ const usableHeight = deviceCellHeight * 0.8;
152
+ const yEighth = usableHeight / 8;
153
+ const radius = Math.min(xEighth, yEighth);
154
+
155
+ for (let bit = 0; bit < 8; bit++) {
156
+ if (pattern & (1 << bit)) {
157
+ const x = brailleDotPositions[bit * 2];
158
+ const y = brailleDotPositions[bit * 2 + 1];
159
+ const cx = xOffset + (x + 1) * xEighth;
160
+ const cy = yOffset + paddingY + (y + 1) * yEighth;
161
+ ctx.beginPath();
162
+ ctx.arc(cx, cy, radius, 0, Math.PI * 2);
163
+ ctx.fill();
164
+ }
165
+ }
166
+ }
167
+
168
+ function drawPathDefinitionCharacter(
169
+ ctx: CanvasRenderingContext2D,
170
+ charDefinition: CustomGlyphPathDrawFunctionDefinition | string,
171
+ xOffset: number,
172
+ yOffset: number,
173
+ deviceCellWidth: number,
174
+ deviceCellHeight: number
175
+ ): void {
176
+ const instructions = typeof charDefinition === 'string' ? charDefinition : charDefinition(0, 0);
177
+ ctx.beginPath();
178
+ let currentX = 0;
179
+ let currentY = 0;
180
+ let lastControlX = 0;
181
+ let lastControlY = 0;
182
+ let lastCommand = '';
183
+ for (const instruction of instructions.split(' ')) {
184
+ const type = instruction[0];
185
+ const args: string[] = instruction.substring(1).split(',');
186
+ if (type === 'Z') {
187
+ ctx.closePath();
188
+ lastCommand = type;
189
+ continue;
190
+ }
191
+ if (type === 'V') {
192
+ const y = yOffset + parseFloat(args[0]) * deviceCellHeight;
193
+ ctx.lineTo(currentX, y);
194
+ currentY = y;
195
+ lastControlX = currentX;
196
+ lastControlY = currentY;
197
+ lastCommand = type;
198
+ continue;
199
+ }
200
+ if (type === 'H') {
201
+ const x = xOffset + parseFloat(args[0]) * deviceCellWidth;
202
+ ctx.lineTo(x, currentY);
203
+ currentX = x;
204
+ lastControlX = currentX;
205
+ lastControlY = currentY;
206
+ lastCommand = type;
207
+ continue;
208
+ }
209
+ if (!args[0] || !args[1]) {
210
+ continue;
211
+ }
212
+ if (type === 'A') {
213
+ // SVG arc: A rx,ry,xAxisRotation,largeArcFlag,sweepFlag,x,y
214
+ const rx = parseFloat(args[0]) * deviceCellWidth;
215
+ const ry = parseFloat(args[1]) * deviceCellHeight;
216
+ const xAxisRotation = parseFloat(args[2]) * Math.PI / 180;
217
+ const largeArcFlag = parseInt(args[3]);
218
+ const sweepFlag = parseInt(args[4]);
219
+ const x = xOffset + parseFloat(args[5]) * deviceCellWidth;
220
+ const y = yOffset + parseFloat(args[6]) * deviceCellHeight;
221
+ drawSvgArc(ctx, currentX, currentY, rx, ry, xAxisRotation, largeArcFlag, sweepFlag, x, y);
222
+ currentX = x;
223
+ currentY = y;
224
+ continue;
225
+ }
226
+ const translatedArgs = args.map((e, i) => {
227
+ const val = parseFloat(e);
228
+ return i % 2 === 0
229
+ ? xOffset + val * deviceCellWidth
230
+ : yOffset + val * deviceCellHeight;
231
+ });
232
+ if (type === 'M') {
233
+ ctx.moveTo(translatedArgs[0], translatedArgs[1]);
234
+ currentX = translatedArgs[0];
235
+ currentY = translatedArgs[1];
236
+ lastControlX = currentX;
237
+ lastControlY = currentY;
238
+ } else if (type === 'L') {
239
+ ctx.lineTo(translatedArgs[0], translatedArgs[1]);
240
+ currentX = translatedArgs[0];
241
+ currentY = translatedArgs[1];
242
+ lastControlX = currentX;
243
+ lastControlY = currentY;
244
+ } else if (type === 'Q') {
245
+ ctx.quadraticCurveTo(translatedArgs[0], translatedArgs[1], translatedArgs[2], translatedArgs[3]);
246
+ lastControlX = translatedArgs[0];
247
+ lastControlY = translatedArgs[1];
248
+ currentX = translatedArgs[2];
249
+ currentY = translatedArgs[3];
250
+ } else if (type === 'T') {
251
+ // T uses reflection of last control point if previous command was Q or T
252
+ let cpX: number;
253
+ let cpY: number;
254
+ if (lastCommand === 'Q' || lastCommand === 'T') {
255
+ cpX = 2 * currentX - lastControlX;
256
+ cpY = 2 * currentY - lastControlY;
257
+ } else {
258
+ cpX = currentX;
259
+ cpY = currentY;
260
+ }
261
+ ctx.quadraticCurveTo(cpX, cpY, translatedArgs[0], translatedArgs[1]);
262
+ lastControlX = cpX;
263
+ lastControlY = cpY;
264
+ currentX = translatedArgs[0];
265
+ currentY = translatedArgs[1];
266
+ } else if (type === 'C') {
267
+ ctx.bezierCurveTo(translatedArgs[0], translatedArgs[1], translatedArgs[2], translatedArgs[3], translatedArgs[4], translatedArgs[5]);
268
+ lastControlX = translatedArgs[2];
269
+ lastControlY = translatedArgs[3];
270
+ currentX = translatedArgs[4];
271
+ currentY = translatedArgs[5];
272
+ }
273
+ lastCommand = type;
274
+ }
275
+ ctx.fill();
276
+ }
277
+
278
+ /**
279
+ * Converts SVG arc parameters to canvas arc/ellipse calls.
280
+ * Based on the SVG spec's endpoint to center parameterization conversion.
281
+ */
282
+ function drawSvgArc(
283
+ ctx: CanvasRenderingContext2D,
284
+ x1: number, y1: number,
285
+ rx: number, ry: number,
286
+ phi: number,
287
+ largeArcFlag: number,
288
+ sweepFlag: number,
289
+ x2: number, y2: number
290
+ ): void {
291
+ // Handle degenerate cases
292
+ if (rx === 0 || ry === 0) {
293
+ ctx.lineTo(x2, y2);
294
+ return;
295
+ }
296
+
297
+ rx = Math.abs(rx);
298
+ ry = Math.abs(ry);
299
+
300
+ const cosPhi = Math.cos(phi);
301
+ const sinPhi = Math.sin(phi);
302
+
303
+ // Step 1: Compute (x1', y1')
304
+ const dx = (x1 - x2) / 2;
305
+ const dy = (y1 - y2) / 2;
306
+ const x1p = cosPhi * dx + sinPhi * dy;
307
+ const y1p = -sinPhi * dx + cosPhi * dy;
308
+
309
+ // Step 2: Compute (cx', cy')
310
+ let rxSq = rx * rx;
311
+ let rySq = ry * ry;
312
+ const x1pSq = x1p * x1p;
313
+ const y1pSq = y1p * y1p;
314
+
315
+ // Correct radii if necessary
316
+ const lambda = x1pSq / rxSq + y1pSq / rySq;
317
+ if (lambda > 1) {
318
+ const lambdaSqrt = Math.sqrt(lambda);
319
+ rx *= lambdaSqrt;
320
+ ry *= lambdaSqrt;
321
+ rxSq = rx * rx;
322
+ rySq = ry * ry;
323
+ }
324
+
325
+ let sq = (rxSq * rySq - rxSq * y1pSq - rySq * x1pSq) / (rxSq * y1pSq + rySq * x1pSq);
326
+ if (sq < 0) sq = 0;
327
+ const coef = (largeArcFlag === sweepFlag ? -1 : 1) * Math.sqrt(sq);
328
+ const cxp = coef * (rx * y1p / ry);
329
+ const cyp = coef * -(ry * x1p / rx);
330
+
331
+ // Step 3: Compute (cx, cy) from (cx', cy')
332
+ const cx = cosPhi * cxp - sinPhi * cyp + (x1 + x2) / 2;
333
+ const cy = sinPhi * cxp + cosPhi * cyp + (y1 + y2) / 2;
334
+
335
+ // Step 4: Compute angles
336
+ const ux = (x1p - cxp) / rx;
337
+ const uy = (y1p - cyp) / ry;
338
+ const vx = (-x1p - cxp) / rx;
339
+ const vy = (-y1p - cyp) / ry;
340
+
341
+ const startAngle = Math.atan2(uy, ux);
342
+ let dTheta = Math.atan2(vy, vx) - startAngle;
343
+
344
+ if (sweepFlag === 0 && dTheta > 0) {
345
+ dTheta -= 2 * Math.PI;
346
+ } else if (sweepFlag === 1 && dTheta < 0) {
347
+ dTheta += 2 * Math.PI;
348
+ }
349
+
350
+ const endAngle = startAngle + dTheta;
351
+
352
+ ctx.ellipse(cx, cy, rx, ry, phi, startAngle, endAngle, sweepFlag === 0);
353
+ }
354
+
355
+ /**
356
+ * Draws a "negative" path where the background color is used to draw the shape on top of a
357
+ * foreground-filled cell. This creates the appearance of a cutout without using actual
358
+ * transparency, which allows SPAA (subpixel anti-aliasing) to work correctly.
359
+ *
360
+ * @param ctx The canvas rendering context (fillStyle should be set to foreground color)
361
+ * @param charDefinition The vector shape definition for the negative shape
362
+ * @param xOffset The x offset to draw at
363
+ * @param yOffset The y offset to draw at
364
+ * @param deviceCellWidth The width of the cell in device pixels
365
+ * @param deviceCellHeight The height of the cell in device pixels
366
+ * @param devicePixelRatio The device pixel ratio
367
+ * @param backgroundColor The background color to use for the "cutout" portion
368
+ */
369
+ function drawPathNegativeDefinitionCharacter(
370
+ ctx: CanvasRenderingContext2D,
371
+ charDefinition: ICustomGlyphVectorShape,
372
+ xOffset: number,
373
+ yOffset: number,
374
+ deviceCellWidth: number,
375
+ deviceCellHeight: number,
376
+ devicePixelRatio: number,
377
+ backgroundColor?: string
378
+ ): void {
379
+ ctx.save();
380
+
381
+ // First, fill the entire cell with foreground color
382
+ ctx.fillRect(xOffset, yOffset, deviceCellWidth, deviceCellHeight);
383
+
384
+ // Then draw the "negative" shape with the background color
385
+ if (backgroundColor) {
386
+ ctx.fillStyle = backgroundColor;
387
+ ctx.strokeStyle = backgroundColor;
388
+ }
389
+
390
+ ctx.lineWidth = devicePixelRatio;
391
+ ctx.lineCap = 'square';
392
+ ctx.beginPath();
393
+ for (const instruction of charDefinition.d.split(' ')) {
394
+ const type = instruction[0];
395
+ const args: string[] = instruction.substring(1).split(',');
396
+ if (!args[0] || !args[1]) {
397
+ if (type === 'Z') {
398
+ ctx.closePath();
399
+ }
400
+ continue;
401
+ }
402
+ const translatedArgs = args.map((e, i) => {
403
+ const val = parseFloat(e);
404
+ return i % 2 === 0
405
+ ? xOffset + val * deviceCellWidth
406
+ : yOffset + val * deviceCellHeight;
407
+ });
408
+ if (type === 'M') {
409
+ ctx.moveTo(translatedArgs[0], translatedArgs[1]);
410
+ } else if (type === 'L') {
411
+ ctx.lineTo(translatedArgs[0], translatedArgs[1]);
412
+ }
413
+ }
414
+
415
+ if (charDefinition.type === CustomGlyphVectorType.STROKE) {
416
+ ctx.stroke();
417
+ } else {
418
+ ctx.fill();
419
+ }
420
+
421
+ ctx.restore();
422
+ }
423
+
424
+ const cachedPatterns: Map<CustomGlyphPatternDefinition, Map</* fillStyle */string, CanvasPattern>> = new Map();
425
+
426
+ function drawPatternChar(
427
+ ctx: CanvasRenderingContext2D,
428
+ charDefinition: number[][],
429
+ xOffset: number,
430
+ yOffset: number,
431
+ deviceCellWidth: number,
432
+ deviceCellHeight: number
433
+ ): void {
434
+ let patternSet = cachedPatterns.get(charDefinition);
435
+ if (!patternSet) {
436
+ patternSet = new Map();
437
+ cachedPatterns.set(charDefinition, patternSet);
438
+ }
439
+ const fillStyle = ctx.fillStyle;
440
+ if (typeof fillStyle !== 'string') {
441
+ throw new Error(`Unexpected fillStyle type "${fillStyle}"`);
442
+ }
443
+ let pattern = patternSet.get(fillStyle);
444
+ if (!pattern) {
445
+ const width = charDefinition[0].length;
446
+ const height = charDefinition.length;
447
+ const tmpCanvas = ctx.canvas.ownerDocument.createElement('canvas');
448
+ tmpCanvas.width = width;
449
+ tmpCanvas.height = height;
450
+ const tmpCtx = throwIfFalsy(tmpCanvas.getContext('2d'));
451
+ const imageData = new ImageData(width, height);
452
+
453
+ // Extract rgba from fillStyle
454
+ let r: number;
455
+ let g: number;
456
+ let b: number;
457
+ let a: number;
458
+ if (fillStyle.startsWith('#')) {
459
+ r = parseInt(fillStyle.slice(1, 3), 16);
460
+ g = parseInt(fillStyle.slice(3, 5), 16);
461
+ b = parseInt(fillStyle.slice(5, 7), 16);
462
+ a = fillStyle.length > 7 && parseInt(fillStyle.slice(7, 9), 16) || 1;
463
+ } else if (fillStyle.startsWith('rgba')) {
464
+ ([r, g, b, a] = fillStyle.substring(5, fillStyle.length - 1).split(',').map(e => parseFloat(e)));
465
+ } else {
466
+ throw new Error(`Unexpected fillStyle color format "${fillStyle}" when drawing pattern glyph`);
467
+ }
468
+
469
+ for (let y = 0; y < height; y++) {
470
+ for (let x = 0; x < width; x++) {
471
+ imageData.data[(y * width + x) * 4 ] = r;
472
+ imageData.data[(y * width + x) * 4 + 1] = g;
473
+ imageData.data[(y * width + x) * 4 + 2] = b;
474
+ imageData.data[(y * width + x) * 4 + 3] = charDefinition[y][x] * (a * 255);
475
+ }
476
+ }
477
+ tmpCtx.putImageData(imageData, 0, 0);
478
+ pattern = throwIfFalsy(ctx.createPattern(tmpCanvas, null));
479
+ patternSet.set(fillStyle, pattern);
480
+ }
481
+ ctx.fillStyle = pattern;
482
+ ctx.fillRect(xOffset, yOffset, deviceCellWidth, deviceCellHeight);
483
+ }
484
+
485
+ function drawPathFunctionCharacter(
486
+ ctx: CanvasRenderingContext2D,
487
+ charDefinition: string | ((xp: number, yp: number) => string),
488
+ xOffset: number,
489
+ yOffset: number,
490
+ deviceCellWidth: number,
491
+ deviceCellHeight: number,
492
+ devicePixelRatio: number,
493
+ strokeWidth?: number
494
+ ): void {
495
+ ctx.beginPath();
496
+ let actualInstructions: string;
497
+ if (typeof charDefinition === 'function') {
498
+ const xp = .15;
499
+ const yp = .15 / deviceCellHeight * deviceCellWidth;
500
+ actualInstructions = charDefinition(xp, yp);
501
+ } else {
502
+ actualInstructions = charDefinition;
503
+ }
504
+ const state: ISvgPathState = { currentX: 0, currentY: 0, lastControlX: 0, lastControlY: 0, lastCommand: '' };
505
+ for (const instruction of actualInstructions.split(' ')) {
506
+ const type = instruction[0];
507
+ if (type === 'Z') {
508
+ ctx.closePath();
509
+ state.lastCommand = type;
510
+ continue;
511
+ }
512
+ const f = svgToCanvasInstructionMap[type];
513
+ if (!f) {
514
+ console.error(`Could not find drawing instructions for "${type}"`);
515
+ continue;
516
+ }
517
+ const args: string[] = instruction.substring(1).split(',');
518
+ if (!args[0] || !args[1]) {
519
+ continue;
520
+ }
521
+ f(ctx, translateArgs(args, deviceCellWidth, deviceCellHeight, xOffset, yOffset, true, devicePixelRatio), state);
522
+ state.lastCommand = type;
523
+ }
524
+ if (strokeWidth !== undefined) {
525
+ ctx.strokeStyle = ctx.fillStyle;
526
+ ctx.lineWidth = devicePixelRatio * strokeWidth;
527
+ ctx.stroke();
528
+ } else {
529
+ ctx.fill();
530
+ }
531
+ ctx.closePath();
532
+ }
533
+
534
+ /**
535
+ * Applies a clip path to the canvas context from SVG-like path instructions.
536
+ */
537
+ function applyClipPath(
538
+ ctx: CanvasRenderingContext2D,
539
+ clipPath: string,
540
+ xOffset: number,
541
+ yOffset: number,
542
+ deviceCellWidth: number,
543
+ deviceCellHeight: number
544
+ ): void {
545
+ ctx.beginPath();
546
+ for (const instruction of clipPath.split(' ')) {
547
+ const type = instruction[0];
548
+ if (type === 'Z') {
549
+ ctx.closePath();
550
+ continue;
551
+ }
552
+ const args: string[] = instruction.substring(1).split(',');
553
+ if (!args[0] || !args[1]) {
554
+ continue;
555
+ }
556
+ const x = xOffset + parseFloat(args[0]) * deviceCellWidth;
557
+ const y = yOffset + parseFloat(args[1]) * deviceCellHeight;
558
+ if (type === 'M') {
559
+ ctx.moveTo(x, y);
560
+ } else if (type === 'L') {
561
+ ctx.lineTo(x, y);
562
+ }
563
+ }
564
+ ctx.clip();
565
+ }
566
+
567
+ function drawVectorShape(
568
+ ctx: CanvasRenderingContext2D,
569
+ charDefinition: ICustomGlyphVectorShape,
570
+ xOffset: number,
571
+ yOffset: number,
572
+ deviceCellWidth: number,
573
+ deviceCellHeight: number,
574
+ fontSize: number,
575
+ devicePixelRatio: number
576
+ ): void {
577
+ // Clip the cell to make sure drawing doesn't occur beyond bounds
578
+ const clipRegion = new Path2D();
579
+ clipRegion.rect(xOffset, yOffset, deviceCellWidth, deviceCellHeight);
580
+ ctx.clip(clipRegion);
581
+
582
+ ctx.beginPath();
583
+ // Scale the stroke with DPR and font size
584
+ const cssLineWidth = fontSize / 12;
585
+ ctx.lineWidth = devicePixelRatio * cssLineWidth;
586
+ const state: ISvgPathState = { currentX: 0, currentY: 0, lastControlX: 0, lastControlY: 0, lastCommand: '' };
587
+ for (const instruction of charDefinition.d.split(' ')) {
588
+ const type = instruction[0];
589
+ if (type === 'Z') {
590
+ ctx.closePath();
591
+ state.lastCommand = type;
592
+ continue;
593
+ }
594
+ const f = svgToCanvasInstructionMap[type];
595
+ if (!f) {
596
+ console.error(`Could not find drawing instructions for "${type}"`);
597
+ continue;
598
+ }
599
+ const args: string[] = instruction.substring(1).split(',');
600
+ if (!args[0] || !args[1]) {
601
+ continue;
602
+ }
603
+ f(ctx, translateArgs(
604
+ args,
605
+ deviceCellWidth,
606
+ deviceCellHeight,
607
+ xOffset,
608
+ yOffset,
609
+ false,
610
+ devicePixelRatio,
611
+ (charDefinition.leftPadding ?? 0) * (cssLineWidth / 2),
612
+ (charDefinition.rightPadding ?? 0) * (cssLineWidth / 2)
613
+ ), state);
614
+ state.lastCommand = type;
615
+ }
616
+ if (charDefinition.type === CustomGlyphVectorType.STROKE) {
617
+ ctx.strokeStyle = ctx.fillStyle;
618
+ ctx.stroke();
619
+ } else {
620
+ ctx.fill();
621
+ }
622
+ ctx.closePath();
623
+ }
624
+
625
+ function clamp(value: number, max: number, min: number = 0): number {
626
+ return Math.max(Math.min(value, max), min);
627
+ }
628
+
629
+ interface ISvgPathState {
630
+ currentX: number;
631
+ currentY: number;
632
+ lastControlX: number;
633
+ lastControlY: number;
634
+ lastCommand: string;
635
+ }
636
+
637
+ const svgToCanvasInstructionMap: { [index: string]: (ctx: CanvasRenderingContext2D, args: number[], state: ISvgPathState) => void } = {
638
+ 'C': (ctx, args, state) => {
639
+ ctx.bezierCurveTo(args[0], args[1], args[2], args[3], args[4], args[5]);
640
+ state.lastControlX = args[2];
641
+ state.lastControlY = args[3];
642
+ state.currentX = args[4];
643
+ state.currentY = args[5];
644
+ },
645
+ 'L': (ctx, args, state) => {
646
+ ctx.lineTo(args[0], args[1]);
647
+ state.lastControlX = state.currentX = args[0];
648
+ state.lastControlY = state.currentY = args[1];
649
+ },
650
+ 'M': (ctx, args, state) => {
651
+ ctx.moveTo(args[0], args[1]);
652
+ state.lastControlX = state.currentX = args[0];
653
+ state.lastControlY = state.currentY = args[1];
654
+ },
655
+ 'Q': (ctx, args, state) => {
656
+ ctx.quadraticCurveTo(args[0], args[1], args[2], args[3]);
657
+ state.lastControlX = args[0];
658
+ state.lastControlY = args[1];
659
+ state.currentX = args[2];
660
+ state.currentY = args[3];
661
+ },
662
+ 'T': (ctx, args, state) => {
663
+ let cpX: number;
664
+ let cpY: number;
665
+ if (state.lastCommand === 'Q' || state.lastCommand === 'T') {
666
+ cpX = 2 * state.currentX - state.lastControlX;
667
+ cpY = 2 * state.currentY - state.lastControlY;
668
+ } else {
669
+ cpX = state.currentX;
670
+ cpY = state.currentY;
671
+ }
672
+ ctx.quadraticCurveTo(cpX, cpY, args[0], args[1]);
673
+ state.lastControlX = cpX;
674
+ state.lastControlY = cpY;
675
+ state.currentX = args[0];
676
+ state.currentY = args[1];
677
+ }
678
+ };
679
+
680
+ function translateArgs(args: string[], cellWidth: number, cellHeight: number, xOffset: number, yOffset: number, doClamp: boolean, devicePixelRatio: number, leftPadding: number = 0, rightPadding: number = 0): number[] {
681
+ const result = args.map(e => parseFloat(e) || parseInt(e));
682
+
683
+ if (result.length < 2) {
684
+ throw new Error('Too few arguments for instruction');
685
+ }
686
+
687
+ for (let x = 0; x < result.length; x += 2) {
688
+ // Translate from 0-1 to 0-cellWidth
689
+ result[x] *= cellWidth - (leftPadding * devicePixelRatio) - (rightPadding * devicePixelRatio);
690
+ // Ensure coordinate doesn't escape cell bounds and round to the nearest 0.5 to ensure a crisp
691
+ // line at 100% devicePixelRatio
692
+ if (doClamp && result[x] !== 0) {
693
+ result[x] = clamp(Math.round(result[x] + 0.5) - 0.5, cellWidth, 0);
694
+ }
695
+ // Apply the cell's offset (ie. x*cellWidth)
696
+ result[x] += xOffset + (leftPadding * devicePixelRatio);
697
+ }
698
+
699
+ for (let y = 1; y < result.length; y += 2) {
700
+ // Translate from 0-1 to 0-cellHeight
701
+ result[y] *= cellHeight;
702
+ // Ensure coordinate doesn't escape cell bounds and round to the nearest 0.5 to ensure a crisp
703
+ // line at 100% devicePixelRatio
704
+ if (doClamp && result[y] !== 0) {
705
+ result[y] = clamp(Math.round(result[y] + 0.5) - 0.5, cellHeight, 0);
706
+ }
707
+ // Apply the cell's offset (ie. x*cellHeight)
708
+ result[y] += yOffset;
709
+ }
710
+
711
+ return result;
712
+ }