convert image settings to a panel in the in-tab UI case, incorporate imageData work...
[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
aad35028 445 let prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
9c2ca9fa 446 .getService(Components.interfaces.nsIPromptService);
aad35028 447 let ok = prompts.confirm(null, gMbrotBundle.getString("zoomConfirmTitle"),
86e67c44 448 gMbrotBundle.getString("zoomConfirmLabel"));
9c2ca9fa 449 // ok is now true if OK was clicked, and false if cancel was clicked
86e67c44
RK
450 if (ok) {
451 // determine new "coordinates"
452 let CWidth = gCurrentImageData.C_max.r - gCurrentImageData.C_min.r;
453 let CHeight = gCurrentImageData.C_max.i - gCurrentImageData.C_min.i;
454 let newC_min = new complex(
455 gCurrentImageData.C_min.r + zoomstart.x / gCurrentImageData.iWidth * CWidth,
456 gCurrentImageData.C_min.i + zoomstart.y / gCurrentImageData.iHeight * CHeight);
457 let newC_max = new complex(
458 gCurrentImageData.C_min.r + zoomend.x / gCurrentImageData.iWidth * CWidth,
459 gCurrentImageData.C_min.i + zoomend.y / gCurrentImageData.iHeight * CHeight);
460
461 adjustCoordsAndDraw(newC_min, newC_max);
462 }
9c2ca9fa 463 }
4d8e7dcb 464 zoomstart = undefined;
7e4a9776
RK
465 break;
466 case 'move':
467 if (event.button == 0 && zoomstart) {
468 context.putImageData(imgBackup, 0, 0);
469 context.strokeStyle = "rgb(255,255,31)";
470 context.strokeRect(zoomstart.x, zoomstart.y,
471 event.clientX - canvas.offsetLeft - zoomstart.x,
472 event.clientY - canvas.offsetTop - zoomstart.y);
473 }
4d8e7dcb
RK
474 break;
475 }
476}
477
37b05b56 478function saveImage() {
740b86d1 479 const nsIFilePicker = Components.interfaces.nsIFilePicker;
aad35028 480 let fp = null;
740b86d1
RK
481 try {
482 fp = Components.classes["@mozilla.org/filepicker;1"]
483 .createInstance(nsIFilePicker);
484 } catch (e) {}
485 if (!fp) return;
aad35028 486 let promptString = gMbrotBundle.getString("savePrompt");
740b86d1 487 fp.init(window, promptString, nsIFilePicker.modeSave);
fa4ecb24 488 fp.appendFilter(gMbrotBundle.getString("pngFilterName"), "*.png");
740b86d1
RK
489 fp.defaultString = "mandelbrot.png";
490
aad35028 491 let fpResult = fp.show();
740b86d1
RK
492 if (fpResult != nsIFilePicker.returnCancel) {
493 saveCanvas(document.getElementById("mbrotImage"), fp.file);
494 }
37b05b56
RK
495}
496
474b436c
RK
497function exitMandelbrot() {
498 var appInfo = Components.classes["@mozilla.org/xre/app-info;1"]
499 .getService(Components.interfaces.nsIXULAppInfo);
500 if (appInfo.ID == "mandelbrot@kairo.at")
501 quitApp(false);
502 else
503 window.close();
504}
505
287a980b
RK
506function updateBookmarkMenu(aParent) {
507 document.getElementById("bookmarkSave").disabled =
508 (!document.getElementById("drawButton").hidden || (gStartTime > 0));
509
510 while (aParent.hasChildNodes() &&
86e67c44 511 aParent.lastChild.id != "bookmarkSeparator")
287a980b
RK
512 aParent.removeChild(aParent.lastChild);
513
aad35028 514 let file = Components.classes["@mozilla.org/file/directory_service;1"]
287a980b
RK
515 .getService(Components.interfaces.nsIProperties)
516 .get("ProfD", Components.interfaces.nsIFile);
517 file.append("mandelbookmarks.sqlite");
518 if (file.exists()) {
aad35028 519 let connection = Components.classes["@mozilla.org/storage/service;1"]
287a980b
RK
520 .getService(Components.interfaces.mozIStorageService)
521 .openDatabase(file);
522 try {
523 if (connection.tableExists("bookmarks")) {
aad35028 524 let statement = connection.createStatement(
86e67c44
RK
525 "SELECT name,ROWID FROM bookmarks ORDER BY ROWID ASC");
526 while (statement.executeStep()) {
527 let newItem = aParent.appendChild(document.createElement("menuitem"));
528 newItem.setAttribute("label", statement.getString(0));
529 newItem.setAttribute("bmRowID", statement.getString(1));
530 }
287a980b
RK
531 statement.reset();
532 statement.finalize();
533 return;
2eed6617 534 }
287a980b
RK
535 } finally {
536 connection.close();
2eed6617 537 }
287a980b
RK
538 }
539 // Create the "Nothing Available" Menu item and disable it.
aad35028 540 let na = aParent.appendChild(document.createElement("menuitem"));
fa4ecb24 541 na.setAttribute("label", gMbrotBundle.getString("noBookmarks"));
287a980b 542 na.setAttribute("disabled", "true");
2eed6617
RK
543}
544
545function callBookmark(evtarget) {
86e67c44 546 if (evtarget.id == "bookmarkSave" || evtarget.id == "bookmarkSeparator")
b8f9a76f
RK
547 return;
548 if (evtarget.id == "bookmarkOverview") {
549 adjustCoordsAndDraw(new complex(0,0), new complex(0,0));
550 return;
551 }
f34775a6
RK
552
553 if (evtarget.getAttribute('bmRowID')) {
554 let iterMax = 0;
555 let C_min = null;
556 let C_max = null;
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 let connection = Components.classes["@mozilla.org/storage/service;1"]
563 .getService(Components.interfaces.mozIStorageService)
564 .openDatabase(file);
565 let statement = connection.createStatement(
566 "SELECT iteration_max,Cr_min,Cr_max,Ci_min,Ci_max FROM bookmarks WHERE ROWID=?1");
567 statement.bindStringParameter(0, evtarget.getAttribute('bmRowID'));
568 while (statement.executeStep()) {
569 iterMax = statement.getInt32(0);
570 C_min = new complex(statement.getDouble(1), statement.getDouble(3));
571 C_max = new complex(statement.getDouble(2), statement.getDouble(4));
572 }
573 statement.finalize();
574 connection.close();
575
576 if (iterMax && C_min && C_max) {
577 gPref.setIntPref("mandelbrot.iteration_max", iterMax);
578 adjustCoordsAndDraw(C_min, C_max);
579 }
580 }
2eed6617
RK
581}
582
583function saveBookmark() {
9c2ca9fa 584 // retrieve wanted bookmark name with a prompt
aad35028 585 let prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
9c2ca9fa 586 .getService(Components.interfaces.nsIPromptService);
aad35028
RK
587 let input = {value: ""}; // empty default value
588 let ok = prompts.prompt(null, gMbrotBundle.getString("saveBookmarkTitle"), gMbrotBundle.getString("saveBookmarkLabel"), input, null, {});
9c2ca9fa
RK
589 // ok is true if OK is pressed, false if Cancel. input.value holds the value of the edit field if "OK" was pressed.
590 if (!ok || !input.value)
591 return
592
aad35028 593 let bmName = input.value;
287a980b
RK
594
595 // Open or create the bookmarks database.
aad35028 596 let file = Components.classes["@mozilla.org/file/directory_service;1"]
287a980b
RK
597 .getService(Components.interfaces.nsIProperties)
598 .get("ProfD", Components.interfaces.nsIFile);
599 file.append("mandelbookmarks.sqlite");
aad35028 600 let connection = Components.classes["@mozilla.org/storage/service;1"]
287a980b
RK
601 .getService(Components.interfaces.mozIStorageService)
602 .openDatabase(file);
603 connection.beginTransaction();
604 if (!connection.tableExists("bookmarks"))
605 connection.createTable("bookmarks", "name TEXT, iteration_max INTEGER, Cr_min REAL, Cr_max REAL, Ci_min REAL, Ci_max REAL");
606 // NULL. The value is a NULL value.
607 // INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.
608 // REAL. The value is a floating point value, stored as an 8-byte IEEE floating point number.
609 // TEXT. The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16-LE).
610
611 // Put value of the current image into the bookmarks table
aad35028 612 let statement = connection.createStatement(
287a980b
RK
613 "INSERT INTO bookmarks (name,iteration_max,Cr_min,Cr_max,Ci_min,Ci_max) VALUES (?1,?2,?3,?4,?5,?6)");
614 statement.bindStringParameter(0, bmName);
86e67c44
RK
615 statement.bindStringParameter(1, gCurrentImageData.iterMax);
616 statement.bindStringParameter(2, gCurrentImageData.C_min.r);
617 statement.bindStringParameter(3, gCurrentImageData.C_max.r);
618 statement.bindStringParameter(4, gCurrentImageData.C_min.i);
619 statement.bindStringParameter(5, gCurrentImageData.C_max.i);
287a980b
RK
620 statement.execute();
621 statement.finalize();
622 connection.commitTransaction();
623 connection.close();
2eed6617
RK
624}
625
6e98af87 626function updateIterMenu() {
aad35028 627 let currentIter = 0;
6e98af87 628 try {
aad35028 629 currentIter = gPref.getIntPref("mandelbrot.iteration_max");
6e98af87 630 }
aad35028 631 catch(e) { }
6e98af87
RK
632 if (currentIter < 10) {
633 currentIter = 500;
634 setIter(currentIter);
635 }
636
aad35028
RK
637 let popup = document.getElementById("menu_iterPopup");
638 let item = popup.firstChild;
6e98af87
RK
639 while (item) {
640 if (item.getAttribute("name") == "iter") {
641 if (item.getAttribute("value") == currentIter)
642 item.setAttribute("checked","true");
643 else
644 item.removeAttribute("checked");
645 }
646 item = item.nextSibling;
647 }
648}
649
650function setIter(aIter) {
651 gPref.setIntPref("mandelbrot.iteration_max", aIter);
652}
653
654function updatePaletteMenu() {
aad35028 655 let currentPalette = '';
6e98af87 656 try {
aad35028 657 currentPalette = gPref.getCharPref("mandelbrot.color_palette");
6e98af87 658 }
aad35028 659 catch(e) { }
6e98af87
RK
660 if (!currentPalette.length) {
661 currentPalette = 'kairo';
662 setPalette(currentPalette);
663 }
664 if (!gColorPalette || !gColorPalette.length)
665 gColorPalette = getColorPalette(currentPalette);
666
aad35028
RK
667 let popup = document.getElementById("menu_palettePopup");
668 let item = popup.firstChild;
6e98af87
RK
669 while (item) {
670 if (item.getAttribute("name") == "palette") {
671 if (item.getAttribute("value") == currentPalette)
672 item.setAttribute("checked", "true");
673 else
674 item.removeAttribute("checked");
675 }
676 item = item.nextSibling;
677 }
678}
679
680function setPalette(aPaletteID) {
681 gPref.setCharPref("mandelbrot.color_palette", aPaletteID);
682 gColorPalette = getColorPalette(aPaletteID);
683}
684
6403d662 685function imgSettings() {
8a2b6e17
RK
686 if (document.getElementById("mandelbrotWindow").nodeName == "page")
687 document.getElementById("imgSettingsPanel").showPopup(null, "before_start");
688 else
689 window.openDialog("chrome://mandelbrot/content/image-settings.xul");
6403d662
RK
690}
691
6e98af87 692function updateDebugMenu() {
84e4253d
RK
693 let scope = (document.getElementById("mandelbrotWindow").nodeName == "page") ? "content" : "chrome";
694 for each (let type in ["tracejit", "methodjit"]) {
695 let jitMenuItem = document.getElementById(type + "Enabled");
696 jitMenuItem.setAttribute("checked", gPref.getBoolPref("javascript.options." + type + "." + scope));
697 }
6e98af87
RK
698}
699
84e4253d
RK
700function toggleJITState(jitMenuItem, jittype) {
701 let scope = (document.getElementById("mandelbrotWindow").nodeName == "page") ? "content" : "chrome";
702 let jitpref = "javascript.options." + jittype + "jit." + scope;
703 let jitEnabled = !gPref.getBoolPref(jitpref);
704 gPref.setBoolPref(jitpref, jitEnabled)
705 jitMenuItem.setAttribute("checked", jitEnabled ? "true" : "false");
6e98af87
RK
706}
707
708function updateAlgoMenu() {
aad35028 709 let currentAlgo = '';
6e98af87 710 try {
aad35028 711 currentAlgo = gPref.getCharPref("mandelbrot.use_algorithm");
6e98af87 712 }
aad35028 713 catch(e) { }
6e98af87
RK
714 if (!currentAlgo.length) {
715 currentAlgo = 'numeric';
716 setAlgorithm(currentAlgo);
717 }
718
aad35028
RK
719 let popup = document.getElementById("menu_algoPopup");
720 let item = popup.firstChild;
6e98af87
RK
721 while (item) {
722 if (item.getAttribute("name") == "algorithm") {
723 if (item.getAttribute("value") == currentAlgo)
724 item.setAttribute("checked", "true");
725 else
726 item.removeAttribute("checked");
727 }
728 item = item.nextSibling;
729 }
730}
731
732function setAlgorithm(algoID) {
733 gPref.setCharPref("mandelbrot.use_algorithm", algoID);
734}
735
af3c147c 736function addonsManager(aPane) {
aad35028 737 let theEM = Components.classes["@mozilla.org/appshell/window-mediator;1"]
af3c147c
RK
738 .getService(Components.interfaces.nsIWindowMediator)
739 .getMostRecentWindow("Extension:Manager");
740 if (theEM) {
741 theEM.focus();
742 if (aPane)
743 theEM.showView(aPane);
744 return;
745 }
746
747 const EMURL = "chrome://mozapps/content/extensions/extensions.xul";
748 const EMFEATURES = "all,dialog=no";
749 if (aPane)
750 window.openDialog(EMURL, "", EMFEATURES, aPane);
751 else
752 window.openDialog(EMURL, "", EMFEATURES);
753}
754
755function errorConsole() {
756 toOpenWindowByType("global:console", "chrome://global/content/console.xul");
757}
758
8a2b6e17
RK
759function initImgSettings() {
760 // Get values from prefs.
761 for each (let coord in ["Cr_min", "Cr_max", "Ci_min", "Ci_max"]) {
762 document.getElementById("is_" + coord).value =
763 roundCoord(parseFloat(gPref.getCharPref("mandelbrot.last_image." + coord)));
764 }
765 for each (let dim in ["width", "height"]) {
766 document.getElementById("is_img_" + dim).value =
767 gPref.getIntPref("mandelbrot.image." + dim);
768 }
769 document.getElementById("is_syncProp").checked =
770 gPref.getBoolPref("mandelbrot.syncProportions");
771
772 // Calculate scales.
773 recalcCoord("Cr", "scale");
774 recalcCoord("Ci", "scale");
775
776 // Clear the preview.
777 let canvas = document.getElementById("is_mbrotPreview");
778 let context = canvas.getContext("2d");
779 context.fillStyle = "rgba(255, 255, 255, 127)";
780 context.fillRect(0, 0, canvas.width, canvas.height);
781}
782
783function closeImgSettings() {
784 // Hide popup, which will automatically make a call to save values.
785 document.getElementById("imgSettingsPanel").hidePopup();
786}
787
788function saveImgSettings() {
789 // Get values to prefs.
790 for each (let coord in ["Cr_min", "Cr_max", "Ci_min", "Ci_max"]) {
791 gPref.setCharPref("mandelbrot.last_image." + coord,
792 document.getElementById("is_" + coord).value);
793 }
794 for each (let dim in ["width", "height"]) {
795 gPref.setIntPref("mandelbrot.image." + dim,
796 document.getElementById("is_img_" + dim).value);
797 }
798 gPref.setBoolPref("mandelbrot.syncProportions",
799 document.getElementById("is_syncProp").checked);
800}
801
802function checkISValue(textbox, type) {
803 if (type == "coord") {
804 textbox.value = roundCoord(parseFloat(textbox.value));
805 }
806 else if (type == "dim") {
807 textbox.value = parseInt(textbox.value);
808 }
809}
810
811function drawPreview() {
812 let canvas = document.getElementById("is_mbrotPreview");
813 let context = canvas.getContext("2d");
814
815 if (document.getElementById("is_img_width").value /
816 document.getElementById("is_img_height").value
817 < 80 / 50) {
818 canvas.height = 50;
819 canvas.width = canvas.height *
820 document.getElementById("is_img_width").value /
821 document.getElementById("is_img_height").value;
822 }
823 else {
824 canvas.width = 80;
825 canvas.height = canvas.width *
826 document.getElementById("is_imgHeight").value /
827 document.getElementById("is_imgWidth").value;
828 }
829
830 let Cr_min = parseFloat(document.getElementById("is_Cr_min").value);
831 let Cr_max = parseFloat(document.getElementById("is_Cr_max").value);
832 if ((Cr_min < -2) || (Cr_min > 2) ||
833 (Cr_max < -2) || (Cr_max > 2) || (Cr_min >= Cr_max)) {
834 Cr_min = -2.0; Cr_max = 1.0;
835 }
836
837 let Ci_min = parseFloat(document.getElementById("is_Ci_min").value);
838 let Ci_max = parseFloat(document.getElementById("is_Ci_max").value);
839 if ((Ci_min < -2) || (Ci_min > 2) ||
840 (Ci_max < -2) || (Ci_max > 2) || (Ci_min >= Ci_max)) {
841 Ci_min = -2.0; Ci_max = 1.0;
842 }
843
844 let iterMax = gPref.getIntPref("mandelbrot.iteration_max");
845 let algorithm = gPref.getCharPref("mandelbrot.use_algorithm");
846
847 context.fillStyle = "rgba(255, 255, 255, 127)";
848 context.fillRect(0, 0, canvas.width, canvas.height);
849
850 try {
851 var currentPalette = gPref.getCharPref("mandelbrot.color_palette");
852 }
853 catch(e) {
854 var currentPalette = "";
855 }
856 if (!currentPalette.length) {
857 currentPalette = "kairo";
858 }
859 gColorPalette = getColorPalette(currentPalette);
860
861 drawLine(0, [Cr_min, Cr_max, Ci_min, Ci_max],
862 canvas, context, iterMax, algorithm);
863}
864
865function recalcCoord(coord, target) {
866 let othercoord = (coord == "Ci") ? "Cr" : "Ci";
867 let owndim = (coord == "Ci") ? "height" : "width";
868 let otherdim = (coord == "Ci") ? "width" : "height";
869 if (target == "scale") {
870 var myscale =
871 parseFloat(document.getElementById("is_" + coord + "_max").value) -
872 parseFloat(document.getElementById("is_" + coord + "_min").value);
873 document.getElementById("is_" + coord + "_scale").value = roundCoord(myscale);
874 }
875 else if (target == 'max') {
876 let mymax =
877 parseFloat(document.getElementById("is_" + coord + "_min").value) +
878 parseFloat(document.getElementById("is_" + coord + "_scale").value);
879 document.getElementById("is_" + coord + "_max").value = roundCoord(mymax);
880 var myscale = document.getElementById("is_" + coord + "_scale").value;
881 }
882 if (document.getElementById("is_syncProp").checked) {
883 let otherscale = myscale *
884 document.getElementById("is_img_" + otherdim).value /
885 document.getElementById("is_img_" + owndim).value;
886 document.getElementById("is_" + othercoord + "_scale").value = roundCoord(otherscale);
887 let othermax =
888 parseFloat(document.getElementById("is_" + othercoord + "_min").value) +
889 parseFloat(document.getElementById("is_" + othercoord + "_scale").value);
890 document.getElementById("is_" + othercoord + "_max").value = roundCoord(othermax);
891 }
892}
893
894function checkProportions() {
895 if (!document.getElementById("is_syncProp").checked) {
896 recalcCoord("Cr", "scale");
897 }
898}
899
900function roundCoord(floatval) {
901 // We should round to 10 decimals here or so
902 return parseFloat(floatval.toFixed(10));
903}
904
6e98af87
RK
905/***** helper functions from external sources *****/
906
740b86d1
RK
907// function below is based on http://developer.mozilla.org/en/docs/Code_snippets:Canvas
908// custom modifications:
909// - use "a"-prefix on function arguments
910// - take an nsILocalFile as aDestFile argument
911// - always do silent download
912function saveCanvas(aCanvas, aDestFile) {
37b05b56
RK
913 // create a data url from the canvas and then create URIs of the source and targets
914 var io = Components.classes["@mozilla.org/network/io-service;1"]
915 .getService(Components.interfaces.nsIIOService);
740b86d1 916 var source = io.newURI(aCanvas.toDataURL("image/png", ""), "UTF8", null);
37b05b56
RK
917
918 // prepare to save the canvas data
919 var persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
920 .createInstance(Components.interfaces.nsIWebBrowserPersist);
921
922 persist.persistFlags = Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
923 persist.persistFlags |= Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION;
924
37b05b56 925 // save the canvas data to the file
740b86d1 926 persist.saveURI(source, null, null, null, null, aDestFile);
37b05b56
RK
927}
928
929// function below is from http://developer.mozilla.org/en/docs/How_to_Quit_a_XUL_Application
930function quitApp(aForceQuit) {
931 var appStartup = Components.classes['@mozilla.org/toolkit/app-startup;1']
932 .getService(Components.interfaces.nsIAppStartup);
933
934 // eAttemptQuit will try to close each XUL window, but the XUL window can cancel the quit
935 // process if there is unsaved data. eForceQuit will quit no matter what.
936 var quitSeverity = aForceQuit ? Components.interfaces.nsIAppStartup.eForceQuit :
937 Components.interfaces.nsIAppStartup.eAttemptQuit;
938 appStartup.quit(quitSeverity);
939}
af3c147c
RK
940
941// functions below are from comm-central/suite/common/tasksOverlay.js
942function toOpenWindow(aWindow) {
943 try {
944 // Try to focus the previously focused window e.g. message compose body
945 aWindow.document.commandDispatcher.focusedWindow.focus();
946 } catch (e) {
947 // e.g. full-page plugin or non-XUL document; just raise the top window
948 aWindow.focus();
949 }
950}
951
952function toOpenWindowByType(inType, uri, features) {
953 // don't do several loads in parallel
954 if (uri in window)
955 return;
956
957 var topWindow = Components.classes["@mozilla.org/appshell/window-mediator;1"]
958 .getService(Components.interfaces.nsIWindowMediator)
959 .getMostRecentWindow(inType);
960 if ( topWindow )
961 toOpenWindow( topWindow );
962 else {
963 // open the requested window, but block it until it's fully loaded
964 function newWindowLoaded(event) {
965 // make sure that this handler is called only once
966 window.removeEventListener("unload", newWindowLoaded, false);
967 window[uri].removeEventListener("load", newWindowLoaded, false);
968 delete window[uri];
969 }
970 // remember the newly loading window until it's fully loaded
971 // or until the current window passes away
972 window[uri] = window.openDialog(uri, "", features || "all,dialog=no");
973 window[uri].addEventListener("load", newWindowLoaded, false);
974 window.addEventListener("unload", newWindowLoaded, false);
975 }
976}