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