summaryrefslogtreecommitdiff
path: root/index.php
blob: 6e9d63e81138da8a423b2a508870521fe1c2e4de (plain)
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
<?php

/*
    hicg -- Harmattan Icon/Color Generator
    Copyright (C) 2011 Javier S. Pedro <maemo@javispedro.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

define('SVGNS', 'http://www.w3.org/2000/svg');

define('COLOR_EXTRACT_RENDER_SIZE', 128);
define('HARMATTAN_ICON_SIZE', 80);
define('HARMATTAN_FOCAL_SIZE', 56);

function svg2png($svg, $w, $h, $png)
{
	$output = array();
	$exitcode = -1;
	$cmd = sprintf("~/bin/rsvg-convert --format=png --width=%d --height=%d --output=%s %s", $w, $h, escapeshellarg($png), escapeshellarg($svg));
	exec($cmd, $output, $exitcode);
	return $exitcode == 0 && file_exists($png);
}

function multiarray($d, $k, $n = 0)
{
	return array_fill(0, $k, $d == 1 ? $n : multiarray($d - 1, $k, $n));
}

function warn($s)
{
	global $warnings;
	$warnings[] = $s;
}

function colfilter_none($c)
{
	return false;
}

function colfilter_pure($c)
{
	return ($c['red'] == 0 && $c['green'] == 0 && $c['blue'] == 0) ||
		   ($c['red'] == 255 && $c['green'] == 255 && $c['blue'] == 255);
}

function colfilter_grey($c)
{
	return ($c['red'] == $c['green']) && ($c['green'] == $c['blue']);
}

function colfilter_grey5($c)
{
	$r = $c['red'] >> 3;
	$g = $c['green'] >> 3;
	$b = $c['blue'] >> 3;
	return ($r == $g) && ($g == $b);
}

function domcolor_mean($img, $flt)
{
	$w = imagesx($img);
	$h = imagesy($img);
	$t = $w * $h;
	$r = 0; $g = 0; $b = 0;
	for ($y = 0; $y < $h; $y++) {
		for ($x = 0; $x < $w; $x++) {
			$c = imagecolorsforindex($img, imagecolorat($img, $x, $y));
			if (call_user_func($flt, $c)) continue;
			$r += $c['red'];
			$g += $c['green'];
			$b += $c['blue'];
		}
	}
	$r /= $t; $g /= $t;	$b /= $t;
	return array($r, $g, $b);
}

function domcolor_mode($img, $flt)
{
	$w = imagesx($img);
	$h = imagesy($img);
	$t = $w * $h;
	$f = multiarray(3, 256, 0);
	$max_c = false;
	$max_f = 0;
	for ($y = 0; $y < $h; $y++) {
		for ($x = 0; $x < $w; $x++) {
			$c = imagecolorsforindex($img, imagecolorat($img, $x, $y));
			if (call_user_func($flt, $c)) continue;
			$this_f = $f[$c['red']][$c['green']][$c['blue']] += 1;
			if ($this_f > $max_f) {
				$max_c = $c;
				$max_f = $this_f;
			}
		}
	}
	if ($max_c)
		return array($max_c['red'], $max_c['green'], $max_c['blue']);
	else
		return false;
}


function domcolor_custom($img, $flt)
{
	$color = $_POST['customcolor'];

	/* Remove prefixing '#' if present. */
	if ($color[0] == '#')	$color = substr($color, 1);

	if (strlen($color) == 6) {
		/* Handle rrggbb format. */
		$r = $color[0].$color[1];
		$g = $color[2].$color[3];
		$b = $color[4].$color[5];
	} elseif (strlen($color) == 3) {
		/* Handle rgb format. */
		$r = $color[0].$color[0];
		$g = $color[1].$color[1];
		$b = $color[2].$color[2];
	} else {
		/* Unknown format. */
		return false;
	}

	return array(hexdec($r), hexdec($g), hexdec($b));
}

$domalgos = array('mean', 'mode', 'custom');
$colfilters = array('none', 'pure', 'grey', 'grey5');

function extract_dominant_color($svg, $algo = 'average', $filter = 'grey')
{
	global $domalgos, $colfilters;
	$png = '/tmp/hicg-icon-' . uniqid() . '.png';
	if (!in_array($algo, $domalgos)) {
		warn('Invalid dominant color extraction algorithm');
		return false;
	}
	if (!in_array($filter, $colfilters)) {
		warn('Invalid colors to ignore');
		return false;
	}
	if (!svg2png($svg, COLOR_EXTRACT_RENDER_SIZE, COLOR_EXTRACT_RENDER_SIZE, $png)) {
		warn('Initial rasterization failed (not an .svg file?)');
		return false;
	}
	$img = imagecreatefrompng($png);
	if (!$img) {
		warn('Initial rasterization generated incorrect PNG');
		return false;
	}
	$color = call_user_func('domcolor_'. $algo, $img, 'colfilter_'.$filter);
	imagedestroy($img);
	unlink($png);
	if (!$color) {
		warn("I failed to get a dominant color. Your icon might be too greyish, so I'm making it grey.");
		return array(128, 128, 128);
	}
	return $color;
}

