95c0e1401eace09be8514a7cb85e4b837421fca5
[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   if (document.getElementById("mandelbrotWindow").nodeName == "page")
687     document.getElementById("imgSettingsPanel").showPopup(null, "before_start");
688   else
689     window.openDialog("chrome://mandelbrot/content/image-settings.xul");
690 }
691
692 function updateDebugMenu() {
693   let scope = (document.getElementById("mandelbrotWindow").nodeName == "page") ? "content" : "chrome";
694   for each (let type in ["tracejit", "methodjit"]) {
695     let jitMenuItem = document.getElementById(type + "Enabled");
696     jitMenuItem.setAttribute("checked", gPref.getBoolPref("javascript.options." + type + "." + scope));
697   }
698 }
699
700 function toggleJITState(jitMenuItem, jittype) {
701   let scope = (document.getElementById("mandelbrotWindow").nodeName == "page") ? "content" : "chrome";
702   let jitpref = "javascript.options." + jittype + "jit." + scope;
703   let jitEnabled = !gPref.getBoolPref(jitpref);
704   gPref.setBoolPref(jitpref, jitEnabled)
705   jitMenuItem.setAttribute("checked", jitEnabled ? "true" : "false");
706 }
707
708 function updateAlgoMenu() {
709   let currentAlgo = '';
710   try {
711     currentAlgo = gPref.getCharPref("mandelbrot.use_algorithm");
712   }
713   catch(e) { }
714   if (!currentAlgo.length) {
715     currentAlgo = 'numeric';
716     setAlgorithm(currentAlgo);
717   }
718
719   let popup = document.getElementById("menu_algoPopup");
720   let item = popup.firstChild;
721   while (item) {
722     if (item.getAttribute("name") == "algorithm") {
723       if (item.getAttribute("value") == currentAlgo)
724         item.setAttribute("checked", "true");
725       else
726         item.removeAttribute("checked");
727     }
728     item = item.nextSibling;
729   }
730 }
731
732 function setAlgorithm(algoID) {
733   gPref.setCharPref("mandelbrot.use_algorithm", algoID);
734 }
735
736 function addonsManager(aPane) {
737   let theEM = Components.classes["@mozilla.org/appshell/window-mediator;1"]
738                         .getService(Components.interfaces.nsIWindowMediator)
739                         .getMostRecentWindow("Extension:Manager");
740   if (theEM) {
741     theEM.focus();
742     if (aPane)
743       theEM.showView(aPane);
744     return;
745   }
746
747   const EMURL = "chrome://mozapps/content/extensions/extensions.xul";
748   const EMFEATURES = "all,dialog=no";
749   if (aPane)
750     window.openDialog(EMURL, "", EMFEATURES, aPane);
751   else
752     window.openDialog(EMURL, "", EMFEATURES);
753 }
754
755 function errorConsole() {
756   toOpenWindowByType("global:console", "chrome://global/content/console.xul");
757 }
758
759 function initImgSettings() {
760   // Get values from prefs.
761   for each (let coord in ["Cr_min", "Cr_max", "Ci_min", "Ci_max"]) {
762     document.getElementById("is_" + coord).value =
763         roundCoord(parseFloat(gPref.getCharPref("mandelbrot.last_image." + coord)));
764   }
765   for each (let dim in ["width", "height"]) {
766     document.getElementById("is_img_" + dim).value =
767         gPref.getIntPref("mandelbrot.image." + dim);
768   }
769   document.getElementById("is_syncProp").checked =
770         gPref.getBoolPref("mandelbrot.syncProportions");
771
772   // Calculate scales.
773   recalcCoord("Cr", "scale");
774   recalcCoord("Ci", "scale");
775
776   // Clear the preview.
777   let canvas = document.getElementById("is_mbrotPreview");
778   let context = canvas.getContext("2d");
779   context.fillStyle = "rgba(255, 255, 255, 127)";
780   context.fillRect(0, 0, canvas.width, canvas.height);
781 }
782
783 function closeImgSettings() {
784   // Hide popup, which will automatically make a call to save values.
785   document.getElementById("imgSettingsPanel").hidePopup();
786 }
787
788 function saveImgSettings() {
789   // Get values to prefs.
790   for each (let coord in ["Cr_min", "Cr_max", "Ci_min", "Ci_max"]) {
791     gPref.setCharPref("mandelbrot.last_image." + coord,
792                       document.getElementById("is_" + coord).value);
793   }
794   for each (let dim in ["width", "height"]) {
795     gPref.setIntPref("mandelbrot.image." + dim,
796                      document.getElementById("is_img_" + dim).value);
797   }
798   gPref.setBoolPref("mandelbrot.syncProportions",
799                     document.getElementById("is_syncProp").checked);
800 }
801
802 function checkISValue(textbox, type) {
803   if (type == "coord") {
804     textbox.value = roundCoord(parseFloat(textbox.value));
805   }
806   else if (type == "dim") {
807     textbox.value = parseInt(textbox.value);
808   }
809 }
810
811 function drawPreview() {
812   let canvas = document.getElementById("is_mbrotPreview");
813   let context = canvas.getContext("2d");
814
815   if (document.getElementById("is_img_width").value /
816       document.getElementById("is_img_height").value
817         < 80 / 50) {
818     canvas.height = 50;
819     canvas.width = canvas.height *
820       document.getElementById("is_img_width").value /
821       document.getElementById("is_img_height").value;
822   }
823   else {
824     canvas.width = 80;
825     canvas.height = canvas.width *
826       document.getElementById("is_imgHeight").value /
827       document.getElementById("is_imgWidth").value;
828   }
829
830   let Cr_min = parseFloat(document.getElementById("is_Cr_min").value);
831   let Cr_max = parseFloat(document.getElementById("is_Cr_max").value);
832   if ((Cr_min < -2) || (Cr_min > 2) ||
833       (Cr_max < -2) || (Cr_max > 2) || (Cr_min >= Cr_max)) {
834     Cr_min = -2.0; Cr_max = 1.0;
835   }
836
837   let Ci_min = parseFloat(document.getElementById("is_Ci_min").value);
838   let Ci_max = parseFloat(document.getElementById("is_Ci_max").value);
839   if ((Ci_min < -2) || (Ci_min > 2) ||
840       (Ci_max < -2) || (Ci_max > 2) || (Ci_min >= Ci_max)) {
841     Ci_min = -2.0; Ci_max = 1.0;
842   }
843
844   let iterMax = gPref.getIntPref("mandelbrot.iteration_max");
845   let algorithm = gPref.getCharPref("mandelbrot.use_algorithm");
846
847   context.fillStyle = "rgba(255, 255, 255, 127)";
848   context.fillRect(0, 0, canvas.width, canvas.height);
849
850   try {
851     var currentPalette = gPref.getCharPref("mandelbrot.color_palette");
852   }
853   catch(e) {
854     var currentPalette = "";
855   }
856   if (!currentPalette.length) {
857     currentPalette = "kairo";
858   }
859   gColorPalette = getColorPalette(currentPalette);
860
861   drawLine(0, [Cr_min, Cr_max, Ci_min, Ci_max],
862               canvas, context, iterMax, algorithm);
863 }
864
865 function recalcCoord(coord, target) {
866   let othercoord = (coord == "Ci") ? "Cr" : "Ci";
867   let owndim = (coord == "Ci") ? "height" : "width";
868   let otherdim = (coord == "Ci") ? "width" : "height";
869   if (target == "scale") {
870     var myscale =
871       parseFloat(document.getElementById("is_" + coord + "_max").value) -
872       parseFloat(document.getElementById("is_" + coord + "_min").value);
873     document.getElementById("is_" + coord + "_scale").value = roundCoord(myscale);
874   }
875   else if (target == 'max') {
876     let mymax =
877       parseFloat(document.getElementById("is_" + coord + "_min").value) +
878       parseFloat(document.getElementById("is_" + coord + "_scale").value);
879     document.getElementById("is_" + coord + "_max").value = roundCoord(mymax);
880     var myscale = document.getElementById("is_" + coord + "_scale").value;
881   }
882   if (document.getElementById("is_syncProp").checked) {
883     let otherscale = myscale *
884       document.getElementById("is_img_" + otherdim).value /
885       document.getElementById("is_img_" + owndim).value;
886     document.getElementById("is_" + othercoord + "_scale").value = roundCoord(otherscale);
887     let othermax =
888       parseFloat(document.getElementById("is_" + othercoord + "_min").value) +
889       parseFloat(document.getElementById("is_" + othercoord + "_scale").value);
890     document.getElementById("is_" + othercoord + "_max").value = roundCoord(othermax);
891   }
892 }
893
894 function checkProportions() {
895   if (!document.getElementById("is_syncProp").checked) {
896     recalcCoord("Cr", "scale");
897   }
898 }
899
900 function roundCoord(floatval) {
901   // We should round to 10 decimals here or so
902   return parseFloat(floatval.toFixed(10));
903 }
904
905 /***** helper functions from external sources *****/
906
907 // function below is based on http://developer.mozilla.org/en/docs/Code_snippets:Canvas
908 // custom modifications:
909 //   - use "a"-prefix on function arguments
910 //   - take an nsILocalFile as aDestFile argument
911 //   - always do silent download
912 function saveCanvas(aCanvas, aDestFile) {
913   // create a data url from the canvas and then create URIs of the source and targets  
914   var io = Components.classes["@mozilla.org/network/io-service;1"]
915                      .getService(Components.interfaces.nsIIOService);
916   var source = io.newURI(aCanvas.toDataURL("image/png", ""), "UTF8", null);
917
918   // prepare to save the canvas data
919   var persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
920                           .createInstance(Components.interfaces.nsIWebBrowserPersist);
921
922   persist.persistFlags = Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
923   persist.persistFlags |= Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION;
924
925   // save the canvas data to the file
926   persist.saveURI(source, null, null, null, null, aDestFile);
927 }
928
929 // function below is from http://developer.mozilla.org/en/docs/How_to_Quit_a_XUL_Application
930 function quitApp(aForceQuit) {
931   var appStartup = Components.classes['@mozilla.org/toolkit/app-startup;1']
932                              .getService(Components.interfaces.nsIAppStartup);
933
934   // eAttemptQuit will try to close each XUL window, but the XUL window can cancel the quit
935   // process if there is unsaved data. eForceQuit will quit no matter what.
936   var quitSeverity = aForceQuit ? Components.interfaces.nsIAppStartup.eForceQuit :
937                                   Components.interfaces.nsIAppStartup.eAttemptQuit;
938   appStartup.quit(quitSeverity);
939 }
940
941 // functions below are from comm-central/suite/common/tasksOverlay.js
942 function toOpenWindow(aWindow) {
943   try {
944     // Try to focus the previously focused window e.g. message compose body
945     aWindow.document.commandDispatcher.focusedWindow.focus();
946   } catch (e) {
947     // e.g. full-page plugin or non-XUL document; just raise the top window
948     aWindow.focus();
949   }
950 }
951
952 function toOpenWindowByType(inType, uri, features) {
953   // don't do several loads in parallel
954   if (uri in window)
955     return;
956
957   var topWindow = Components.classes["@mozilla.org/appshell/window-mediator;1"]
958                             .getService(Components.interfaces.nsIWindowMediator)
959                             .getMostRecentWindow(inType);
960   if ( topWindow )
961     toOpenWindow( topWindow );
962   else {
963     // open the requested window, but block it until it's fully loaded
964     function newWindowLoaded(event) {
965       // make sure that this handler is called only once
966       window.removeEventListener("unload", newWindowLoaded, false);
967       window[uri].removeEventListener("load", newWindowLoaded, false);
968       delete window[uri];
969     }
970     // remember the newly loading window until it's fully loaded
971     // or until the current window passes away
972     window[uri] = window.openDialog(uri, "", features || "all,dialog=no");
973     window[uri].addEventListener("load", newWindowLoaded, false);
974     window.addEventListener("unload", newWindowLoaded, false);
975   }
976 }