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