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