forked from Rush/Font-Awesome-SVG-PNG
-
Notifications
You must be signed in to change notification settings - Fork 0
/
font-awesome-svg-png.js
executable file
·250 lines (204 loc) · 6.97 KB
/
font-awesome-svg-png.js
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
#!/usr/bin/env node
var fs = require('graceful-fs');
var SVGO = require('svgo');
var svgo = new SVGO({
removeViewBox: true
});
var template =
'<svg width="{width}" height="{height}" viewBox="0 0 {width} {height}" xmlns="http://www.w3.org/2000/svg">' +
'<g transform="translate({shiftX} {shiftY})">' +
'<g transform="scale(1 -1) translate(0 -1280)">' +
'<path d="{path}" fill="{color}" />' +
'</g></g>' +
'</svg>';
var spawn = require('child_process').spawn;
var http = require('http');
var request = require('request');
var yaml = require('js-yaml');
var extend = require('extend');
var pathModule = require('path');
var async = require('async');
var code2name = {};
var argv = require('optimist').usage("Usage: $0 -color white --sprites").describe('sizes', "Provide comma separated sizes to generate").describe('sprites', 'Generate sprites.svg to use SVG as icons (http://tympanus.net/codrops/2013/11/27/svg-icons-ftw/)').describe('nopadding', "Do not add padding for PNG pixel perfection").default({sizes: "16,22,24,32,48,64,128,256"}).argv;
if(argv.help || (!argv.color && !argv.sprites)) {
return console.log(require('optimist').help());
}
var requestOptions = {
proxy: process.env.HTTPS_PROXY
};
function run() {
var sizes = (argv.sizes || '').toString().split(',');
function mkdir(dir) {
try {
fs.mkdirSync(dir);
} catch(err) {
if(err.code != 'EEXIST')
throw err
}
}
if(argv.color) {
mkdir(argv.color);
mkdir(pathModule.join(argv.color, 'svg'));
mkdir(pathModule.join(argv.color, 'png'));
sizes.forEach(function(siz) {
mkdir(pathModule.join(argv.color, 'png', siz.toString()));
});
}
var PIXEL = 128;
var outSvgSheet;
if(argv.sprites) {
outSvgSheet = fs.createWriteStream(pathModule.join('sprites.svg'));
outSvgSheet.write('<svg height="0" width="0" style="position:absolute;margin-left: -100%;">\n');
}
function generateIcon(name, path, params, cb) {
var out = template.substr(0);
out = out.replace("{path}", path);
function getTemplate(options) {
params = extend({}, params, {
shiftX: -(-(14*PIXEL - params.advWidth)/2 - options.paddingLeft),
shiftY: -(-2*PIXEL - options.paddingTop),
width: 14*PIXEL + options.paddingLeft + options.paddingRight,
height: 14*PIXEL + options.paddingBottom + options.paddingTop,
});
out = out.substr(0);
Object.keys(params).forEach(function(key) {
out = out.replace(new RegExp("{" + key + "}", 'g'), params[key]);
});
return out;
}
function optionsForSize(siz) {
var padding;
var ns = [1, 2, 4, 8, 16];
for(var i = 0;i < ns.length && !argv.nopadding;++i) {
var n = ns[i];
if(siz > n*14 && siz <= n*16) {
padding = (siz - n*14)/2 * PIXEL;
}
else
continue;
if(padding - parseInt(padding) > 0) {
padding = 0;
}
return {
paddingTop: padding,
paddingBottom: padding,
paddingLeft: padding,
paddingRight: padding,
};
};
return {
paddingTop: 0,
paddingBottom: 0,
paddingLeft: 0,
paddingRight: 0
};
}
console.log("Generating icon", name);
var workChain = [];
if(argv.color) {
workChain.push(function(cb) {
async.eachSeries(sizes, function(siz, cb) {
var rsvgConvert;
var svgCode = getTemplate(optionsForSize(siz));
rsvgConvert = spawn('rsvg-convert', ['-f', 'png', '-w', siz, '-o', pathModule.join(argv.color, 'png', siz.toString(), name+'.png')]);
if(process.env.INTERMEDIATE_SVG) {
console.log(svgCode);
fs.writeFileSync(pathModule.join(argv.color, 'png', siz.toString(), name+'.svg'), svgCode);
}
rsvgConvert.stdin.end(svgCode);
rsvgConvert.once('error', cb);
rsvgConvert.once('exit', cb);
}, cb);
});
}
if(argv.color) {
workChain.push(function(cb) {
var outSvg = fs.createWriteStream(pathModule.join(argv.color, 'svg', name + '.svg'));
svgo.optimize(getTemplate({
paddingTop: 0,
paddingLeft: 0,
paddingBottom: 0,
paddingRight: 0
}), function(result) {
outSvg.end(result.data);
cb();
});
});
}
if(argv.sprites) {
workChain.push(function(cb) {
svgo.optimize(getTemplate({
paddingTop: 0,
paddingLeft: 0,
paddingBottom: 0,
paddingRight: 0
}), function(result) {
var m = result.data.match('(<path.*\/>)');
var svgPath = m[1].replace('path', 'path id="fa-' + name + '"');
if(outSvgSheet)
outSvgSheet.write(svgPath.replace(/\s*fill="[^"]+"/, '') + '\n');
cb();
});
});
}
async.parallel(workChain, cb);
}
console.log("Downloading latest icons.yml ...");
request(extend(true, requestOptions, {
url: 'https://raw.github.com/FortAwesome/Font-Awesome/master/src/icons.yml'
}), function(error, response, iconsYaml) {
if(error) throw error;
console.log("Downloading latest fontawesome-webfont.svg ...");
request(extend(true, requestOptions, {
url: 'https://raw.github.com/FortAwesome/Font-Awesome/master/fonts/fontawesome-webfont.svg'
}), function(error, response, fontData) {
if(error) throw error;
fontData = fontData.toString('utf8');
var icons = yaml.safeLoad(iconsYaml).icons;
icons.forEach(function(icon) {
code2name[icon.unicode] = icon.id;
});
lines = fontData.split('\n');
async.eachLimit(lines, 4, function(line, cb) {
var m = line.match(/^<glyph unicode="&#x([^"]+);"\s*(?:horiz-adv-x="(\d+)")?\s*d="([^"]+)"/);
if(m) {
var str = m[1];
if(code2name[str]) {
generateIcon(code2name[str], m[3], {advWidth: m[2]?m[2]:1536, color: argv.color }, cb);
}
else {
cb();
}
}
else
cb();
}, function(err, cb) {
if(err) {
console.log("Make sure 'rsvg-convert' command is available in the PATH");
return console.log("Error occured:", err);
}
if(outSvgSheet) {
outSvgSheet.end('<\/svg>\n');
}
console.log("All generated");
});
});
});
}
var convertTest = spawn('rsvg-convert', ['--help']);
convertTest.once('error', function() {
console.warn("Error: cannot start `rsvg-convert` command. Please install it or verify that it is in your PATH.");
});
convertTest.once('exit', function() {
if(requestOptions.HTTPS_PROXY) return run();
var npm = spawn('npm', ['config', 'get', 'https-proxy']);
npm.stdout.once('data', function(data) {
data = data.toString('utf8').split(/\n/)[0];
if(data !== 'null' && data !== 'undefined') {
console.log("Setting https proxy to '" + data + "'");
requestOptions.proxy = data;
}
});
npm.once('exit', run);
npm.once('error', run);
});