-
Notifications
You must be signed in to change notification settings - Fork 369
Expand file tree
/
Copy pathfont.ts
More file actions
267 lines (215 loc) · 8.43 KB
/
Copy pathfont.ts
File metadata and controls
267 lines (215 loc) · 8.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
import { Font, Glyph, Path, parse } from "opentype.js";
import { SVGPathData } from "svg-pathdata";
import { compress, decompress} from 'woff2-encoder';
import type { FileData, FileFormat, FormatHandler } from "../FormatHandler.ts";
import CommonFormats from 'src/CommonFormats.ts';
function escapeHtml(str: string) {
const map = new Map<string, string>();
map.set("&", "&");
map.set("<", "<");
map.set(">", ">");
map.set("\"", """);
map.set("'", "'");
map.set("\n", "
");
return str.replace(/[&<>"'\n]/g, match => map.get(match)!);
}
function sfntToSvg(inputFile: FileData, encoder: TextEncoder) {
const font = parse(inputFile.bytes.buffer);
const unitsPerEm = font.unitsPerEm;
const family = escapeHtml(font.names.fontFamily?.en || "ConvertedFont");
const glyphElements: string[] = [];
// Second line of the demo text is the longest, calculating width of the image based on it
let alphabetStringWidth = 0;
for (let i = 0; i < font.glyphs.length; i++) {
const glyph = font.glyphs.get(i);
if (!glyph || !glyph.unicode)
continue;
const path = glyph.getPath(0, 0, unitsPerEm);
// flip Y axis, since svg fonts use a different coordinate system than ttf/otf
path.commands.forEach(cmd => {
if ("y" in cmd)
cmd.y = -cmd.y;
if ("y1" in cmd)
cmd.y1 = -cmd.y1;
if ("y2" in cmd)
cmd.y2 = -cmd.y2;
});
const d = path.toPathData(5);
glyphElements.push(`<glyph unicode="${escapeHtml(String.fromCharCode(glyph.unicode))}" glyph-name="${glyph.name || ""}" horiz-adv-x="${glyph.advanceWidth}" d="${d}"/>`);
// alphabetStringWidth = width of "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz"
if (glyph.unicode === 32 || glyph.unicode >= 65 && glyph.unicode <= 90 || glyph.unicode >= 97 && glyph.unicode <= 122) {
alphabetStringWidth += glyph.advanceWidth ? glyph.advanceWidth : unitsPerEm;
}
}
// write svg font data & give a little demonstration of the font so that the SVG image isnt empty (and thus can [kind-of] be converted to things such as png, jpeg, etc)
const svgFont = `<svg xmlns="http://www.w3.org/2000/svg" width="${alphabetStringWidth / unitsPerEm * 2 + 4}em" height="10em">
<defs>
<font id="${escapeHtml(font.names.fullName?.en || "ConvertedFont")}"
horiz-adv-x="${unitsPerEm}">
<font-face
font-family="${family}"
style-name="Regular"
units-per-em="${unitsPerEm}"
ascent="${font.ascender}"
descent="${font.descender}"
/>
${glyphElements.join("\n")}
</font>
</defs>
<style>
text {
font-family: "${family}";
font-size: 2em;
fill: black;
}
</style>
<text x="1em" y="1em">
The quick brown fox jumps over the lazy dog.
</text>
<text x="1em" y="3em">
ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz
</text>
<text x="1em" y="4.5em">
0123456789 !@#$%^&*() -=_+[]{};':",./<>?\\|\`~
</text>
</svg>`;
const name = inputFile.name.split(".").slice(0, -1).join(".") + ".svg";
const bytes = encoder.encode(svgFont);
return { bytes, name };
}
function svgPathToOpenTypePath(d: string): Path {
const path = new Path();
const commands = new SVGPathData(d).toAbs().commands;
for (const cmd of commands) {
switch (cmd.type) {
case SVGPathData.MOVE_TO:
path.moveTo(cmd.x, cmd.y);
break;
case SVGPathData.LINE_TO:
path.lineTo(cmd.x, cmd.y);
break;
case SVGPathData.CURVE_TO:
path.curveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y);
break;
case SVGPathData.QUAD_TO:
path.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y);
break;
case SVGPathData.CLOSE_PATH:
path.close();
break;
}
}
return path;
}
function svgToOtf(inputFile: FileData, decoder: TextDecoder) {
const parser = new DOMParser();
const doc = parser.parseFromString(decoder.decode(inputFile.bytes), "image/svg+xml");
const fontFace = doc.querySelector("font-face");
const fontEl = doc.querySelector("font");
if (!fontFace || !fontEl)
throw new Error("Invalid SVG font format");
const unitsPerEm = Number(fontFace.getAttribute("units-per-em")) || 1000;
const ascent = Number(fontFace.getAttribute("ascent")) || 800;
const descent = Number(fontFace.getAttribute("descent")) || -200;
const glyphNodes = Array.from(doc.querySelectorAll("glyph"));
const glyphs: Glyph[] = [];
glyphs.push(
new Glyph({
name: ".notdef",
unicode: undefined,
advanceWidth: unitsPerEm / 2,
path: new Path()
})
);
for (const node of glyphNodes) {
const unicodeAttr = node.getAttribute("unicode");
const d = node.getAttribute("d");
if (!unicodeAttr || !d)
continue;
const unicode = unicodeAttr.codePointAt(0);
if (!unicode)
continue;
const advanceWidth =
Number(node.getAttribute("horiz-adv-x")) || unitsPerEm;
const path = svgPathToOpenTypePath(d);
const glyphName = node.getAttribute("glyph-name");
glyphs.push(
new Glyph({
name: glyphName ?? `uni${unicode.toString(16).toUpperCase()}`,
unicode,
advanceWidth,
path
})
);
}
const font = new Font({
familyName: fontFace.getAttribute("font-family") || "ConvertedFont",
styleName: fontFace.getAttribute("style-name") || "Regular",
unitsPerEm,
ascender: ascent,
descender: descent,
glyphs
});
const bytes = new Uint8Array(font.toArrayBuffer());
const name = inputFile.name.split(".").slice(0, -1).join(".") + ".otf";
return { bytes, name };
}
// opentype.js only supports writing CFF (OTF)
// this hangs on some woff2 font files; for some reason, opentype.js thinks that the tables array is massive (>200k items) when dealing with certain files
// to replicate, use DroidSansFallback.woff2 (found at https://github.com/GodotEngine/Godot/tree/master/thirdparty/fonts/DroidSansFallback.woff2) as input and select OTF as file output type
function sfntToOtf(inputFile: FileData) {
const font = parse(inputFile.bytes.buffer);
const bytes = new Uint8Array(font.toArrayBuffer());
const name = inputFile.name.split(".").slice(0, -1).join(".") + ".otf";
return { bytes, name };
}
async function sfntToWoff2(inputFile: FileData): Promise<FileData> {
const font = parse(inputFile.bytes.buffer);
const sfnt = new Uint8Array(font.toArrayBuffer());
const bytes = await compress(sfnt);
const name =inputFile.name.split(".").slice(0, -1).join(".") + ".woff2";
return { bytes, name };
}
async function normalizeToSfnt(inputFile: FileData, inputFormat: FileFormat, decoder: TextDecoder): Promise<Uint8Array> {
if (inputFormat.internal === "woff2")
return await decompress(inputFile.bytes);
else if (inputFormat.internal === "svg")
return svgToOtf(inputFile, decoder).bytes;
return inputFile.bytes;
}
class fontHandler implements FormatHandler {
public name: string = "font";
public supportedFormats?: FileFormat[];
public ready: boolean = false;
async init() {
this.supportedFormats = [
CommonFormats.TTF.builder("ttf").allowFrom().markLossless(),
CommonFormats.OTF.builder("otf").allowFrom().allowTo().markLossless(),
CommonFormats.WOFF.builder("woff").allowFrom().markLossless(),
CommonFormats.WOFF2.builder("woff2").allowFrom().allowTo().markLossless(),
CommonFormats.SVG.builder("svg").allowFrom().allowTo() // svg fonts lose a lot of font metadata, since they only convert the glyphs, so we can't mark it as lossless
];
this.ready = true;
}
async doConvert(
inputFiles: FileData[],
inputFormat: FileFormat,
outputFormat: FileFormat
): Promise<FileData[]> {
if (outputFormat.internal !== "svg" && outputFormat.internal !== "otf" && outputFormat.internal !== "woff2") throw new TypeError(`Unsupported output format: ${outputFormat.internal}`);
const outputFiles: FileData[] = [];
const encoder = new TextEncoder();
const decoder = new TextDecoder();
for (const inputFile of inputFiles) {
const nFile = { ...inputFile, bytes: await normalizeToSfnt(inputFile, inputFormat, decoder) };
if (outputFormat.internal === "svg")
outputFiles.push(sfntToSvg(nFile, encoder));
else if (outputFormat.internal === "otf")
outputFiles.push(sfntToOtf(nFile));
else if (outputFormat.internal === "woff2")
outputFiles.push(await sfntToWoff2(nFile));
}
return outputFiles;
}
}
export default fontHandler;