implement graphical drag feedback for zooming
[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 var imgBackup;
405
406 function mouseevent(etype, event) {
407   let canvas = document.getElementById("mbrotImage");
408   let context = canvas.getContext("2d");
409   switch (etype) {
410     case 'down':
411       if (event.button == 0) {
412         // left button - start dragzoom
413         zoomstart = {x: event.clientX - canvas.offsetLeft,
414                      y: event.clientY - canvas.offsetTop};
415         imgBackup = context.getImageData(0, 0, canvas.width, canvas.height);
416       }
417       break;
418     case 'up':
419       if (event.button == 0 && zoomstart) {
420         context.putImageData(imgBackup, 0, 0);
421         let zoomend = {x: event.clientX - canvas.offsetLeft,
422                        y: event.clientY - canvas.offsetTop};
423
424         // make sure zoomend is bigger than zoomstart
425         if ((zoomend.x == zoomstart.x) || (zoomend.y == zoomstart.y)) {
426           // cannot zoom what has no area, discard it
427           zoomstart = undefined;
428           return;
429         }
430         if (zoomend.x < zoomstart.x)
431           [zoomend.x, zoomstart.x] = [zoomstart.x, zoomend.x];
432         if (zoomend.y < zoomstart.y)
433           [zoomend.y, zoomstart.y] = [zoomstart.y, zoomend.y];
434
435         let prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
436                                 .getService(Components.interfaces.nsIPromptService);
437         let ok = prompts.confirm(null, gMbrotBundle.getString("zoomConfirmTitle"),
438                                  gMbrotBundle.getString("zoomConfirmLabel"));
439         // ok is now true if OK was clicked, and false if cancel was clicked
440         if (ok) {
441           // determine new "coordinates"
442           let CWidth = gCurrentImageData.C_max.r - gCurrentImageData.C_min.r;
443           let CHeight = gCurrentImageData.C_max.i - gCurrentImageData.C_min.i;
444           let newC_min = new complex(
445               gCurrentImageData.C_min.r + zoomstart.x / gCurrentImageData.iWidth * CWidth,
446               gCurrentImageData.C_min.i + zoomstart.y / gCurrentImageData.iHeight * CHeight);
447           let newC_max = new complex(
448               gCurrentImageData.C_min.r + zoomend.x / gCurrentImageData.iWidth * CWidth,
449               gCurrentImageData.C_min.i + zoomend.y / gCurrentImageData.iHeight * CHeight);
450
451           adjustCoordsAndDraw(newC_min, newC_max);
452         }
453       }
454       zoomstart = undefined;
455       break;
456     case 'move':
457       if (event.button == 0 && zoomstart) {
458         context.putImageData(imgBackup, 0, 0);
459         context.strokeStyle = "rgb(255,255,31)";
460         context.strokeRect(zoomstart.x, zoomstart.y,
461                            event.clientX - canvas.offsetLeft - zoomstart.x,
462                            event.clientY - canvas.offsetTop - zoomstart.y);
463       }
464     break;
465   }
466 }
467
468 function saveImage() {
469   const nsIFilePicker = Components.interfaces.nsIFilePicker;
470   let fp = null;
471   try {
472     fp = Components.classes["@mozilla.org/filepicker;1"]
473                    .createInstance(nsIFilePicker);
474   } catch (e) {}
475   if (!fp) return;
476   let promptString = gMbrotBundle.getString("savePrompt");
477   fp.init(window, promptString, nsIFilePicker.modeSave);
478   fp.appendFilter(gMbrotBundle.getString("pngFilterName"), "*.png");
479   fp.defaultString = "mandelbrot.png";
480
481   let fpResult = fp.show();
482   if (fpResult != nsIFilePicker.returnCancel) {
483     saveCanvas(document.getElementById("mbrotImage"), fp.file);
484   }
485 }
486
487 function updateBookmarkMenu(aParent) {
488   document.getElementById("bookmarkSave").disabled =
489     (!document.getElementById("drawButton").hidden || (gStartTime > 0));
490
491   while (aParent.hasChildNodes() &&
492          aParent.lastChild.id != "bookmarkSeparator")
493     aParent.removeChild(aParent.lastChild);
494
495   let file = Components.classes["@mozilla.org/file/directory_service;1"]
496                        .getService(Components.interfaces.nsIProperties)
497                        .get("ProfD", Components.interfaces.nsIFile);
498   file.append("mandelbookmarks.sqlite");
499   if (file.exists()) {
500     let connection = Components.classes["@mozilla.org/storage/service;1"]
501                                .getService(Components.interfaces.mozIStorageService)
502                                .openDatabase(file);
503     try {
504       if (connection.tableExists("bookmarks")) {
505         let statement = connection.createStatement(
506             "SELECT name,ROWID FROM bookmarks ORDER BY ROWID ASC");
507         while (statement.executeStep()) {
508           let newItem = aParent.appendChild(document.createElement("menuitem"));
509           newItem.setAttribute("label", statement.getString(0));
510           newItem.setAttribute("bmRowID", statement.getString(1));
511         }
512         statement.reset();
513         statement.finalize();
514         return;
515       }
516     } finally {
517       connection.close();
518     }
519   }
520   // Create the "Nothing Available" Menu item and disable it.
521   let na = aParent.appendChild(document.createElement("menuitem"));
522   na.setAttribute("label", gMbrotBundle.getString("noBookmarks"));
523   na.setAttribute("disabled", "true");
524 }
525
526 function callBookmark(evtarget) {
527   if (evtarget.id == "bookmarkSave" || evtarget.id == "bookmarkSeparator")
528     return;
529   if (evtarget.id == "bookmarkOverview") {
530     adjustCoordsAndDraw(new complex(0,0), new complex(0,0));
531     return;
532   }
533
534   if (evtarget.getAttribute('bmRowID')) {
535     let iterMax = 0;
536     let C_min = null;
537     let C_max = null;
538
539     let file = Components.classes["@mozilla.org/file/directory_service;1"]
540                          .getService(Components.interfaces.nsIProperties)
541                          .get("ProfD", Components.interfaces.nsIFile);
542     file.append("mandelbookmarks.sqlite");
543     let connection = Components.classes["@mozilla.org/storage/service;1"]
544                                .getService(Components.interfaces.mozIStorageService)
545                                .openDatabase(file);
546     let statement = connection.createStatement(
547         "SELECT iteration_max,Cr_min,Cr_max,Ci_min,Ci_max FROM bookmarks WHERE ROWID=?1");
548     statement.bindStringParameter(0, evtarget.getAttribute('bmRowID'));
549     while (statement.executeStep()) {
550       iterMax = statement.getInt32(0);
551       C_min = new complex(statement.getDouble(1), statement.getDouble(3));
552       C_max = new complex(statement.getDouble(2), statement.getDouble(4));
553     }
554     statement.finalize();
555     connection.close();
556
557     if (iterMax && C_min && C_max) {
558       gPref.setIntPref("mandelbrot.iteration_max", iterMax);
559       adjustCoordsAndDraw(C_min, C_max);
560     }
561   }
562 }
563
564 function saveBookmark() {
565   // retrieve wanted bookmark name with a prompt
566   let prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
567                           .getService(Components.interfaces.nsIPromptService);
568   let input = {value: ""}; // empty default value
569   let ok = prompts.prompt(null, gMbrotBundle.getString("saveBookmarkTitle"), gMbrotBundle.getString("saveBookmarkLabel"), input, null, {});
570   // ok is true if OK is pressed, false if Cancel. input.value holds the value of the edit field if "OK" was pressed.
571   if (!ok || !input.value)
572     return
573
574   let bmName = input.value;
575
576   // Open or create the bookmarks database.
577   let file = Components.classes["@mozilla.org/file/directory_service;1"]
578                        .getService(Components.interfaces.nsIProperties)
579                        .get("ProfD", Components.interfaces.nsIFile);
580   file.append("mandelbookmarks.sqlite");
581   let connection = Components.classes["@mozilla.org/storage/service;1"]
582                              .getService(Components.interfaces.mozIStorageService)
583                              .openDatabase(file);
584   connection.beginTransaction();
585   if (!connection.tableExists("bookmarks"))
586     connection.createTable("bookmarks", "name TEXT, iteration_max INTEGER, Cr_min REAL, Cr_max REAL, Ci_min REAL, Ci_max REAL");
587   // NULL. The value is a NULL value.
588   // INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.
589   // REAL. The value is a floating point value, stored as an 8-byte IEEE floating point number.
590   // TEXT. The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16-LE).
591
592   // Put value of the current image into the bookmarks table
593   let statement = connection.createStatement(
594       "INSERT INTO bookmarks (name,iteration_max,Cr_min,Cr_max,Ci_min,Ci_max) VALUES (?1,?2,?3,?4,?5,?6)");
595   statement.bindStringParameter(0, bmName);
596   statement.bindStringParameter(1, gCurrentImageData.iterMax);
597   statement.bindStringParameter(2, gCurrentImageData.C_min.r);
598   statement.bindStringParameter(3, gCurrentImageData.C_max.r);
599   statement.bindStringParameter(4, gCurrentImageData.C_min.i);
600   statement.bindStringParameter(5, gCurrentImageData.C_max.i);
601   statement.execute();
602   statement.finalize();
603   connection.commitTransaction();
604   connection.close();
605 }
606
607 function updateIterMenu() {
608   let currentIter = 0;
609   try {
610     currentIter = gPref.getIntPref("mandelbrot.iteration_max");
611   }
612   catch(e) { }
613   if (currentIter < 10) {
614     currentIter = 500;
615     setIter(currentIter);
616   }
617
618   let popup = document.getElementById("menu_iterPopup");
619   let item = popup.firstChild;
620   while (item) {
621     if (item.getAttribute("name") == "iter") {
622       if (item.getAttribute("value") == currentIter)
623         item.setAttribute("checked","true");
624       else
625         item.removeAttribute("checked");
626     }
627     item = item.nextSibling;
628   }
629 }
630
631 function setIter(aIter) {
632   gPref.setIntPref("mandelbrot.iteration_max", aIter);
633 }
634
635 function updatePaletteMenu() {
636   let currentPalette = '';
637   try {
638     currentPalette = gPref.getCharPref("mandelbrot.color_palette");
639   }
640   catch(e) { }
641   if (!currentPalette.length) {
642     currentPalette = 'kairo';
643     setPalette(currentPalette);
644   }
645   if (!gColorPalette || !gColorPalette.length)
646     gColorPalette = getColorPalette(currentPalette);
647
648   let popup = document.getElementById("menu_palettePopup");
649   let item = popup.firstChild;
650   while (item) {
651     if (item.getAttribute("name") == "palette") {
652       if (item.getAttribute("value") == currentPalette)
653         item.setAttribute("checked", "true");
654       else
655         item.removeAttribute("checked");
656     }
657     item = item.nextSibling;
658   }
659 }
660
661 function setPalette(aPaletteID) {
662   gPref.setCharPref("mandelbrot.color_palette", aPaletteID);
663   gColorPalette = getColorPalette(aPaletteID);
664 }
665
666 function imgSettings() {
667   window.openDialog("chrome://mandelbrot/content/image-settings.xul");
668 }
669
670 function updateDebugMenu() {
671   var jitMenuItem = document.getElementById("jitEnabled");
672   jitMenuItem.setAttribute("checked", gPref.getBoolPref("javascript.options.jit.chrome"));
673 }
674
675 function toggleJITState(jitMenuItem) {
676   var jitEnabled = !gPref.getBoolPref("javascript.options.jit.chrome");
677   gPref.setBoolPref("javascript.options.jit.chrome", jitEnabled)
678   jitMenuItem.setAttribute("checked", jitEnabled? "true" : "false");
679 }
680
681 function updateAlgoMenu() {
682   let currentAlgo = '';
683   try {
684     currentAlgo = gPref.getCharPref("mandelbrot.use_algorithm");
685   }
686   catch(e) { }
687   if (!currentAlgo.length) {
688     currentAlgo = 'numeric';
689     setAlgorithm(currentAlgo);
690   }
691
692   let popup = document.getElementById("menu_algoPopup");
693   let item = popup.firstChild;
694   while (item) {
695     if (item.getAttribute("name") == "algorithm") {
696       if (item.getAttribute("value") == currentAlgo)
697         item.setAttribute("checked", "true");
698       else
699         item.removeAttribute("checked");
700     }
701     item = item.nextSibling;
702   }
703 }
704
705 function setAlgorithm(algoID) {
706   gPref.setCharPref("mandelbrot.use_algorithm", algoID);
707 }
708
709 function addonsManager(aPane) {
710   let theEM = Components.classes["@mozilla.org/appshell/window-mediator;1"]
711                         .getService(Components.interfaces.nsIWindowMediator)
712                         .getMostRecentWindow("Extension:Manager");
713   if (theEM) {
714     theEM.focus();
715     if (aPane)
716       theEM.showView(aPane);
717     return;
718   }
719
720   const EMURL = "chrome://mozapps/content/extensions/extensions.xul";
721   const EMFEATURES = "all,dialog=no";
722   if (aPane)
723     window.openDialog(EMURL, "", EMFEATURES, aPane);
724   else
725     window.openDialog(EMURL, "", EMFEATURES);
726 }
727
728 function errorConsole() {
729   toOpenWindowByType("global:console", "chrome://global/content/console.xul");
730 }
731
732 /***** helper functions from external sources *****/
733
734 // function below is based on http://developer.mozilla.org/en/docs/Code_snippets:Canvas
735 // custom modifications:
736 //   - use "a"-prefix on function arguments
737 //   - take an nsILocalFile as aDestFile argument
738 //   - always do silent download
739 function saveCanvas(aCanvas, aDestFile) {
740   // create a data url from the canvas and then create URIs of the source and targets  
741   var io = Components.classes["@mozilla.org/network/io-service;1"]
742                      .getService(Components.interfaces.nsIIOService);
743   var source = io.newURI(aCanvas.toDataURL("image/png", ""), "UTF8", null);
744
745   // prepare to save the canvas data
746   var persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
747                           .createInstance(Components.interfaces.nsIWebBrowserPersist);
748
749   persist.persistFlags = Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
750   persist.persistFlags |= Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION;
751
752   // save the canvas data to the file
753   persist.saveURI(source, null, null, null, null, aDestFile);
754 }
755
756 // function below is from http://developer.mozilla.org/en/docs/How_to_Quit_a_XUL_Application
757 function quitApp(aForceQuit) {
758   var appStartup = Components.classes['@mozilla.org/toolkit/app-startup;1']
759                              .getService(Components.interfaces.nsIAppStartup);
760
761   // eAttemptQuit will try to close each XUL window, but the XUL window can cancel the quit
762   // process if there is unsaved data. eForceQuit will quit no matter what.
763   var quitSeverity = aForceQuit ? Components.interfaces.nsIAppStartup.eForceQuit :
764                                   Components.interfaces.nsIAppStartup.eAttemptQuit;
765   appStartup.quit(quitSeverity);
766 }
767
768 // functions below are from comm-central/suite/common/tasksOverlay.js
769 function toOpenWindow(aWindow) {
770   try {
771     // Try to focus the previously focused window e.g. message compose body
772     aWindow.document.commandDispatcher.focusedWindow.focus();
773   } catch (e) {
774     // e.g. full-page plugin or non-XUL document; just raise the top window
775     aWindow.focus();
776   }
777 }
778
779 function toOpenWindowByType(inType, uri, features) {
780   // don't do several loads in parallel
781   if (uri in window)
782     return;
783
784   var topWindow = Components.classes["@mozilla.org/appshell/window-mediator;1"]
785                             .getService(Components.interfaces.nsIWindowMediator)
786                             .getMostRecentWindow(inType);
787   if ( topWindow )
788     toOpenWindow( topWindow );
789   else {
790     // open the requested window, but block it until it's fully loaded
791     function newWindowLoaded(event) {
792       // make sure that this handler is called only once
793       window.removeEventListener("unload", newWindowLoaded, false);
794       window[uri].removeEventListener("load", newWindowLoaded, false);
795       delete window[uri];
796     }
797     // remember the newly loading window until it's fully loaded
798     // or until the current window passes away
799     window[uri] = window.openDialog(uri, "", features || "all,dialog=no");
800     window[uri].addEventListener("load", newWindowLoaded, false);
801     window.addEventListener("unload", newWindowLoaded, false);
802   }
803 }