function clip_color_value($c)
{
	if ($c < 0) return 0;
	else if ($c > 255) return 255;
	return $c;
}

function clip_color($c)
{
	return array_map('clip_color_value', $c);
}

function greyscale_color($c)
{
	return .299*$c[0] + .587*$c[1] + .114*$c[2];
}

function color2hex($c)
{
	return sprintf("%02x%02x%02x", $c[0], $c[1], $c[2]);
}

function get_disabled_color($c)
{
	/* Clear and desature a bit. */
	$nc = array_map(create_function('$x', 'return $x + 90;'), $c);
	$grey = greyscale_color($nc);
	$nc = array_map(create_function('$x', 'return $x * 0.8 + ('.$grey.') * 0.2;'), $nc);
	return clip_color($nc);
}

function get_pressed_color($c)
{
	/* Desaturate and darken. */
	$grey = greyscale_color($c);
	$nc = array_map(create_function('$x', 'return $x * 0.5 + ('.$grey.') * 0.5;'), $c);
	$nc = array_map(create_function('$x', 'return $x - 40;'), $nc);

	return clip_color($nc);
}

function get_icon_light_color($c)
{
	$nc = array_map(create_function('$x', 'return $x + 60;'), $c);
	return clip_color($nc);
}

function get_icon_dark_color($c)
{
	$nc = array_map(create_function('$x', 'return $x - 50;'), $c);
	return clip_color($nc);
}

function get_svg_attribute($node, $attrib)
{
	$v = $node->getAttributeNS(SVGNS, 'svg:' . $attrib);
	if (empty($v)) {
		$v = $node->getAttribute('svg:' . $attrib);
		if (empty($v)) {
			$v = $node->getAttribute($attrib);
		}
	}

	return $v;
}

function calc_scale_ratios($w, $h, &$s, &$tx, &$ty)
{
	if ($w > $h) {
		$s = HARMATTAN_FOCAL_SIZE / $w;
		$sw = HARMATTAN_FOCAL_SIZE;
		$sh = $s * $h;
	} else {
		$s = HARMATTAN_FOCAL_SIZE / $h;
		$sw = $s * $w;
		$sh = HARMATTAN_FOCAL_SIZE;
	}
	$tx = HARMATTAN_ICON_SIZE / 2 - $sw / 2;
	$ty = HARMATTAN_ICON_SIZE / 2 - $sh / 2;
}

function make_icon($src, $template, $dst, $color, $shadow)
{
	$srcDoc = new DOMDocument();
	$srcDoc->load($src);
	$doc = new DOMDocument();
	$doc->load($template);
	$xpath = new DOMXPath($doc);
	$xpath->registerNamespace('svg', SVGNS);

	/* Get scaling ratios from source SVG. */
	$srcNode = $srcDoc->documentElement;
	$w = intval(get_svg_attribute($srcNode, 'width'));
	$h = intval(get_svg_attribute($srcNode, 'height'));
	calc_scale_ratios($w, $h, $s, $tx, $ty);

	/* Set background color */
	$bkg = $xpath->query('/svg:svg/svg:g/svg:path[@id="hicg_background"]');
	$bkg->item(0)->setAttribute('fill', '#' . color2hex($color));

	/* Create the scaling & centering transform. */
	$g = $doc->createElement('g');
	$g->setAttribute('transform', "translate($tx, $ty) scale($s)");

	/* Add drop shadow filter if selected. */
	if ($shadow) {
		$g->setAttribute('filter', 'url(#hicg_drop_shadow)');
	}

	foreach ($srcNode->childNodes as $node) {
		$n = $doc->importNode($node, TRUE);
		$g->appendChild($n);
	}
	
	$doc->documentElement->appendChild($g);

	$doc->save($dst);

	return true;
}

function make_png($src, $dst)
{
	if (!svg2png($src, HARMATTAN_ICON_SIZE, HARMATTAN_ICON_SIZE, $dst)) {
		warn("I failed to generate a 80x80 PNG.");
		return false;
	}
	return true;
}

$warnings = array();
$loadsample = true;

if (@isset($_POST['send'])) {
	$prefix = './files/' . uniqid() . '_';
	$srcfile = $prefix . 'src.svg';
	if (!move_uploaded_file($_FILES['iconfile']['tmp_name'], $srcfile)) {
		die('Upload failed.');
	}
	$domalgo = $_POST['domalgo'];
	$colfilter = $_POST['colfilter'];
	$dropshadow = $_POST['dropshadow'] == 'dropshadow';
	$iconfile = $prefix . 'icon.svg';
	$pngfile = $prefix . 'icon.png';

	$domcolor = extract_dominant_color($srcfile, $domalgo, $colfilter);
	if ($domcolor) {
		$loadsample = false;
		$discolor = get_disabled_color($domcolor);
		$prscolor = get_pressed_color($domcolor);
	}

	if (!$loadsample) {
		make_icon($srcfile, 'template.svg', $iconfile, $domcolor, $dropshadow);
		make_png($iconfile, $pngfile);
	} else {
		/* Something went really wrong and we will show the sample, so delete uploaded SVG. */
		unlink($srcfile);
	}

	$srcurl = $srcfile;
	$iconurl = $iconfile;
	$pngurl = $pngfile;
}

