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