Skip to content

Commit 08d66de

Browse files
committed
add back font related functionality
TODO: review FontManagerLinux dlopen stuff
1 parent 9d5e3b5 commit 08d66de

49 files changed

Lines changed: 6088 additions & 80 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎build.zig‎

Lines changed: 51 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,11 @@ pub fn build(b: *std.Build) void {
44
const target = b.standardTargetOptions(.{});
55
const optimize = b.standardOptimizeOption(.{});
66
const cairo = b.dependency("cairo", .{
7-
.use_spectre = false,
8-
.use_xlib = false,
97
.use_xcb = false,
108
.use_png = true,
119
.use_glib = false,
1210
.use_dwrite = false,
13-
.use_fontconfig = false,
14-
.use_freetype = false,
11+
.use_freetype = true,
1512
.use_quartz = false,
1613
.target = target,
1714
.optimize = optimize,
@@ -31,6 +28,35 @@ pub fn build(b: *std.Build) void {
3128
.target = target,
3229
.optimize = optimize,
3330
}).artifact("png");
31+
32+
const sheenbidi = b.dependency("sheenbidi", .{
33+
.target = target,
34+
.optimize = optimize,
35+
}).artifact("sheenbidi");
36+
37+
const zg = b.dependency("zg", .{
38+
.target = target,
39+
.optimize = optimize,
40+
});
41+
42+
const harfbuzz = b.dependency("harfbuzz", .{
43+
.target = target,
44+
.optimize = optimize,
45+
}).artifact("harfbuzz");
46+
47+
const unicode = b.addLibrary(.{
48+
.name = "unicode",
49+
.linkage = .static,
50+
.root_module = b.createModule(.{
51+
.target = target,
52+
.optimize = optimize,
53+
.root_source_file = b.path("src/unicode.zig"),
54+
})
55+
});
56+
57+
unicode.root_module.addImport("Scripts", zg.module("Scripts"));
58+
unicode.root_module.addImport("Graphemes", zg.module("Graphemes"));
59+
unicode.linkLibC();
3460

3561
const canvas = b.addLibrary(.{
3662
.name = "canvas",
@@ -58,11 +84,23 @@ pub fn build(b: *std.Build) void {
5884
"src/Image.cc",
5985
"src/ImageData.cc",
6086
"src/init.cc",
61-
"src/FontParser.cc"
87+
"src/itemize.cc",
88+
"src/FontManager.cc",
89+
switch (target.result.os.tag) {
90+
.windows => "src/FontManagerWindows.cc",
91+
.macos => "src/FontManagerMacos.cc",
92+
else => "src/FontManagerLinux.cc",
93+
},
94+
"src/FontFace.cc",
95+
"src/FontFaceSet.cc",
96+
"src/FontParser.cc",
97+
"src/FontLayout.cc"
6298
} ,
6399
.flags = &.{
64100
"-DNAPI_DISABLE_CPP_EXCEPTIONS",
65101
"-DNODE_ADDON_API_ENABLE_MAYBE",
102+
"-D_USE_MATH_DEFINES",
103+
"-std=c++20",
66104
if (target.result.os.tag == .windows) "-DCAIRO_WIN32_STATIC_BUILD" else "",
67105
}
68106
});
@@ -80,7 +118,14 @@ pub fn build(b: *std.Build) void {
80118
canvas.linkLibrary(libjpeg_turbo);
81119
canvas.linkLibrary(libpng);
82120
canvas.linkLibrary(giflib);
83-
121+
canvas.linkLibrary(sheenbidi);
122+
canvas.linkLibrary(unicode);
123+
canvas.linkLibrary(harfbuzz);
124+
125+
if (target.result.os.tag == .windows) {
126+
canvas.linkSystemLibrary("dwrite");
127+
}
128+
84129
const move = b.addInstallFile(canvas.getEmittedBin(), "../bin/canvas.node");
85130
move.step.dependOn(&canvas.step);
86131
b.getInstallStep().dependOn(&move.step);

‎build.zig.zon‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
.hash = "node_api-0.0.0-AAAAAAQgAAB-W9HyzJg5Vhja3uNMMcDiFaCJvBLt41GD",
1111
},
1212
.cairo = .{ .path = "./pkg/cairo" },
13+
// TODO: this needs to be kept in sync with freetype's build.zig.zon
1314
.libpng = .{
1415
.url = "https://github.com/allyourcodebase/libpng/archive/d512607515687aa60b975d6a191aef9a692dac87.zip",
1516
.hash = "libpng-1.6.50-oiaFGt4qAAB_vzrtvz9hA7_UiBW4arSaMVGc7ekKMCZ2",
@@ -22,5 +23,12 @@
2223
.url = "https://github.com/chearon/giflib/archive/986b2816254c3cebf7f9f735eb32564e4600cc66.tar.gz",
2324
.hash = "giflib-5.2.2-TakyOnIKIwCYvNoi8kEaGj5KYEc9hZ900YBld700u-PM",
2425
},
26+
.zg = .{
27+
.url = "https://codeberg.org/atman/zg/archive/d9f596626e8ec05a9f3e47f7bc83aedd5bd2f989.tar.gz",
28+
.hash = "zg-0.15.3-oGqU3P5ItAJHmwDLfzX6sg6Xc5MhSJU2TctHfWu_sKLv",
29+
},
30+
.sheenbidi = .{ .path = "./pkg/sheenbidi" },
31+
.harfbuzz = .{ .path = "./pkg/harfbuzz" },
32+
.freetype = .{ .path = "./pkg/freetype" },
2533
},
2634
}

