788e198bd6059fba5259f21dce6bb6ab2b8b1a06
[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
19  * the Initial Developer. All Rights Reserved.
20  *
21  * Contributor(s):
22  *   Robert Kaiser <kairo@kairo.at>
23  *
24  * Alternatively, the contents of this file may be used under the terms of
25  * either the GNU General Public License Version 2 or later (the "GPL"), or
26  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
27  * in which case the provisions of the GPL or the LGPL are applicable instead
28  * of those above. If you wish to allow use of your version of this file only
29  * under the terms of either the GPL or the LGPL, and not to allow others to
30  * use your version of this file under the terms of the MPL, indicate your
31  * decision by deleting the provisions above and replace them with the notice
32  * and other provisions required by the GPL or the LGPL. If you do not delete
33  * the provisions above, a recipient may use your version of this file under
34  * the terms of any one of the MPL, the GPL or the LGPL.
35  *
36  * ***** END LICENSE BLOCK ***** */
37
38 var gColorPalette = [];
39 var gPref = Components.classes["@mozilla.org/preferences-service;1"]
40                       .getService(Components.interfaces.nsIPrefService)
41                       .getBranch(null);
42 var gStartTime = 0;
43 var gMbrotBundle;
44 var gCurrentImageData;
45
46 function Startup() {
47   updateIterMenu();
48   updatePaletteMenu();
49   gMbrotBundle = document.getElementById("mbrotBundle");
50   document.getElementById("statusLabel").value = gMbrotBundle.getString("statusEmpty");
51 }
52
53 function adjustCoordsAndDraw(aC_min, aC_max) {
54   let iWidth = 0;
55   try {
56     iWidth = gPref.getIntPref("mandelbrot.image.width");
57   }
58   catch (e) { }
59   if ((iWidth < 10) || (iWidth > 5000)) {
60     iWidth = 300;
61     gPref.setIntPref("mandelbrot.image.width", iWidth);
62   }
63   let iHeight = 0;
64   try {
65     iHeight = gPref.getIntPref("mandelbrot.image.height");
66   }
67   catch (e) { }
68   if ((iHeight < 10) || (iHeight > 5000)) {
69     iHeight = 300;
70     gPref.setIntPref("mandelbrot.image.height", iHeight);
71   }
72
73   // correct coordinates
74   if (aC_min.r < -2)
75     aC_min.r = -2;
76   if (aC_max.r > 2)
77     aC_max.r = 2;
78   if ((aC_min.r > 2) || (aC_max.r < -2) || (aC_min.r >= aC_max.r)) {
79     aC_min.r = -2.0; aC_max.r = 1.0;
80   }
81   if (aC_min.i < -2)
82     aC_min.i = -2;
83   if (aC_max.i > 2)
84     aC_max.i = 2;
85   if ((aC_min.i > 2) || (aC_max.i < -2) || (aC_min.i >= aC_max.i)) {
86     aC_min.i = -1.3; aC_max.i = 1.3;
87   }
88
89   let CWidth = aC_max.r - aC_min.r;
90   let CHeight = aC_max.i - aC_min.i;
91   let C_mid = new complex(aC_min.r + CWidth / 2, aC_min.i + CHeight / 2);
92
93   let CRatio = Math.max(CWidth / iWidth, CHeight / iHeight);
94
95   gPref.setCharPref("mandelbrot.last_image.Cr_min", C_mid.r - iWidth * CRatio / 2);
96   gPref.setCharPref("mandelbrot.last_image.Cr_max", C_mid.r + iWidth * CRatio / 2);
97   gPref.setCharPref("mandelbrot.last_image.Ci_min", C_mid.i - iHeight * CRatio / 2);
98   gPref.setCharPref("mandelbrot.last_image.Ci_max", C_mid.i + iHeight * CRatio / 2);
99
100   drawImage();
101 }
102
103 function drawImage() {
104   let canvas = document.getElementById("mbrotImage");
105   let context = canvas.getContext("2d");
106
107   document.getElementById("drawButton").hidden = true;
108
109   document.getElementById("statusLabel").value = gMbrotBundle.getString("statusDrawing");
110
111   let Cr_min = -2.0;
112   let Cr_max = 1.0;
113   try {
114     Cr_min = parseFloat(gPref.getCharPref("mandelbrot.last_image.Cr_min"));
115     Cr_max = parseFloat(gPref.getCharPref("mandelbrot.last_image.Cr_max"));
116   }
117   catch (e) { }
118   if ((Cr_min < -3) || (Cr_min > 2) ||
119       (Cr_max < -3) || (Cr_max > 2) || (Cr_min >= Cr_max)) {
120     Cr_min = -2.0; Cr_max = 1.0;
121   }
122   gPref.setCharPref("mandelbrot.last_image.Cr_min", Cr_min);
123   gPref.setCharPref("mandelbrot.last_image.Cr_max", Cr_max);
124
125   let Ci_min = -1.5;
126   let Ci_max = 1.5;
127   try {
128     Ci_min = parseFloat(gPref.getCharPref("mandelbrot.last_image.Ci_min"));
129     Ci_max = parseFloat(gPref.getCharPref("mandelbrot.last_image.Ci_max"));
130   }
131   catch (e) { }
132   if ((Ci_min < -2.5) || (Ci_min > 2.5) ||
133       (Ci_max < -2.5) || (Ci_max > 2.5) || (Ci_min >= Ci_max)) {
134     Ci_min = -1.5; Ci_max = 1.5;
135   }
136   gPref.setCharPref("mandelbrot.last_image.Ci_min", Ci_min);
137   gPref.setCharPref("mandelbrot.last_image.Ci_max", Ci_max);
138
139   let iterMax = gPref.getIntPref("mandelbrot.iteration_max");
140   let algorithm = gPref.getCharPref("mandelbrot.use_algorithm");
141
142   let iWidth = 0;
143   try {
144     iWidth = gPref.getIntPref("mandelbrot.image.width");
145   }
146   catch (e) { }
147   if ((iWidth < 10) || (iWidth > 5000)) {
148     iWidth = 300;
149     gPref.setIntPref("mandelbrot.image.width", iWidth);
150   }
151   let iHeight = 0;
152   try {
153     iHeight = gPref.getIntPref("mandelbrot.image.height");
154   }
155   catch (e) { }
156   if ((iHeight < 10) || (iHeight > 5000)) {
157     iHeight = 300;
158     gPref.setIntPref("mandelbrot.image.height", iHeight);
159   }
160
161   gCurrentImageData = {
162     C_min: new complex(Cr_min, Ci_min),
163     C_max: new complex(Cr_max, Ci_max),
164     iWidth: iWidth,
165     iHeight: iHeight,
166     iterMax: iterMax
167   };
168
169   canvas.width = iWidth;
170   canvas.height = iHeight;
171
172   context.fillStyle = "rgba(255, 255, 255, 127)";
173   context.fillRect(0, 0, canvas.width, canvas.height);
174
175   gStartTime = new Date();
176
177   drawLine(0, [Cr_min, Cr_max, Ci_min, Ci_max],
178               canvas, context, iterMax, algorithm);
179 }
180
181 function drawLine(line, dimensions, canvas, context, iterMax, algorithm) {
182   let Cr_min = dimensions[0];
183   let Cr_max = dimensions[1];
184   let Cr_scale = Cr_max - Cr_min;
185
186   let Ci_min = dimensions[2];
187   let Ci_max = dimensions[3];
188   let Ci_scale = Ci_max - Ci_min;
189
190   let pixels = [];
191   for (var img_y = line; img_y < canvas.height && img_y < line+8; img_y++)
192     for (let img_x = 0; img_x < canvas.width; img_x++) {
193       let C = new complex(Cr_min + (img_x / canvas.width) * Cr_scale,
194                           Ci_min + (img_y / canvas.height) * Ci_scale);
195       pixels.push.apply(pixels, drawPoint(context, img_x, img_y, C, iterMax, algorithm));
196     }
197   context.putImageData({width: canvas.width, height: pixels.length/4/canvas.width, data: pixels}, 0, line);
198
199   if (img_y < canvas.height)
200     setTimeout(drawLine, 0, img_y, dimensions, canvas, context, iterMax, algorithm);
201   else if (gStartTime)
202     EndCalc();
203 }
204
205 function EndCalc() {
206   let endTime = new Date();
207   let timeUsed = (endTime.getTime() - gStartTime.getTime()) / 1000;
208   document.getElementById("statusLabel").value =
209       gMbrotBundle.getFormattedString("statusTime", [timeUsed.toFixed(3)]);
210   gStartTime = 0;
211 }
212
213 function complex(aReal, aImag) {
214   this.r = aReal;
215   this.i = aImag;
216 }
217 complex.prototype = {
218   square: function() {
219     return new complex(this.r * this.r - this.i * this.i,
220                        2 * this.r * this.i);
221   },
222   dist: function() {
223     return Math.sqrt(this.r * this.r + this.i * this.i);
224   },
225   add: function(aComplex) {
226     return new complex(this.r + aComplex.r, this.i + aComplex.i);
227   }
228 }
229
230 function mandelbrotValueOO (aC, aIterMax) {
231   // this would be nice code in general but it looks like JS objects are too heavy for normal use.
232   let Z = new complex(0.0, 0.0);
233   for (var iter = 0; iter < aIterMax; iter++) {
234     Z = Z.square().add(aC);
235     if (Z.r * Z.r + Z.i * Z.i > 256) { break; }
236   }
237   return iter;
238 }
239
240 function mandelbrotValueNumeric (aC, aIterMax) {
241   // optimized numeric code for fast calculation
242   let Cr = aC.r, Ci = aC.i;
243   let Zr = 0.0, Zi = 0.0;
244   let Zr2 = Zr * Zr, Zi2 = Zi * Zi;
245   for (var iter = 0; iter < aIterMax; iter++) {
246     Zi = 2 * Zr * Zi + Ci;
247     Zr = Zr2 - Zi2 + Cr;
248
249     Zr2 = Zr * Zr; Zi2 = Zi * Zi;
250     if (Zr2 + Zi2 > 256) { break; }
251   }
252   return iter;
253 }
254
255 function getColor(aIterValue, aIterMax) {
256   let standardizedValue = Math.round(aIterValue * 1024 / aIterMax);
257   if (gColorPalette && gColorPalette.length)
258     return gColorPalette[standardizedValue];
259
260   // fallback to simple b/w if for some reason we don't have a palette
261   if (aIterValue == aIterMax)
262     return [0, 0, 0, 255];
263   else
264     return [255, 255, 255, 255];
265 }
266
267 function getColorPalette(palName) {
268   var palette = [];
269   switch (palName) {
270     case 'bw':
271       for (let i = 0; i < 1024; i++) {
272         palette[i] = [255, 255, 255, 255];
273       }
274       palette[1024] = [0, 0, 0, 255];
275       break;
276     case 'kairo':
277       // outer areas
278       for (let i = 0; i < 32; i++) {
279         let cc1 = Math.floor(i * 127 / 31);
280         let cc2 = 170 - Math.floor(i * 43 / 31);
281         palette[i] = [cc1, cc2, cc1, 255];
282       }
283       // inner areas
284       for (let i = 0; i < 51; i++) {
285         let cc = Math.floor(i * 170 / 50);
286         palette[32 + i] = [cc, 0, (170-cc), 255];
287       }
288       // corona
289       for (let i = 0; i < 101; i++) {
290         let cc = Math.floor(i * 200 / 100);
291         palette[83 + i] = [255, cc, 0, 255];
292       }
293       // inner corona
294       for (let i = 0; i < 201; i++) {
295         let cc1 = 255 - Math.floor(i * 85 / 200);
296         let cc2 = 200 - Math.floor(i * 30 / 200);
297         let cc3 = Math.floor(i * 170 / 200);
298         palette[184 + i] = [cc1, cc2, cc3, 255];
299       }
300       for (let i = 0; i < 301; i++) {
301         let cc1 = 170 - Math.floor(i * 43 / 300);
302         let cc2 = 170 + Math.floor(i * 85 / 300);
303         palette[385 + i] = [cc1, cc1, cc2, 255];
304       }
305       for (let i = 0; i < 338; i++) {
306         let cc = 127 + Math.floor(i * 128 / 337);
307         palette[686 + i] = [cc, cc, 255, 255];
308       }
309       palette[1024] = [0, 0, 0, 255];
310       break;
311     case 'rainbow-linear1':
312       for (let i = 0; i < 256; i++) {
313         palette[i] = [i, 0, 0, 255];
314         palette[256 + i] = [255, i, 0, 255];
315         palette[512 + i] = [255 - i, 255, i, 255];
316         palette[768 + i] = [i, 255-i, 255, 255];
317       }
318       palette[1024] = [0, 0, 0, 255];
319       break;
320     case 'rainbow-squared1':
321       for (let i = 0; i < 34; i++) {
322         let cc = Math.floor(i * 255 / 33);
323         palette[i] = [cc, 0, 0, 255];
324       }
325       for (let i = 0; i < 137; i++) {
326         let cc = Math.floor(i * 255 / 136);
327         palette[34 + i] = [255, cc, 0, 255];
328       }
329       for (let i = 0; i < 307; i++) {
330         let cc = Math.floor(i * 255 / 306);
331         palette[171 + i] = [255 - cc, 255, cc, 255];
332       }
333       for (let i = 0; i < 546; i++) {
334         let cc = Math.floor(i * 255 / 545);
335         palette[478 + i] = [cc, 255 - cc, 255, 255];
336       }
337       palette[1024] = [0, 0, 0, 255];
338       break;
339     case 'rainbow-linear2':
340       for (let i = 0; i < 205; i++) {
341         let cc = Math.floor(i * 255 / 204);
342         palette[i] = [255, cc, 0, 255];
343         palette[204 + i] = [255 - cc, 255, 0, 255];
344         palette[409 + i] = [0, 255, cc, 255];
345         palette[614 + i] = [0, 255 - cc, 255, 255];
346         palette[819 + i] = [cc, 0, 255, 255];
347       }
348       palette[1024] = [0, 0, 0, 255];
349       break;
350     case 'rainbow-squared2':
351       for (let i = 0; i < 19; i++) {
352         let cc = Math.floor(i * 255 / 18);
353         palette[i] = [255, cc, 0, 255];
354       }
355       for (let i = 0; i < 74; i++) {
356         let cc = Math.floor(i * 255 / 73);
357         palette[19 + i] = [255 - cc, 255, 0, 255];
358       }
359       for (let i = 0; i < 168; i++) {
360         let cc = Math.floor(i * 255 / 167);
361         palette[93 + i] = [0, 255, cc, 255];
362       }
363       for (let i = 0; i < 298; i++) {
364         let cc = Math.floor(i * 255 / 297);
365         palette[261 + i] = [0, 255 - cc, 255, 255];
366       }
367       for (let i = 0; i < 465; i++) {
368         let cc = Math.floor(i * 255 / 464);
369         palette[559 + i] = [cc, 0, 255, 255];
370       }
371       palette[1024] = [0, 0, 0, 255];
372       break;
373   }
374   /*
375      'Standard-Palette (QB-Colors)
376      For i = 0 To 1024
377          xx = CInt(i * 500 / 1024 + 2)
378          If xx <= 15 Then clr = xx
379          If xx > 15 Then clr = CInt(Sqr((xx - 15 + 1) * 15 ^ 2 / 485))
380          If xx >= 500 Then clr = 0
381          palette(i) = QBColor(clr)
382      Next
383   */
384   return palette;
385 }
386
387 function drawPoint(context, img_x, img_y, C, iterMax, algorithm) {
388   var itVal;
389   switch (algorithm) {
390     case 'oo':
391       itVal = mandelbrotValueOO(C, iterMax);
392       break;
393     case 'numeric':
394     default:
395       itVal = mandelbrotValueNumeric(C, iterMax);
396       break;
397   }
398   return getColor(itVal, iterMax);
399 }
400
401 /***** pure UI functions *****/
402
403 var zoomstart;
404
405 function mouseevent(etype, event) {
406   let canvas = document.getElementById("mbrotImage");
407   switch (etype) {
408     case 'down':
409       if (event.button == 0)
410         // left button - start dragzoom
411         zoomstart = {x: event.clientX - canvas.offsetLeft,
412                      y: event.clientY - canvas.offsetTop};
413       break;
414     case 'up':
415       if (event.button == 0 && zoomstart) {
416         let zoomend = {x: event.clientX - canvas.offsetLeft,
417                        y: event.clientY - canvas.offsetTop};
418
419         // make sure zoomend is bigger than zoomstart
420         if ((zoomend.x == zoomstart.x) || (zoomend.y == zoomstart.y)) {
421           // cannot zoom what has no area, discard it
422           zoomstart = undefined;
423           return;
424         }
425         if (zoomend.x < zoomstart.x)
426           [zoomend.x, zoomstart.x] = [zoomstart.x, zoomend.x];
427         if (zoomend.y < zoomstart.y)
428           [zoomend.y, zoomstart.y] = [zoomstart.y, zoomend.y];
429
430         let prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
431                                 .getService(Components.interfaces.nsIPromptService);
432         let ok = prompts.confirm(null, gMbrotBundle.getString("zoomConfirmTitle"),
433                                  gMbrotBundle.getString("zoomConfirmLabel"));
434         // ok is now true if OK was clicked, and false if cancel was clicked
435         if (ok) {
436           // determine new "coordinates"
437           let CWidth = gCurrentImageData.C_max.r - gCurrentImageData.C_min.r;
438           let CHeight = gCurrentImageData.C_max.i - gCurrentImageData.C_min.i;
439           let newC_min = new complex(
440               gCurrentImageData.C_min.r + zoomstart.x / gCurrentImageData.iWidth * CWidth,
441               gCurrentImageData.C_min.i + zoomstart.y / gCurrentImageData.iHeight * CHeight);
442           let newC_max = new complex(
443               gCurrentImageData.C_min.r + zoomend.x / gCurrentImageData.iWidth * CWidth,
444               gCurrentImageData.C_min.i + zoomend.y / gCurrentImageData.iHeight * CHeight);
445
446           adjustCoordsAndDraw(newC_min, newC_max);
447         }
448       }
449       zoomstart = undefined;
450     break;
451   }
452 }
453
454 function saveImage() {
455   const nsIFilePicker = Components.interfaces.nsIFilePicker;
456   let fp = null;
457   try {
458     fp = Components.classes["@mozilla.org/filepicker;1"]
459                    .createInstance(nsIFilePicker);
460   } catch (e) {}
461   if (!fp) return;
462   let promptString = gMbrotBundle.getString("savePrompt");
463   fp.init(window, promptString, nsIFilePicker.modeSave);
464   fp.appendFilter(gMbrotBundle.getString("pngFilterName"), "*.png");
465   fp.defaultString = "mandelbrot.png";
466
467   let fpResult = fp.show();
468   if (fpResult != nsIFilePicker.returnCancel) {
469     saveCanvas(document.getElementById("mbrotImage"), fp.file);
470   }
471 }
472
473 function updateBookmarkMenu(aParent) {
474   document.getElementById("bookmarkSave").disabled =
475     (!document.getElementById("drawButton").hidden || (gStartTime > 0));
476
477   while (aParent.hasChildNodes() &&
478          aParent.lastChild.id != "bookmarkSeparator")
479     aParent.removeChild(aParent.lastChild);
480
481   let file = Components.classes["@mozilla.org/file/directory_service;1"]
482                        .getService(Components.interfaces.nsIProperties)
483                        .get("ProfD", Components.interfaces.nsIFile);
484   file.append("mandelbookmarks.sqlite");
485   if (file.exists()) {
486     let connection = Components.classes["@mozilla.org/storage/service;1"]
487                                .getService(Components.interfaces.mozIStorageService)
488                                .openDatabase(file);
489     try {
490       if (connection.tableExists("bookmarks")) {
491         let statement = connection.createStatement(
492             "SELECT name,ROWID FROM bookmarks ORDER BY ROWID ASC");
493         while (statement.executeStep()) {
494           let newItem = aParent.appendChild(document.createElement("menuitem"));
495           newItem.setAttribute("label", statement.getString(0));
496           newItem.setAttribute("bmRowID", statement.getString(1));
497         }
498         statement.reset();
499         statement.finalize();
500         return;
501       }
502     } finally {
503       connection.close();
504     }
505   }
506   // Create the "Nothing Available" Menu item and disable it.
507   let na = aParent.appendChild(document.createElement("menuitem"));
508   na.setAttribute("label", gMbrotBundle.getString("noBookmarks"));
509   na.setAttribute("disabled", "true");
510 }
511
512 function callBookmark(evtarget) {
513   if (evtarget.id == "bookmarkSave" || evtarget.id == "bookmarkSeparator")
514     return;
515   if (evtarget.id == "bookmarkOverview") {
516     adjustCoordsAndDraw(new complex(0,0), new complex(0,0));
517     return;
518   }
519
520   if (evtarget.getAttribute('bmRowID')) {
521     let iterMax = 0;
522     let C_min = null;
523     let C_max = null;
524
525     let file = Components.classes["@mozilla.org/file/directory_service;1"]
526                          .getService(Components.interfaces.nsIProperties)
527                          .get("ProfD", Components.interfaces.nsIFile);
528     file.append("mandelbookmarks.sqlite");
529     let connection = Components.classes["@mozilla.org/storage/service;1"]
530                                .getService(Components.interfaces.mozIStorageService)
531                                .openDatabase(file);
532     let statement = connection.createStatement(
533         "SELECT iteration_max,Cr_min,Cr_max,Ci_min,Ci_max FROM bookmarks WHERE ROWID=?1");
534     statement.bindStringParameter(0, evtarget.getAttribute('bmRowID'));
535     while (statement.executeStep()) {
536       iterMax = statement.getInt32(0);
537       C_min = new complex(statement.getDouble(1), statement.getDouble(3));
538       C_max = new complex(statement.getDouble(2), statement.getDouble(4));
539     }
540     statement.finalize();
541     connection.close();
542
543     if (iterMax && C_min && C_max) {
544       gPref.setIntPref("mandelbrot.iteration_max", iterMax);
545       adjustCoordsAndDraw(C_min, C_max);
546     }
547   }
548 }
549
550 function saveBookmark() {
551   // retrieve wanted bookmark name with a prompt
552   let prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
553                           .getService(Components.interfaces.nsIPromptService);
554   let input = {value: ""}; // empty default value
555   let ok = prompts.prompt(null, gMbrotBundle.getString("saveBookmarkTitle"), gMbrotBundle.getString("saveBookmarkLabel"), input, null, {});
556   // ok is true if OK is pressed, false if Cancel. input.value holds the value of the edit field if "OK" was pressed.
557   if (!ok || !input.value)
558     return
559
560   let bmName = input.value;
561
562   // Open or create the bookmarks database.
563   let file = Components.classes["@mozilla.org/file/directory_service;1"]
564                        .getService(Components.interfaces.nsIProperties)
565                        .get("ProfD", Components.interfaces.nsIFile);
566   file.append("mandelbookmarks.sqlite");
567   let connection = Components.classes["@mozilla.org/storage/service;1"]
568                              .getService(Components.interfaces.mozIStorageService)
569                              .openDatabase(file);
570   connection.beginTransaction();
571   if (!connection.tableExists("bookmarks"))
572     connection.createTable("bookmarks", "name TEXT, iteration_max INTEGER, Cr_min REAL, Cr_max REAL, Ci_min REAL, Ci_max REAL");
573   // NULL. The value is a NULL value.
574   // INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.
575   // REAL. The value is a floating point value, stored as an 8-byte IEEE floating point number.
576   // TEXT. The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16-LE).
577
578   // Put value of the current image into the bookmarks table
579   let statement = connection.createStatement(
580       "INSERT INTO bookmarks (name,iteration_max,Cr_min,Cr_max,Ci_min,Ci_max) VALUES (?1,?2,?3,?4,?5,?6)");
581   statement.bindStringParameter(0, bmName);
582   statement.bindStringParameter(1, gCurrentImageData.iterMax);
583   statement.bindStringParameter(2, gCurrentImageData.C_min.r);
584   statement.bindStringParameter(3, gCurrentImageData.C_max.r);
585   statement.bindStringParameter(4, gCurrentImageData.C_min.i);
586   statement.bindStringParameter(5, gCurrentImageData.C_max.i);
587   statement.execute();
588   statement.finalize();
589   connection.commitTransaction();
590   connection.close();
591 }
592
593 function updateIterMenu() {
594   let currentIter = 0;
595   try {
596     currentIter = gPref.getIntPref("mandelbrot.iteration_max");
597   }
598   catch(e) { }
599   if (currentIter < 10) {
600     currentIter = 500;
601     setIter(currentIter);
602   }
603
604   let popup = document.getElementById("menu_iterPopup");
605   let item = popup.firstChild;
606   while (item) {
607     if (item.getAttribute("name") == "iter") {
608       if (item.getAttribute("value") == currentIter)
609         item.setAttribute("checked","true");
610       else
611         item.removeAttribute("checked");
612     }
613     item = item.nextSibling;
614   }
615 }
616
617 function setIter(aIter) {
618   gPref.setIntPref("mandelbrot.iteration_max", aIter);
619 }
620
621 function updatePaletteMenu() {
622   let currentPalette = '';
623   try {
624     currentPalette = gPref.getCharPref("mandelbrot.color_palette");
625   }
626   catch(e) { }
627   if (!currentPalette.length) {
628     currentPalette = 'kairo';
629     setPalette(currentPalette);
630   }
631   if (!gColorPalette || !gColorPalette.length)
632     gColorPalette = getColorPalette(currentPalette);
633
634   let popup = document.getElementById("menu_palettePopup");
635   let item = popup.firstChild;
636   while (item) {
637     if (item.getAttribute("name") == "palette") {
638       if (item.getAttribute("value") == currentPalette)
639         item.setAttribute("checked", "true");
640       else
641         item.removeAttribute("checked");
642     }
643     item = item.nextSibling;
644   }
645 }
646
647 function setPalette(aPaletteID) {
648   gPref.setCharPref("mandelbrot.color_palette", aPaletteID);
649   gColorPalette = getColorPalette(aPaletteID);
650 }
651
652 function imgSettings() {
653   window.openDialog("chrome://mandelbrot/content/image-settings.xul");
654 }
655
656 function updateDebugMenu() {
657   var jitMenuItem = document.getElementById("jitEnabled");
658   jitMenuItem.setAttribute("checked", gPref.getBoolPref("javascript.options.jit.chrome"));
659 }
660
661 function toggleJITState(jitMenuItem) {
662   var jitEnabled = !gPref.getBoolPref("javascript.options.jit.chrome");
663   gPref.setBoolPref("javascript.options.jit.chrome", jitEnabled)
664   jitMenuItem.setAttribute("checked", jitEnabled? "true" : "false");
665 }
666
667 function updateAlgoMenu() {
668   let currentAlgo = '';
669   try {
670     currentAlgo = gPref.getCharPref("mandelbrot.use_algorithm");
671   }
672   catch(e) { }
673   if (!currentAlgo.length) {
674     currentAlgo = 'numeric';
675     setAlgorithm(currentAlgo);
676   }
677
678   let popup = document.getElementById("menu_algoPopup");
679   let item = popup.firstChild;
680   while (item) {
681     if (item.getAttribute("name") == "algorithm") {
682       if (item.getAttribute("value") == currentAlgo)
683         item.setAttribute("checked", "true");
684       else
685         item.removeAttribute("checked");
686     }
687     item = item.nextSibling;
688   }
689 }
690
691 function setAlgorithm(algoID) {
692   gPref.setCharPref("mandelbrot.use_algorithm", algoID);
693 }
694
695 function addonsManager(aPane) {
696   let theEM = Components.classes["@mozilla.org/appshell/window-mediator;1"]
697                         .getService(Components.interfaces.nsIWindowMediator)
698                         .getMostRecentWindow("Extension:Manager");
699   if (theEM) {
700     theEM.focus();
701     if (aPane)
702       theEM.showView(aPane);
703     return;
704   }
705
706   const EMURL = "chrome://mozapps/content/extensions/extensions.xul";
707   const EMFEATURES = "all,dialog=no";
708   if (aPane)
709     window.openDialog(EMURL, "", EMFEATURES, aPane);
710   else
711     window.openDialog(EMURL, "", EMFEATURES);
712 }
713
714 function errorConsole() {
715   toOpenWindowByType("global:console", "chrome://global/content/console.xul");
716 }
717
718 /***** helper functions from external sources *****/
719
720 // function below is based on http://developer.mozilla.org/en/docs/Code_snippets:Canvas
721 // custom modifications:
722 //   - use "a"-prefix on function arguments
723 //   - take an nsILocalFile as aDestFile argument
724 //   - always do silent download
725 function saveCanvas(aCanvas, aDestFile) {
726   // create a data url from the canvas and then create URIs of the source and targets  
727   var io = Components.classes["@mozilla.org/network/io-service;1"]
728                      .getService(Components.interfaces.nsIIOService);
729   var source = io.newURI(aCanvas.toDataURL("image/png", ""), "UTF8", null);
730
731   // prepare to save the canvas data
732   var persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
733                           .createInstance(Components.interfaces.nsIWebBrowserPersist);
734
735   persist.persistFlags = Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
736   persist.persistFlags |= Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION;
737
738   // save the canvas data to the file
739   persist.saveURI(source, null, null, null, null, aDestFile);
740 }
741
742 // function below is from http://developer.mozilla.org/en/docs/How_to_Quit_a_XUL_Application
743 function quitApp(aForceQuit) {
744   var appStartup = Components.classes['@mozilla.org/toolkit/app-startup;1']
745                              .getService(Components.interfaces.nsIAppStartup);
746
747   // eAttemptQuit will try to close each XUL window, but the XUL window can cancel the quit
748   // process if there is unsaved data. eForceQuit will quit no matter what.
749   var quitSeverity = aForceQuit ? Components.interfaces.nsIAppStartup.eForceQuit :
750                                   Components.interfaces.nsIAppStartup.eAttemptQuit;
751   appStartup.quit(quitSeverity);
752 }
753
754 // functions below are from comm-central/suite/common/tasksOverlay.js
755 function toOpenWindow(aWindow) {
756   try {
757     // Try to focus the previously focused window e.g. message compose body
758     aWindow.document.commandDispatcher.focusedWindow.focus();
759   } catch (e) {
760     // e.g. full-page plugin or non-XUL document; just raise the top window
761     aWindow.focus();
762   }
763 }
764
765 function toOpenWindowByType(inType, uri, features) {
766   // don't do several loads in parallel
767   if (uri in window)
768     return;
769
770   var topWindow = Components.classes["@mozilla.org/appshell/window-mediator;1"]
771                             .getService(Components.interfaces.nsIWindowMediator)
772                             .getMostRecentWindow(inType);
773   if ( topWindow )
774     toOpenWindow( topWindow );
775   else {
776     // open the requested window, but block it until it's fully loaded
777     function newWindowLoaded(event) {
778       // make sure that this handler is called only once
779       window.removeEventListener("unload", newWindowLoaded, false);
780       window[uri].removeEventListener("load", newWindowLoaded, false);
781       delete window[uri];
782     }
783     // remember the newly loading window until it's fully loaded
784     // or until the current window passes away
785     window[uri] = window.openDialog(uri, "", features || "all,dialog=no");
786     window[uri].addEventListener("load", newWindowLoaded, false);
787     window.addEventListener("unload", newWindowLoaded, false);
788   }
789 }