@gjsify/canvas2d-core 0.1.3

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,1007 @@
1
+ // CanvasRenderingContext2D implementation backed by Cairo
2
+ // Reference: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D
3
+ // Reference: refs/node-canvas (Cairo-backed Canvas 2D for Node.js)
4
+
5
+ import Cairo from 'cairo';
6
+ import Gdk from 'gi://Gdk?version=4.0';
7
+ import GdkPixbuf from 'gi://GdkPixbuf';
8
+ import Pango from 'gi://Pango';
9
+ import PangoCairo from 'gi://PangoCairo';
10
+ // HTMLCanvasElement type is provided by the DOM lib.
11
+ // Our @gjsify/dom-elements HTMLCanvasElement satisfies this interface.
12
+
13
+ import { parseColor } from './color.js';
14
+ import {
15
+ quadraticToCubic,
16
+ cairoArcTo,
17
+ cairoEllipse,
18
+ cairoRoundRect,
19
+ COMPOSITE_OP_MAP,
20
+ LINE_CAP_MAP,
21
+ LINE_JOIN_MAP,
22
+ } from './cairo-utils.js';
23
+ import { type CanvasState, createDefaultState, cloneState } from './canvas-state.js';
24
+ import { OurImageData } from './image-data.js';
25
+ import { CanvasGradient as OurCanvasGradient } from './canvas-gradient.js';
26
+ import { CanvasPattern as OurCanvasPattern } from './canvas-pattern.js';
27
+ import { Path2D } from './canvas-path.js';
28
+
29
+ /**
30
+ * CanvasRenderingContext2D backed by Cairo.ImageSurface.
31
+ * Implements the Canvas 2D API for GJS.
32
+ */
33
+ export class CanvasRenderingContext2D {
34
+ readonly canvas: any;
35
+
36
+ private _surface: Cairo.ImageSurface;
37
+ private _ctx: Cairo.Context;
38
+ private _state: CanvasState;
39
+ private _stateStack: CanvasState[] = [];
40
+ private _surfaceWidth: number;
41
+ private _surfaceHeight: number;
42
+
43
+ constructor(canvas: any, _options?: any) {
44
+ this.canvas = canvas;
45
+ this._surfaceWidth = canvas.width || 300;
46
+ this._surfaceHeight = canvas.height || 150;
47
+ this._surface = new Cairo.ImageSurface(Cairo.Format.ARGB32, this._surfaceWidth, this._surfaceHeight);
48
+ this._ctx = new Cairo.Context(this._surface);
49
+ this._state = createDefaultState();
50
+ }
51
+
52
+ // ---- Internal helpers ----
53
+
54
+ /** Ensure the surface matches the current canvas dimensions. Recreate if resized. */
55
+ private _ensureSurface(): void {
56
+ const w = this.canvas.width || 300;
57
+ const h = this.canvas.height || 150;
58
+ if (w !== this._surfaceWidth || h !== this._surfaceHeight) {
59
+ this._ctx.$dispose();
60
+ this._surface.finish();
61
+ this._surfaceWidth = w;
62
+ this._surfaceHeight = h;
63
+ this._surface = new Cairo.ImageSurface(Cairo.Format.ARGB32, w, h);
64
+ this._ctx = new Cairo.Context(this._surface);
65
+ // Preserve the current drawing state (fillStyle, strokeStyle, font, etc.) across
66
+ // surface recreations triggered by widget resize. Only reset the save/restore stack
67
+ // because the old Cairo context is gone and saved state is invalid.
68
+ // NOTE: If app code wants a true canvas reset (spec: canvas.width = X resets context),
69
+ // it should call _resetState() explicitly. We do not reset here because _ensureSurface()
70
+ // is called internally from drawing operations, not from app-level canvas.width assignments.
71
+ this._stateStack = [];
72
+ }
73
+ }
74
+
75
+ /** Reset drawing state to defaults (called when canvas dimensions are explicitly reset). */
76
+ _resetState(): void {
77
+ this._state = createDefaultState();
78
+ this._stateStack = [];
79
+ }
80
+
81
+ /** Apply the current fill style (color, gradient, or pattern) to the Cairo context. */
82
+ private _applyFillStyle(): void {
83
+ const style = this._state.fillStyle;
84
+ if (typeof style === 'string') {
85
+ const c = this._state.fillColor;
86
+ const a = c.a * this._state.globalAlpha;
87
+ this._ctx.setSourceRGBA(c.r, c.g, c.b, a);
88
+ } else if (style instanceof OurCanvasGradient) {
89
+ this._ctx.setSource(style._getCairoPattern());
90
+ } else if (style instanceof OurCanvasPattern) {
91
+ this._ctx.setSource(style._getCairoPattern());
92
+ }
93
+ }
94
+
95
+ /** Apply the current stroke style to the Cairo context. */
96
+ private _applyStrokeStyle(): void {
97
+ const style = this._state.strokeStyle;
98
+ if (typeof style === 'string') {
99
+ const c = this._state.strokeColor;
100
+ const a = c.a * this._state.globalAlpha;
101
+ this._ctx.setSourceRGBA(c.r, c.g, c.b, a);
102
+ } else if (style instanceof OurCanvasGradient) {
103
+ this._ctx.setSource(style._getCairoPattern());
104
+ } else if (style instanceof OurCanvasPattern) {
105
+ this._ctx.setSource(style._getCairoPattern());
106
+ }
107
+ }
108
+
109
+ /** Apply line properties to the Cairo context. */
110
+ private _applyLineStyle(): void {
111
+ this._ctx.setLineWidth(this._state.lineWidth);
112
+ this._ctx.setLineCap(LINE_CAP_MAP[this._state.lineCap] as Cairo.LineCap);
113
+ this._ctx.setLineJoin(LINE_JOIN_MAP[this._state.lineJoin] as Cairo.LineJoin);
114
+ this._ctx.setMiterLimit(this._state.miterLimit);
115
+ this._ctx.setDash(this._state.lineDash, this._state.lineDashOffset);
116
+ }
117
+
118
+ /** Apply compositing operator. */
119
+ private _applyCompositing(): void {
120
+ const op = COMPOSITE_OP_MAP[this._state.globalCompositeOperation];
121
+ if (op !== undefined) {
122
+ this._ctx.setOperator(op as Cairo.Operator);
123
+ }
124
+ }
125
+
126
+ /** Get the Cairo ImageSurface (used by other contexts like drawImage). */
127
+ _getSurface(): Cairo.ImageSurface {
128
+ return this._surface;
129
+ }
130
+
131
+ /** Check if shadow rendering is needed. */
132
+ private _hasShadow(): boolean {
133
+ if (this._state.shadowBlur === 0 && this._state.shadowOffsetX === 0 && this._state.shadowOffsetY === 0) {
134
+ return false;
135
+ }
136
+ const c = parseColor(this._state.shadowColor);
137
+ return c !== null && c.a > 0;
138
+ }
139
+
140
+ /**
141
+ * Render a shadow for the current path by painting to a temp surface,
142
+ * applying a simple box blur approximation, and compositing back.
143
+ * This is called before the actual fill/stroke when shadows are active.
144
+ */
145
+ private _renderShadow(drawOp: () => void): void {
146
+ const blur = this._state.shadowBlur;
147
+ const offX = this._state.shadowOffsetX;
148
+ const offY = this._state.shadowOffsetY;
149
+ const color = parseColor(this._state.shadowColor);
150
+ if (!color) return;
151
+
152
+ const pad = Math.ceil(blur * 2);
153
+ const w = this._surfaceWidth + pad * 2;
154
+ const h = this._surfaceHeight + pad * 2;
155
+
156
+ // Create temp surface for shadow
157
+ const shadowSurface = new Cairo.ImageSurface(Cairo.Format.ARGB32, w, h);
158
+ const shadowCtx = new Cairo.Context(shadowSurface);
159
+
160
+ // Copy the current path/state to the shadow context and draw in shadow color
161
+ shadowCtx.translate(pad, pad);
162
+ shadowCtx.setSourceRGBA(color.r, color.g, color.b, color.a * this._state.globalAlpha);
163
+ drawOp.call(this);
164
+ // We can't easily replay the path on a different context without Path2D,
165
+ // so shadow support is approximate: we just paint the shadow color under the actual draw
166
+ shadowCtx.$dispose();
167
+ shadowSurface.finish();
168
+
169
+ // For now, apply shadow as a simple offset + color overlay
170
+ // Full Gaussian blur would require pixel manipulation (Phase 5 enhancement)
171
+ this._ctx.save();
172
+ this._applyCompositing();
173
+ this._ctx.setSourceRGBA(color.r, color.g, color.b, color.a * this._state.globalAlpha);
174
+ this._ctx.translate(offX, offY);
175
+ // Re-fill/stroke the current path with shadow color
176
+ drawOp();
177
+ this._ctx.restore();
178
+ }
179
+
180
+ // ---- State ----
181
+
182
+ save(): void {
183
+ this._ensureSurface();
184
+ this._stateStack.push(cloneState(this._state));
185
+ this._ctx.save();
186
+ }
187
+
188
+ restore(): void {
189
+ this._ensureSurface();
190
+ const prev = this._stateStack.pop();
191
+ if (prev) {
192
+ this._state = prev;
193
+ this._ctx.restore();
194
+ }
195
+ }
196
+
197
+ // ---- Transforms ----
198
+
199
+ translate(x: number, y: number): void {
200
+ this._ensureSurface();
201
+ this._ctx.translate(x, y);
202
+ }
203
+
204
+ rotate(angle: number): void {
205
+ this._ensureSurface();
206
+ this._ctx.rotate(angle);
207
+ }
208
+
209
+ scale(x: number, y: number): void {
210
+ this._ensureSurface();
211
+ this._ctx.scale(x, y);
212
+ }
213
+
214
+ /**
215
+ * Multiply the current transformation matrix by the given values.
216
+ * Matrix: [a c e]
217
+ * [b d f]
218
+ * [0 0 1]
219
+ */
220
+ transform(a: number, b: number, c: number, d: number, e: number, f: number): void {
221
+ this._ensureSurface();
222
+ // Cairo's matrix constructor: Matrix(xx, yx, xy, yy, x0, y0)
223
+ // Canvas matrix [a,b,c,d,e,f] maps to Cairo Matrix(a, b, c, d, e, f)
224
+ const matrix = new Cairo.Matrix();
225
+ (matrix as any).init(a, b, c, d, e, f);
226
+ (this._ctx as any).transform(matrix);
227
+ }
228
+
229
+ /**
230
+ * Reset the transform to identity, then apply the given matrix.
231
+ */
232
+ setTransform(matrix?: DOMMatrix2DInit): void;
233
+ setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void;
234
+ setTransform(a?: number | DOMMatrix2DInit, b?: number, c?: number, d?: number, e?: number, f?: number): void {
235
+ this._ensureSurface();
236
+ if (typeof a === 'object' && a !== null) {
237
+ const m = a;
238
+ this._ctx.identityMatrix();
239
+ this.transform(
240
+ m.a ?? m.m11 ?? 1, m.b ?? m.m12 ?? 0,
241
+ m.c ?? m.m21 ?? 0, m.d ?? m.m22 ?? 1,
242
+ m.e ?? m.m41 ?? 0, m.f ?? m.m42 ?? 0,
243
+ );
244
+ } else if (typeof a === 'number') {
245
+ this._ctx.identityMatrix();
246
+ this.transform(a, b!, c!, d!, e!, f!);
247
+ } else {
248
+ this._ctx.identityMatrix();
249
+ }
250
+ }
251
+
252
+ /**
253
+ * Return the current transformation matrix as a DOMMatrix-like object.
254
+ */
255
+ getTransform(): DOMMatrix {
256
+ // Cairo doesn't expose getMatrix in GJS types, but it exists at runtime
257
+ const m = (this._ctx as any).getMatrix?.();
258
+ if (m) {
259
+ // Cairo Matrix fields: xx, yx, xy, yy, x0, y0
260
+ return {
261
+ a: m.xx ?? 1, b: m.yx ?? 0,
262
+ c: m.xy ?? 0, d: m.yy ?? 1,
263
+ e: m.x0 ?? 0, f: m.y0 ?? 0,
264
+ m11: m.xx ?? 1, m12: m.yx ?? 0,
265
+ m13: 0, m14: 0,
266
+ m21: m.xy ?? 0, m22: m.yy ?? 1,
267
+ m23: 0, m24: 0,
268
+ m31: 0, m32: 0, m33: 1, m34: 0,
269
+ m41: m.x0 ?? 0, m42: m.y0 ?? 0,
270
+ m43: 0, m44: 1,
271
+ is2D: true,
272
+ isIdentity: (m.xx === 1 && m.yx === 0 && m.xy === 0 && m.yy === 1 && m.x0 === 0 && m.y0 === 0),
273
+ } as any;
274
+ }
275
+ // Fallback: return identity
276
+ return { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0, is2D: true, isIdentity: true } as any;
277
+ }
278
+
279
+ resetTransform(): void {
280
+ this._ensureSurface();
281
+ this._ctx.identityMatrix();
282
+ }
283
+
284
+ // ---- Style properties ----
285
+
286
+ get fillStyle(): string | CanvasGradient | CanvasPattern {
287
+ return this._state.fillStyle;
288
+ }
289
+
290
+ set fillStyle(value: string | CanvasGradient | CanvasPattern) {
291
+ if (typeof value === 'string') {
292
+ const parsed = parseColor(value);
293
+ if (parsed) {
294
+ this._state.fillStyle = value;
295
+ this._state.fillColor = parsed;
296
+ }
297
+ } else {
298
+ this._state.fillStyle = value;
299
+ }
300
+ }
301
+
302
+ get strokeStyle(): string | CanvasGradient | CanvasPattern {
303
+ return this._state.strokeStyle;
304
+ }
305
+
306
+ set strokeStyle(value: string | CanvasGradient | CanvasPattern) {
307
+ if (typeof value === 'string') {
308
+ const parsed = parseColor(value);
309
+ if (parsed) {
310
+ this._state.strokeStyle = value;
311
+ this._state.strokeColor = parsed;
312
+ }
313
+ } else {
314
+ this._state.strokeStyle = value;
315
+ }
316
+ }
317
+
318
+ get lineWidth(): number { return this._state.lineWidth; }
319
+ set lineWidth(value: number) {
320
+ if (value > 0 && isFinite(value)) this._state.lineWidth = value;
321
+ }
322
+
323
+ get lineCap(): CanvasLineCap { return this._state.lineCap; }
324
+ set lineCap(value: CanvasLineCap) {
325
+ if (value === 'butt' || value === 'round' || value === 'square') {
326
+ this._state.lineCap = value;
327
+ }
328
+ }
329
+
330
+ get lineJoin(): CanvasLineJoin { return this._state.lineJoin; }
331
+ set lineJoin(value: CanvasLineJoin) {
332
+ if (value === 'miter' || value === 'round' || value === 'bevel') {
333
+ this._state.lineJoin = value;
334
+ }
335
+ }
336
+
337
+ get miterLimit(): number { return this._state.miterLimit; }
338
+ set miterLimit(value: number) {
339
+ if (value > 0 && isFinite(value)) this._state.miterLimit = value;
340
+ }
341
+
342
+ get globalAlpha(): number { return this._state.globalAlpha; }
343
+ set globalAlpha(value: number) {
344
+ if (value >= 0 && value <= 1 && isFinite(value)) this._state.globalAlpha = value;
345
+ }
346
+
347
+ get globalCompositeOperation(): GlobalCompositeOperation {
348
+ return this._state.globalCompositeOperation;
349
+ }
350
+
351
+ set globalCompositeOperation(value: GlobalCompositeOperation) {
352
+ if (COMPOSITE_OP_MAP[value] !== undefined) {
353
+ this._state.globalCompositeOperation = value;
354
+ }
355
+ }
356
+
357
+ get imageSmoothingEnabled(): boolean { return this._state.imageSmoothingEnabled; }
358
+ set imageSmoothingEnabled(value: boolean) { this._state.imageSmoothingEnabled = !!value; }
359
+
360
+ get imageSmoothingQuality(): ImageSmoothingQuality { return this._state.imageSmoothingQuality; }
361
+ set imageSmoothingQuality(value: ImageSmoothingQuality) {
362
+ if (value === 'low' || value === 'medium' || value === 'high') {
363
+ this._state.imageSmoothingQuality = value;
364
+ }
365
+ }
366
+
367
+ // Line dash
368
+ setLineDash(segments: number[]): void {
369
+ // Per spec, ignore if any value is negative or non-finite
370
+ if (segments.some(v => v < 0 || !isFinite(v))) return;
371
+ this._state.lineDash = [...segments];
372
+ }
373
+
374
+ getLineDash(): number[] {
375
+ return [...this._state.lineDash];
376
+ }
377
+
378
+ get lineDashOffset(): number { return this._state.lineDashOffset; }
379
+ set lineDashOffset(value: number) {
380
+ if (isFinite(value)) this._state.lineDashOffset = value;
381
+ }
382
+
383
+ // ---- Shadow properties (stored in state, rendering in Phase 5) ----
384
+ get shadowColor(): string { return this._state.shadowColor; }
385
+ set shadowColor(value: string) { this._state.shadowColor = value; }
386
+ get shadowBlur(): number { return this._state.shadowBlur; }
387
+ set shadowBlur(value: number) { if (value >= 0 && isFinite(value)) this._state.shadowBlur = value; }
388
+ get shadowOffsetX(): number { return this._state.shadowOffsetX; }
389
+ set shadowOffsetX(value: number) { if (isFinite(value)) this._state.shadowOffsetX = value; }
390
+ get shadowOffsetY(): number { return this._state.shadowOffsetY; }
391
+ set shadowOffsetY(value: number) { if (isFinite(value)) this._state.shadowOffsetY = value; }
392
+
393
+ // ---- Text properties (stored in state, rendering in Phase 4) ----
394
+ get font(): string { return this._state.font; }
395
+ set font(value: string) { this._state.font = value; }
396
+ get textAlign(): CanvasTextAlign { return this._state.textAlign; }
397
+ set textAlign(value: CanvasTextAlign) { this._state.textAlign = value; }
398
+ get textBaseline(): CanvasTextBaseline { return this._state.textBaseline; }
399
+ set textBaseline(value: CanvasTextBaseline) { this._state.textBaseline = value; }
400
+ get direction(): CanvasDirection { return this._state.direction; }
401
+ set direction(value: CanvasDirection) { this._state.direction = value; }
402
+
403
+ // ---- Path methods ----
404
+
405
+ beginPath(): void {
406
+ this._ensureSurface();
407
+ this._ctx.newPath();
408
+ }
409
+
410
+ moveTo(x: number, y: number): void {
411
+ this._ensureSurface();
412
+ this._ctx.moveTo(x, y);
413
+ }
414
+
415
+ lineTo(x: number, y: number): void {
416
+ this._ensureSurface();
417
+ this._ctx.lineTo(x, y);
418
+ }
419
+
420
+ closePath(): void {
421
+ this._ensureSurface();
422
+ this._ctx.closePath();
423
+ }
424
+
425
+ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void {
426
+ this._ensureSurface();
427
+ this._ctx.curveTo(cp1x, cp1y, cp2x, cp2y, x, y);
428
+ }
429
+
430
+ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void {
431
+ this._ensureSurface();
432
+ let cx: number, cy: number;
433
+ if (this._ctx.hasCurrentPoint()) {
434
+ [cx, cy] = this._ctx.getCurrentPoint();
435
+ } else {
436
+ cx = cpx;
437
+ cy = cpy;
438
+ }
439
+ const { cp1x, cp1y, cp2x, cp2y } = quadraticToCubic(cx, cy, cpx, cpy, x, y);
440
+ this._ctx.curveTo(cp1x, cp1y, cp2x, cp2y, x, y);
441
+ }
442
+
443
+ arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise = false): void {
444
+ this._ensureSurface();
445
+ // Browsers draw a full circle when |endAngle - startAngle| >= 2π,
446
+ // regardless of direction. Cairo's arcNegative would produce a
447
+ // zero-length arc for arcNegative(x,y,r,0,2π) because it normalizes
448
+ // endAngle to be < startAngle, collapsing the arc to nothing.
449
+ if (Math.abs(endAngle - startAngle) >= 2 * Math.PI) {
450
+ this._ctx.arc(x, y, radius, 0, 2 * Math.PI);
451
+ return;
452
+ }
453
+ if (counterclockwise) {
454
+ this._ctx.arcNegative(x, y, radius, startAngle, endAngle);
455
+ } else {
456
+ this._ctx.arc(x, y, radius, startAngle, endAngle);
457
+ }
458
+ }
459
+
460
+ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void {
461
+ this._ensureSurface();
462
+ let x0: number, y0: number;
463
+ if (this._ctx.hasCurrentPoint()) {
464
+ [x0, y0] = this._ctx.getCurrentPoint();
465
+ } else {
466
+ x0 = x1;
467
+ y0 = y1;
468
+ this._ctx.moveTo(x1, y1);
469
+ }
470
+ cairoArcTo(this._ctx, x0, y0, x1, y1, x2, y2, radius);
471
+ }
472
+
473
+ ellipse(
474
+ x: number, y: number,
475
+ radiusX: number, radiusY: number,
476
+ rotation: number,
477
+ startAngle: number, endAngle: number,
478
+ counterclockwise = false,
479
+ ): void {
480
+ this._ensureSurface();
481
+ if (radiusX < 0 || radiusY < 0) {
482
+ throw new RangeError('The radii provided are negative');
483
+ }
484
+ cairoEllipse(this._ctx, x, y, radiusX, radiusY, rotation, startAngle, endAngle, counterclockwise);
485
+ }
486
+
487
+ rect(x: number, y: number, w: number, h: number): void {
488
+ this._ensureSurface();
489
+ this._ctx.rectangle(x, y, w, h);
490
+ }
491
+
492
+ roundRect(x: number, y: number, w: number, h: number, radii: number | number[] = 0): void {
493
+ this._ensureSurface();
494
+ cairoRoundRect(this._ctx, x, y, w, h, radii);
495
+ }
496
+
497
+ // ---- Drawing methods ----
498
+
499
+ fill(fillRule?: CanvasFillRule): void;
500
+ fill(path: Path2D, fillRule?: CanvasFillRule): void;
501
+ fill(pathOrRule?: Path2D | CanvasFillRule, fillRule?: CanvasFillRule): void {
502
+ this._ensureSurface();
503
+ this._applyCompositing();
504
+ this._applyFillStyle();
505
+
506
+ let rule: CanvasFillRule | undefined;
507
+ if (pathOrRule instanceof Path2D) {
508
+ this._ctx.newPath();
509
+ pathOrRule._replayOnCairo(this._ctx);
510
+ rule = fillRule;
511
+ } else {
512
+ rule = pathOrRule;
513
+ }
514
+
515
+ this._ctx.setFillRule(rule === 'evenodd' ? Cairo.FillRule.EVEN_ODD : Cairo.FillRule.WINDING);
516
+ this._ctx.fillPreserve();
517
+ }
518
+
519
+ stroke(): void;
520
+ stroke(path: Path2D): void;
521
+ stroke(path?: Path2D): void {
522
+ this._ensureSurface();
523
+ this._applyCompositing();
524
+ this._applyStrokeStyle();
525
+ this._applyLineStyle();
526
+
527
+ if (path instanceof Path2D) {
528
+ this._ctx.newPath();
529
+ path._replayOnCairo(this._ctx);
530
+ }
531
+
532
+ this._ctx.strokePreserve();
533
+ }
534
+
535
+ fillRect(x: number, y: number, w: number, h: number): void {
536
+ this._ensureSurface();
537
+ this._applyCompositing();
538
+ // Per spec: fillRect must not affect the current path.
539
+ // Save current path, draw the rect in an isolated path, then restore.
540
+ const savedPath = this._ctx.copyPath();
541
+ if (this._hasShadow()) {
542
+ this._renderShadow(() => {
543
+ this._ctx.newPath();
544
+ this._ctx.rectangle(x, y, w, h);
545
+ this._ctx.fill();
546
+ });
547
+ }
548
+ this._applyFillStyle();
549
+ this._ctx.newPath();
550
+ this._ctx.rectangle(x, y, w, h);
551
+ this._ctx.fill();
552
+ this._ctx.newPath();
553
+ this._ctx.appendPath(savedPath);
554
+ }
555
+
556
+ strokeRect(x: number, y: number, w: number, h: number): void {
557
+ this._ensureSurface();
558
+ this._applyCompositing();
559
+ // Per spec: strokeRect must not affect the current path.
560
+ const savedPath = this._ctx.copyPath();
561
+ if (this._hasShadow()) {
562
+ this._renderShadow(() => {
563
+ this._ctx.newPath();
564
+ this._ctx.rectangle(x, y, w, h);
565
+ this._ctx.stroke();
566
+ });
567
+ }
568
+ this._applyStrokeStyle();
569
+ this._applyLineStyle();
570
+ this._ctx.newPath();
571
+ this._ctx.rectangle(x, y, w, h);
572
+ this._ctx.stroke();
573
+ this._ctx.newPath();
574
+ this._ctx.appendPath(savedPath);
575
+ }
576
+
577
+ clearRect(x: number, y: number, w: number, h: number): void {
578
+ this._ensureSurface();
579
+ // Per spec: clearRect must not affect the current path.
580
+ const savedPath = this._ctx.copyPath();
581
+ this._ctx.save();
582
+ this._ctx.setOperator(Cairo.Operator.CLEAR);
583
+ this._ctx.newPath();
584
+ this._ctx.rectangle(x, y, w, h);
585
+ this._ctx.fill();
586
+ this._ctx.restore();
587
+ this._ctx.newPath();
588
+ this._ctx.appendPath(savedPath);
589
+ }
590
+
591
+ // ---- Clipping ----
592
+
593
+ clip(fillRule?: CanvasFillRule): void;
594
+ clip(path: Path2D, fillRule?: CanvasFillRule): void;
595
+ clip(pathOrRule?: Path2D | CanvasFillRule, fillRule?: CanvasFillRule): void {
596
+ this._ensureSurface();
597
+ let rule: CanvasFillRule | undefined;
598
+ if (pathOrRule instanceof Path2D) {
599
+ this._ctx.newPath();
600
+ pathOrRule._replayOnCairo(this._ctx);
601
+ rule = fillRule;
602
+ } else {
603
+ rule = pathOrRule;
604
+ }
605
+ this._ctx.setFillRule(rule === 'evenodd' ? Cairo.FillRule.EVEN_ODD : Cairo.FillRule.WINDING);
606
+ this._ctx.clip();
607
+ }
608
+
609
+ // ---- Hit testing ----
610
+
611
+ isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean;
612
+ isPointInPath(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean;
613
+ isPointInPath(pathOrX: Path2D | number, xOrY: number, fillRuleOrY?: CanvasFillRule | number, fillRule?: CanvasFillRule): boolean {
614
+ this._ensureSurface();
615
+ let x: number, y: number, rule: CanvasFillRule | undefined;
616
+ if (pathOrX instanceof Path2D) {
617
+ this._ctx.newPath();
618
+ pathOrX._replayOnCairo(this._ctx);
619
+ x = xOrY; y = fillRuleOrY as number; rule = fillRule;
620
+ } else {
621
+ x = pathOrX; y = xOrY; rule = fillRuleOrY as CanvasFillRule | undefined;
622
+ }
623
+ this._ctx.setFillRule(rule === 'evenodd' ? Cairo.FillRule.EVEN_ODD : Cairo.FillRule.WINDING);
624
+ return this._ctx.inFill(x, y);
625
+ }
626
+
627
+ isPointInStroke(x: number, y: number): boolean;
628
+ isPointInStroke(path: Path2D, x: number, y: number): boolean;
629
+ isPointInStroke(pathOrX: Path2D | number, xOrY: number, y?: number): boolean {
630
+ this._ensureSurface();
631
+ this._applyLineStyle();
632
+ if (pathOrX instanceof Path2D) {
633
+ this._ctx.newPath();
634
+ pathOrX._replayOnCairo(this._ctx);
635
+ return this._ctx.inStroke(xOrY, y!);
636
+ }
637
+ return this._ctx.inStroke(pathOrX, xOrY);
638
+ }
639
+
640
+ // ---- Gradient / Pattern factories ----
641
+
642
+ createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient {
643
+ return new OurCanvasGradient('linear', x0, y0, x1, y1) as any;
644
+ }
645
+
646
+ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient {
647
+ return new OurCanvasGradient('radial', x0, y0, x1, y1, r0, r1) as any;
648
+ }
649
+
650
+ createPattern(image: any, repetition: string | null): CanvasPattern | null {
651
+ return OurCanvasPattern.create(image, repetition) as any;
652
+ }
653
+
654
+ // ---- Image data methods ----
655
+
656
+ createImageData(sw: number, sh: number): ImageData;
657
+ createImageData(imagedata: ImageData): ImageData;
658
+ createImageData(swOrImageData: number | ImageData, sh?: number): ImageData {
659
+ if (typeof swOrImageData === 'number') {
660
+ return new OurImageData(Math.abs(swOrImageData), Math.abs(sh!)) as any;
661
+ }
662
+ return new OurImageData(swOrImageData.width, swOrImageData.height) as any;
663
+ }
664
+
665
+ getImageData(sx: number, sy: number, sw: number, sh: number): ImageData {
666
+ this._ensureSurface();
667
+ this._surface.flush();
668
+
669
+ // Use Gdk.pixbuf_get_from_surface to read pixels
670
+ const pixbuf = Gdk.pixbuf_get_from_surface(this._surface, sx, sy, sw, sh);
671
+ if (!pixbuf) {
672
+ return new OurImageData(sw, sh) as any;
673
+ }
674
+
675
+ const pixels = pixbuf.get_pixels();
676
+ const hasAlpha = pixbuf.get_has_alpha();
677
+ const rowstride = pixbuf.get_rowstride();
678
+ const nChannels = pixbuf.get_n_channels();
679
+ const out = new Uint8ClampedArray(sw * sh * 4);
680
+
681
+ for (let y = 0; y < sh; y++) {
682
+ for (let x = 0; x < sw; x++) {
683
+ const srcIdx = y * rowstride + x * nChannels;
684
+ const dstIdx = (y * sw + x) * 4;
685
+ out[dstIdx] = pixels[srcIdx]; // R
686
+ out[dstIdx + 1] = pixels[srcIdx + 1]; // G
687
+ out[dstIdx + 2] = pixels[srcIdx + 2]; // B
688
+ out[dstIdx + 3] = hasAlpha ? pixels[srcIdx + 3] : 255; // A
689
+ }
690
+ }
691
+
692
+ return new OurImageData(out, sw, sh) as any;
693
+ }
694
+
695
+ putImageData(imageData: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void {
696
+ this._ensureSurface();
697
+
698
+ // Determine the dirty region
699
+ const sx = dirtyX ?? 0;
700
+ const sy = dirtyY ?? 0;
701
+ const sw = dirtyWidth ?? imageData.width;
702
+ const sh = dirtyHeight ?? imageData.height;
703
+
704
+ // Create a GdkPixbuf from the ImageData RGBA
705
+ const srcData = imageData.data;
706
+ const srcWidth = imageData.width;
707
+
708
+ // Create a temporary buffer for the dirty region (RGBA, no padding)
709
+ const regionData = new Uint8Array(sw * sh * 4);
710
+ for (let y = 0; y < sh; y++) {
711
+ for (let x = 0; x < sw; x++) {
712
+ const srcIdx = ((sy + y) * srcWidth + (sx + x)) * 4;
713
+ const dstIdx = (y * sw + x) * 4;
714
+ regionData[dstIdx] = srcData[srcIdx];
715
+ regionData[dstIdx + 1] = srcData[srcIdx + 1];
716
+ regionData[dstIdx + 2] = srcData[srcIdx + 2];
717
+ regionData[dstIdx + 3] = srcData[srcIdx + 3];
718
+ }
719
+ }
720
+
721
+ const pixbuf = GdkPixbuf.Pixbuf.new_from_bytes(
722
+ regionData as unknown as import('@girs/glib-2.0').default.Bytes,
723
+ GdkPixbuf.Colorspace.RGB,
724
+ true, // has_alpha
725
+ 8, // bits_per_sample
726
+ sw,
727
+ sh,
728
+ sw * 4, // rowstride
729
+ );
730
+
731
+ // putImageData per spec ignores compositing — always uses SOURCE operator
732
+ this._ctx.save();
733
+ this._ctx.setOperator(Cairo.Operator.SOURCE);
734
+ Gdk.cairo_set_source_pixbuf(this._ctx as any, pixbuf, dx + sx, dy + sy);
735
+ this._ctx.rectangle(dx + sx, dy + sy, sw, sh);
736
+ this._ctx.fill();
737
+ this._ctx.restore();
738
+ }
739
+
740
+ // ---- drawImage ----
741
+
742
+ drawImage(image: any, dx: number, dy: number): void;
743
+ drawImage(image: any, dx: number, dy: number, dw: number, dh: number): void;
744
+ drawImage(image: any, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void;
745
+ drawImage(
746
+ image: any,
747
+ a1: number, a2: number,
748
+ a3?: number, a4?: number,
749
+ a5?: number, a6?: number,
750
+ a7?: number, a8?: number,
751
+ ): void {
752
+ this._ensureSurface();
753
+ this._applyCompositing();
754
+
755
+ let sx: number, sy: number, sw: number, sh: number;
756
+ let dx: number, dy: number, dw: number, dh: number;
757
+
758
+ // Get source surface/pixbuf
759
+ const sourceInfo = this._getDrawImageSource(image);
760
+ if (!sourceInfo) return;
761
+ const { pixbuf, imgWidth, imgHeight } = sourceInfo;
762
+
763
+ if (a3 === undefined) {
764
+ // drawImage(image, dx, dy)
765
+ sx = 0; sy = 0; sw = imgWidth; sh = imgHeight;
766
+ dx = a1; dy = a2; dw = imgWidth; dh = imgHeight;
767
+ } else if (a5 === undefined) {
768
+ // drawImage(image, dx, dy, dw, dh)
769
+ sx = 0; sy = 0; sw = imgWidth; sh = imgHeight;
770
+ dx = a1; dy = a2; dw = a3; dh = a4!;
771
+ } else {
772
+ // drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
773
+ sx = a1; sy = a2; sw = a3; sh = a4!;
774
+ dx = a5; dy = a6!; dw = a7!; dh = a8!;
775
+ }
776
+
777
+ // Scale the source to fill the destination
778
+ this._ctx.save();
779
+ this._ctx.translate(dx, dy);
780
+ this._ctx.scale(dw / sw, dh / sh);
781
+ this._ctx.translate(-sx, -sy);
782
+
783
+ Gdk.cairo_set_source_pixbuf(this._ctx as any, pixbuf, 0, 0);
784
+ this._ctx.rectangle(sx, sy, sw, sh);
785
+ this._ctx.fill();
786
+ this._ctx.restore();
787
+ }
788
+
789
+ private _getDrawImageSource(image: any): { pixbuf: GdkPixbuf.Pixbuf; imgWidth: number; imgHeight: number } | null {
790
+ // HTMLImageElement (GdkPixbuf-backed)
791
+ if (typeof image?.isPixbuf === 'function' && image.isPixbuf()) {
792
+ const pixbuf = image._pixbuf as GdkPixbuf.Pixbuf;
793
+ return { pixbuf, imgWidth: pixbuf.get_width(), imgHeight: pixbuf.get_height() };
794
+ }
795
+
796
+ // HTMLCanvasElement with a 2D context
797
+ if (typeof image?.getContext === 'function') {
798
+ const ctx2d = image.getContext('2d');
799
+ if (ctx2d && typeof ctx2d._getSurface === 'function') {
800
+ const surface = ctx2d._getSurface() as Cairo.ImageSurface;
801
+ surface.flush();
802
+ const pixbuf = Gdk.pixbuf_get_from_surface(surface, 0, 0, image.width, image.height);
803
+ if (pixbuf) {
804
+ return { pixbuf, imgWidth: image.width, imgHeight: image.height };
805
+ }
806
+ }
807
+ }
808
+
809
+ return null;
810
+ }
811
+
812
+ // ---- Text methods (PangoCairo) ----
813
+
814
+ /** Create a PangoCairo layout configured with current font/text settings. */
815
+ private _createTextLayout(text: string): Pango.Layout {
816
+ const layout = PangoCairo.create_layout(this._ctx as any);
817
+ layout.set_text(text, -1);
818
+
819
+ // Force LTR base direction so text is never rendered mirrored
820
+ // regardless of system locale or Pango context defaults.
821
+ const pangoCtx = layout.get_context();
822
+ pangoCtx.set_base_dir(Pango.Direction.LTR);
823
+ layout.context_changed();
824
+
825
+ // Parse CSS font string into Pango font description
826
+ const fontDesc = this._parseFontToDescription(this._state.font);
827
+ layout.set_font_description(fontDesc);
828
+
829
+ return layout;
830
+ }
831
+
832
+ /** Parse a CSS font string (e.g. "bold 16px Arial") into a Pango.FontDescription. */
833
+ private _parseFontToDescription(cssFont: string): Pango.FontDescription {
834
+ // CSS font: [style] [variant] [weight] size[/line-height] family[, family...]
835
+ // Pango expects: "Family Weight Style Size" format
836
+ const match = cssFont.match(
837
+ /^\s*(italic|oblique|normal)?\s*(small-caps|normal)?\s*(bold|bolder|lighter|[1-9]00|normal)?\s*(\d+(?:\.\d+)?)(px|pt|em|rem|%)?\s*(?:\/\S+)?\s*(.+)?$/i
838
+ );
839
+
840
+ if (!match) {
841
+ // Fallback: pass directly to Pango
842
+ return Pango.font_description_from_string(cssFont);
843
+ }
844
+
845
+ const style = match[1] || '';
846
+ const weight = match[3] || '';
847
+ let size = parseFloat(match[4]) || 10;
848
+ const unit = match[5] || 'px';
849
+ const family = (match[6] || 'sans-serif').replace(/['"]/g, '').trim();
850
+
851
+ // Convert units to points (Pango uses points)
852
+ if (unit === 'px') size = size * 0.75; // 1px = 0.75pt approximately
853
+ else if (unit === 'em' || unit === 'rem') size = size * 12; // assume 16px base = 12pt
854
+ else if (unit === '%') size = (size / 100) * 12;
855
+
856
+ let pangoStr = family;
857
+ if (style === 'italic') pangoStr += ' Italic';
858
+ else if (style === 'oblique') pangoStr += ' Oblique';
859
+ if (weight === 'bold' || weight === 'bolder' || (parseInt(weight) >= 600)) pangoStr += ' Bold';
860
+ else if (weight === 'lighter' || (parseInt(weight) > 0 && parseInt(weight) <= 300)) pangoStr += ' Light';
861
+ pangoStr += ` ${Math.round(size)}`;
862
+
863
+ return Pango.font_description_from_string(pangoStr);
864
+ }
865
+
866
+ /**
867
+ * Compute the x-offset for text alignment relative to the given x coordinate.
868
+ */
869
+ private _getTextAlignOffset(layout: Pango.Layout): number {
870
+ const [, logicalRect] = layout.get_pixel_extents();
871
+ const width = logicalRect.width;
872
+
873
+ switch (this._state.textAlign) {
874
+ case 'center': return -width / 2;
875
+ case 'right':
876
+ case 'end': return -width;
877
+ case 'left':
878
+ case 'start':
879
+ default: return 0;
880
+ }
881
+ }
882
+
883
+ /**
884
+ * Compute the y-offset for text baseline positioning.
885
+ *
886
+ * PangoCairo.show_layout() places the layout TOP-LEFT at the current Cairo point
887
+ * (not the baseline). Within the layout, the first line's baseline is at
888
+ * approximately `ascent` pixels below the layout top.
889
+ *
890
+ * For CSS textBaseline semantics, we shift the current point UP (negative offset)
891
+ * so the layout top lands at the right position relative to the user's y coordinate.
892
+ */
893
+ private _getTextBaselineOffset(layout: Pango.Layout): number {
894
+ const fontDesc = layout.get_font_description() || this._parseFontToDescription(this._state.font);
895
+ const context = layout.get_context();
896
+ const metrics = context.get_metrics(fontDesc, null);
897
+ const ascent = metrics.get_ascent() / Pango.SCALE;
898
+ const descent = metrics.get_descent() / Pango.SCALE;
899
+ const height = ascent + descent;
900
+
901
+ // layout top = current point; baseline within layout ≈ ascent below top.
902
+ // yOff is added to user's y to get the layout top-left y.
903
+ switch (this._state.textBaseline) {
904
+ case 'top': return 0; // top of em square = y
905
+ case 'hanging': return -(ascent * 0.2); // hanging ≈ 0.2*ascent below top
906
+ case 'middle': return -(height / 2); // center of em square = y
907
+ case 'alphabetic': return -ascent; // baseline = y
908
+ case 'ideographic': return -(ascent + descent * 0.5); // below alphabetic baseline
909
+ case 'bottom': return -height; // bottom of em square = y
910
+ default: return -ascent; // default = alphabetic
911
+ }
912
+ }
913
+
914
+ fillText(text: string, x: number, y: number, _maxWidth?: number): void {
915
+ this._ensureSurface();
916
+ this._applyCompositing();
917
+ this._applyFillStyle();
918
+
919
+ const layout = this._createTextLayout(text);
920
+ const xOff = this._getTextAlignOffset(layout);
921
+ const yOff = this._getTextBaselineOffset(layout);
922
+
923
+ this._ctx.save();
924
+ this._ctx.moveTo(x + xOff, y + yOff);
925
+ PangoCairo.show_layout(this._ctx as any, layout);
926
+ this._ctx.restore();
927
+ }
928
+
929
+ strokeText(text: string, x: number, y: number, _maxWidth?: number): void {
930
+ this._ensureSurface();
931
+ this._applyCompositing();
932
+ this._applyStrokeStyle();
933
+ this._applyLineStyle();
934
+
935
+ const layout = this._createTextLayout(text);
936
+ const xOff = this._getTextAlignOffset(layout);
937
+ const yOff = this._getTextBaselineOffset(layout);
938
+
939
+ this._ctx.save();
940
+ this._ctx.moveTo(x + xOff, y + yOff);
941
+ PangoCairo.layout_path(this._ctx as any, layout);
942
+ this._ctx.stroke();
943
+ this._ctx.restore();
944
+ }
945
+
946
+ measureText(text: string): TextMetrics {
947
+ this._ensureSurface();
948
+ const layout = this._createTextLayout(text);
949
+ const [inkRect, logicalRect] = layout.get_pixel_extents();
950
+ const fontDesc = layout.get_font_description() || this._parseFontToDescription(this._state.font);
951
+ const context = layout.get_context();
952
+ const metrics = context.get_metrics(fontDesc, null);
953
+ const ascent = metrics.get_ascent() / Pango.SCALE;
954
+ const descent = metrics.get_descent() / Pango.SCALE;
955
+
956
+ return {
957
+ width: logicalRect.width,
958
+ actualBoundingBoxAscent: ascent,
959
+ actualBoundingBoxDescent: descent,
960
+ actualBoundingBoxLeft: -inkRect.x,
961
+ actualBoundingBoxRight: inkRect.x + inkRect.width,
962
+ fontBoundingBoxAscent: ascent,
963
+ fontBoundingBoxDescent: descent,
964
+ alphabeticBaseline: 0,
965
+ emHeightAscent: ascent,
966
+ emHeightDescent: descent,
967
+ hangingBaseline: ascent * 0.8,
968
+ ideographicBaseline: -descent,
969
+ };
970
+ }
971
+
972
+ // ---- toDataURL/toBlob support ----
973
+
974
+ /**
975
+ * Write the canvas surface to a PNG file and return as data URL.
976
+ * Used by HTMLCanvasElement.toDataURL() when a '2d' context is active.
977
+ */
978
+ _toDataURL(type?: string, _quality?: number): string {
979
+ if (type && type !== 'image/png') {
980
+ // Cairo only supports PNG natively
981
+ // For other formats, return PNG anyway (per spec, PNG is the required format)
982
+ }
983
+ this._surface.flush();
984
+
985
+ // Write to a temp file, read back as base64
986
+ const Gio = imports.gi.Gio;
987
+ const GLib = imports.gi.GLib;
988
+ const [, tempPath] = GLib.file_open_tmp('canvas-XXXXXX.png');
989
+ try {
990
+ this._surface.writeToPNG(tempPath);
991
+ const file = Gio.File.new_for_path(tempPath);
992
+ const [, contents] = file.load_contents(null);
993
+ const base64 = GLib.base64_encode(contents);
994
+ return `data:image/png;base64,${base64}`;
995
+ } finally {
996
+ try { GLib.unlink(tempPath); } catch (_e) { /* ignore */ }
997
+ }
998
+ }
999
+
1000
+ // ---- Cleanup ----
1001
+
1002
+ /** Release native Cairo resources. Call when the canvas is discarded. */
1003
+ _dispose(): void {
1004
+ this._ctx.$dispose();
1005
+ this._surface.finish();
1006
+ }
1007
+ }