-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathgenerate.js
More file actions
299 lines (214 loc) · 7.12 KB
/
generate.js
File metadata and controls
299 lines (214 loc) · 7.12 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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import fs from 'fs/promises';
import YAML from 'yaml'
import ora from 'ora';
import base32Encode from 'base32-encode';
import tmp from 'tmp-promise';
import { promisify } from 'util';
import { exec } from 'child_process';
import asyncPool from "tiny-async-pool";
import os from 'os';
import { dirname } from 'path';
import svgo from 'svgo';
import applyTranslations from './applyTranslations.js';
const CPUS = os.cpus().length;
console.log(`Running on ${CPUS} threads`)
/*
Utils
*/
function symbolId(symbol) {
let id = `${symbol.package}-${symbol.fontenc}-${symbol.symbol.replace("\\", "_")}`;
let buffer = new TextEncoder().encode(id);
return base32Encode(buffer, 'RFC4648', { padding: false });
}
function asyncPoolProgress(poolLimit, array, iteratorFn, tickCallback) {
var len = array.length;
var progress = 0;
function tick() {
progress++;
tickCallback(progress, len);
}
return asyncPool(poolLimit, array, async (item) => {
let value = await iteratorFn(item);
tick();
return value;
});
}
function execute(command) {
return promisify(exec)(command);
}
/*
1. Load symbols from symbols.yaml
*/
let spinner = ora('Parsing symbols.yaml').start();
let symbols = await (async function () {
const file = await fs.readFile("./symbols.yaml", "utf-8");
const yaml = YAML.parse(file);
let symbols = [];
const defaultSymbol = {
package: "latex2e",
fontenc: "OT1",
textmode: true,
mathmode: false
};
for (let symbol of yaml) {
if (typeof symbol === "string") {
symbols.push({ ...defaultSymbol, symbol });
} else {
let s = {
fontenc: symbol.fontenc || defaultSymbol.fontenc,
package: symbol.package || defaultSymbol.package,
};
if ('bothmodes' in symbol) {
for (let innerSymbol of symbol.bothmodes) {
symbols.push({ ...s, symbol: innerSymbol, textmode: true, mathmode: true });
}
}
if ('textmode' in symbol) {
for (let innerSymbol of symbol.textmode) {
symbols.push({ ...s, symbol: innerSymbol, textmode: true, mathmode: false });
}
}
if ('mathmode' in symbol) {
for (let innerSymbol of symbol.mathmode) {
symbols.push({ ...s, symbol: innerSymbol, textmode: false, mathmode: true });
}
}
}
}
return symbols;
})();
// symbols = symbols.slice(0, 1);
spinner.succeed(`Found ${symbols.length} symbols`);
/*
2. Write LaTeX
*/
spinner = ora('Writing latex files').start();
const generateLatexFile = async (symbol) => {
const { path } = await tmp.file({ postfix: "latex" });
const handle = await fs.open(path, "w");
let command = symbol.mathmode ? `$${symbol.symbol}$` : symbol.symbol;
let usepackage = symbol.package == "latex2e" ? "" : `\\usepackage{${symbol.package}}`;
const latex = `
\\documentclass[10pt]{article}
\\usepackage[utf8]{inputenc}
\\usepackage[${symbol.fontenc}]{fontenc}
${usepackage}
\\pagestyle{empty}
\\begin{document}
${command}
\\end{document}
`;
await handle.writeFile(latex);
await handle.close();
return { symbol, path };
};
const latexFiles = await asyncPoolProgress(CPUS, symbols, generateLatexFile, (progress, len) => {
spinner.text = `Writing latex files (${progress}/${len})`;
});
spinner.succeed(`Written latex files`);
/*
3. Render PDF's
*/
spinner = ora('Rendering PDFs').start();
const renderLatexFile = async ({ symbol, path }) => {
await execute(`pdflatex -output-directory ${dirname(path)} ${path}`);
return { symbol, path: `${path}.pdf` };
};
const pdfs = await asyncPoolProgress(CPUS, latexFiles, renderLatexFile, (progress, len) => {
spinner.text = `Rendering PDFs (${progress}/${len})`;
});
spinner.succeed(`Rendered PDFs`);
/*
4. PDF to SVG
*/
spinner = ora('Converting PDFs').start();
const convertPDF = async ({ symbol, path }) => {
let newpath = path.replace(".pdf", ".svg");
await execute(`pdf2svg ${path} ${newpath}`);
return { symbol, path: newpath };
}
const svgs = await asyncPoolProgress(CPUS, pdfs, convertPDF, (progress, len) => {
spinner.text = `Converting PDFs (${progress}/${len})`;
});
spinner.succeed(`Converted PDFs`)
/*
5. Crop to drawing
*/
spinner = ora('Cropping SVGs').start()
const cropSVG = async ({ symbol, path }) => {
let newpath = path.replace(".svg", ".cropped.svg");
await execute(`inkscape -D -o ${newpath} ${path}`);
return { symbol, path: newpath };
}
const croppedSvgs = await asyncPoolProgress(CPUS, svgs, cropSVG, (progress, len) => {
spinner.text = `Cropping SVGs (${progress}/${len})`;
});
spinner.succeed(`Cropped SVGs`);
/*
6. Resizing SVGs
*/
spinner = ora('Resizing SVGs').start();
const resizeSVG = async ({ path }) => {
let handle = await fs.open(path, "r");
let svg = await handle.readFile({ encoding: 'utf-8' });
svg = svg.replace(/height\=\"[0-9]*\.[0-9]*pt\"/g, `height="64px"`);
svg = svg.replace(/width\=\"[0-9]*\.[0-9]*pt\"/g, `width="64px"`);
await handle.close();
handle = await fs.open(path, "w");
await handle.writeFile(svg);
await handle.close();
};
await asyncPoolProgress(CPUS, croppedSvgs, resizeSVG, (progress, len) => {
spinner.text = `Resizing SVGs (${progress}/${len})`;
})
spinner.succeed(`Resized SVGs`);
/*
7. Minimize SVGs
We are using a fork of svgo, strarsis/svgo#dereferenceUses-plugin that has the dereferenceUses
plugin. For some reason <use>'s do not play well with uwp <Image> controls, plus we save some
space by inlining them.
*/
spinner = ora('Minimizing SVGs').start();
const minimizeSVG = async ({ symbol, path }) => {
let handle = await fs.open(path, "r");
const svg = await handle.readFile({ encoding: 'utf-8' });
const result = svgo.optimize(svg, {
path,
multipass: true,
plugins: svgo.extendDefaultPlugins([
{
name: "dereferenceUses",
params: {
symbolContainer: 'svg'
}
},
applyTranslations
])
});
await handle.close();
handle = await fs.open(path, "w");
if (result.error) {
spinner.fail(`Failed to minimize ${symbol.symbol}: ${result.error}`);
return;
}
await handle.writeFile(result.data);
await handle.close();
return { symbol, path }
};
await asyncPoolProgress(1, croppedSvgs, minimizeSVG, (progress, len) => {
spinner.text = `Minimizing SVGs (${progress}/${len})`;
})
spinner.succeed(`Minimized SVGs`);
/*
8. Rename SVGs
*/
const symbolsDir = `${process.cwd()}/symbols`;
await fs.mkdir(symbolsDir, { recursive: true });
spinner = ora('Renaming SVGs').start();
const renameSVG = async ({ symbol, path }) => {
await execute(`mv ${path} ${symbolsDir}/${symbolId(symbol)}.svg`)
}
await asyncPoolProgress(1, croppedSvgs, renameSVG, (progress, len) => {
spinner.text = `Renaming SVGs (${progress}/${len})`;
});
spinner.succeed(`Renamed SVGs`);