finish things up for 4.0b3
[mandelbrot.git] / content / mandelbrot.js
CommitLineData
5b823560
RK
1/* ***** BEGIN LICENSE BLOCK *****
2 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
3 *
4 * The contents of this file are subject to the Mozilla Public License Version
5 * 1.1 (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 * http://www.mozilla.org/MPL/
8 *
9 * Software distributed under the License is distributed on an "AS IS" basis,
10 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
11 * for the specific language governing rights and limitations under the
12 * License.
13 *
14 * The Original Code is KaiRo.at Mandelbrot, XULRunner version.
15 *
16 * The Initial Developer of the Original Code is
17 * Robert Kaiser <kairo@kairo.at>.
8a2b6e17 18 * Portions created by the Initial Developer are Copyright (C) 2008-2011
5b823560
RK
19 * the Initial Developer. All Rights Reserved.
20 *
21 * Contributor(s):
22 * Robert Kaiser <kairo@kairo.at>
8a2b6e17
RK
23 * prefiks (patch for some speedups)
24 * Boris Zbarsky <bzbarsky@mit.edu> (use imageData for canvas interaction)
5b823560
RK
25 *
26 * Alternatively, the contents of this file may be used under the terms of
27 * either the GNU General Public License Version 2 or later (the "GPL"), or
28 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
29 * in which case the provisions of the GPL or the LGPL are applicable instead
30 * of those above. If you wish to allow use of your version of this file only
31 * under the terms of either the GPL or the LGPL, and not to allow others to
32 * use your version of this file under the terms of the MPL, indicate your
33 * decision by deleting the provisions above and replace them with the notice
34 * and other provisions required by the GPL or the LGPL. If you do not delete
35 * the provisions above, a recipient may use your version of this file under
36 * the terms of any one of the MPL, the GPL or the LGPL.
37 *
38 * ***** END LICENSE BLOCK ***** */
39
140e460f
RK
40Components.utils.import("resource://gre/modules/Services.jsm");
41
6e98af87 42var gColorPalette = [];
6e98af87 43var gStartTime = 0;
fa4ecb24 44var gMbrotBundle;
86e67c44 45var gCurrentImageData;
6e98af87
RK
46
47function Startup() {
fa4ecb24
RK
48 gMbrotBundle = document.getElementById("mbrotBundle");
49 document.getElementById("statusLabel").value = gMbrotBundle.getString("statusEmpty");
3fd66836
RK
50
51 let img = document.getElementById("mbrotImage");
52 img.addEventListener("mouseup", imgEvHandler, false);
53 img.addEventListener("mousedown", imgEvHandler, false);
54 img.addEventListener("mousemove", imgEvHandler, false);
55 img.addEventListener("touchstart", imgEvHandler, false);
56 img.addEventListener("touchend", imgEvHandler, false);
57 img.addEventListener("touchcancel", imgEvHandler, false);
58 img.addEventListener("touchleave", imgEvHandler, false);
59 img.addEventListener("touchmove", imgEvHandler, false);
140e460f
RK
60
61 Services.obs.notifyObservers(window, "mandelbrot-loaded", null);
6e98af87 62}
37b05b56 63
a79ddf52
RK
64function getAdjustPref(prefname) {
65 let value;
66 switch (prefname) {
67 case "image.width":
68 case "image.height":
69 value = 0;
70 try {
140e460f 71 value = Services.prefs.getIntPref("mandelbrot." + prefname);
a79ddf52
RK
72 }
73 catch (e) { }
74 if ((value < 10) || (value > 5000)) {
75 value = 300;
140e460f 76 Services.prefs.setIntPref("mandelbrot." + prefname, value);
a79ddf52
RK
77 }
78 return value;
79 case "last_image.Cr_*":
80 let Cr_min = -2.0;
81 let Cr_max = 1.0;
82 try {
140e460f
RK
83 Cr_min = parseFloat(Services.prefs.getCharPref("mandelbrot.last_image.Cr_min"));
84 Cr_max = parseFloat(Services.prefs.getCharPref("mandelbrot.last_image.Cr_max"));
a79ddf52
RK
85 }
86 catch (e) { }
87 if ((Cr_min < -3) || (Cr_min > 2) ||
88 (Cr_max < -3) || (Cr_max > 2) || (Cr_min >= Cr_max)) {
89 Cr_min = -2.0; Cr_max = 1.0;
90 }
140e460f
RK
91 Services.prefs.setCharPref("mandelbrot.last_image.Cr_min", Cr_min);
92 Services.prefs.setCharPref("mandelbrot.last_image.Cr_max", Cr_max);
a79ddf52
RK
93 return {Cr_min: Cr_min, Cr_max: Cr_max};
94 case "last_image.Ci_*":
95 let Ci_min = -1.5;
96 let Ci_max = 1.5;
97 try {
140e460f
RK
98 Ci_min = parseFloat(Services.prefs.getCharPref("mandelbrot.last_image.Ci_min"));
99 Ci_max = parseFloat(Services.prefs.getCharPref("mandelbrot.last_image.Ci_max"));
a79ddf52
RK
100 }
101 catch (e) { }
102 if ((Ci_min < -2.5) || (Ci_min > 2.5) ||
103 (Ci_max < -2.5) || (Ci_max > 2.5) || (Ci_min >= Ci_max)) {
104 Ci_min = -1.5; Ci_max = 1.5;
105 }
140e460f
RK
106 Services.prefs.setCharPref("mandelbrot.last_image.Ci_min", Ci_min);
107 Services.prefs.setCharPref("mandelbrot.last_image.Ci_max", Ci_max);
a79ddf52
RK
108 return {Ci_min: Ci_min, Ci_max: Ci_max};
109 case "iteration_max":
110 value = 500;
111 try {
140e460f 112 value = Services.prefs.getIntPref("mandelbrot." + prefname);
a79ddf52
RK
113 }
114 catch (e) {
115 setIter(value);
116 }
117 if (value < 10 || value > 10000) {
118 value = 500;
119 setIter(value);
120 }
121 return value;
122 case "use_algorithm":
123 value = "numeric";
124 try {
140e460f 125 value = Services.prefs.getCharPref("mandelbrot." + prefname);
a79ddf52
RK
126 }
127 catch (e) {
128 setAlgorithm(value);
129 }
130 return value;
131 case "color_palette":
132 value = "kairo";
133 try {
140e460f 134 value = Services.prefs.getCharPref("mandelbrot." + prefname);
a79ddf52
RK
135 }
136 catch(e) {
137 setPalette(value);
138 }
139 return value;
140 case "syncProportions":
141 value = true;
142 try {
140e460f 143 value = Services.prefs.getBoolPref("mandelbrot." + prefname);
a79ddf52
RK
144 }
145 catch(e) {
140e460f 146 Services.prefs.setBoolPref("mandelbrot." + prefname, value);
a79ddf52
RK
147 }
148 return value;
149 default:
150 return false;
86e67c44 151 }
a79ddf52
RK
152}
153
154function adjustCoordsAndDraw(aC_min, aC_max) {
155 let iWidth = getAdjustPref("image.width");
156 let iHeight = getAdjustPref("image.height");
86e67c44
RK
157
158 // correct coordinates
159 if (aC_min.r < -2)
160 aC_min.r = -2;
161 if (aC_max.r > 2)
162 aC_max.r = 2;
163 if ((aC_min.r > 2) || (aC_max.r < -2) || (aC_min.r >= aC_max.r)) {
164 aC_min.r = -2.0; aC_max.r = 1.0;
165 }
166 if (aC_min.i < -2)
167 aC_min.i = -2;
168 if (aC_max.i > 2)
169 aC_max.i = 2;
170 if ((aC_min.i > 2) || (aC_max.i < -2) || (aC_min.i >= aC_max.i)) {
30586599 171 aC_min.i = -1.3; aC_max.i = 1.3;
86e67c44
RK
172 }
173
174 let CWidth = aC_max.r - aC_min.r;
175 let CHeight = aC_max.i - aC_min.i;
176 let C_mid = new complex(aC_min.r + CWidth / 2, aC_min.i + CHeight / 2);
177
178 let CRatio = Math.max(CWidth / iWidth, CHeight / iHeight);
179
140e460f
RK
180 Services.prefs.setCharPref("mandelbrot.last_image.Cr_min", C_mid.r - iWidth * CRatio / 2);
181 Services.prefs.setCharPref("mandelbrot.last_image.Cr_max", C_mid.r + iWidth * CRatio / 2);
182 Services.prefs.setCharPref("mandelbrot.last_image.Ci_min", C_mid.i - iHeight * CRatio / 2);
183 Services.prefs.setCharPref("mandelbrot.last_image.Ci_max", C_mid.i + iHeight * CRatio / 2);
86e67c44
RK
184
185 drawImage();
186}
187
37b05b56 188function drawImage() {
8a9c8e3f 189 let canvas = document.getElementById("mbrotImage");
2cb9a6b5 190 let context = canvas.getContext("2d");
37b05b56 191
5366c7d6
RK
192 document.getElementById("drawButton").hidden = true;
193
fa4ecb24 194 document.getElementById("statusLabel").value = gMbrotBundle.getString("statusDrawing");
2cb9a6b5 195
a79ddf52
RK
196 let Cr_vals = getAdjustPref("last_image.Cr_*");
197 let Cr_min = Cr_vals.Cr_min;
198 let Cr_max = Cr_vals.Cr_max;
eceff1c9 199
a79ddf52
RK
200 let Ci_vals = getAdjustPref("last_image.Ci_*");
201 let Ci_min = Ci_vals.Ci_min;
202 let Ci_max = Ci_vals.Ci_max;
eceff1c9 203
a79ddf52
RK
204 let iterMax = getAdjustPref("iteration_max");
205 let algorithm = getAdjustPref("use_algorithm");
6e98af87 206
a79ddf52
RK
207 let iWidth = getAdjustPref("image.width");
208 let iHeight = getAdjustPref("image.height");
eceff1c9 209
86e67c44
RK
210 gCurrentImageData = {
211 C_min: new complex(Cr_min, Ci_min),
212 C_max: new complex(Cr_max, Ci_max),
213 iWidth: iWidth,
214 iHeight: iHeight,
215 iterMax: iterMax
216 };
217
eceff1c9
RK
218 canvas.width = iWidth;
219 canvas.height = iHeight;
220
221 context.fillStyle = "rgba(255, 255, 255, 127)";
2cb9a6b5 222 context.fillRect(0, 0, canvas.width, canvas.height);
37b05b56 223
2cb9a6b5
RK
224 gStartTime = new Date();
225
eceff1c9
RK
226 drawLine(0, [Cr_min, Cr_max, Ci_min, Ci_max],
227 canvas, context, iterMax, algorithm);
2cb9a6b5
RK
228}
229
eceff1c9 230function drawLine(line, dimensions, canvas, context, iterMax, algorithm) {
aad35028
RK
231 let Cr_min = dimensions[0];
232 let Cr_max = dimensions[1];
233 let Cr_scale = Cr_max - Cr_min;
234
235 let Ci_min = dimensions[2];
236 let Ci_max = dimensions[3];
237 let Ci_scale = Ci_max - Ci_min;
238
8a2b6e17
RK
239 let lines = Math.min(canvas.height - line, 8);
240 let imageData = context.createImageData(canvas.width, lines);
241 let pixels = imageData.data;
242 let idx = 0;
aad35028
RK
243 for (var img_y = line; img_y < canvas.height && img_y < line+8; img_y++)
244 for (let img_x = 0; img_x < canvas.width; img_x++) {
245 let C = new complex(Cr_min + (img_x / canvas.width) * Cr_scale,
246 Ci_min + (img_y / canvas.height) * Ci_scale);
8a2b6e17
RK
247 let colors = drawPoint(context, img_x, img_y, C, iterMax, algorithm);
248 pixels[idx++] = colors[0];
249 pixels[idx++] = colors[1];
250 pixels[idx++] = colors[2];
251 pixels[idx++] = colors[3];
aad35028 252 }
8a2b6e17 253 context.putImageData(imageData, 0, line);
2cb9a6b5 254
aad35028
RK
255 if (img_y < canvas.height)
256 setTimeout(drawLine, 0, img_y, dimensions, canvas, context, iterMax, algorithm);
257 else if (gStartTime)
258 EndCalc();
37b05b56
RK
259}
260
6e98af87
RK
261function EndCalc() {
262 let endTime = new Date();
263 let timeUsed = (endTime.getTime() - gStartTime.getTime()) / 1000;
264 document.getElementById("statusLabel").value =
fa4ecb24 265 gMbrotBundle.getFormattedString("statusTime", [timeUsed.toFixed(3)]);
287a980b 266 gStartTime = 0;
6e98af87
RK
267}
268
37b05b56
RK
269function complex(aReal, aImag) {
270 this.r = aReal;
271 this.i = aImag;
2cb9a6b5
RK
272}
273complex.prototype = {
274 square: function() {
37b05b56
RK
275 return new complex(this.r * this.r - this.i * this.i,
276 2 * this.r * this.i);
2cb9a6b5
RK
277 },
278 dist: function() {
37b05b56 279 return Math.sqrt(this.r * this.r + this.i * this.i);
2cb9a6b5
RK
280 },
281 add: function(aComplex) {
37b05b56
RK
282 return new complex(this.r + aComplex.r, this.i + aComplex.i);
283 }
284}
285
6e98af87
RK
286function mandelbrotValueOO (aC, aIterMax) {
287 // this would be nice code in general but it looks like JS objects are too heavy for normal use.
8444612a 288 let Z = new complex(0.0, 0.0);
37b05b56
RK
289 for (var iter = 0; iter < aIterMax; iter++) {
290 Z = Z.square().add(aC);
291 if (Z.r * Z.r + Z.i * Z.i > 256) { break; }
292 }
6e98af87
RK
293 return iter;
294}
8444612a 295
6e98af87
RK
296function mandelbrotValueNumeric (aC, aIterMax) {
297 // optimized numeric code for fast calculation
8444612a
RK
298 let Cr = aC.r, Ci = aC.i;
299 let Zr = 0.0, Zi = 0.0;
300 let Zr2 = Zr * Zr, Zi2 = Zi * Zi;
301 for (var iter = 0; iter < aIterMax; iter++) {
302 Zi = 2 * Zr * Zi + Ci;
303 Zr = Zr2 - Zi2 + Cr;
304
305 Zr2 = Zr * Zr; Zi2 = Zi * Zi;
306 if (Zr2 + Zi2 > 256) { break; }
307 }
37b05b56
RK
308 return iter;
309}
310
311function getColor(aIterValue, aIterMax) {
8a9c8e3f 312 let standardizedValue = Math.round(aIterValue * 1024 / aIterMax);
6e98af87
RK
313 if (gColorPalette && gColorPalette.length)
314 return gColorPalette[standardizedValue];
315
316 // fallback to simple b/w if for some reason we don't have a palette
317 if (aIterValue == aIterMax)
2cb9a6b5 318 return [0, 0, 0, 255];
6e98af87 319 else
2cb9a6b5 320 return [255, 255, 255, 255];
37b05b56
RK
321}
322
323function getColorPalette(palName) {
324 var palette = [];
325 switch (palName) {
326 case 'bw':
8a9c8e3f 327 for (let i = 0; i < 1024; i++) {
2cb9a6b5 328 palette[i] = [255, 255, 255, 255];
37b05b56 329 }
2cb9a6b5 330 palette[1024] = [0, 0, 0, 255];
37b05b56
RK
331 break;
332 case 'kairo':
333 // outer areas
8a9c8e3f
RK
334 for (let i = 0; i < 32; i++) {
335 let cc1 = Math.floor(i * 127 / 31);
336 let cc2 = 170 - Math.floor(i * 43 / 31);
2cb9a6b5 337 palette[i] = [cc1, cc2, cc1, 255];
37b05b56
RK
338 }
339 // inner areas
8a9c8e3f
RK
340 for (let i = 0; i < 51; i++) {
341 let cc = Math.floor(i * 170 / 50);
2cb9a6b5 342 palette[32 + i] = [cc, 0, (170-cc), 255];
37b05b56
RK
343 }
344 // corona
8a9c8e3f
RK
345 for (let i = 0; i < 101; i++) {
346 let cc = Math.floor(i * 200 / 100);
2cb9a6b5 347 palette[83 + i] = [255, cc, 0, 255];
37b05b56
RK
348 }
349 // inner corona
8a9c8e3f
RK
350 for (let i = 0; i < 201; i++) {
351 let cc1 = 255 - Math.floor(i * 85 / 200);
352 let cc2 = 200 - Math.floor(i * 30 / 200);
353 let cc3 = Math.floor(i * 170 / 200);
2cb9a6b5 354 palette[184 + i] = [cc1, cc2, cc3, 255];
37b05b56 355 }
8a9c8e3f
RK
356 for (let i = 0; i < 301; i++) {
357 let cc1 = 170 - Math.floor(i * 43 / 300);
358 let cc2 = 170 + Math.floor(i * 85 / 300);
2cb9a6b5 359 palette[385 + i] = [cc1, cc1, cc2, 255];
37b05b56 360 }
8a9c8e3f
RK
361 for (let i = 0; i < 338; i++) {
362 let cc = 127 + Math.floor(i * 128 / 337);
2cb9a6b5 363 palette[686 + i] = [cc, cc, 255, 255];
37b05b56 364 }
2cb9a6b5 365 palette[1024] = [0, 0, 0, 255];
37b05b56
RK
366 break;
367 case 'rainbow-linear1':
8a9c8e3f 368 for (let i = 0; i < 256; i++) {
2cb9a6b5
RK
369 palette[i] = [i, 0, 0, 255];
370 palette[256 + i] = [255, i, 0, 255];
371 palette[512 + i] = [255 - i, 255, i, 255];
372 palette[768 + i] = [i, 255-i, 255, 255];
37b05b56 373 }
2cb9a6b5 374 palette[1024] = [0, 0, 0, 255];
37b05b56 375 break;
72eff464
RK
376 case 'rainbow-squared1':
377 for (let i = 0; i < 34; i++) {
378 let cc = Math.floor(i * 255 / 33);
379 palette[i] = [cc, 0, 0, 255];
380 }
381 for (let i = 0; i < 137; i++) {
382 let cc = Math.floor(i * 255 / 136);
383 palette[34 + i] = [255, cc, 0, 255];
384 }
385 for (let i = 0; i < 307; i++) {
386 let cc = Math.floor(i * 255 / 306);
387 palette[171 + i] = [255 - cc, 255, cc, 255];
388 }
389 for (let i = 0; i < 546; i++) {
390 let cc = Math.floor(i * 255 / 545);
391 palette[478 + i] = [cc, 255 - cc, 255, 255];
392 }
393 palette[1024] = [0, 0, 0, 255];
394 break;
395 case 'rainbow-linear2':
396 for (let i = 0; i < 205; i++) {
397 let cc = Math.floor(i * 255 / 204);
398 palette[i] = [255, cc, 0, 255];
399 palette[204 + i] = [255 - cc, 255, 0, 255];
400 palette[409 + i] = [0, 255, cc, 255];
401 palette[614 + i] = [0, 255 - cc, 255, 255];
402 palette[819 + i] = [cc, 0, 255, 255];
403 }
404 palette[1024] = [0, 0, 0, 255];
405 break;
406 case 'rainbow-squared2':
407 for (let i = 0; i < 19; i++) {
408 let cc = Math.floor(i * 255 / 18);
409 palette[i] = [255, cc, 0, 255];
410 }
411 for (let i = 0; i < 74; i++) {
412 let cc = Math.floor(i * 255 / 73);
413 palette[19 + i] = [255 - cc, 255, 0, 255];
414 }
415 for (let i = 0; i < 168; i++) {
416 let cc = Math.floor(i * 255 / 167);
417 palette[93 + i] = [0, 255, cc, 255];
418 }
419 for (let i = 0; i < 298; i++) {
420 let cc = Math.floor(i * 255 / 297);
421 palette[261 + i] = [0, 255 - cc, 255, 255];
422 }
423 for (let i = 0; i < 465; i++) {
424 let cc = Math.floor(i * 255 / 464);
425 palette[559 + i] = [cc, 0, 255, 255];
426 }
427 palette[1024] = [0, 0, 0, 255];
428 break;
37b05b56 429 }
72eff464
RK
430 /*
431 'Standard-Palette (QB-Colors)
37b05b56
RK
432 For i = 0 To 1024
433 xx = CInt(i * 500 / 1024 + 2)
434 If xx <= 15 Then clr = xx
435 If xx > 15 Then clr = CInt(Sqr((xx - 15 + 1) * 15 ^ 2 / 485))
436 If xx >= 500 Then clr = 0
437 palette(i) = QBColor(clr)
438 Next
72eff464 439 */
37b05b56
RK
440 return palette;
441}
442
6e98af87
RK
443function drawPoint(context, img_x, img_y, C, iterMax, algorithm) {
444 var itVal;
445 switch (algorithm) {
446 case 'oo':
447 itVal = mandelbrotValueOO(C, iterMax);
448 break;
449 case 'numeric':
450 default:
451 itVal = mandelbrotValueNumeric(C, iterMax);
452 break;
453 }
2cb9a6b5 454 return getColor(itVal, iterMax);
37b05b56
RK
455}
456
6e98af87
RK
457/***** pure UI functions *****/
458
4d8e7dcb 459var zoomstart;
7e4a9776 460var imgBackup;
4d8e7dcb 461
3fd66836
RK
462let imgEvHandler = {
463 handleEvent: function(aEvent) {
464 let canvas = document.getElementById("mbrotImage");
465 let context = canvas.getContext("2d");
466 switch (aEvent.type) {
467 case 'mousedown':
468 case 'touchstart':
469 if (aEvent.button == 0) {
470 // left button - start dragzoom
471 zoomstart = {x: aEvent.clientX - canvas.offsetLeft,
472 y: aEvent.clientY - canvas.offsetTop};
473 imgBackup = context.getImageData(0, 0, canvas.width, canvas.height);
474 }
475 break;
476 case 'mouseup':
477 case 'touchend':
478 if (aEvent.button == 0 && zoomstart) {
479 context.putImageData(imgBackup, 0, 0);
480 let zoomend = {x: aEvent.clientX - canvas.offsetLeft,
481 y: aEvent.clientY - canvas.offsetTop};
482
483 // make sure zoomend is bigger than zoomstart
484 if ((zoomend.x == zoomstart.x) || (zoomend.y == zoomstart.y)) {
485 // cannot zoom what has no area, discard it
486 zoomstart = undefined;
487 return;
488 }
489 if (zoomend.x < zoomstart.x)
490 [zoomend.x, zoomstart.x] = [zoomstart.x, zoomend.x];
491 if (zoomend.y < zoomstart.y)
492 [zoomend.y, zoomstart.y] = [zoomstart.y, zoomend.y];
493
494 // determine new "coordinates"
495 let CWidth = gCurrentImageData.C_max.r - gCurrentImageData.C_min.r;
496 let CHeight = gCurrentImageData.C_max.i - gCurrentImageData.C_min.i;
497 let newC_min = new complex(
498 gCurrentImageData.C_min.r + zoomstart.x / gCurrentImageData.iWidth * CWidth,
499 gCurrentImageData.C_min.i + zoomstart.y / gCurrentImageData.iHeight * CHeight);
500 let newC_max = new complex(
501 gCurrentImageData.C_min.r + zoomend.x / gCurrentImageData.iWidth * CWidth,
502 gCurrentImageData.C_min.i + zoomend.y / gCurrentImageData.iHeight * CHeight);
503
504 adjustCoordsAndDraw(newC_min, newC_max);
505 }
506 zoomstart = undefined;
507 break;
508 case 'mousemove':
509 case 'touchmove':
510 if (aEvent.button == 0 && zoomstart) {
511 context.putImageData(imgBackup, 0, 0);
512 context.strokeStyle = "rgb(255,255,31)";
513 context.strokeRect(zoomstart.x, zoomstart.y,
514 aEvent.clientX - canvas.offsetLeft - zoomstart.x,
515 aEvent.clientY - canvas.offsetTop - zoomstart.y);
86e67c44 516 }
7e4a9776 517 break;
3fd66836 518 }
4d8e7dcb 519 }
3fd66836 520};
4d8e7dcb 521
37b05b56 522function saveImage() {
740b86d1 523 const nsIFilePicker = Components.interfaces.nsIFilePicker;
aad35028 524 let fp = null;
740b86d1
RK
525 try {
526 fp = Components.classes["@mozilla.org/filepicker;1"]
527 .createInstance(nsIFilePicker);
528 } catch (e) {}
529 if (!fp) return;
aad35028 530 let promptString = gMbrotBundle.getString("savePrompt");
740b86d1 531 fp.init(window, promptString, nsIFilePicker.modeSave);
fa4ecb24 532 fp.appendFilter(gMbrotBundle.getString("pngFilterName"), "*.png");
740b86d1
RK
533 fp.defaultString = "mandelbrot.png";
534
aad35028 535 let fpResult = fp.show();
740b86d1
RK
536 if (fpResult != nsIFilePicker.returnCancel) {
537 saveCanvas(document.getElementById("mbrotImage"), fp.file);
538 }
37b05b56
RK
539}
540
474b436c
RK
541function exitMandelbrot() {
542 var appInfo = Components.classes["@mozilla.org/xre/app-info;1"]
543 .getService(Components.interfaces.nsIXULAppInfo);
544 if (appInfo.ID == "mandelbrot@kairo.at")
545 quitApp(false);
546 else
547 window.close();
548}
549
287a980b
RK
550function updateBookmarkMenu(aParent) {
551 document.getElementById("bookmarkSave").disabled =
552 (!document.getElementById("drawButton").hidden || (gStartTime > 0));
553
554 while (aParent.hasChildNodes() &&
86e67c44 555 aParent.lastChild.id != "bookmarkSeparator")
287a980b
RK
556 aParent.removeChild(aParent.lastChild);
557
aad35028 558 let file = Components.classes["@mozilla.org/file/directory_service;1"]
287a980b
RK
559 .getService(Components.interfaces.nsIProperties)
560 .get("ProfD", Components.interfaces.nsIFile);
561 file.append("mandelbookmarks.sqlite");
562 if (file.exists()) {
aad35028 563 let connection = Components.classes["@mozilla.org/storage/service;1"]
287a980b
RK
564 .getService(Components.interfaces.mozIStorageService)
565 .openDatabase(file);
566 try {
567 if (connection.tableExists("bookmarks")) {
aad35028 568 let statement = connection.createStatement(
86e67c44
RK
569 "SELECT name,ROWID FROM bookmarks ORDER BY ROWID ASC");
570 while (statement.executeStep()) {
571 let newItem = aParent.appendChild(document.createElement("menuitem"));
572 newItem.setAttribute("label", statement.getString(0));
573 newItem.setAttribute("bmRowID", statement.getString(1));
574 }
287a980b
RK
575 statement.reset();
576 statement.finalize();
577 return;
2eed6617 578 }
287a980b
RK
579 } finally {
580 connection.close();
2eed6617 581 }
287a980b
RK
582 }
583 // Create the "Nothing Available" Menu item and disable it.
aad35028 584 let na = aParent.appendChild(document.createElement("menuitem"));
fa4ecb24 585 na.setAttribute("label", gMbrotBundle.getString("noBookmarks"));
287a980b 586 na.setAttribute("disabled", "true");
2eed6617
RK
587}
588
589function callBookmark(evtarget) {
86e67c44 590 if (evtarget.id == "bookmarkSave" || evtarget.id == "bookmarkSeparator")
b8f9a76f
RK
591 return;
592 if (evtarget.id == "bookmarkOverview") {
593 adjustCoordsAndDraw(new complex(0,0), new complex(0,0));
594 return;
595 }
f34775a6
RK
596
597 if (evtarget.getAttribute('bmRowID')) {
598 let iterMax = 0;
599 let C_min = null;
600 let C_max = null;
601
602 let file = Components.classes["@mozilla.org/file/directory_service;1"]
603 .getService(Components.interfaces.nsIProperties)
604 .get("ProfD", Components.interfaces.nsIFile);
605 file.append("mandelbookmarks.sqlite");
606 let connection = Components.classes["@mozilla.org/storage/service;1"]
607 .getService(Components.interfaces.mozIStorageService)
608 .openDatabase(file);
609 let statement = connection.createStatement(
610 "SELECT iteration_max,Cr_min,Cr_max,Ci_min,Ci_max FROM bookmarks WHERE ROWID=?1");
611 statement.bindStringParameter(0, evtarget.getAttribute('bmRowID'));
612 while (statement.executeStep()) {
613 iterMax = statement.getInt32(0);
614 C_min = new complex(statement.getDouble(1), statement.getDouble(3));
615 C_max = new complex(statement.getDouble(2), statement.getDouble(4));
616 }
617 statement.finalize();
618 connection.close();
619
620 if (iterMax && C_min && C_max) {
140e460f 621 Services.prefs.setIntPref("mandelbrot.iteration_max", iterMax);
f34775a6
RK
622 adjustCoordsAndDraw(C_min, C_max);
623 }
624 }
2eed6617
RK
625}
626
627function saveBookmark() {
9c2ca9fa 628 // retrieve wanted bookmark name with a prompt
aad35028 629 let prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
9c2ca9fa 630 .getService(Components.interfaces.nsIPromptService);
aad35028
RK
631 let input = {value: ""}; // empty default value
632 let ok = prompts.prompt(null, gMbrotBundle.getString("saveBookmarkTitle"), gMbrotBundle.getString("saveBookmarkLabel"), input, null, {});
9c2ca9fa
RK
633 // ok is true if OK is pressed, false if Cancel. input.value holds the value of the edit field if "OK" was pressed.
634 if (!ok || !input.value)
635 return
636
aad35028 637 let bmName = input.value;
287a980b
RK
638
639 // Open or create the bookmarks database.
aad35028 640 let file = Components.classes["@mozilla.org/file/directory_service;1"]
287a980b
RK
641 .getService(Components.interfaces.nsIProperties)
642 .get("ProfD", Components.interfaces.nsIFile);
643 file.append("mandelbookmarks.sqlite");
aad35028 644 let connection = Components.classes["@mozilla.org/storage/service;1"]
287a980b
RK
645 .getService(Components.interfaces.mozIStorageService)
646 .openDatabase(file);
647 connection.beginTransaction();
648 if (!connection.tableExists("bookmarks"))
649 connection.createTable("bookmarks", "name TEXT, iteration_max INTEGER, Cr_min REAL, Cr_max REAL, Ci_min REAL, Ci_max REAL");
650 // NULL. The value is a NULL value.
651 // INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.
652 // REAL. The value is a floating point value, stored as an 8-byte IEEE floating point number.
653 // TEXT. The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16-LE).
654
655 // Put value of the current image into the bookmarks table
aad35028 656 let statement = connection.createStatement(
287a980b
RK
657 "INSERT INTO bookmarks (name,iteration_max,Cr_min,Cr_max,Ci_min,Ci_max) VALUES (?1,?2,?3,?4,?5,?6)");
658 statement.bindStringParameter(0, bmName);
86e67c44
RK
659 statement.bindStringParameter(1, gCurrentImageData.iterMax);
660 statement.bindStringParameter(2, gCurrentImageData.C_min.r);
661 statement.bindStringParameter(3, gCurrentImageData.C_max.r);
662 statement.bindStringParameter(4, gCurrentImageData.C_min.i);
663 statement.bindStringParameter(5, gCurrentImageData.C_max.i);
287a980b
RK
664 statement.execute();
665 statement.finalize();
666 connection.commitTransaction();
667 connection.close();
2eed6617
RK
668}
669
6403d662 670function imgSettings() {
60e048b2
RK
671 let anchor = null;
672 let position = "before_start";
5fb4a082 673 if (document.getElementById("mandelbrot-page").nodeName == "page") {
60e048b2
RK
674 anchor = document.getElementById("mandelbrotToolbar");
675 }
676 else {
677 anchor = document.getElementById("mandelbrotMenubar");
678 position = "after_start";
679 }
680 document.getElementById("imgSettingsPanel").showPopup(anchor, position);
6403d662
RK
681}
682
8a2b6e17
RK
683function initImgSettings() {
684 // Get values from prefs.
a79ddf52
RK
685 for each (let coord in ["Cr", "Ci"]) {
686 let coord_vals = getAdjustPref("last_image." + coord + "_*");
687 document.getElementById("is_" + coord + "_min").value = coord_vals[coord + "_min"];
688 document.getElementById("is_" + coord + "_max").value = coord_vals[coord + "_max"];
8a2b6e17
RK
689 }
690 for each (let dim in ["width", "height"]) {
a79ddf52 691 document.getElementById("is_img_" + dim).value = getAdjustPref("image." + dim);
8a2b6e17 692 }
a79ddf52 693 document.getElementById("is_syncProp").checked = getAdjustPref("syncProportions");
8a2b6e17
RK
694
695 // Calculate scales.
696 recalcCoord("Cr", "scale");
697 recalcCoord("Ci", "scale");
698
699 // Clear the preview.
700 let canvas = document.getElementById("is_mbrotPreview");
701 let context = canvas.getContext("2d");
702 context.fillStyle = "rgba(255, 255, 255, 127)";
703 context.fillRect(0, 0, canvas.width, canvas.height);
5fb4a082
RK
704
705 // Set lists to correct values.
706 updateIterList();
707 updatePaletteList();
708 updateAlgoList();
8a2b6e17
RK
709}
710
711function closeImgSettings() {
712 // Hide popup, which will automatically make a call to save values.
713 document.getElementById("imgSettingsPanel").hidePopup();
714}
715
716function saveImgSettings() {
717 // Get values to prefs.
718 for each (let coord in ["Cr_min", "Cr_max", "Ci_min", "Ci_max"]) {
140e460f
RK
719 Services.prefs.setCharPref("mandelbrot.last_image." + coord,
720 document.getElementById("is_" + coord).value);
8a2b6e17
RK
721 }
722 for each (let dim in ["width", "height"]) {
140e460f
RK
723 Services.prefs.setIntPref("mandelbrot.image." + dim,
724 document.getElementById("is_img_" + dim).value);
8a2b6e17 725 }
140e460f
RK
726 Services.prefs.setBoolPref("mandelbrot.syncProportions",
727 document.getElementById("is_syncProp").checked);
8a2b6e17
RK
728}
729
730function checkISValue(textbox, type) {
731 if (type == "coord") {
732 textbox.value = roundCoord(parseFloat(textbox.value));
733 }
734 else if (type == "dim") {
735 textbox.value = parseInt(textbox.value);
736 }
737}
738
739function drawPreview() {
740 let canvas = document.getElementById("is_mbrotPreview");
741 let context = canvas.getContext("2d");
742
743 if (document.getElementById("is_img_width").value /
744 document.getElementById("is_img_height").value
745 < 80 / 50) {
746 canvas.height = 50;
747 canvas.width = canvas.height *
748 document.getElementById("is_img_width").value /
749 document.getElementById("is_img_height").value;
750 }
751 else {
752 canvas.width = 80;
753 canvas.height = canvas.width *
754 document.getElementById("is_imgHeight").value /
755 document.getElementById("is_imgWidth").value;
756 }
757
758 let Cr_min = parseFloat(document.getElementById("is_Cr_min").value);
759 let Cr_max = parseFloat(document.getElementById("is_Cr_max").value);
760 if ((Cr_min < -2) || (Cr_min > 2) ||
761 (Cr_max < -2) || (Cr_max > 2) || (Cr_min >= Cr_max)) {
762 Cr_min = -2.0; Cr_max = 1.0;
763 }
764
765 let Ci_min = parseFloat(document.getElementById("is_Ci_min").value);
766 let Ci_max = parseFloat(document.getElementById("is_Ci_max").value);
767 if ((Ci_min < -2) || (Ci_min > 2) ||
768 (Ci_max < -2) || (Ci_max > 2) || (Ci_min >= Ci_max)) {
769 Ci_min = -2.0; Ci_max = 1.0;
770 }
771
a79ddf52
RK
772 let iterMax = getAdjustPref("iteration_max");
773 let algorithm = getAdjustPref("use_algorithm");
8a2b6e17
RK
774
775 context.fillStyle = "rgba(255, 255, 255, 127)";
776 context.fillRect(0, 0, canvas.width, canvas.height);
777
a79ddf52 778 let currentPalette = getAdjustPref("color_palette");
8a2b6e17
RK
779 gColorPalette = getColorPalette(currentPalette);
780
781 drawLine(0, [Cr_min, Cr_max, Ci_min, Ci_max],
782 canvas, context, iterMax, algorithm);
783}
784
785function recalcCoord(coord, target) {
786 let othercoord = (coord == "Ci") ? "Cr" : "Ci";
787 let owndim = (coord == "Ci") ? "height" : "width";
788 let otherdim = (coord == "Ci") ? "width" : "height";
3fd66836 789 let myscale;
8a2b6e17 790 if (target == "scale") {
3fd66836 791 myscale =
8a2b6e17
RK
792 parseFloat(document.getElementById("is_" + coord + "_max").value) -
793 parseFloat(document.getElementById("is_" + coord + "_min").value);
794 document.getElementById("is_" + coord + "_scale").value = roundCoord(myscale);
795 }
796 else if (target == 'max') {
797 let mymax =
798 parseFloat(document.getElementById("is_" + coord + "_min").value) +
799 parseFloat(document.getElementById("is_" + coord + "_scale").value);
800 document.getElementById("is_" + coord + "_max").value = roundCoord(mymax);
3fd66836 801 myscale = document.getElementById("is_" + coord + "_scale").value;
8a2b6e17
RK
802 }
803 if (document.getElementById("is_syncProp").checked) {
804 let otherscale = myscale *
805 document.getElementById("is_img_" + otherdim).value /
806 document.getElementById("is_img_" + owndim).value;
807 document.getElementById("is_" + othercoord + "_scale").value = roundCoord(otherscale);
808 let othermax =
809 parseFloat(document.getElementById("is_" + othercoord + "_min").value) +
810 parseFloat(document.getElementById("is_" + othercoord + "_scale").value);
811 document.getElementById("is_" + othercoord + "_max").value = roundCoord(othermax);
812 }
813}
814
815function checkProportions() {
816 if (!document.getElementById("is_syncProp").checked) {
817 recalcCoord("Cr", "scale");
818 }
819}
820
821function roundCoord(floatval) {
822 // We should round to 10 decimals here or so
823 return parseFloat(floatval.toFixed(10));
824}
825
5fb4a082
RK
826function updateIterList() {
827 let currentIter = getAdjustPref("iteration_max");
828 document.getElementById("iterList").value = currentIter;
829}
830
831function updatePaletteList() {
832 let currentPalette = getAdjustPref("color_palette");
833 if (!gColorPalette || !gColorPalette.length)
834 gColorPalette = getColorPalette(currentPalette);
835 document.getElementById("colorList").value = currentPalette;
836}
837
838function updateAlgoList() {
839 let currentAlgo = getAdjustPref("use_algorithm");
840 document.getElementById("algoList").value = currentAlgo;
841}
842
843function setIter(aIter) {
844 Services.prefs.setIntPref("mandelbrot.iteration_max", aIter);
845}
846
847function setPalette(aPaletteID) {
848 Services.prefs.setCharPref("mandelbrot.color_palette", aPaletteID);
849 gColorPalette = getColorPalette(aPaletteID);
850}
851
852function setAlgorithm(algoID) {
853 Services.prefs.setCharPref("mandelbrot.use_algorithm", algoID);
854}
855
856
6e98af87
RK
857/***** helper functions from external sources *****/
858
740b86d1
RK
859// function below is based on http://developer.mozilla.org/en/docs/Code_snippets:Canvas
860// custom modifications:
861// - use "a"-prefix on function arguments
862// - take an nsILocalFile as aDestFile argument
863// - always do silent download
864function saveCanvas(aCanvas, aDestFile) {
37b05b56
RK
865 // create a data url from the canvas and then create URIs of the source and targets
866 var io = Components.classes["@mozilla.org/network/io-service;1"]
867 .getService(Components.interfaces.nsIIOService);
740b86d1 868 var source = io.newURI(aCanvas.toDataURL("image/png", ""), "UTF8", null);
37b05b56
RK
869
870 // prepare to save the canvas data
871 var persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
872 .createInstance(Components.interfaces.nsIWebBrowserPersist);
873
874 persist.persistFlags = Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
875 persist.persistFlags |= Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION;
876
37b05b56 877 // save the canvas data to the file
740b86d1 878 persist.saveURI(source, null, null, null, null, aDestFile);
37b05b56 879}