‎examples/font.js‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
const fs = require('fs')
22
const path = require('path')
3-
const Canvas = require('..')
3+
const { createCanvas, FontFace, fonts } = require('..')
44

55
function fontFile (name) {
66
return path.join(__dirname, '/pfennigFont/', name)
@@ -10,12 +10,12 @@ function fontFile (name) {
1010
// `registerFont`. When you set `ctx.font`, refer to the styles and the family
1111
// name as it is embedded in the TTF. If you aren't sure, open the font in
1212
// FontForge and visit Element -> Font Information and copy the Family Name
13-
Canvas.registerFont(fontFile('Pfennig.ttf'), { family: 'pfennigFont' })
14-
Canvas.registerFont(fontFile('PfennigBold.ttf'), { family: 'pfennigFont', weight: 'bold' })
15-
Canvas.registerFont(fontFile('PfennigItalic.ttf'), { family: 'pfennigFont', style: 'italic' })
16-
Canvas.registerFont(fontFile('PfennigBoldItalic.ttf'), { family: 'pfennigFont', weight: 'bold', style: 'italic' })
13+
fonts.add(new FontFace('pfennigFont', fontFile('Pfennig.ttf')))
14+
fonts.add(new FontFace('pfennigFont', fontFile('PfennigBold.ttf'), { weight: 'bold' }))
15+
fonts.add(new FontFace('pfennigFont', fontFile('PfennigItalic.ttf'), { style: 'italic' }))
16+
fonts.add(new FontFace('pfennigFont', fontFile('PfennigBoldItalic.ttf'), { weight: 'bold', style: 'italic' }))
1717

18-
const canvas = Canvas.createCanvas(320, 320)
18+
const canvas = createCanvas(320, 320)
1919
const ctx = canvas.getContext('2d')
2020

2121
ctx.font = 'normal normal 50px Helvetica'

‎index.d.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,11 +210,14 @@ export class CanvasRenderingContext2D {
210210
clip(fillRule?: CanvasFillRule): void;
211211
fill(fillRule?: CanvasFillRule): void;
212212
stroke(): void;
213+
fillText(text: string, x: number, y: number, maxWidth?: number): void;
214+
strokeText(text: string, x: number, y: number, maxWidth?: number): void;
213215
fillRect(x: number, y: number, w: number, h: number): void;
214216
strokeRect(x: number, y: number, w: number, h: number): void;
215217
clearRect(x: number, y: number, w: number, h: number): void;
216218
rect(x: number, y: number, w: number, h: number): void;
217219
roundRect(x: number, y: number, w: number, h: number, radii?: number | number[]): void;
220+
measureText(text: string): TextMetrics;
218221
moveTo(x: number, y: number): void;
219222
lineTo(x: number, y: number): void;
220223
bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void;
@@ -250,6 +253,30 @@ export class CanvasRenderingContext2D {
250253
shadowBlur: number;
251254
/** _Non-standard_. Sets the antialiasing mode. */
252255
antialias: 'default' | 'gray' | 'none' | 'subpixel'
256+
/**
257+
* Defaults to 'path'. The effect depends on the canvas type:
258+
*
259+
* * **Standard (image)** `'glyph'` and `'path'` both result in rasterized
260+
* text. Glyph mode is faster than path, but may result in lower-quality
261+
* text, especially when rotated or translated.
262+
*
263+
* * **PDF** `'glyph'` will embed text instead of paths into the PDF. This
264+
* is faster to encode, faster to open with PDF viewers, yields a smaller
265+
* file size and makes the text selectable. The subset of the font needed
266+
* to render the glyphs will be embedded in the PDF. This is usually the
267+
* mode you want to use with PDF canvases.
268+
*
269+
* * **SVG** glyph does not cause `<text>` elements to be produced as one
270+
* might expect ([cairo bug](https://gitlab.freedesktop.org/cairo/cairo/issues/253)).
271+
* Rather, glyph will create a `<defs>` section with a `<symbol>` for each
272+
* glyph, then those glyphs be reused via `<use>` elements. `'path'` mode
273+
* creates a `<path>` element for each text string. glyph mode is faster
274+
* and yields a smaller file size.
275+
*
276+
* In glyph mode, `ctx.strokeText()` and `ctx.fillText()` behave the same
277+
* (aside from using the stroke and fill style, respectively).
278+
*/
279+
textDrawingMode: 'path' | 'glyph'
253280
/**
254281
* _Non-standard_. Defaults to 'good'. Like `patternQuality`, but applies to
255282
* transformations affecting more than just patterns.
@@ -259,7 +286,12 @@ export class CanvasRenderingContext2D {
259286
currentTransform: DOMMatrix
260287
fillStyle: string | CanvasGradient | CanvasPattern;
261288
strokeStyle: string | CanvasGradient | CanvasPattern;
289+
font: string;
290+
textBaseline: CanvasTextBaseline;
291+
textAlign: CanvasTextAlign;
262292
canvas: Canvas;
293+
direction: 'ltr' | 'rtl';
294+
lang: string;
263295
}
264296

265297
export class CanvasGradient {
@@ -346,6 +378,35 @@ export function createImageData(width: number, height: number): ImageData
346378
*/
347379
export function loadImage(src: string|Buffer, options?: any): Promise<Image>
348380

381+
interface FontFaceDescriptors {
382+
weight?: number;
383+
style?: string;
384+
}
385+
386+
export class FontFace {
387+
constructor(
388+
family: string,
389+
url: string | ArrayBuffer | Uint8Array,
390+
descriptors?: FontFaceDescriptors
391+
);
392+
393+
family: string;
394+
style: string;
395+
weight: string;
396+
status: 'loaded' | 'unloaded' | 'error';
397+
}
398+
399+
declare class FontFaceSet {
400+
add(face: FontFace): void;
401+
has(face: FontFace): boolean;
402+
clear(): void;
403+
delete(face: FontFace): boolean;
404+
[Symbol.iterator](): Iterator<FontFace>;
405+
size: number;
406+
}
407+
408+
export const fonts: FontFaceSet;
409+
349410
/** This class must not be constructed directly; use `canvas.createPNGStream()`. */
350411
export class PNGStream extends Readable {}
351412
/** This class must not be constructed directly; use `canvas.createJPEGStream()`. */

‎index.js‎

Lines changed: 2 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ const CanvasRenderingContext2D = require('./lib/context2d')
44
const CanvasPattern = require('./lib/pattern')
55
const packageJson = require('./package.json')
66
const bindings = require('./lib/bindings')
7-
const fs = require('fs')
87
const PNGStream = require('./lib/pngstream')
98
const PDFStream = require('./lib/pdfstream')
109
const JPEGStream = require('./lib/jpegstream')
@@ -36,31 +35,12 @@ function loadImage (src) {
3635
})
3736
}
3837

39-
/**
40-
* Resolve paths for registerFont. Must be called *before* creating a Canvas
41-
* instance.
42-
* @param src {string} Path to font file.
43-
* @param fontFace {{family: string, weight?: string, style?: string}} Object
44-
* specifying font information. `weight` and `style` default to `"normal"`.
45-
*/
46-
function registerFont (src, fontFace) {
47-
// TODO this doesn't need to be on Canvas; it should just be a static method
48-
// of `bindings`.
49-
return Canvas._registerFont(fs.realpathSync(src), fontFace)
50-
}
51-
52-
/**
53-
* Unload all fonts from pango to free up memory
54-
*/
55-
function deregisterAllFonts () {
56-
return Canvas._deregisterAllFonts()
57-
}
58-
5938
exports.Canvas = Canvas
6039
exports.Context2d = CanvasRenderingContext2D // Legacy/compat export
6140
exports.CanvasRenderingContext2D = CanvasRenderingContext2D
6241
exports.CanvasGradient = bindings.CanvasGradient
6342
exports.CanvasPattern = CanvasPattern
43+
exports.FontFace = bindings.FontFace
6444
exports.Image = Image
6545
exports.ImageData = bindings.ImageData
6646
exports.PNGStream = PNGStream
@@ -69,8 +49,7 @@ exports.JPEGStream = JPEGStream
6949
exports.DOMMatrix = DOMMatrix
7050
exports.DOMPoint = DOMPoint
7151

72-
exports.registerFont = registerFont
73-
exports.deregisterAllFonts = deregisterAllFonts
52+
exports.fonts = bindings.fonts
7453

7554
exports.createCanvas = createCanvas
7655
exports.createImageData = createImageData

‎index.test-d.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,22 @@
11
import { expectAssignable, expectType } from 'tsd'
2-
import * as path from 'path'
32
import { Readable } from 'stream'
43

54
import * as Canvas from './index'
65

7-
Canvas.registerFont(path.join(__dirname, '../pfennigFont/Pfennig.ttf'), {family: 'pfennigFont'})
6+
const font = new Canvas.FontFace('../pfennigFont/Pfennig.ttf', 'pfennigFont', {
7+
weight: 'normal',
8+
style: 'normal'
9+
});
10+
11+
Canvas.fonts.add(font)
12+
font.status;
13+
font.family = 'pfennig';
14+
font.style = 'italic';
15+
font.weight = 'bold';
16+
Canvas.fonts.delete(font);
17+
Canvas.fonts.clear();
18+
Canvas.fonts.size;
19+
for (const font of Canvas.fonts) font.status;
820

921
Canvas.createCanvas(5, 10)
1022
Canvas.createCanvas(200, 200, 'pdf')
@@ -49,5 +61,3 @@ expectType<Canvas.ImageData>(id2)
4961
ctx.putImageData(id2, 0, 0)
5062

5163
ctx.drawImage(canv, 0, 0)
52-
53-
Canvas.deregisterAllFonts()

‎lib/bindings.js‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,8 @@ Object.defineProperty(bindings.CanvasRenderingContext2d.prototype, Symbol.toStri
4141
value: 'CanvasRenderingContext2d',
4242
configurable: true
4343
})
44+
45+
Object.defineProperty(bindings.FontFace.prototype, Symbol.toStringTag, {
46+
value: 'FontFace',
47+
configurable: true
48+
})

‎package.json‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,6 @@
5959
"tsd": "^0.29.0",
6060
"typescript": "^4.2.2"
6161
},
62-
"engines": {
63-
"node": "^18.12.0 || >= 20.9.0"
64-
},
6562
"binary": {
6663
"napi_versions": [
6764
7

0 commit comments

Comments
 (0)