@gjsify/canvas2d-core 0.3.21 → 0.4.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.
@@ -1,1187 +0,0 @@
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
- this._applyPatternFilter();
93
- }
94
- }
95
-
96
- /** Apply the current stroke style to the Cairo context. */
97
- private _applyStrokeStyle(): void {
98
- const style = this._state.strokeStyle;
99
- if (typeof style === 'string') {
100
- const c = this._state.strokeColor;
101
- const a = c.a * this._state.globalAlpha;
102
- this._ctx.setSourceRGBA(c.r, c.g, c.b, a);
103
- } else if (style instanceof OurCanvasGradient) {
104
- this._ctx.setSource(style._getCairoPattern());
105
- } else if (style instanceof OurCanvasPattern) {
106
- this._ctx.setSource(style._getCairoPattern());
107
- this._applyPatternFilter();
108
- }
109
- }
110
-
111
- /**
112
- * Apply the current imageSmoothingEnabled + imageSmoothingQuality state
113
- * to the currently installed Cairo source pattern. Per Canvas 2D spec,
114
- * the filter is read from the context at *draw* time, not at pattern
115
- * creation — so we re-apply it on every fill/stroke.
116
- */
117
- private _applyPatternFilter(): void {
118
- const pat = (this._ctx as any).getSource?.();
119
- if (pat && typeof pat.setFilter === 'function') {
120
- let filter: number;
121
- if (!this._state.imageSmoothingEnabled) {
122
- filter = Cairo.Filter.NEAREST as unknown as number;
123
- } else if (this._state.imageSmoothingQuality === 'high') {
124
- filter = Cairo.Filter.BEST as unknown as number;
125
- } else {
126
- filter = Cairo.Filter.BILINEAR as unknown as number;
127
- }
128
- pat.setFilter(filter);
129
- }
130
- }
131
-
132
- /** Apply line properties to the Cairo context. */
133
- private _applyLineStyle(): void {
134
- this._ctx.setLineWidth(this._state.lineWidth);
135
- this._ctx.setLineCap(LINE_CAP_MAP[this._state.lineCap] as Cairo.LineCap);
136
- this._ctx.setLineJoin(LINE_JOIN_MAP[this._state.lineJoin] as Cairo.LineJoin);
137
- this._ctx.setMiterLimit(this._state.miterLimit);
138
- this._ctx.setDash(this._state.lineDash, this._state.lineDashOffset);
139
- }
140
-
141
- /** Apply compositing operator. */
142
- private _applyCompositing(): void {
143
- const op = COMPOSITE_OP_MAP[this._state.globalCompositeOperation];
144
- if (op !== undefined) {
145
- this._ctx.setOperator(op as Cairo.Operator);
146
- }
147
- }
148
-
149
- /** Get the Cairo ImageSurface (used by other contexts like drawImage). */
150
- _getSurface(): Cairo.ImageSurface {
151
- return this._surface;
152
- }
153
-
154
- /** Check if shadow rendering is needed. */
155
- private _hasShadow(): boolean {
156
- if (this._state.shadowBlur === 0 && this._state.shadowOffsetX === 0 && this._state.shadowOffsetY === 0) {
157
- return false;
158
- }
159
- const c = parseColor(this._state.shadowColor);
160
- return c !== null && c.a > 0;
161
- }
162
-
163
- /**
164
- * Convert a distance from device pixels to Cairo user space by inverting
165
- * the linear part of the current CTM (translation doesn't affect distances).
166
- *
167
- * Canvas 2D spec: shadowOffsetX/Y are in CSS pixels and are NOT scaled by
168
- * the current transform. This helper converts them to user-space offsets so
169
- * that `ctx.moveTo(x + sdx, y + sdy)` produces the correct pixel offset
170
- * regardless of any ctx.scale() or ctx.rotate() in effect.
171
- */
172
- private _deviceToUserDistance(dx: number, dy: number): [number, number] {
173
- const origin = (this._ctx as any).userToDevice(0, 0);
174
- const xAxis = (this._ctx as any).userToDevice(1, 0);
175
- const yAxis = (this._ctx as any).userToDevice(0, 1);
176
- const a = (xAxis[0] ?? 0) - (origin[0] ?? 0);
177
- const b = (xAxis[1] ?? 0) - (origin[1] ?? 0);
178
- const c = (yAxis[0] ?? 0) - (origin[0] ?? 0);
179
- const d = (yAxis[1] ?? 0) - (origin[1] ?? 0);
180
- const det = a * d - b * c;
181
- if (Math.abs(det) < 1e-10) return [dx, dy]; // degenerate transform — no conversion
182
- return [
183
- ( d * dx - c * dy) / det,
184
- (-b * dx + a * dy) / det,
185
- ];
186
- }
187
-
188
- /**
189
- * Shadow rendering is intentionally a no-op.
190
- *
191
- * Proper Canvas 2D shadows require a Gaussian blur pass on an isolated
192
- * temporary surface, which cannot be emulated reliably without a full
193
- * Path2D replay or pixel-level manipulation. The previous implementation
194
- * attempted to use a temp surface but never replayed the path onto it
195
- * (because `drawOp` closes over the main context), leaving the shadow
196
- * surface empty while still leaking memory.
197
- *
198
- * Excalibur and most 2D game engines bake glow/outline effects into
199
- * sprites rather than relying on canvas shadows, so this no-op does not
200
- * affect the showcase. A correct implementation is tracked as a
201
- * separate Canvas 2D Phase-5 enhancement.
202
- */
203
- private _renderShadow(_drawOp: () => void): void {
204
- // Intentionally empty. See the doc-comment above.
205
- }
206
-
207
- // ---- State ----
208
-
209
- save(): void {
210
- this._ensureSurface();
211
- this._stateStack.push(cloneState(this._state));
212
- this._ctx.save();
213
- }
214
-
215
- restore(): void {
216
- this._ensureSurface();
217
- const prev = this._stateStack.pop();
218
- if (prev) {
219
- this._state = prev;
220
- this._ctx.restore();
221
- }
222
- }
223
-
224
- // ---- Transforms ----
225
-
226
- translate(x: number, y: number): void {
227
- this._ensureSurface();
228
- this._ctx.translate(x, y);
229
- }
230
-
231
- rotate(angle: number): void {
232
- this._ensureSurface();
233
- this._ctx.rotate(angle);
234
- }
235
-
236
- scale(x: number, y: number): void {
237
- this._ensureSurface();
238
- this._ctx.scale(x, y);
239
- }
240
-
241
- /**
242
- * Multiply the current transformation matrix by the given values.
243
- * Matrix: [a c e]
244
- * [b d f]
245
- * [0 0 1]
246
- */
247
- transform(a: number, b: number, c: number, d: number, e: number, f: number): void {
248
- this._ensureSurface();
249
- // Guard against NaN / undefined / Infinity — Cairo will hard-crash
250
- // on invalid matrix values.
251
- if (!Number.isFinite(a) || !Number.isFinite(b) || !Number.isFinite(c) ||
252
- !Number.isFinite(d) || !Number.isFinite(e) || !Number.isFinite(f)) {
253
- return;
254
- }
255
- // Cairo.Context in GJS does NOT expose a generic `transform(matrix)` /
256
- // `setMatrix()` call — only `translate()`, `rotate()`, `scale()` and
257
- // `identityMatrix()`. So we decompose the affine 2D matrix
258
- // [a c e]
259
- // [b d f]
260
- // [0 0 1]
261
- // into translate + rotate + scale (ignoring shear, which Excalibur /
262
- // three.js 2D users don't rely on). Shear would require a combined
263
- // matrix multiply, which isn't available in this binding.
264
- const tx = e;
265
- const ty = f;
266
- const sx = Math.hypot(a, b);
267
- const sy = Math.hypot(c, d);
268
- const rotation = Math.atan2(b, a);
269
- this._ctx.translate(tx, ty);
270
- if (rotation !== 0) this._ctx.rotate(rotation);
271
- if (sx !== 1 || sy !== 1) this._ctx.scale(sx, sy);
272
- }
273
-
274
- /**
275
- * Reset the transform to identity, then apply the given matrix.
276
- */
277
- setTransform(matrix?: DOMMatrix2DInit): void;
278
- setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void;
279
- setTransform(a?: number | DOMMatrix2DInit, b?: number, c?: number, d?: number, e?: number, f?: number): void {
280
- this._ensureSurface();
281
- if (typeof a === 'object' && a !== null) {
282
- const m = a;
283
- this._ctx.identityMatrix();
284
- this.transform(
285
- m.a ?? m.m11 ?? 1, m.b ?? m.m12 ?? 0,
286
- m.c ?? m.m21 ?? 0, m.d ?? m.m22 ?? 1,
287
- m.e ?? m.m41 ?? 0, m.f ?? m.m42 ?? 0,
288
- );
289
- } else if (typeof a === 'number') {
290
- this._ctx.identityMatrix();
291
- this.transform(a, b!, c!, d!, e!, f!);
292
- } else {
293
- this._ctx.identityMatrix();
294
- }
295
- }
296
-
297
- /**
298
- * Return the current transformation matrix as a DOMMatrix-like object.
299
- */
300
- getTransform(): DOMMatrix {
301
- // Cairo.Context in GJS doesn't expose `getMatrix()`, but it does
302
- // expose `userToDevice(x, y)`. We reconstruct the current affine
303
- // matrix [a,b,c,d,e,f] by transforming three reference points:
304
- // userToDevice(0, 0) = (e, f) — translation
305
- // userToDevice(1, 0) = (a + e, b + f) — first basis vector
306
- // userToDevice(0, 1) = (c + e, d + f) — second basis vector
307
- const origin = (this._ctx as any).userToDevice(0, 0);
308
- const xAxis = (this._ctx as any).userToDevice(1, 0);
309
- const yAxis = (this._ctx as any).userToDevice(0, 1);
310
- const e = origin[0] ?? 0;
311
- const f = origin[1] ?? 0;
312
- const a = (xAxis[0] ?? 0) - e;
313
- const b = (xAxis[1] ?? 0) - f;
314
- const c = (yAxis[0] ?? 0) - e;
315
- const d = (yAxis[1] ?? 0) - f;
316
-
317
- const DOMMatrixCtor = (globalThis as any).DOMMatrix;
318
- if (typeof DOMMatrixCtor === 'function') {
319
- return new DOMMatrixCtor([a, b, c, d, e, f]);
320
- }
321
- return {
322
- a, b, c, d, e, f,
323
- m11: a, m12: b, m13: 0, m14: 0,
324
- m21: c, m22: d, m23: 0, m24: 0,
325
- m31: 0, m32: 0, m33: 1, m34: 0,
326
- m41: e, m42: f, m43: 0, m44: 1,
327
- is2D: true,
328
- isIdentity: (a === 1 && b === 0 && c === 0 && d === 1 && e === 0 && f === 0),
329
- } as any;
330
- }
331
-
332
- resetTransform(): void {
333
- this._ensureSurface();
334
- this._ctx.identityMatrix();
335
- }
336
-
337
- // ---- Style properties ----
338
-
339
- get fillStyle(): string | CanvasGradient | CanvasPattern {
340
- return this._state.fillStyle;
341
- }
342
-
343
- set fillStyle(value: string | CanvasGradient | CanvasPattern) {
344
- if (typeof value === 'string') {
345
- const parsed = parseColor(value);
346
- if (parsed) {
347
- this._state.fillStyle = value;
348
- this._state.fillColor = parsed;
349
- }
350
- } else {
351
- this._state.fillStyle = value;
352
- }
353
- }
354
-
355
- get strokeStyle(): string | CanvasGradient | CanvasPattern {
356
- return this._state.strokeStyle;
357
- }
358
-
359
- set strokeStyle(value: string | CanvasGradient | CanvasPattern) {
360
- if (typeof value === 'string') {
361
- const parsed = parseColor(value);
362
- if (parsed) {
363
- this._state.strokeStyle = value;
364
- this._state.strokeColor = parsed;
365
- }
366
- } else {
367
- this._state.strokeStyle = value;
368
- }
369
- }
370
-
371
- get lineWidth(): number { return this._state.lineWidth; }
372
- set lineWidth(value: number) {
373
- if (value > 0 && isFinite(value)) this._state.lineWidth = value;
374
- }
375
-
376
- get lineCap(): CanvasLineCap { return this._state.lineCap; }
377
- set lineCap(value: CanvasLineCap) {
378
- if (value === 'butt' || value === 'round' || value === 'square') {
379
- this._state.lineCap = value;
380
- }
381
- }
382
-
383
- get lineJoin(): CanvasLineJoin { return this._state.lineJoin; }
384
- set lineJoin(value: CanvasLineJoin) {
385
- if (value === 'miter' || value === 'round' || value === 'bevel') {
386
- this._state.lineJoin = value;
387
- }
388
- }
389
-
390
- get miterLimit(): number { return this._state.miterLimit; }
391
- set miterLimit(value: number) {
392
- if (value > 0 && isFinite(value)) this._state.miterLimit = value;
393
- }
394
-
395
- get globalAlpha(): number { return this._state.globalAlpha; }
396
- set globalAlpha(value: number) {
397
- if (value >= 0 && value <= 1 && isFinite(value)) this._state.globalAlpha = value;
398
- }
399
-
400
- get globalCompositeOperation(): GlobalCompositeOperation {
401
- return this._state.globalCompositeOperation;
402
- }
403
-
404
- set globalCompositeOperation(value: GlobalCompositeOperation) {
405
- if (COMPOSITE_OP_MAP[value] !== undefined) {
406
- this._state.globalCompositeOperation = value;
407
- }
408
- }
409
-
410
- get imageSmoothingEnabled(): boolean { return this._state.imageSmoothingEnabled; }
411
- set imageSmoothingEnabled(value: boolean) { this._state.imageSmoothingEnabled = !!value; }
412
-
413
- get imageSmoothingQuality(): ImageSmoothingQuality { return this._state.imageSmoothingQuality; }
414
- set imageSmoothingQuality(value: ImageSmoothingQuality) {
415
- if (value === 'low' || value === 'medium' || value === 'high') {
416
- this._state.imageSmoothingQuality = value;
417
- }
418
- }
419
-
420
- // Line dash
421
- setLineDash(segments: number[]): void {
422
- // Per spec, ignore if any value is negative or non-finite
423
- if (segments.some(v => v < 0 || !isFinite(v))) return;
424
- this._state.lineDash = [...segments];
425
- }
426
-
427
- getLineDash(): number[] {
428
- return [...this._state.lineDash];
429
- }
430
-
431
- get lineDashOffset(): number { return this._state.lineDashOffset; }
432
- set lineDashOffset(value: number) {
433
- if (isFinite(value)) this._state.lineDashOffset = value;
434
- }
435
-
436
- // ---- Shadow properties (stored in state, rendering in Phase 5) ----
437
- get shadowColor(): string { return this._state.shadowColor; }
438
- set shadowColor(value: string) { this._state.shadowColor = value; }
439
- get shadowBlur(): number { return this._state.shadowBlur; }
440
- set shadowBlur(value: number) { if (value >= 0 && isFinite(value)) this._state.shadowBlur = value; }
441
- get shadowOffsetX(): number { return this._state.shadowOffsetX; }
442
- set shadowOffsetX(value: number) { if (isFinite(value)) this._state.shadowOffsetX = value; }
443
- get shadowOffsetY(): number { return this._state.shadowOffsetY; }
444
- set shadowOffsetY(value: number) { if (isFinite(value)) this._state.shadowOffsetY = value; }
445
-
446
- // ---- Text properties (stored in state, rendering in Phase 4) ----
447
- get font(): string { return this._state.font; }
448
- set font(value: string) { this._state.font = value; }
449
- get textAlign(): CanvasTextAlign { return this._state.textAlign; }
450
- set textAlign(value: CanvasTextAlign) { this._state.textAlign = value; }
451
- get textBaseline(): CanvasTextBaseline { return this._state.textBaseline; }
452
- set textBaseline(value: CanvasTextBaseline) { this._state.textBaseline = value; }
453
- get direction(): CanvasDirection { return this._state.direction; }
454
- set direction(value: CanvasDirection) { this._state.direction = value; }
455
-
456
- // ---- Path methods ----
457
-
458
- beginPath(): void {
459
- this._ensureSurface();
460
- this._ctx.newPath();
461
- }
462
-
463
- moveTo(x: number, y: number): void {
464
- this._ensureSurface();
465
- this._ctx.moveTo(x, y);
466
- }
467
-
468
- lineTo(x: number, y: number): void {
469
- this._ensureSurface();
470
- this._ctx.lineTo(x, y);
471
- }
472
-
473
- closePath(): void {
474
- this._ensureSurface();
475
- this._ctx.closePath();
476
- }
477
-
478
- bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void {
479
- this._ensureSurface();
480
- this._ctx.curveTo(cp1x, cp1y, cp2x, cp2y, x, y);
481
- }
482
-
483
- quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void {
484
- this._ensureSurface();
485
- let cx: number, cy: number;
486
- if (this._ctx.hasCurrentPoint()) {
487
- [cx, cy] = this._ctx.getCurrentPoint();
488
- } else {
489
- cx = cpx;
490
- cy = cpy;
491
- }
492
- const { cp1x, cp1y, cp2x, cp2y } = quadraticToCubic(cx, cy, cpx, cpy, x, y);
493
- this._ctx.curveTo(cp1x, cp1y, cp2x, cp2y, x, y);
494
- }
495
-
496
- arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise = false): void {
497
- this._ensureSurface();
498
- // Browsers draw a full circle when |endAngle - startAngle| >= 2π,
499
- // regardless of direction. Cairo's arcNegative would produce a
500
- // zero-length arc for arcNegative(x,y,r,0,2π) because it normalizes
501
- // endAngle to be < startAngle, collapsing the arc to nothing.
502
- if (Math.abs(endAngle - startAngle) >= 2 * Math.PI) {
503
- this._ctx.arc(x, y, radius, 0, 2 * Math.PI);
504
- return;
505
- }
506
- if (counterclockwise) {
507
- this._ctx.arcNegative(x, y, radius, startAngle, endAngle);
508
- } else {
509
- this._ctx.arc(x, y, radius, startAngle, endAngle);
510
- }
511
- }
512
-
513
- arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void {
514
- this._ensureSurface();
515
- let x0: number, y0: number;
516
- if (this._ctx.hasCurrentPoint()) {
517
- [x0, y0] = this._ctx.getCurrentPoint();
518
- } else {
519
- x0 = x1;
520
- y0 = y1;
521
- this._ctx.moveTo(x1, y1);
522
- }
523
- cairoArcTo(this._ctx, x0, y0, x1, y1, x2, y2, radius);
524
- }
525
-
526
- ellipse(
527
- x: number, y: number,
528
- radiusX: number, radiusY: number,
529
- rotation: number,
530
- startAngle: number, endAngle: number,
531
- counterclockwise = false,
532
- ): void {
533
- this._ensureSurface();
534
- if (radiusX < 0 || radiusY < 0) {
535
- throw new RangeError('The radii provided are negative');
536
- }
537
- cairoEllipse(this._ctx, x, y, radiusX, radiusY, rotation, startAngle, endAngle, counterclockwise);
538
- }
539
-
540
- rect(x: number, y: number, w: number, h: number): void {
541
- this._ensureSurface();
542
- this._ctx.rectangle(x, y, w, h);
543
- }
544
-
545
- roundRect(x: number, y: number, w: number, h: number, radii: number | number[] = 0): void {
546
- this._ensureSurface();
547
- cairoRoundRect(this._ctx, x, y, w, h, radii);
548
- }
549
-
550
- // ---- Drawing methods ----
551
-
552
- fill(fillRule?: CanvasFillRule): void;
553
- fill(path: Path2D, fillRule?: CanvasFillRule): void;
554
- fill(pathOrRule?: Path2D | CanvasFillRule, fillRule?: CanvasFillRule): void {
555
- this._ensureSurface();
556
- this._applyCompositing();
557
- this._applyFillStyle();
558
-
559
- let rule: CanvasFillRule | undefined;
560
- if (pathOrRule instanceof Path2D) {
561
- this._ctx.newPath();
562
- pathOrRule._replayOnCairo(this._ctx);
563
- rule = fillRule;
564
- } else {
565
- rule = pathOrRule;
566
- }
567
-
568
- this._ctx.setFillRule(rule === 'evenodd' ? Cairo.FillRule.EVEN_ODD : Cairo.FillRule.WINDING);
569
- this._ctx.fillPreserve();
570
- }
571
-
572
- stroke(): void;
573
- stroke(path: Path2D): void;
574
- stroke(path?: Path2D): void {
575
- this._ensureSurface();
576
- this._applyCompositing();
577
- this._applyStrokeStyle();
578
- this._applyLineStyle();
579
-
580
- if (path instanceof Path2D) {
581
- this._ctx.newPath();
582
- path._replayOnCairo(this._ctx);
583
- }
584
-
585
- this._ctx.strokePreserve();
586
- }
587
-
588
- fillRect(x: number, y: number, w: number, h: number): void {
589
- this._ensureSurface();
590
- this._applyCompositing();
591
- // Per spec: fillRect must not affect the current path.
592
- // Save current path, draw the rect in an isolated path, then restore.
593
- const savedPath = this._ctx.copyPath();
594
- if (this._hasShadow()) {
595
- this._renderShadow(() => {
596
- this._ctx.newPath();
597
- this._ctx.rectangle(x, y, w, h);
598
- this._ctx.fill();
599
- });
600
- }
601
- this._applyFillStyle();
602
- this._ctx.newPath();
603
- this._ctx.rectangle(x, y, w, h);
604
- this._ctx.fill();
605
- this._ctx.newPath();
606
- this._ctx.appendPath(savedPath);
607
- }
608
-
609
- strokeRect(x: number, y: number, w: number, h: number): void {
610
- this._ensureSurface();
611
- this._applyCompositing();
612
- // Per spec: strokeRect must not affect the current path.
613
- const savedPath = this._ctx.copyPath();
614
- if (this._hasShadow()) {
615
- this._renderShadow(() => {
616
- this._ctx.newPath();
617
- this._ctx.rectangle(x, y, w, h);
618
- this._ctx.stroke();
619
- });
620
- }
621
- this._applyStrokeStyle();
622
- this._applyLineStyle();
623
- this._ctx.newPath();
624
- this._ctx.rectangle(x, y, w, h);
625
- this._ctx.stroke();
626
- this._ctx.newPath();
627
- this._ctx.appendPath(savedPath);
628
- }
629
-
630
- clearRect(x: number, y: number, w: number, h: number): void {
631
- this._ensureSurface();
632
- // Per spec: clearRect must not affect the current path.
633
- const savedPath = this._ctx.copyPath();
634
- this._ctx.save();
635
- this._ctx.setOperator(Cairo.Operator.CLEAR);
636
- this._ctx.newPath();
637
- this._ctx.rectangle(x, y, w, h);
638
- this._ctx.fill();
639
- this._ctx.restore();
640
- this._ctx.newPath();
641
- this._ctx.appendPath(savedPath);
642
- }
643
-
644
- // ---- Clipping ----
645
-
646
- clip(fillRule?: CanvasFillRule): void;
647
- clip(path: Path2D, fillRule?: CanvasFillRule): void;
648
- clip(pathOrRule?: Path2D | CanvasFillRule, fillRule?: CanvasFillRule): void {
649
- this._ensureSurface();
650
- let rule: CanvasFillRule | undefined;
651
- if (pathOrRule instanceof Path2D) {
652
- this._ctx.newPath();
653
- pathOrRule._replayOnCairo(this._ctx);
654
- rule = fillRule;
655
- } else {
656
- rule = pathOrRule;
657
- }
658
- this._ctx.setFillRule(rule === 'evenodd' ? Cairo.FillRule.EVEN_ODD : Cairo.FillRule.WINDING);
659
- this._ctx.clip();
660
- }
661
-
662
- // ---- Hit testing ----
663
-
664
- isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean;
665
- isPointInPath(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean;
666
- isPointInPath(pathOrX: Path2D | number, xOrY: number, fillRuleOrY?: CanvasFillRule | number, fillRule?: CanvasFillRule): boolean {
667
- this._ensureSurface();
668
- let x: number, y: number, rule: CanvasFillRule | undefined;
669
- if (pathOrX instanceof Path2D) {
670
- this._ctx.newPath();
671
- pathOrX._replayOnCairo(this._ctx);
672
- x = xOrY; y = fillRuleOrY as number; rule = fillRule;
673
- } else {
674
- x = pathOrX; y = xOrY; rule = fillRuleOrY as CanvasFillRule | undefined;
675
- }
676
- this._ctx.setFillRule(rule === 'evenodd' ? Cairo.FillRule.EVEN_ODD : Cairo.FillRule.WINDING);
677
- return this._ctx.inFill(x, y);
678
- }
679
-
680
- isPointInStroke(x: number, y: number): boolean;
681
- isPointInStroke(path: Path2D, x: number, y: number): boolean;
682
- isPointInStroke(pathOrX: Path2D | number, xOrY: number, y?: number): boolean {
683
- this._ensureSurface();
684
- this._applyLineStyle();
685
- if (pathOrX instanceof Path2D) {
686
- this._ctx.newPath();
687
- pathOrX._replayOnCairo(this._ctx);
688
- return this._ctx.inStroke(xOrY, y!);
689
- }
690
- return this._ctx.inStroke(pathOrX, xOrY);
691
- }
692
-
693
- // ---- Gradient / Pattern factories ----
694
-
695
- createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient {
696
- return new OurCanvasGradient('linear', x0, y0, x1, y1) as any;
697
- }
698
-
699
- createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient {
700
- return new OurCanvasGradient('radial', x0, y0, x1, y1, r0, r1) as any;
701
- }
702
-
703
- createPattern(image: any, repetition: string | null): CanvasPattern | null {
704
- return OurCanvasPattern.create(image, repetition) as any;
705
- }
706
-
707
- // ---- Image data methods ----
708
-
709
- createImageData(sw: number, sh: number): ImageData;
710
- createImageData(imagedata: ImageData): ImageData;
711
- createImageData(swOrImageData: number | ImageData, sh?: number): ImageData {
712
- if (typeof swOrImageData === 'number') {
713
- return new OurImageData(Math.abs(swOrImageData), Math.abs(sh!)) as any;
714
- }
715
- return new OurImageData(swOrImageData.width, swOrImageData.height) as any;
716
- }
717
-
718
- getImageData(sx: number, sy: number, sw: number, sh: number): ImageData {
719
- this._ensureSurface();
720
- this._surface.flush();
721
-
722
- // Use Gdk.pixbuf_get_from_surface to read pixels
723
- const pixbuf = Gdk.pixbuf_get_from_surface(this._surface, sx, sy, sw, sh);
724
- if (!pixbuf) {
725
- return new OurImageData(sw, sh) as any;
726
- }
727
-
728
- const pixels = pixbuf.get_pixels();
729
- const hasAlpha = pixbuf.get_has_alpha();
730
- const rowstride = pixbuf.get_rowstride();
731
- const nChannels = pixbuf.get_n_channels();
732
- const out = new Uint8ClampedArray(sw * sh * 4);
733
-
734
- for (let y = 0; y < sh; y++) {
735
- for (let x = 0; x < sw; x++) {
736
- const srcIdx = y * rowstride + x * nChannels;
737
- const dstIdx = (y * sw + x) * 4;
738
- out[dstIdx] = pixels[srcIdx]; // R
739
- out[dstIdx + 1] = pixels[srcIdx + 1]; // G
740
- out[dstIdx + 2] = pixels[srcIdx + 2]; // B
741
- out[dstIdx + 3] = hasAlpha ? pixels[srcIdx + 3] : 255; // A
742
- }
743
- }
744
-
745
- return new OurImageData(out, sw, sh) as any;
746
- }
747
-
748
- putImageData(imageData: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void {
749
- this._ensureSurface();
750
-
751
- // Determine the dirty region
752
- const sx = dirtyX ?? 0;
753
- const sy = dirtyY ?? 0;
754
- const sw = dirtyWidth ?? imageData.width;
755
- const sh = dirtyHeight ?? imageData.height;
756
-
757
- // Create a GdkPixbuf from the ImageData RGBA
758
- const srcData = imageData.data;
759
- const srcWidth = imageData.width;
760
-
761
- // Create a temporary buffer for the dirty region (RGBA, no padding)
762
- const regionData = new Uint8Array(sw * sh * 4);
763
- for (let y = 0; y < sh; y++) {
764
- for (let x = 0; x < sw; x++) {
765
- const srcIdx = ((sy + y) * srcWidth + (sx + x)) * 4;
766
- const dstIdx = (y * sw + x) * 4;
767
- regionData[dstIdx] = srcData[srcIdx];
768
- regionData[dstIdx + 1] = srcData[srcIdx + 1];
769
- regionData[dstIdx + 2] = srcData[srcIdx + 2];
770
- regionData[dstIdx + 3] = srcData[srcIdx + 3];
771
- }
772
- }
773
-
774
- const pixbuf = GdkPixbuf.Pixbuf.new_from_bytes(
775
- regionData as unknown as import('@girs/glib-2.0').default.Bytes,
776
- GdkPixbuf.Colorspace.RGB,
777
- true, // has_alpha
778
- 8, // bits_per_sample
779
- sw,
780
- sh,
781
- sw * 4, // rowstride
782
- );
783
-
784
- // putImageData per spec ignores compositing — always uses SOURCE operator
785
- this._ctx.save();
786
- this._ctx.setOperator(Cairo.Operator.SOURCE);
787
- Gdk.cairo_set_source_pixbuf(this._ctx as any, pixbuf, dx + sx, dy + sy);
788
- this._ctx.rectangle(dx + sx, dy + sy, sw, sh);
789
- this._ctx.fill();
790
- this._ctx.restore();
791
- }
792
-
793
- // ---- drawImage ----
794
-
795
- drawImage(image: any, dx: number, dy: number): void;
796
- drawImage(image: any, dx: number, dy: number, dw: number, dh: number): void;
797
- drawImage(image: any, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void;
798
- drawImage(
799
- image: any,
800
- a1: number, a2: number,
801
- a3?: number, a4?: number,
802
- a5?: number, a6?: number,
803
- a7?: number, a8?: number,
804
- ): void {
805
- this._ensureSurface();
806
- this._applyCompositing();
807
-
808
- let sx: number, sy: number, sw: number, sh: number;
809
- let dx: number, dy: number, dw: number, dh: number;
810
-
811
- // Get source surface/pixbuf
812
- const sourceInfo = this._getDrawImageSource(image);
813
- if (!sourceInfo) return;
814
- const { pixbuf, imgWidth, imgHeight } = sourceInfo;
815
-
816
- if (a3 === undefined) {
817
- // drawImage(image, dx, dy)
818
- sx = 0; sy = 0; sw = imgWidth; sh = imgHeight;
819
- dx = a1; dy = a2; dw = imgWidth; dh = imgHeight;
820
- } else if (a5 === undefined) {
821
- // drawImage(image, dx, dy, dw, dh)
822
- sx = 0; sy = 0; sw = imgWidth; sh = imgHeight;
823
- dx = a1; dy = a2; dw = a3; dh = a4!;
824
- } else {
825
- // drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
826
- sx = a1; sy = a2; sw = a3; sh = a4!;
827
- dx = a5; dy = a6!; dw = a7!; dh = a8!;
828
- }
829
-
830
- // Spec: drawImage with any zero-width/height source or destination
831
- // rectangle is a no-op (and MUST NOT throw). Without this guard,
832
- // `scale(dw / sw, dh / sh)` produces 0 or Infinity which Cairo
833
- // rejects with "invalid matrix (not invertible)".
834
- //
835
- // Non-finite (NaN / Infinity / -Infinity) inputs reach us when the
836
- // caller derives a dimension from a not-yet-resized canvas (e.g.
837
- // Excalibur's logo overlay computes `Math.min(logoWidth, n * 0.75)`
838
- // before the engine's pixelRatio / canvas size are known). Treat
839
- // them the same as 0: spec-correct, and avoids cascading Cairo
840
- // matrix failures that abort frames mid-paint.
841
- if (
842
- !Number.isFinite(sx) || !Number.isFinite(sy) ||
843
- !Number.isFinite(sw) || !Number.isFinite(sh) ||
844
- !Number.isFinite(dx) || !Number.isFinite(dy) ||
845
- !Number.isFinite(dw) || !Number.isFinite(dh) ||
846
- sw === 0 || sh === 0 || dw === 0 || dh === 0
847
- ) {
848
- return;
849
- }
850
-
851
- // Clip to the destination rectangle so the source pattern is only
852
- // painted inside it; this lets us use paint() (which fills the
853
- // entire clip) + paintWithAlpha() for globalAlpha support.
854
- this._ctx.save();
855
- this._ctx.rectangle(dx, dy, dw, dh);
856
- this._ctx.clip();
857
-
858
- // Scale the source to fill the destination
859
- this._ctx.translate(dx, dy);
860
- this._ctx.scale(dw / sw, dh / sh);
861
- this._ctx.translate(-sx, -sy);
862
-
863
- Gdk.cairo_set_source_pixbuf(this._ctx as any, pixbuf, 0, 0);
864
-
865
- // Apply Cairo interpolation filter based on imageSmoothingEnabled +
866
- // imageSmoothingQuality. setSource installs a fresh SurfacePattern and
867
- // resets any filter to Cairo's default (BILINEAR), so setFilter MUST
868
- // be called between setSource and paint. Without this, Excalibur's
869
- // pixel-art mode (imageSmoothingEnabled=false) renders blurry because
870
- // Cairo uses bilinear interpolation by default.
871
- //
872
- // Cairo.Filter values (verified runtime in GJS 1.86):
873
- // FAST=0 GOOD=1 BEST=2 NEAREST=3 BILINEAR=4 GAUSSIAN=5
874
- // GIR typings are incomplete for Cairo.SurfacePattern so we go via any.
875
- const pat = (this._ctx as any).getSource?.();
876
- if (pat && typeof pat.setFilter === 'function') {
877
- let filter: number;
878
- if (!this._state.imageSmoothingEnabled) {
879
- filter = Cairo.Filter.NEAREST as unknown as number;
880
- } else if (this._state.imageSmoothingQuality === 'high') {
881
- filter = Cairo.Filter.BEST as unknown as number;
882
- } else {
883
- filter = Cairo.Filter.BILINEAR as unknown as number;
884
- }
885
- pat.setFilter(filter);
886
- }
887
-
888
- // paint() vs fill(): paint() composites the current source over the
889
- // current clip region uniformly, honoring paintWithAlpha for global
890
- // alpha multiplication. fill() would require a rectangle path and
891
- // doesn't support per-draw alpha, so paint() is the spec-correct
892
- // choice for drawImage. The clip above confines the paint to dx,dy,dw,dh.
893
- if (this._state.globalAlpha < 1) {
894
- (this._ctx as any).paintWithAlpha(this._state.globalAlpha);
895
- } else {
896
- this._ctx.paint();
897
- }
898
- this._ctx.restore();
899
- }
900
-
901
- private _getDrawImageSource(image: any): { pixbuf: GdkPixbuf.Pixbuf; imgWidth: number; imgHeight: number } | null {
902
- // HTMLImageElement (GdkPixbuf-backed)
903
- if (typeof image?.isPixbuf === 'function' && image.isPixbuf()) {
904
- const pixbuf = image._pixbuf as GdkPixbuf.Pixbuf;
905
- return { pixbuf, imgWidth: pixbuf.get_width(), imgHeight: pixbuf.get_height() };
906
- }
907
-
908
- // HTMLCanvasElement with a 2D context
909
- if (typeof image?.getContext === 'function') {
910
- const w = image.width;
911
- const h = image.height;
912
- // Reject non-positive / non-finite dimensions before they reach
913
- // GdkPixbuf — `pixbuf_get_from_surface` logs a GLib-CRITICAL on
914
- // `width > 0 && height > 0` assertion failure for NaN/0 inputs.
915
- if (!Number.isFinite(w) || !Number.isFinite(h) || w <= 0 || h <= 0) {
916
- return null;
917
- }
918
- const ctx2d = image.getContext('2d');
919
- if (ctx2d && typeof ctx2d._getSurface === 'function') {
920
- const surface = ctx2d._getSurface() as Cairo.ImageSurface;
921
- surface.flush();
922
- const pixbuf = Gdk.pixbuf_get_from_surface(surface, 0, 0, w, h);
923
- if (pixbuf) {
924
- return { pixbuf, imgWidth: w, imgHeight: h };
925
- }
926
- }
927
- }
928
-
929
- return null;
930
- }
931
-
932
- // ---- Text methods (PangoCairo) ----
933
-
934
- /** Create a PangoCairo layout configured with current font/text settings. */
935
- private _createTextLayout(text: string): Pango.Layout {
936
- const layout = PangoCairo.create_layout(this._ctx as any);
937
- layout.set_text(text, -1);
938
-
939
- // Force LTR base direction so text is never rendered mirrored
940
- // regardless of system locale or Pango context defaults.
941
- const pangoCtx = layout.get_context();
942
- pangoCtx.set_base_dir(Pango.Direction.LTR);
943
- layout.context_changed();
944
-
945
- // Parse CSS font string into Pango font description
946
- const fontDesc = this._parseFontToDescription(this._state.font);
947
- layout.set_font_description(fontDesc);
948
-
949
- return layout;
950
- }
951
-
952
- /** Parse a CSS font string (e.g. "bold 16px Arial") into a Pango.FontDescription. */
953
- private _parseFontToDescription(cssFont: string): Pango.FontDescription {
954
- // CSS font: [style] [variant] [weight] size[/line-height] family[, family...]
955
- const match = cssFont.match(
956
- /^\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
957
- );
958
-
959
- if (!match) {
960
- // Fallback: pass directly to Pango (may have DPI-scaling quirks)
961
- return Pango.font_description_from_string(cssFont);
962
- }
963
-
964
- const style = match[1] || '';
965
- const weight = match[3] || '';
966
- let size = parseFloat(match[4]) || 10;
967
- const unit = (match[5] || 'px').toLowerCase();
968
- const family = (match[6] || 'sans-serif').replace(/['"]/g, '').trim();
969
-
970
- // Normalise everything to CSS pixels.
971
- // We use set_absolute_size() below which bypasses Pango's DPI scaling,
972
- // so 1 CSS pixel == 1 device pixel on a 1:1 surface (standard for Canvas2D).
973
- if (unit === 'pt') size = size * 96 / 72; // 1pt = 96/72 px
974
- else if (unit === 'em' || unit === 'rem') size = size * 16; // assume 16px base
975
- else if (unit === '%') size = (size / 100) * 16;
976
- // 'px' stays as-is
977
-
978
- // Build description string WITHOUT size — size is set via set_absolute_size.
979
- let pangoStr = family;
980
- if (style === 'italic') pangoStr += ' Italic';
981
- else if (style === 'oblique') pangoStr += ' Oblique';
982
- if (weight === 'bold' || weight === 'bolder' || parseInt(weight) >= 600) pangoStr += ' Bold';
983
- else if (weight === 'lighter' || (parseInt(weight) > 0 && parseInt(weight) <= 300)) pangoStr += ' Light';
984
-
985
- const desc = Pango.font_description_from_string(pangoStr);
986
- // Absolute size: Pango.SCALE units per device pixel, no DPI conversion.
987
- // This ensures "9px Round9x13" renders at exactly 9 pixels — pixel-perfect.
988
- desc.set_absolute_size(size * Pango.SCALE);
989
- return desc;
990
- }
991
-
992
- /**
993
- * Compute the x-offset for text alignment relative to the given x coordinate.
994
- */
995
- private _getTextAlignOffset(layout: Pango.Layout): number {
996
- const [, logicalRect] = layout.get_pixel_extents();
997
- const width = logicalRect.width;
998
-
999
- switch (this._state.textAlign) {
1000
- case 'center': return -width / 2;
1001
- case 'right':
1002
- case 'end': return -width;
1003
- case 'left':
1004
- case 'start':
1005
- default: return 0;
1006
- }
1007
- }
1008
-
1009
- /**
1010
- * Compute the y-offset for text baseline positioning.
1011
- *
1012
- * PangoCairo.show_layout() places the layout TOP-LEFT at the current Cairo point
1013
- * (not the baseline). Within the layout, the first line's baseline is at
1014
- * approximately `ascent` pixels below the layout top.
1015
- *
1016
- * For CSS textBaseline semantics, we shift the current point UP (negative offset)
1017
- * so the layout top lands at the right position relative to the user's y coordinate.
1018
- */
1019
- private _getTextBaselineOffset(layout: Pango.Layout): number {
1020
- const fontDesc = layout.get_font_description() || this._parseFontToDescription(this._state.font);
1021
- const context = layout.get_context();
1022
- const metrics = context.get_metrics(fontDesc, null);
1023
- const ascent = metrics.get_ascent() / Pango.SCALE;
1024
- const descent = metrics.get_descent() / Pango.SCALE;
1025
- const height = ascent + descent;
1026
-
1027
- // layout top = current point; baseline within layout ≈ ascent below top.
1028
- // yOff is added to user's y to get the layout top-left y.
1029
- switch (this._state.textBaseline) {
1030
- case 'top': return 0; // top of em square = y
1031
- case 'hanging': return -(ascent * 0.2); // hanging ≈ 0.2*ascent below top
1032
- case 'middle': return -(height / 2); // center of em square = y
1033
- case 'alphabetic': return -ascent; // baseline = y
1034
- case 'ideographic': return -(ascent + descent * 0.5); // below alphabetic baseline
1035
- case 'bottom': return -height; // bottom of em square = y
1036
- default: return -ascent; // default = alphabetic
1037
- }
1038
- }
1039
-
1040
- fillText(text: string, x: number, y: number, _maxWidth?: number): void {
1041
- this._ensureSurface();
1042
- this._applyCompositing();
1043
-
1044
- const layout = this._createTextLayout(text);
1045
- const xOff = this._getTextAlignOffset(layout);
1046
- const yOff = this._getTextBaselineOffset(layout);
1047
-
1048
- // Shadow pass: draw text at offset position with shadowColor.
1049
- // shadowOffsetX/Y are in CSS pixels (not scaled by CTM per Canvas2D spec),
1050
- // so we convert them to user-space before applying to moveTo.
1051
- // shadowBlur is approximated with a 5-tap cross kernel: one center tap at full
1052
- // alpha plus four arm taps at half alpha, spread by blur_u in each direction.
1053
- // This simulates Gaussian spreading without an actual blur pass.
1054
- if (this._hasShadow()) {
1055
- const sc = parseColor(this._state.shadowColor);
1056
- if (sc) {
1057
- const [sdx, sdy] = this._deviceToUserDistance(
1058
- this._state.shadowOffsetX,
1059
- this._state.shadowOffsetY,
1060
- );
1061
- const blur = this._state.shadowBlur;
1062
- type Tap = [number, number, number];
1063
- let taps: Tap[];
1064
- if (blur > 0) {
1065
- const [bu] = this._deviceToUserDistance(blur, 0);
1066
- const [, bv] = this._deviceToUserDistance(0, blur);
1067
- taps = [
1068
- [sdx, sdy, sc.a],
1069
- [sdx + bu, sdy, sc.a * 0.5],
1070
- [sdx - bu, sdy, sc.a * 0.5],
1071
- [sdx, sdy + bv, sc.a * 0.5],
1072
- [sdx, sdy - bv, sc.a * 0.5],
1073
- ];
1074
- } else {
1075
- taps = [[sdx, sdy, sc.a]];
1076
- }
1077
- const aa = this._state.imageSmoothingEnabled ? Cairo.Antialias.DEFAULT : Cairo.Antialias.NONE;
1078
- for (const [tx, ty, ta] of taps) {
1079
- this._ctx.save();
1080
- (this._ctx as any).setAntialias(aa);
1081
- this._ctx.setSourceRGBA(sc.r, sc.g, sc.b, ta);
1082
- this._ctx.moveTo(x + xOff + tx, y + yOff + ty);
1083
- PangoCairo.show_layout(this._ctx as any, layout);
1084
- this._ctx.restore();
1085
- }
1086
- }
1087
- }
1088
-
1089
- this._applyFillStyle();
1090
- this._ctx.save();
1091
- // Disable anti-aliasing so pixel/bitmap fonts render crisp (matching browser
1092
- // behaviour for fonts with no outline hints). cairo_save/restore covers antialias.
1093
- (this._ctx as any).setAntialias(this._state.imageSmoothingEnabled ? Cairo.Antialias.DEFAULT : Cairo.Antialias.NONE);
1094
- this._ctx.moveTo(x + xOff, y + yOff);
1095
- PangoCairo.show_layout(this._ctx as any, layout);
1096
- this._ctx.restore();
1097
- }
1098
-
1099
- strokeText(text: string, x: number, y: number, _maxWidth?: number): void {
1100
- this._ensureSurface();
1101
- this._applyCompositing();
1102
- this._applyStrokeStyle();
1103
- this._applyLineStyle();
1104
-
1105
- const layout = this._createTextLayout(text);
1106
- const xOff = this._getTextAlignOffset(layout);
1107
- const yOff = this._getTextBaselineOffset(layout);
1108
-
1109
- this._ctx.save();
1110
- (this._ctx as any).setAntialias(this._state.imageSmoothingEnabled ? Cairo.Antialias.DEFAULT : Cairo.Antialias.NONE);
1111
- this._ctx.moveTo(x + xOff, y + yOff);
1112
- PangoCairo.layout_path(this._ctx as any, layout);
1113
- this._ctx.stroke();
1114
- this._ctx.restore();
1115
- }
1116
-
1117
- measureText(text: string): TextMetrics {
1118
- this._ensureSurface();
1119
- const layout = this._createTextLayout(text);
1120
- const [inkRect, logicalRect] = layout.get_pixel_extents();
1121
-
1122
- // Baseline of first line in pixels from layout top (Pango.SCALE units → px).
1123
- const baselinePx = layout.get_baseline() / Pango.SCALE;
1124
-
1125
- // actualBoundingBox: ink-based, relative to baseline (positive = above/right of baseline).
1126
- // inkRect.y is pixels below layout top — compare against baseline to get baseline-relative values.
1127
- const actualAscent = Math.max(0, baselinePx - inkRect.y);
1128
- const actualDescent = Math.max(0, (inkRect.y + inkRect.height) - baselinePx);
1129
-
1130
- // fontBoundingBox: font-level metrics (same for all glyphs at this font/size).
1131
- const fontDesc = layout.get_font_description() || this._parseFontToDescription(this._state.font);
1132
- const metrics = layout.get_context().get_metrics(fontDesc, null);
1133
- const fontAscent = metrics.get_ascent() / Pango.SCALE;
1134
- const fontDescent = metrics.get_descent() / Pango.SCALE;
1135
-
1136
- return {
1137
- width: logicalRect.width,
1138
- actualBoundingBoxAscent: actualAscent,
1139
- actualBoundingBoxDescent: actualDescent,
1140
- actualBoundingBoxLeft: Math.max(0, -inkRect.x),
1141
- actualBoundingBoxRight: inkRect.x + inkRect.width,
1142
- fontBoundingBoxAscent: fontAscent,
1143
- fontBoundingBoxDescent: fontDescent,
1144
- alphabeticBaseline: 0,
1145
- emHeightAscent: fontAscent,
1146
- emHeightDescent: fontDescent,
1147
- hangingBaseline: fontAscent * 0.8,
1148
- ideographicBaseline: -fontDescent,
1149
- };
1150
- }
1151
-
1152
- // ---- toDataURL/toBlob support ----
1153
-
1154
- /**
1155
- * Write the canvas surface to a PNG file and return as data URL.
1156
- * Used by HTMLCanvasElement.toDataURL() when a '2d' context is active.
1157
- */
1158
- _toDataURL(type?: string, _quality?: number): string {
1159
- if (type && type !== 'image/png') {
1160
- // Cairo only supports PNG natively
1161
- // For other formats, return PNG anyway (per spec, PNG is the required format)
1162
- }
1163
- this._surface.flush();
1164
-
1165
- // Write to a temp file, read back as base64
1166
- const Gio = imports.gi.Gio;
1167
- const GLib = imports.gi.GLib;
1168
- const [, tempPath] = GLib.file_open_tmp('canvas-XXXXXX.png');
1169
- try {
1170
- this._surface.writeToPNG(tempPath);
1171
- const file = Gio.File.new_for_path(tempPath);
1172
- const [, contents] = file.load_contents(null);
1173
- const base64 = GLib.base64_encode(contents);
1174
- return `data:image/png;base64,${base64}`;
1175
- } finally {
1176
- try { GLib.unlink(tempPath); } catch (_e) { /* ignore */ }
1177
- }
1178
- }
1179
-
1180
- // ---- Cleanup ----
1181
-
1182
- /** Release native Cairo resources. Call when the canvas is discarded. */
1183
- _dispose(): void {
1184
- this._ctx.$dispose();
1185
- this._surface.finish();
1186
- }
1187
- }