if (php_sapi_name() == 'cli' && $argc >= 2) {
	$loadsample = false;
	$srcfile = $argv[1];
	$domalgo = 'mode';
	$dropshadow = true;
	$colfilter = 'grey';
	$iconfile = 'cliicon.svg';
	$pngfile = 'cliicon.png';

	$domcolor = extract_dominant_color($srcfile, $domalgo, $colfilter);

	make_icon($srcfile, 'template.svg', $iconfile, $domcolor, $dropshadow);
	make_png($iconfile, $pngfile);

	exit(0);
}

if ($loadsample) {
	/* Load some sample data. */
	$srcfile = 'samplesrc.svg';
	$domalgo = 'mode';
	$dropshadow = true;
	$colfilter = 'grey';
	$iconfile = 'sampleicon.svg';
	$pngfile = 'sampleicon.png';

	$domcolor = extract_dominant_color($srcfile, $domalgo, $colfilter);
	$discolor = get_disabled_color($domcolor);
	$prscolor = get_pressed_color($domcolor);

	$srcurl = $srcfile;
	$iconurl = $iconfile;
	$pngurl = $pngfile;
}

echo '<?xml version="1.0" encoding="utf-8" ?>';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Harmattan Icon Generator</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<?php if (!empty($warnings)): ?>
<h1>Warnings</h1>
<?php foreach ($warnings as $w): ?>
	<p><strong>Warning:</strong> <?php echo $w; ?></p>
<?php endforeach; ?>
<?php endif; ?>
<h1>Upload your icon</h1>
<form enctype="multipart/form-data" action="." method="post">
	<fieldset>
		<legend>Your application's current icon file</legend>
		<label>SVG icon file:
			<input type="file" name="iconfile" size="60" />
		</label>
	</fieldset>
	<fieldset>
		<legend>Algorithm for dominant color extraction</legend>
		<label><input type="radio" name="domalgo" value="mean" />Mean / Average</label>
		<label><input type="radio" name="domalgo" value="mode" checked="true" />Mode</label>
		<label><input type="radio" name="domalgo" value="custom" />Custom: <input type="text" name="customcolor" /></label>
	</fieldset>
	<fieldset>
		<legend>Colors to ignore</legend>
		<label><input type="radio" name="colfilter" value="none" />None</label>
		<label><input type="radio" name="colfilter" value="pure" />Pure white/blacks</label>
		<label><input type="radio" name="colfilter" value="grey" checked="true" />Pure greys</label>
		<label><input type="radio" name="colfilter" value="grey5" />Greys at 5bpp per channel</label>
	</fieldset>
	<fieldset>
		<legend>Drop shadow</legend>
		<label><input type="checkbox" name="dropshadow" value="dropshadow" checked="true" />Add drop shadow</label>
	</fieldset>
	<div class="buttons">
		<input type="submit" name="send" value="Submit" />
	</div>
</form>
<h1>Results</h1>
<div id="uploaded">
	<p>You uploaded:</p>
	<object type="image/svg+xml" data="<?php echo $srcurl; ?>" width="200" height="200"></object>
</div>
<div id="results">
	<div id="yourcolor">
		<p>Your icon's dominant color is <span class="color">#<?php echo color2hex($domcolor); ?></span></p>
		<div class="color" style="background-color: #<?php echo color2hex($domcolor); ?>;"></div>
	</div>
	<div id="discolor">
		<p>A suggested disabled color is <span class="color">#<?php echo color2hex($discolor); ?></span></p>
		<div class="color" style="background-color: #<?php echo color2hex($discolor); ?>;"></div>
	</div>
	<div id="prscolor">
		<p>A suggested pressed color is <span class="color">#<?php echo color2hex($prscolor); ?></span></p>
		<div class="color" style="background-color: #<?php echo color2hex($prscolor); ?>;"></div>
	</div>
	<div id="youricon">
		<p>Harmattan style icon:</p>
		<div>
			<div class="icon">
				<object type="image/svg+xml" data="<?php echo $iconurl; ?>" width="80" height="80"></object>
				<p>YourApp</p>
			</div>
		</div>
	</div>
	<p>Download the prerendered 80x80 <a href="<?php echo $pngurl; ?>">PNG file</a>. Or a <a href="<?php echo $iconurl; ?>">SVG file</a>, if you want to make more changes.</p>
</div>
<h1>Suggested reading</h1>
<ul>
	<li><a href="http://www.developer.nokia.com/swipe/ux/pages/Colour.html">Nokia N9 UX Color Guidelines</a></li>
	<li><a href="http://www.developer.nokia.com/swipe/ux/pages/Icons.html">Nokia N9 UX Icon Guidelines</a></li>
	<li><a href="https://gitorious.org/hicg/hicg">The source for this tool</a></li>
</ul>
</body>
</html>