add item to new Firefox button menu, make Firefox and SeaMonkey open Mandelbrot in...
[mandelbrot.git] / xulapp / chrome / mandelbrot / 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
6e98af87
RK
40var gColorPalette = [];
41var gPref = Components.classes["@mozilla.org/preferences-service;1"]
42 .getService(Components.interfaces.nsIPrefService)
43 .getBranch(null);
44var gStartTime = 0;
fa4ecb24 45var gMbrotBundle;
86e67c44 46var gCurrentImageData;
6e98af87
RK
47
48function Startup() {
49 updateIterMenu();
920e1fea 50 updateAlgoMenu();
6e98af87 51 updatePaletteMenu();
fa4ecb24
RK
52 gMbrotBundle = document.getElementById("mbrotBundle");
53 document.getElementById("statusLabel").value = gMbrotBundle.getString("statusEmpty");
6e98af87 54}
37b05b56 55
a79ddf52
RK
56function getAdjustPref(prefname) {
57 let value;
58 switch (prefname) {
59 case "image.width":
60 case "image.height":
61 value = 0;
62 try {
63 value = gPref.getIntPref("mandelbrot." + prefname);
64 }
65 catch (e) { }
66 if ((value < 10) || (value > 5000)) {
67 value = 300;
68 gPref.setIntPref("mandelbrot." + prefname, value);
69 }
70 return value;
71 case "last_image.Cr_*":
72 let Cr_min = -2.0;
73 let Cr_max = 1.0;
74 try {
75 Cr_min = parseFloat(gPref.getCharPref("mandelbrot.last_image.Cr_min"));
76 Cr_max = parseFloat(gPref.getCharPref("mandelbrot.last_image.Cr_max"));
77 }
78 catch (e) { }
79 if ((Cr_min < -3) || (Cr_min > 2) ||
80 (Cr_max < -3) || (Cr_max > 2) || (Cr_min >= Cr_max)) {
81 Cr_min = -2.0; Cr_max = 1.0;
82 }
83 gPref.setCharPref("mandelbrot.last_image.Cr_min", Cr_min);
84 gPref.setCharPref("mandelbrot.last_image.Cr_max", Cr_max);
85 return {Cr_min: Cr_min, Cr_max: Cr_max};
86 case "last_image.Ci_*":
87 let Ci_min = -1.5;
88 let Ci_max = 1.5;
89 try {
90 Ci_min = parseFloat(gPref.getCharPref("mandelbrot.last_image.Ci_min"));
91 Ci_max = parseFloat(gPref.getCharPref("mandelbrot.last_image.Ci_max"));
92 }
93 catch (e) { }
94 if ((Ci_min < -2.5) || (Ci_min > 2.5) ||
95 (Ci_max < -2.5) || (Ci_max > 2.5) || (Ci_min >= Ci_max)) {
96 Ci_min = -1.5; Ci_max = 1.5;
97 }
98 gPref.setCharPref("mandelbrot.last_image.Ci_min", Ci_min);
99 gPref.setCharPref("mandelbrot.last_image.Ci_max", Ci_max);
100 return {Ci_min: Ci_min, Ci_max: Ci_max};
101 case "iteration_max":
102 value = 500;
103 try {
104 value = gPref.getIntPref("mandelbrot." + prefname);
105 }
106 catch (e) {
107 setIter(value);
108 }
109 if (value < 10 || value > 10000) {
110 value = 500;
111 setIter(value);
112 }
113 return value;
114 case "use_algorithm":
115 value = "numeric";
116 try {
117 value = gPref.getCharPref("mandelbrot." + prefname);
118 }
119 catch (e) {
120 setAlgorithm(value);
121 }
122 return value;
123 case "color_palette":
124 value = "kairo";
125 try {
126 value = gPref.getCharPref("mandelbrot." + prefname);
127 }
128 catch(e) {
129 setPalette(value);
130 }
131 return value;
132 case "syncProportions":
133 value = true;
134 try {
135 value = gPref.getBoolPref("mandelbrot." + prefname);
136 }
137 catch(e) {
138 gPref.setBoolPref("mandelbrot." + prefname, value);
139 }
140 return value;
141 default:
142 return false;
86e67c44 143 }
a79ddf52
RK
144}
145
146function adjustCoordsAndDraw(aC_min, aC_max) {
147 let iWidth = getAdjustPref("image.width");
148 let iHeight = getAdjustPref("image.height");
86e67c44
RK
149
150 // correct coordinates
151 if (aC_min.r < -2)
152 aC_min.r = -2;
153 if (aC_max.r > 2)
154 aC_max.r = 2;
155 if ((aC_min.r > 2) || (aC_max.r < -2) || (aC_min.r >= aC_max.r)) {
156 aC_min.r = -2.0; aC_max.r = 1.0;
157 }
158 if (aC_min.i < -2)
159 aC_min.i = -2;
160 if (aC_max.i > 2)
161 aC_max.i = 2;
162 if ((aC_min.i > 2) || (aC_max.i < -2) || (aC_min.i >= aC_max.i)) {
30586599 163 aC_min.i = -1.3; aC_max.i = 1.3;
86e67c44
RK
164 }
165
166 let CWidth = aC_max.r - aC_min.r;
167 let CHeight = aC_max.i - aC_min.i;
168 let C_mid = new complex(aC_min.r + CWidth / 2, aC_min.i + CHeight / 2);
169
170 let CRatio = Math.max(CWidth / iWidth, CHeight / iHeight);
171
172 gPref.setCharPref("mandelbrot.last_image.Cr_min", C_mid.r - iWidth * CRatio / 2);
173 gPref.setCharPref("mandelbrot.last_image.Cr_max", C_mid.r + iWidth * CRatio / 2);
174 gPref.setCharPref("mandelbrot.last_image.Ci_min", C_mid.i - iHeight * CRatio / 2);
175 gPref.setCharPref("mandelbrot.last_image.Ci_max", C_mid.i + iHeight * CRatio / 2);
176
177 drawImage();
178}
179
37b05b56 180function drawImage() {
8a9c8e3f 181 let canvas = document.getElementById("mbrotImage");
2cb9a6b5 182 let context = canvas.getContext("2d");
37b05b56 183
5366c7d6
RK
184 document.getElementById("drawButton").hidden = true;
185
fa4ecb24 186 document.getElementById("statusLabel").value = gMbrotBundle.getString("statusDrawing");
2cb9a6b5 187
a79ddf52
RK
188 let Cr_vals = getAdjustPref("last_image.Cr_*");
189 let Cr_min = Cr_vals.Cr_min;
190 let Cr_max = Cr_vals.Cr_max;
eceff1c9 191
a79ddf52
RK
192 let Ci_vals = getAdjustPref("last_image.Ci_*");
193 let Ci_min = Ci_vals.Ci_min;
194 let Ci_max = Ci_vals.Ci_max;
eceff1c9 195
a79ddf52
RK
196 let iterMax = getAdjustPref("iteration_max");
197 let algorithm = getAdjustPref("use_algorithm");
6e98af87 198
a79ddf52
RK
199 let iWidth = getAdjustPref("image.width");
200 let iHeight = getAdjustPref("image.height");
eceff1c9 201
86e67c44
RK
202 gCurrentImageData = {
203 C_min: new complex(Cr_min, Ci_min),
204 C_max: new complex(Cr_max, Ci_max),
205 iWidth: iWidth,
206 iHeight: iHeight,
207 iterMax: iterMax
208 };
209
eceff1c9
RK
210 canvas.width = iWidth;
211 canvas.height = iHeight;
212
213 context.fillStyle = "rgba(255, 255, 255, 127)";
2cb9a6b5 214 context.fillRect(0, 0, canvas.width, canvas.height);
37b05b56 215
2cb9a6b5
RK
216 gStartTime = new Date();
217
eceff1c9
RK
218 drawLine(0, [Cr_min, Cr_max, Ci_min, Ci_max],
219 canvas, context, iterMax, algorithm);
2cb9a6b5
RK
220}
221
eceff1c9 222function drawLine(line, dimensions, canvas, context, iterMax, algorithm) {
aad35028
RK
223 let Cr_min = dimensions[0];
224 let Cr_max = dimensions[1];
225 let Cr_scale = Cr_max - Cr_min;
226
227 let Ci_min = dimensions[2];
228 let Ci_max = dimensions[3];
229 let Ci_scale = Ci_max - Ci_min;
230
8a2b6e17
RK
231 let lines = Math.min(canvas.height - line, 8);
232 let imageData = context.createImageData(canvas.width, lines);
233 let pixels = imageData.data;
234 let idx = 0;
aad35028
RK
235 for (var img_y = line; img_y < canvas.height && img_y < line+8; img_y++)
236 for (let img_x = 0; img_x < canvas.width; img_x++) {
237 let C = new complex(Cr_min + (img_x / canvas.width) * Cr_scale,
238 Ci_min + (img_y / canvas.height) * Ci_scale);
8a2b6e17
RK
239 let colors = drawPoint(context, img_x, img_y, C, iterMax, algorithm);
240 pixels[idx++] = colors[0];
241 pixels[idx++] = colors[1];
242 pixels[idx++] = colors[2];
243 pixels[idx++] = colors[3];
aad35028 244 }
8a2b6e17 245 context.putImageData(imageData, 0, line);
2cb9a6b5 246
aad35028
RK
247 if (img_y < canvas.height)
248 setTimeout(drawLine, 0, img_y, dimensions, canvas, context, iterMax, algorithm);
249 else if (gStartTime)
250 EndCalc();
37b05b56
RK
251}
252
6e98af87
RK
253function EndCalc() {
254 let endTime = new Date();
255 let timeUsed = (endTime.getTime() - gStartTime.getTime()) / 1000;
256 document.getElementById("statusLabel").value =
fa4ecb24 257 gMbrotBundle.getFormattedString("statusTime", [timeUsed.toFixed(3)]);
287a980b 258 gStartTime = 0;
6e98af87
RK
259}
260
37b05b56
RK
261function complex(aReal, aImag) {
262 this.r = aReal;
263 this.i = aImag;
2cb9a6b5
RK
264}
265complex.prototype = {
266 square: function() {
37b05b56
RK
267 return new complex(this.r * this.r - this.i * this.i,
268 2 * this.r * this.i);
2cb9a6b5
RK
269 },
270 dist: function() {
37b05b56 271 return Math.sqrt(this.r * this.r + this.i * this.i);
2cb9a6b5
RK
272 },
273 add: function(aComplex) {
37b05b56
RK
274 return new complex(this.r + aComplex.r, this.i + aComplex.i);
275 }
276}
277
6e98af87
RK
278function mandelbrotValueOO (aC, aIterMax) {
279 // this would be nice code in general but it looks like JS objects are too heavy for normal use.
8444612a 280 let Z = new complex(0.0, 0.0);
37b05b56
RK
281 for (var iter = 0; iter < aIterMax; iter++) {
282 Z = Z.square().add(aC);
283 if (Z.r * Z.r + Z.i * Z.i > 256) { break; }
284 }
6e98af87
RK
285 return iter;
286}
8444612a 287
6e98af87
RK
288function mandelbrotValueNumeric (aC, aIterMax) {
289 // optimized numeric code for fast calculation
8444612a
RK
290 let Cr = aC.r, Ci = aC.i;
291 let Zr = 0.0, Zi = 0.0;
292 let Zr2 = Zr * Zr, Zi2 = Zi * Zi;
293 for (var iter = 0; iter < aIterMax; iter++) {
294 Zi = 2 * Zr * Zi + Ci;
295 Zr = Zr2 - Zi2 + Cr;
296
297 Zr2 = Zr * Zr; Zi2 = Zi * Zi;
298 if (Zr2 + Zi2 > 256) { break; }
299 }
37b05b56
RK
300 return iter;
301}
302
303function getColor(aIterValue, aIterMax) {
8a9c8e3f 304 let standardizedValue = Math.round(aIterValue * 1024 / aIterMax);
6e98af87
RK
305 if (gColorPalette && gColorPalette.length)
306 return gColorPalette[standardizedValue];
307
308 // fallback to simple b/w if for some reason we don't have a palette
309 if (aIterValue == aIterMax)
2cb9a6b5 310 return [0, 0, 0, 255];
6e98af87 311 else
2cb9a6b5 312 return [255, 255, 255, 255];
37b05b56
RK
313}
314
315function getColorPalette(palName) {
316 var palette = [];
317 switch (palName) {
318 case 'bw':
8a9c8e3f 319 for (let i = 0; i < 1024; i++) {
2cb9a6b5 320 palette[i] = [255, 255, 255, 255];
37b05b56 321 }
2cb9a6b5 322 palette[1024] = [0, 0, 0, 255];
37b05b56
RK
323 break;
324 case 'kairo':
325 // outer areas
8a9c8e3f
RK
326 for (let i = 0; i < 32; i++) {
327 let cc1 = Math.floor(i * 127 / 31);
328 let cc2 = 170 - Math.floor(i * 43 / 31);
2cb9a6b5 329 palette[i] = [cc1, cc2, cc1, 255];
37b05b56
RK
330 }
331 // inner areas
8a9c8e3f
RK
332 for (let i = 0; i < 51; i++) {
333 let cc = Math.floor(i * 170 / 50);
2cb9a6b5 334 palette[32 + i] = [cc, 0, (170-cc), 255];
37b05b56
RK
335 }
336 // corona
8a9c8e3f
RK
337 for (let i = 0; i < 101; i++) {
338 let cc = Math.floor(i * 200 / 100);
2cb9a6b5 339 palette[83 + i] = [255, cc, 0, 255];
37b05b56
RK
340 }
341 // inner corona
8a9c8e3f
RK
342 for (let i = 0; i < 201; i++) {
343 let cc1 = 255 - Math.floor(i * 85 / 200);
344 let cc2 = 200 - Math.floor(i * 30 / 200);
345 let cc3 = Math.floor(i * 170 / 200);
2cb9a6b5 346 palette[184 + i] = [cc1, cc2, cc3, 255];
37b05b56 347 }
8a9c8e3f
RK
348 for (let i = 0; i < 301; i++) {
349 let cc1 = 170 - Math.floor(i * 43 / 300);
350 let cc2 = 170 + Math.floor(i * 85 / 300);
2cb9a6b5 351 palette[385 + i] = [cc1, cc1, cc2, 255];
37b05b56 352 }
8a9c8e3f
RK
353 for (let i = 0; i < 338; i++) {
354 let cc = 127 + Math.floor(i * 128 / 337);
2cb9a6b5 355 palette[686 + i] = [cc, cc, 255, 255];
37b05b56 356 }
2cb9a6b5 357 palette[1024] = [0, 0, 0, 255];
37b05b56
RK
358 break;
359 case 'rainbow-linear1':
8a9c8e3f 360 for (let i = 0; i < 256; i++) {
2cb9a6b5
RK
361 palette[i] = [i, 0, 0, 255];
362 palette[256 + i] = [255, i, 0, 255];
363 palette[512 + i] = [255 - i, 255, i, 255];
364 palette[768 + i] = [i, 255-i, 255, 255];
37b05b56 365 }
2cb9a6b5 366 palette[1024] = [0, 0, 0, 255];
37b05b56 367 break;
72eff464
RK
368 case 'rainbow-squared1':
369 for (let i = 0; i < 34; i++) {
370 let cc = Math.floor(i * 255 / 33);
371 palette[i] = [cc, 0, 0, 255];
372 }
373 for (let i = 0; i < 137; i++) {
374 let cc = Math.floor(i * 255 / 136);
375 palette[34 + i] = [255, cc, 0, 255];
376 }
377 for (let i = 0; i < 307; i++) {
378 let cc = Math.floor(i * 255 / 306);
379 palette[171 + i] = [255 - cc, 255, cc, 255];
380 }
381 for (let i = 0; i < 546; i++) {
382 let cc = Math.floor(i * 255 / 545);
383 palette[478 + i] = [cc, 255 - cc, 255, 255];
384 }
385 palette[1024] = [0, 0, 0, 255];
386 break;
387 case 'rainbow-linear2':
388 for (let i = 0; i < 205; i++) {
389 let cc = Math.floor(i * 255 / 204);
390 palette[i] = [255, cc, 0, 255];
391 palette[204 + i] = [255 - cc, 255, 0, 255];
392 palette[409 + i] = [0, 255, cc, 255];
393 palette[614 + i] = [0, 255 - cc, 255, 255];
394 palette[819 + i] = [cc, 0, 255, 255];
395 }
396 palette[1024] = [0, 0, 0, 255];
397 break;
398 case 'rainbow-squared2':
399 for (let i = 0; i < 19; i++) {
400 let cc = Math.floor(i * 255 / 18);
401 palette[i] = [255, cc, 0, 255];
402 }
403 for (let i = 0; i < 74; i++) {
404 let cc = Math.floor(i * 255 / 73);
405 palette[19 + i] = [255 - cc, 255, 0, 255];
406 }
407 for (let i = 0; i < 168; i++) {
408 let cc = Math.floor(i * 255 / 167);
409 palette[93 + i] = [0, 255, cc, 255];
410 }
411 for (let i = 0; i < 298; i++) {
412 let cc = Math.floor(i * 255 / 297);
413 palette[261 + i] = [0, 255 - cc, 255, 255];
414 }
415 for (let i = 0; i < 465; i++) {
416 let cc = Math.floor(i * 255 / 464);
417 palette[559 + i] = [cc, 0, 255, 255];
418 }
419 palette[1024] = [0, 0, 0, 255];
420 break;
37b05b56 421 }
72eff464
RK
422 /*
423 'Standard-Palette (QB-Colors)
37b05b56
RK
424 For i = 0 To 1024
425 xx = CInt(i * 500 / 1024 + 2)
426 If xx <= 15 Then clr = xx
427 If xx > 15 Then clr = CInt(Sqr((xx - 15 + 1) * 15 ^ 2 / 485))
428 If xx >= 500 Then clr = 0
429 palette(i) = QBColor(clr)
430 Next
72eff464 431 */
37b05b56
RK
432 return palette;
433}
434
6e98af87
RK
435function drawPoint(context, img_x, img_y, C, iterMax, algorithm) {
436 var itVal;
437 switch (algorithm) {
438 case 'oo':
439 itVal = mandelbrotValueOO(C, iterMax);
440 break;
441 case 'numeric':
442 default:
443 itVal = mandelbrotValueNumeric(C, iterMax);
444 break;
445 }
2cb9a6b5 446 return getColor(itVal, iterMax);
37b05b56
RK
447}
448
6e98af87
RK
449/***** pure UI functions *****/
450
4d8e7dcb 451var zoomstart;
7e4a9776 452var imgBackup;
4d8e7dcb
RK
453
454function mouseevent(etype, event) {
455 let canvas = document.getElementById("mbrotImage");
7e4a9776 456 let context = canvas.getContext("2d");
4d8e7dcb
RK
457 switch (etype) {
458 case 'down':
7e4a9776 459 if (event.button == 0) {
4d8e7dcb
RK
460 // left button - start dragzoom
461 zoomstart = {x: event.clientX - canvas.offsetLeft,
462 y: event.clientY - canvas.offsetTop};
7e4a9776
RK
463 imgBackup = context.getImageData(0, 0, canvas.width, canvas.height);
464 }
4d8e7dcb
RK
465 break;
466 case 'up':
aad35028 467 if (event.button == 0 && zoomstart) {
7e4a9776 468 context.putImageData(imgBackup, 0, 0);
86e67c44
RK
469 let zoomend = {x: event.clientX - canvas.offsetLeft,
470 y: event.clientY - canvas.offsetTop};
471
472 // make sure zoomend is bigger than zoomstart
473 if ((zoomend.x == zoomstart.x) || (zoomend.y == zoomstart.y)) {
474 // cannot zoom what has no area, discard it
475 zoomstart = undefined;
476 return;
477 }
478 if (zoomend.x < zoomstart.x)
479 [zoomend.x, zoomstart.x] = [zoomstart.x, zoomend.x];
480 if (zoomend.y < zoomstart.y)
481 [zoomend.y, zoomstart.y] = [zoomstart.y, zoomend.y];
482
3e3d9a1d
RK
483 // determine new "coordinates"
484 let CWidth = gCurrentImageData.C_max.r - gCurrentImageData.C_min.r;
485 let CHeight = gCurrentImageData.C_max.i - gCurrentImageData.C_min.i;
486 let newC_min = new complex(
487 gCurrentImageData.C_min.r + zoomstart.x / gCurrentImageData.iWidth * CWidth,
488 gCurrentImageData.C_min.i + zoomstart.y / gCurrentImageData.iHeight * CHeight);
489 let newC_max = new complex(
490 gCurrentImageData.C_min.r + zoomend.x / gCurrentImageData.iWidth * CWidth,
491 gCurrentImageData.C_min.i + zoomend.y / gCurrentImageData.iHeight * CHeight);
492
493 adjustCoordsAndDraw(newC_min, newC_max);
9c2ca9fa 494 }
4d8e7dcb 495 zoomstart = undefined;
7e4a9776
RK
496 break;
497 case 'move':
498 if (event.button == 0 && zoomstart) {
499 context.putImageData(imgBackup, 0, 0);
500 context.strokeStyle = "rgb(255,255,31)";
501 context.strokeRect(zoomstart.x, zoomstart.y,
502 event.clientX - canvas.offsetLeft - zoomstart.x,
503 event.clientY - canvas.offsetTop - zoomstart.y);
504 }
4d8e7dcb
RK
505 break;
506 }
507}
508
37b05b56 509function saveImage() {
740b86d1 510 const nsIFilePicker = Components.interfaces.nsIFilePicker;
aad35028 511 let fp = null;
740b86d1
RK
512 try {
513 fp = Components.classes["@mozilla.org/filepicker;1"]
514 .createInstance(nsIFilePicker);
515 } catch (e) {}
516 if (!fp) return;
aad35028 517 let promptString = gMbrotBundle.getString("savePrompt");
740b86d1 518 fp.init(window, promptString, nsIFilePicker.modeSave);
fa4ecb24 519 fp.appendFilter(gMbrotBundle.getString("pngFilterName"), "*.png");
740b86d1
RK
520 fp.defaultString = "mandelbrot.png";
521
aad35028 522 let fpResult = fp.show();
740b86d1
RK
523 if (fpResult != nsIFilePicker.returnCancel) {
524 saveCanvas(document.getElementById("mbrotImage"), fp.file);
525 }
37b05b56
RK
526}
527
474b436c
RK
528function exitMandelbrot() {
529 var appInfo = Components.classes["@mozilla.org/xre/app-info;1"]
530 .getService(Components.interfaces.nsIXULAppInfo);
531 if (appInfo.ID == "mandelbrot@kairo.at")
532 quitApp(false);
533 else
534 window.close();
535}
536
287a980b
RK
537function updateBookmarkMenu(aParent) {
538 document.getElementById("bookmarkSave").disabled =
539 (!document.getElementById("drawButton").hidden || (gStartTime > 0));
540
541 while (aParent.hasChildNodes() &&
86e67c44 542 aParent.lastChild.id != "bookmarkSeparator")
287a980b
RK
543 aParent.removeChild(aParent.lastChild);
544
aad35028 545 let file = Components.classes["@mozilla.org/file/directory_service;1"]
287a980b
RK
546 .getService(Components.interfaces.nsIProperties)
547 .get("ProfD", Components.interfaces.nsIFile);
548 file.append("mandelbookmarks.sqlite");
549 if (file.exists()) {
aad35028 550 let connection = Components.classes["@mozilla.org/storage/service;1"]
287a980b
RK
551 .getService(Components.interfaces.mozIStorageService)
552 .openDatabase(file);
553 try {
554 if (connection.tableExists("bookmarks")) {
aad35028 555 let statement = connection.createStatement(
86e67c44
RK
556 "SELECT name,ROWID FROM bookmarks ORDER BY ROWID ASC");
557 while (statement.executeStep()) {
558 let newItem = aParent.appendChild(document.createElement("menuitem"));
559 newItem.setAttribute("label", statement.getString(0));
560 newItem.setAttribute("bmRowID", statement.getString(1));
561 }
287a980b
RK
562 statement.reset();
563 statement.finalize();
564 return;
2eed6617 565 }
287a980b
RK
566 } finally {
567 connection.close();
2eed6617 568 }
287a980b
RK
569 }
570 // Create the "Nothing Available" Menu item and disable it.
aad35028 571 let na = aParent.appendChild(document.createElement("menuitem"));
fa4ecb24 572 na.setAttribute("label", gMbrotBundle.getString("noBookmarks"));
287a980b 573 na.setAttribute("disabled", "true");
2eed6617
RK
574}
575
576function callBookmark(evtarget) {
86e67c44 577 if (evtarget.id == "bookmarkSave" || evtarget.id == "bookmarkSeparator")
b8f9a76f
RK
578 return;
579 if (evtarget.id == "bookmarkOverview") {
580 adjustCoordsAndDraw(new complex(0,0), new complex(0,0));
581 return;
582 }
f34775a6
RK
583
584 if (evtarget.getAttribute('bmRowID')) {
585 let iterMax = 0;
586 let C_min = null;
587 let C_max = null;
588
589 let file = Components.classes["@mozilla.org/file/directory_service;1"]
590 .getService(Components.interfaces.nsIProperties)
591 .get("ProfD", Components.interfaces.nsIFile);
592 file.append("mandelbookmarks.sqlite");
593 let connection = Components.classes["@mozilla.org/storage/service;1"]
594 .getService(Components.interfaces.mozIStorageService)
595 .openDatabase(file);
596 let statement = connection.createStatement(
597 "SELECT iteration_max,Cr_min,Cr_max,Ci_min,Ci_max FROM bookmarks WHERE ROWID=?1");
598 statement.bindStringParameter(0, evtarget.getAttribute('bmRowID'));
599 while (statement.executeStep()) {
600 iterMax = statement.getInt32(0);
601 C_min = new complex(statement.getDouble(1), statement.getDouble(3));
602 C_max = new complex(statement.getDouble(2), statement.getDouble(4));
603 }
604 statement.finalize();
605 connection.close();
606
607 if (iterMax && C_min && C_max) {
608 gPref.setIntPref("mandelbrot.iteration_max", iterMax);
609 adjustCoordsAndDraw(C_min, C_max);
610 }
611 }
2eed6617
RK
612}
613
614function saveBookmark() {
9c2ca9fa 615 // retrieve wanted bookmark name with a prompt
aad35028 616 let prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
9c2ca9fa 617 .getService(Components.interfaces.nsIPromptService);
aad35028
RK
618 let input = {value: ""}; // empty default value
619 let ok = prompts.prompt(null, gMbrotBundle.getString("saveBookmarkTitle"), gMbrotBundle.getString("saveBookmarkLabel"), input, null, {});
9c2ca9fa
RK
620 // ok is true if OK is pressed, false if Cancel. input.value holds the value of the edit field if "OK" was pressed.
621 if (!ok || !input.value)
622 return
623
aad35028 624 let bmName = input.value;
287a980b
RK
625
626 // Open or create the bookmarks database.
aad35028 627 let file = Components.classes["@mozilla.org/file/directory_service;1"]
287a980b
RK
628 .getService(Components.interfaces.nsIProperties)
629 .get("ProfD", Components.interfaces.nsIFile);
630 file.append("mandelbookmarks.sqlite");
aad35028 631 let connection = Components.classes["@mozilla.org/storage/service;1"]
287a980b
RK
632 .getService(Components.interfaces.mozIStorageService)
633 .openDatabase(file);
634 connection.beginTransaction();
635 if (!connection.tableExists("bookmarks"))
636 connection.createTable("bookmarks", "name TEXT, iteration_max INTEGER, Cr_min REAL, Cr_max REAL, Ci_min REAL, Ci_max REAL");
637 // NULL. The value is a NULL value.
638 // INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.
639 // REAL. The value is a floating point value, stored as an 8-byte IEEE floating point number.
640 // TEXT. The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16-LE).
641
642 // Put value of the current image into the bookmarks table
aad35028 643 let statement = connection.createStatement(
287a980b
RK
644 "INSERT INTO bookmarks (name,iteration_max,Cr_min,Cr_max,Ci_min,Ci_max) VALUES (?1,?2,?3,?4,?5,?6)");
645 statement.bindStringParameter(0, bmName);
86e67c44
RK
646 statement.bindStringParameter(1, gCurrentImageData.iterMax);
647 statement.bindStringParameter(2, gCurrentImageData.C_min.r);
648 statement.bindStringParameter(3, gCurrentImageData.C_max.r);
649 statement.bindStringParameter(4, gCurrentImageData.C_min.i);
650 statement.bindStringParameter(5, gCurrentImageData.C_max.i);
287a980b
RK
651 statement.execute();
652 statement.finalize();
653 connection.commitTransaction();
654 connection.close();
2eed6617
RK
655}
656
6e98af87 657function updateIterMenu() {
a79ddf52 658 let currentIter = getAdjustPref("iteration_max");
6e98af87 659
aad35028
RK
660 let popup = document.getElementById("menu_iterPopup");
661 let item = popup.firstChild;
6e98af87
RK
662 while (item) {
663 if (item.getAttribute("name") == "iter") {
664 if (item.getAttribute("value") == currentIter)
665 item.setAttribute("checked","true");
666 else
667 item.removeAttribute("checked");
668 }
669 item = item.nextSibling;
670 }
671}
672
673function setIter(aIter) {
674 gPref.setIntPref("mandelbrot.iteration_max", aIter);
675}
676
677function updatePaletteMenu() {
a79ddf52 678 let currentPalette = getAdjustPref("color_palette");
6e98af87
RK
679 if (!gColorPalette || !gColorPalette.length)
680 gColorPalette = getColorPalette(currentPalette);
681
aad35028
RK
682 let popup = document.getElementById("menu_palettePopup");
683 let item = popup.firstChild;
6e98af87
RK
684 while (item) {
685 if (item.getAttribute("name") == "palette") {
686 if (item.getAttribute("value") == currentPalette)
687 item.setAttribute("checked", "true");
688 else
689 item.removeAttribute("checked");
690 }
691 item = item.nextSibling;
692 }
693}
694
695function setPalette(aPaletteID) {
696 gPref.setCharPref("mandelbrot.color_palette", aPaletteID);
697 gColorPalette = getColorPalette(aPaletteID);
698}
699
6403d662 700function imgSettings() {
60e048b2
RK
701 let anchor = null;
702 let position = "before_start";
703 if (document.getElementById("mandelbrotWindow").nodeName == "page") {
704 anchor = document.getElementById("mandelbrotToolbar");
705 }
706 else {
707 anchor = document.getElementById("mandelbrotMenubar");
708 position = "after_start";
709 }
710 document.getElementById("imgSettingsPanel").showPopup(anchor, position);
6403d662
RK
711}
712
6e98af87 713function updateDebugMenu() {
84e4253d
RK
714 let scope = (document.getElementById("mandelbrotWindow").nodeName == "page") ? "content" : "chrome";
715 for each (let type in ["tracejit", "methodjit"]) {
716 let jitMenuItem = document.getElementById(type + "Enabled");
717 jitMenuItem.setAttribute("checked", gPref.getBoolPref("javascript.options." + type + "." + scope));
718 }
6e98af87
RK
719}
720
84e4253d
RK
721function toggleJITState(jitMenuItem, jittype) {
722 let scope = (document.getElementById("mandelbrotWindow").nodeName == "page") ? "content" : "chrome";
723 let jitpref = "javascript.options." + jittype + "jit." + scope;
724 let jitEnabled = !gPref.getBoolPref(jitpref);
725 gPref.setBoolPref(jitpref, jitEnabled)
726 jitMenuItem.setAttribute("checked", jitEnabled ? "true" : "false");
6e98af87
RK
727}
728
729function updateAlgoMenu() {
a79ddf52 730 let currentAlgo = getAdjustPref("use_algorithm");
6e98af87 731
aad35028
RK
732 let popup = document.getElementById("menu_algoPopup");
733 let item = popup.firstChild;
6e98af87
RK
734 while (item) {
735 if (item.getAttribute("name") == "algorithm") {
736 if (item.getAttribute("value") == currentAlgo)
737 item.setAttribute("checked", "true");
738 else
739 item.removeAttribute("checked");
740 }
741 item = item.nextSibling;
742 }
743}
744
745function setAlgorithm(algoID) {
746 gPref.setCharPref("mandelbrot.use_algorithm", algoID);
747}
748
af3c147c 749function addonsManager(aPane) {
aad35028 750 let theEM = Components.classes["@mozilla.org/appshell/window-mediator;1"]
af3c147c
RK
751 .getService(Components.interfaces.nsIWindowMediator)
752 .getMostRecentWindow("Extension:Manager");
753 if (theEM) {
754 theEM.focus();
755 if (aPane)
756 theEM.showView(aPane);
757 return;
758 }
759
760 const EMURL = "chrome://mozapps/content/extensions/extensions.xul";
761 const EMFEATURES = "all,dialog=no";
762 if (aPane)
763 window.openDialog(EMURL, "", EMFEATURES, aPane);
764 else
765 window.openDialog(EMURL, "", EMFEATURES);
766}
767
768function errorConsole() {
769 toOpenWindowByType("global:console", "chrome://global/content/console.xul");
770}
771
8a2b6e17
RK
772function initImgSettings() {
773 // Get values from prefs.
a79ddf52
RK
774 for each (let coord in ["Cr", "Ci"]) {
775 let coord_vals = getAdjustPref("last_image." + coord + "_*");
776 document.getElementById("is_" + coord + "_min").value = coord_vals[coord + "_min"];
777 document.getElementById("is_" + coord + "_max").value = coord_vals[coord + "_max"];
8a2b6e17
RK
778 }
779 for each (let dim in ["width", "height"]) {
a79ddf52 780 document.getElementById("is_img_" + dim).value = getAdjustPref("image." + dim);
8a2b6e17 781 }
a79ddf52 782 document.getElementById("is_syncProp").checked = getAdjustPref("syncProportions");
8a2b6e17
RK
783
784 // Calculate scales.
785 recalcCoord("Cr", "scale");
786 recalcCoord("Ci", "scale");
787
788 // Clear the preview.
789 let canvas = document.getElementById("is_mbrotPreview");
790 let context = canvas.getContext("2d");
791 context.fillStyle = "rgba(255, 255, 255, 127)";
792 context.fillRect(0, 0, canvas.width, canvas.height);
793}
794
795function closeImgSettings() {
796 // Hide popup, which will automatically make a call to save values.
797 document.getElementById("imgSettingsPanel").hidePopup();
798}
799
800function saveImgSettings() {
801 // Get values to prefs.
802 for each (let coord in ["Cr_min", "Cr_max", "Ci_min", "Ci_max"]) {
803 gPref.setCharPref("mandelbrot.last_image." + coord,
804 document.getElementById("is_" + coord).value);
805 }
806 for each (let dim in ["width", "height"]) {
807 gPref.setIntPref("mandelbrot.image." + dim,
808 document.getElementById("is_img_" + dim).value);
809 }
810 gPref.setBoolPref("mandelbrot.syncProportions",
811 document.getElementById("is_syncProp").checked);
812}
813
814function checkISValue(textbox, type) {
815 if (type == "coord") {
816 textbox.value = roundCoord(parseFloat(textbox.value));
817 }
818 else if (type == "dim") {
819 textbox.value = parseInt(textbox.value);
820 }
821}
822
823function drawPreview() {
824 let canvas = document.getElementById("is_mbrotPreview");
825 let context = canvas.getContext("2d");
826
827 if (document.getElementById("is_img_width").value /
828 document.getElementById("is_img_height").value
829 < 80 / 50) {
830 canvas.height = 50;
831 canvas.width = canvas.height *
832 document.getElementById("is_img_width").value /
833 document.getElementById("is_img_height").value;
834 }
835 else {
836 canvas.width = 80;
837 canvas.height = canvas.width *
838 document.getElementById("is_imgHeight").value /
839 document.getElementById("is_imgWidth").value;
840 }
841
842 let Cr_min = parseFloat(document.getElementById("is_Cr_min").value);
843 let Cr_max = parseFloat(document.getElementById("is_Cr_max").value);
844 if ((Cr_min < -2) || (Cr_min > 2) ||
845 (Cr_max < -2) || (Cr_max > 2) || (Cr_min >= Cr_max)) {
846 Cr_min = -2.0; Cr_max = 1.0;
847 }
848
849 let Ci_min = parseFloat(document.getElementById("is_Ci_min").value);
850 let Ci_max = parseFloat(document.getElementById("is_Ci_max").value);
851 if ((Ci_min < -2) || (Ci_min > 2) ||
852 (Ci_max < -2) || (Ci_max > 2) || (Ci_min >= Ci_max)) {
853 Ci_min = -2.0; Ci_max = 1.0;
854 }
855
a79ddf52
RK
856 let iterMax = getAdjustPref("iteration_max");
857 let algorithm = getAdjustPref("use_algorithm");
8a2b6e17
RK
858
859 context.fillStyle = "rgba(255, 255, 255, 127)";
860 context.fillRect(0, 0, canvas.width, canvas.height);
861
a79ddf52 862 let currentPalette = getAdjustPref("color_palette");
8a2b6e17
RK
863 gColorPalette = getColorPalette(currentPalette);
864
865 drawLine(0, [Cr_min, Cr_max, Ci_min, Ci_max],
866 canvas, context, iterMax, algorithm);
867}
868
869function recalcCoord(coord, target) {
870 let othercoord = (coord == "Ci") ? "Cr" : "Ci";
871 let owndim = (coord == "Ci") ? "height" : "width";
872 let otherdim = (coord == "Ci") ? "width" : "height";
873 if (target == "scale") {
874 var myscale =
875 parseFloat(document.getElementById("is_" + coord + "_max").value) -
876 parseFloat(document.getElementById("is_" + coord + "_min").value);
877 document.getElementById("is_" + coord + "_scale").value = roundCoord(myscale);
878 }
879 else if (target == 'max') {
880 let mymax =
881 parseFloat(document.getElementById("is_" + coord + "_min").value) +
882 parseFloat(document.getElementById("is_" + coord + "_scale").value);
883 document.getElementById("is_" + coord + "_max").value = roundCoord(mymax);
884 var myscale = document.getElementById("is_" + coord + "_scale").value;
885 }
886 if (document.getElementById("is_syncProp").checked) {
887 let otherscale = myscale *
888 document.getElementById("is_img_" + otherdim).value /
889 document.getElementById("is_img_" + owndim).value;
890 document.getElementById("is_" + othercoord + "_scale").value = roundCoord(otherscale);
891 let othermax =
892 parseFloat(document.getElementById("is_" + othercoord + "_min").value) +
893 parseFloat(document.getElementById("is_" + othercoord + "_scale").value);
894 document.getElementById("is_" + othercoord + "_max").value = roundCoord(othermax);
895 }
896}
897
898function checkProportions() {
899 if (!document.getElementById("is_syncProp").checked) {
900 recalcCoord("Cr", "scale");
901 }
902}
903
904function roundCoord(floatval) {
905 // We should round to 10 decimals here or so
906 return parseFloat(floatval.toFixed(10));
907}
908
6e98af87
RK
909/***** helper functions from external sources *****/
910
740b86d1
RK
911// function below is based on http://developer.mozilla.org/en/docs/Code_snippets:Canvas
912// custom modifications:
913// - use "a"-prefix on function arguments
914// - take an nsILocalFile as aDestFile argument
915// - always do silent download
916function saveCanvas(aCanvas, aDestFile) {
37b05b56
RK
917 // create a data url from the canvas and then create URIs of the source and targets
918 var io = Components.classes["@mozilla.org/network/io-service;1"]
919 .getService(Components.interfaces.nsIIOService);
740b86d1 920 var source = io.newURI(aCanvas.toDataURL("image/png", ""), "UTF8", null);
37b05b56
RK
921
922 // prepare to save the canvas data
923 var persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
924 .createInstance(Components.interfaces.nsIWebBrowserPersist);
925
926 persist.persistFlags = Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
927 persist.persistFlags |= Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION;
928
37b05b56 929 // save the canvas data to the file
740b86d1 930 persist.saveURI(source, null, null, null, null, aDestFile);
37b05b56
RK
931}
932
933// function below is from http://developer.mozilla.org/en/docs/How_to_Quit_a_XUL_Application
934function quitApp(aForceQuit) {
935 var appStartup = Components.classes['@mozilla.org/toolkit/app-startup;1']
936 .getService(Components.interfaces.nsIAppStartup);
937
938 // eAttemptQuit will try to close each XUL window, but the XUL window can cancel the quit
939 // process if there is unsaved data. eForceQuit will quit no matter what.
940 var quitSeverity = aForceQuit ? Components.interfaces.nsIAppStartup.eForceQuit :
941 Components.interfaces.nsIAppStartup.eAttemptQuit;
942 appStartup.quit(quitSeverity);
943}
af3c147c
RK
944
945// functions below are from comm-central/suite/common/tasksOverlay.js
946function toOpenWindow(aWindow) {
947 try {
948 // Try to focus the previously focused window e.g. message compose body
949 aWindow.document.commandDispatcher.focusedWindow.focus();
950 } catch (e) {
951 // e.g. full-page plugin or non-XUL document; just raise the top window
952 aWindow.focus();
953 }
954}
955
956function toOpenWindowByType(inType, uri, features) {
957 // don't do several loads in parallel
958 if (uri in window)
959 return;
960
961 var topWindow = Components.classes["@mozilla.org/appshell/window-mediator;1"]
962 .getService(Components.interfaces.nsIWindowMediator)
963 .getMostRecentWindow(inType);
964 if ( topWindow )
965 toOpenWindow( topWindow );
966 else {
967 // open the requested window, but block it until it's fully loaded
968 function newWindowLoaded(event) {
969 // make sure that this handler is called only once
970 window.removeEventListener("unload", newWindowLoaded, false);
971 window[uri].removeEventListener("load", newWindowLoaded, false);
972 delete window[uri];
973 }
974 // remember the newly loading window until it's fully loaded
975 // or until the current window passes away
976 window[uri] = window.openDialog(uri, "", features || "all,dialog=no");
977 window[uri].addEventListener("load", newWindowLoaded, false);
978 window.addEventListener("unload", newWindowLoaded, false);
979 }
980}