-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy paththemeroller-image.js
355 lines (299 loc) · 9.19 KB
/
themeroller-image.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
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
"use strict";
const path = require( "node:path" );
const async = require( "async" );
const spawn = require( "cross-spawn" );
const Cache = require( "./cache" );
const semver = require( "semver" );
const dimensionLimit = 3000;
const namedColors = require( "./themeroller-colors" );
const cache = new Cache( "Image Cache" );
function processImageMagick( args, callback ) {
const proc = spawn( "magick", args );
const stdoutBuffers = [];
const stderrBuffers = [];
proc.stdout.on( "data", data => stdoutBuffers.push( data ) );
proc.stderr.on( "data", data => stderrBuffers.push( data ) );
proc.on( "close", code => {
if ( code !== 0 ) {
return callback( new Error( `magick process exited with code ${ code }: ${ Buffer.concat( stderrBuffers ).toString() }` ) );
}
callback( null, Buffer.concat( stdoutBuffers ) );
} );
proc.on( "error", callback );
}
function expandColor( color ) {
if ( color.length === 3 && /^[0-9a-f]+$/i.test( color ) ) {
return [ 0, 0, 1, 1, 2, 2 ].map( function( i ) {
return color[ i ];
} ).join( "" );
}
return color;
}
function hashColor( color ) {
if ( ( color.length === 3 || color.length === 6 ) && /^[0-9a-f]+$/i.test( color ) ) {
color = "#" + color;
}
return color;
}
function validateColor( color ) {
color = color.replace( /^#/, "" );
if ( ( color.length === 3 || color.length === 6 ) && /^[0-9a-f]+$/i.test( color ) ) {
// ok
} else if ( namedColors.indexOf( color.toLowerCase() ) !== -1 ) {
// ok
} else {
throw new Error( "invalid color \"" + color + "\"" );
}
}
function validateDimension( params, dimensionParams ) {
var invalidParams = dimensionParams.filter( function( param ) {
return parseInt( params[ param ], 10 ) > dimensionLimit;
} );
if ( invalidParams.length ) {
const reportedInvalidParams = Object.create( null );
for ( const key in invalidParams ) {
reportedInvalidParams[ key ] = params[ key ];
}
throw new Error( "dimension bigger than allowed limit " +
JSON.stringify( reportedInvalidParams ) );
}
}
function validateInteger( params, integerParams ) {
var invalidParams = integerParams.filter( function( param ) {
return isNaN( parseInt( params[ param ], 10 ) ) || ( /[^0-9]/ ).test( params[ param ] );
} );
if ( invalidParams.length ) {
const reportedInvalidParams = Object.create( null );
for ( const key in invalidParams ) {
reportedInvalidParams[ key ] = params[ key ];
}
throw new Error( "got a non-integer " +
JSON.stringify( reportedInvalidParams ) );
}
}
function validateOpacity( opacity ) {
opacity = parseInt( opacity, 10 );
if ( !( opacity >= 0 && opacity <= 100 ) ) {
throw new Error( "invalid opacity \"" + opacity + "\"" );
}
}
function validatePresence( params, requiredParams ) {
var missingParams = requiredParams.filter( function( param ) {
return !params[ param ];
} );
if ( missingParams.length ) {
throw new Error( "missing \"" + missingParams.join( "\", \"" ) + "\"" );
}
}
var generateIcon, generateImage, generateTexture,
concurrentQueues = 4,
imageQueue = async.queue( function( task, callback ) {
task( callback );
}, concurrentQueues );
// We'll `resume()` it once we know the ImageMagic version.
imageQueue.pause();
generateImage = function( params, callback ) {
if ( params.icon ) {
generateIcon( params.icon, callback );
} else {
generateTexture( params.texture, callback );
}
};
generateIcon = function( params, callback ) {
var color;
// Add '#' in the beginning of the colors if needed
color = hashColor( params.color );
// https://usage.imagemagick.org/masking/#shapes
// See https://github.com/jquery/download.jqueryui.com/issues/132 for why
// * `-set colorspace RGB` is needed (twice) in IM >6.7.9.
// * `-channel A -gamma 0.5` is needed so that partially transparent
// pixels are not too dark.
// Full command:
// $ magick <icons_mask_filename> -set colorspace RGB -background <color> -alpha shape -channel A -gamma 0.5 -set colorspace sRGB output.png
imageQueue.push( function( innerCallback ) {
try {
processImageMagick( [
path.join( __dirname, "/../template/themeroller/icon/mask.png" ),
"-set", "colorspace", "RGB",
"-background", color,
"-alpha", "shape",
"-channel", "A", "-gamma", "0.45",
"-set", "colorspace", "sRGB",
"png:-"
], innerCallback );
} catch ( err ) {
return innerCallback( err );
}
}, callback );
};
generateTexture = function( params, callback ) {
var color, filename;
// Add '#' in the beginning of the colors if needed
color = hashColor( params.color );
filename = params.type.replace( /-/g, "_" ).replace( /$/, ".png" );
// https://usage.imagemagick.org/compose/#dissolve
// $ magick -size <width>x<height> 'xc:<color>' <texture_filename> -compose dissolve -define compose:args=<opacity>,100 -composite output.png
imageQueue.push( function( innerCallback ) {
try {
processImageMagick( [
"-size", `${ params.width }x${ params.height }`,
"canvas:" + color,
path.join( __dirname, "/../template/themeroller/texture/", filename ),
"-compose", "dissolve",
"-define", `compose:args=${ params.opacity },100`,
"-composite",
"png:-"
], innerCallback );
} catch ( err ) {
return innerCallback( err );
}
}, callback );
};
/**
* Image
*/
function Image( params ) {
if ( typeof params === "string" ) {
params = this._parse( params );
} else {
params = params || {};
}
if ( params.icon ) {
params.icon = params.icon || {};
// Validate Icon
if ( !params.icon.color ) {
throw new Error( "missing color" );
}
validateColor( params.icon.color );
} else if ( params.texture ) {
params.texture = params.texture || {};
// Validate Texture
validatePresence( params.texture, [ "color", "height", "opacity", "type", "width" ] );
validateColor( params.texture.color );
validateInteger( params.texture, [ "height", "opacity", "width" ] );
validateDimension( params.texture, [ "height", "width" ] );
validateOpacity( params.texture.opacity );
} else {
throw new Error( "invalid parameters ", JSON.stringify( params ) );
}
this.params = params;
}
Image.prototype = {
_parse: function( filename ) {
var match, params;
if ( /^ui-icons/i.test( filename ) ) {
// ui-icons_<color>_256x240.png
match = filename.match( /^ui-icons_(\w+)_256x240.png$/i );
if ( match == null ) {
throw new Error( "Invalid format: " + filename );
}
params = {
icon: { color: match[ 1 ] }
};
} else {
// ui-bg_<type>_<opacity>_<color>_<width>x<height>.png
match = filename.match( /^ui-bg_([a-z0-9\-]+)_(\w+)_(\w+)_(\d+)x(\d+).png$/i );
if ( match == null ) {
throw new Error( "Invalid format: " + filename );
}
params = {
texture: {
type: match[ 1 ],
opacity: match[ 2 ],
color: match[ 3 ],
width: match[ 4 ],
height: match[ 5 ]
}
};
}
return params;
},
filename: function() {
var color, params;
if ( !this._filename ) {
if ( this.params.icon ) {
params = this.params.icon;
color = expandColor( params.color ).replace( /^#/, "" );
// ui-icons_<color>_256x240.png
this._filename = "ui-icons_" + color + "_256x240.png";
} else {
params = this.params.texture;
color = expandColor( params.color ).replace( /^#/, "" );
// ui-bg_<type>_<opacity>_<color>_<width>x<height>.png
this._filename = "ui-bg_" + params.type.replace( /_/g, "-" ) + "_" + params.opacity + "_" + color + "_" + params.width + "x" + params.height + ".png";
}
}
return this._filename;
},
get: function( callback ) {
var filename = this.filename(),
params = this.params,
cached = cache.get( filename );
if ( cached ) {
// if we have data, call the callback, otherwise push ours
if ( cached.data ) {
callback( null, filename, cached.data );
} else {
cached.callbacks.push( callback );
}
return true;
}
cached = {
callbacks: [ callback ]
};
cache.set( filename, cached );
generateImage( params, function( err, data ) {
var callbacks = cached.callbacks;
if ( !err ) {
cached.data = data;
delete cached.callbacks;
}
callbacks.forEach( function( callback ) {
callback( err, filename, data );
} );
delete cached.callbacks;
if ( err ) {
cache.destroy( filename );
}
} );
}
};
// Check the ImageMagick installation.
async.series( [
function( callback ) {
var wrappedCallback = function( err ) {
if ( err ) {
return callback( new Error( "ImageMagick not found.\n" + err.message ) );
}
callback();
};
try {
processImageMagick( [ "-version" ], wrappedCallback );
} catch ( err ) {
return wrappedCallback( err );
}
},
function( callback ) {
processImageMagick( [ "-version" ], function( err, buffer ) {
if ( err ) {
return callback( err );
}
var output = buffer.toString( "utf8" );
if ( !( /ImageMagick/ ).test( output ) ) {
return callback( new Error( "ImageMagick not installed.\n" + output ) );
}
const imVersion = output.split( /\r?\n/ )[ 0 ].replace( /^Version: ImageMagick ([^ ]*).*/, "$1" );
if ( !semver.valid( imVersion ) ) {
return callback( new Error( "Could not identify ImageMagick version.\n" + output ) );
}
imageQueue.resume();
callback();
} );
}
], function( err ) {
if ( err ) {
// On error, abort
throw new Error( err );
}
} );
module.exports = Image;