start functionality for zooming, right now just alert with coordinates we dragged...
[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>.
18 * Portions created by the Initial Developer are Copyright (C) 2008
19 * the Initial Developer. All Rights Reserved.
20 *
21 * Contributor(s):
22 * Robert Kaiser <kairo@kairo.at>
23 *
24 * Alternatively, the contents of this file may be used under the terms of
25 * either the GNU General Public License Version 2 or later (the "GPL"), or
26 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
27 * in which case the provisions of the GPL or the LGPL are applicable instead
28 * of those above. If you wish to allow use of your version of this file only
29 * under the terms of either the GPL or the LGPL, and not to allow others to
30 * use your version of this file under the terms of the MPL, indicate your
31 * decision by deleting the provisions above and replace them with the notice
32 * and other provisions required by the GPL or the LGPL. If you do not delete
33 * the provisions above, a recipient may use your version of this file under
34 * the terms of any one of the MPL, the GPL or the LGPL.
35 *
36 * ***** END LICENSE BLOCK ***** */
37
6e98af87
RK
38var gColorPalette = [];
39var gPref = Components.classes["@mozilla.org/preferences-service;1"]
40 .getService(Components.interfaces.nsIPrefService)
41 .getBranch(null);
42var gStartTime = 0;
43
44function Startup() {
45 updateIterMenu();
46 updatePaletteMenu();
47 document.getElementById("statusLabel").value =
48 document.getElementById("mbrotBundle").getString("statusEmpty");
49}
37b05b56
RK
50
51function drawImage() {
8a9c8e3f 52 let canvas = document.getElementById("mbrotImage");
2cb9a6b5 53 let context = canvas.getContext("2d");
37b05b56 54
5366c7d6
RK
55 document.getElementById("drawButton").hidden = true;
56
2cb9a6b5
RK
57 document.getElementById("statusLabel").value =
58 document.getElementById("mbrotBundle").getString("statusDrawing");
59
eceff1c9
RK
60 let Cr_min = -2.0;
61 let Cr_max = 1.0;
62 try {
63 Cr_min = parseFloat(gPref.getCharPref("mandelbrot.last_image.Cr_min"));
64 Cr_max = parseFloat(gPref.getCharPref("mandelbrot.last_image.Cr_max"));
65 }
66 catch (e) { }
67 if ((Cr_min < -2) || (Cr_min > 2) ||
68 (Cr_max < -2) || (Cr_max > 2) || (Cr_min >= Cr_max)) {
69 Cr_min = -2.0; Cr_max = 1.0;
70 }
71 gPref.setCharPref("mandelbrot.last_image.Cr_min", Cr_min);
72 gPref.setCharPref("mandelbrot.last_image.Cr_max", Cr_max);
73
74 let Ci_min = -1.5;
75 let Ci_max = 1.5;
76 try {
77 Ci_min = parseFloat(gPref.getCharPref("mandelbrot.last_image.Ci_min"));
78 Ci_max = parseFloat(gPref.getCharPref("mandelbrot.last_image.Ci_max"));
79 }
80 catch (e) { }
81 if ((Ci_min < -2) || (Ci_min > 2) ||
82 (Ci_max < -2) || (Ci_max > 2) || (Ci_min >= Ci_max)) {
83 Ci_min = -2.0; Ci_max = 1.0;
84 }
85 gPref.setCharPref("mandelbrot.last_image.Ci_min", Ci_min);
86 gPref.setCharPref("mandelbrot.last_image.Ci_max", Ci_max);
87
2cb9a6b5
RK
88 let iterMax = gPref.getIntPref("mandelbrot.iteration_max");
89 let algorithm = gPref.getCharPref("mandelbrot.use_algorithm");
6e98af87 90
eceff1c9
RK
91 let iWidth = 0;
92 try {
93 iWidth = gPref.getIntPref("mandelbrot.image.width");
94 }
95 catch (e) { }
96 if ((iWidth < 10) || (iWidth > 5000)) {
97 iWidth = 300;
98 gPref.setIntPref("mandelbrot.image.width", iWidth);
99 }
100 let iHeight = 0;
101 try {
102 iHeight = gPref.getIntPref("mandelbrot.image.height");
103 }
104 catch (e) { }
105 if ((iHeight < 10) || (iHeight > 5000)) {
106 iHeight = 300;
107 gPref.setIntPref("mandelbrot.image.height", iHeight);
108 }
109
110 canvas.width = iWidth;
111 canvas.height = iHeight;
112
113 context.fillStyle = "rgba(255, 255, 255, 127)";
2cb9a6b5 114 context.fillRect(0, 0, canvas.width, canvas.height);
37b05b56 115
2cb9a6b5
RK
116 gStartTime = new Date();
117
eceff1c9
RK
118 drawLine(0, [Cr_min, Cr_max, Ci_min, Ci_max],
119 canvas, context, iterMax, algorithm);
2cb9a6b5
RK
120}
121
eceff1c9
RK
122function drawLine(line, dimensions, canvas, context, iterMax, algorithm) {
123 let Cr_min = dimensions[0];
124 let Cr_max = dimensions[1];
8a9c8e3f 125 let Cr_scale = Cr_max - Cr_min;
37b05b56 126
eceff1c9
RK
127 let Ci_min = dimensions[2];
128 let Ci_max = dimensions[3];
8a9c8e3f 129 let Ci_scale = Ci_max - Ci_min;
37b05b56 130
2cb9a6b5
RK
131 let pixels = [];
132 for (var img_y = line; img_y < canvas.height && img_y < line+8; img_y++)
133 for (let img_x = 0; img_x < canvas.width; img_x++) {
8a9c8e3f 134 let C = new complex(Cr_min + (img_x / canvas.width) * Cr_scale,
37b05b56 135 Ci_min + (img_y / canvas.height) * Ci_scale);
2cb9a6b5 136 pixels.push.apply(pixels, drawPoint(context, img_x, img_y, C, iterMax, algorithm));
37b05b56 137 }
2cb9a6b5
RK
138 context.putImageData({width: canvas.width, height: pixels.length/4/canvas.width, data: pixels}, 0, line);
139
140 if (img_y < canvas.height)
eceff1c9 141 setTimeout(drawLine, 0, img_y, dimensions, canvas, context, iterMax, algorithm);
7727ce46 142 else if (gStartTime)
2cb9a6b5 143 EndCalc();
37b05b56
RK
144}
145
6e98af87
RK
146function EndCalc() {
147 let endTime = new Date();
148 let timeUsed = (endTime.getTime() - gStartTime.getTime()) / 1000;
149 document.getElementById("statusLabel").value =
150 document.getElementById("mbrotBundle").getFormattedString("statusTime", [timeUsed.toFixed(3)]);
151}
152
37b05b56
RK
153function complex(aReal, aImag) {
154 this.r = aReal;
155 this.i = aImag;
2cb9a6b5
RK
156}
157complex.prototype = {
158 square: function() {
37b05b56
RK
159 return new complex(this.r * this.r - this.i * this.i,
160 2 * this.r * this.i);
2cb9a6b5
RK
161 },
162 dist: function() {
37b05b56 163 return Math.sqrt(this.r * this.r + this.i * this.i);
2cb9a6b5
RK
164 },
165 add: function(aComplex) {
37b05b56
RK
166 return new complex(this.r + aComplex.r, this.i + aComplex.i);
167 }
168}
169
6e98af87
RK
170function mandelbrotValueOO (aC, aIterMax) {
171 // this would be nice code in general but it looks like JS objects are too heavy for normal use.
8444612a 172 let Z = new complex(0.0, 0.0);
37b05b56
RK
173 for (var iter = 0; iter < aIterMax; iter++) {
174 Z = Z.square().add(aC);
175 if (Z.r * Z.r + Z.i * Z.i > 256) { break; }
176 }
6e98af87
RK
177 return iter;
178}
8444612a 179
6e98af87
RK
180function mandelbrotValueNumeric (aC, aIterMax) {
181 // optimized numeric code for fast calculation
8444612a
RK
182 let Cr = aC.r, Ci = aC.i;
183 let Zr = 0.0, Zi = 0.0;
184 let Zr2 = Zr * Zr, Zi2 = Zi * Zi;
185 for (var iter = 0; iter < aIterMax; iter++) {
186 Zi = 2 * Zr * Zi + Ci;
187 Zr = Zr2 - Zi2 + Cr;
188
189 Zr2 = Zr * Zr; Zi2 = Zi * Zi;
190 if (Zr2 + Zi2 > 256) { break; }
191 }
37b05b56
RK
192 return iter;
193}
194
195function getColor(aIterValue, aIterMax) {
8a9c8e3f 196 let standardizedValue = Math.round(aIterValue * 1024 / aIterMax);
6e98af87
RK
197 if (gColorPalette && gColorPalette.length)
198 return gColorPalette[standardizedValue];
199
200 // fallback to simple b/w if for some reason we don't have a palette
201 if (aIterValue == aIterMax)
2cb9a6b5 202 return [0, 0, 0, 255];
6e98af87 203 else
2cb9a6b5 204 return [255, 255, 255, 255];
37b05b56
RK
205}
206
207function getColorPalette(palName) {
208 var palette = [];
209 switch (palName) {
210 case 'bw':
8a9c8e3f 211 for (let i = 0; i < 1024; i++) {
2cb9a6b5 212 palette[i] = [255, 255, 255, 255];
37b05b56 213 }
2cb9a6b5 214 palette[1024] = [0, 0, 0, 255];
37b05b56
RK
215 break;
216 case 'kairo':
217 // outer areas
8a9c8e3f
RK
218 for (let i = 0; i < 32; i++) {
219 let cc1 = Math.floor(i * 127 / 31);
220 let cc2 = 170 - Math.floor(i * 43 / 31);
2cb9a6b5 221 palette[i] = [cc1, cc2, cc1, 255];
37b05b56
RK
222 }
223 // inner areas
8a9c8e3f
RK
224 for (let i = 0; i < 51; i++) {
225 let cc = Math.floor(i * 170 / 50);
2cb9a6b5 226 palette[32 + i] = [cc, 0, (170-cc), 255];
37b05b56
RK
227 }
228 // corona
8a9c8e3f
RK
229 for (let i = 0; i < 101; i++) {
230 let cc = Math.floor(i * 200 / 100);
2cb9a6b5 231 palette[83 + i] = [255, cc, 0, 255];
37b05b56
RK
232 }
233 // inner corona
8a9c8e3f
RK
234 for (let i = 0; i < 201; i++) {
235 let cc1 = 255 - Math.floor(i * 85 / 200);
236 let cc2 = 200 - Math.floor(i * 30 / 200);
237 let cc3 = Math.floor(i * 170 / 200);
2cb9a6b5 238 palette[184 + i] = [cc1, cc2, cc3, 255];
37b05b56 239 }
8a9c8e3f
RK
240 for (let i = 0; i < 301; i++) {
241 let cc1 = 170 - Math.floor(i * 43 / 300);
242 let cc2 = 170 + Math.floor(i * 85 / 300);
2cb9a6b5 243 palette[385 + i] = [cc1, cc1, cc2, 255];
37b05b56 244 }
8a9c8e3f
RK
245 for (let i = 0; i < 338; i++) {
246 let cc = 127 + Math.floor(i * 128 / 337);
2cb9a6b5 247 palette[686 + i] = [cc, cc, 255, 255];
37b05b56 248 }
2cb9a6b5 249 palette[1024] = [0, 0, 0, 255];
37b05b56
RK
250 break;
251 case 'rainbow-linear1':
8a9c8e3f 252 for (let i = 0; i < 256; i++) {
2cb9a6b5
RK
253 palette[i] = [i, 0, 0, 255];
254 palette[256 + i] = [255, i, 0, 255];
255 palette[512 + i] = [255 - i, 255, i, 255];
256 palette[768 + i] = [i, 255-i, 255, 255];
37b05b56 257 }
2cb9a6b5 258 palette[1024] = [0, 0, 0, 255];
37b05b56
RK
259 break;
260 }
261/*
262Select Case palnr
263Case 1 'Standard-Palette (QB-Colors)
264 For i = 0 To 1024
265 xx = CInt(i * 500 / 1024 + 2)
266 If xx <= 15 Then clr = xx
267 If xx > 15 Then clr = CInt(Sqr((xx - 15 + 1) * 15 ^ 2 / 485))
268 If xx >= 500 Then clr = 0
269 palette(i) = QBColor(clr)
270 Next
271Case 3 'Regenbogen-Palette 1 (qu.)
272 For i = 0 To 33
273 clr = CInt(i * 255 / 33)
274 palette(i) = RGB(clr, 0, 0)
275 Next
276 For i = 0 To 136
277 clr = CInt(i * 255 / 136)
278 palette(34 + i) = RGB(255, clr, 0)
279 Next
280 For i = 0 To 306
281 clr = CInt(i * 255 / 306)
282 palette(171 + i) = RGB(255 - clr, 255, clr)
283 Next
284 For i = 0 To 545
285 clr = CInt(i * 255 / 545)
286 palette(478 + i) = RGB(clr, 255 - clr, 255)
287 Next
288Case 4 'Regenbogen-Palette 2 (linear)
289 For i = 0 To 204
290 clr = CInt(i * 255 / 204)
291 palette(i) = RGB(255, clr, 0)
292 palette(204 + i) = RGB(255 - clr, 255, 0)
293 palette(409 + i) = RGB(0, 255, clr)
294 palette(614 + i) = RGB(0, 255 - clr, 255)
295 palette(819 + i) = RGB(clr, 0, 255)
296 Next
297Case 5 'Regenbogen-Palette 2 (qu.)
298 For i = 0 To 18
299 clr = CInt(i * 255 / 18)
300 palette(i) = RGB(255, clr, 0)
301 Next
302 For i = 0 To 73
303 clr = CInt(i * 255 / 73)
304 palette(20 + i) = RGB(255 - clr, 255, 0)
305 Next
306 For i = 0 To 167
307 clr = CInt(i * 255 / 167)
308 palette(93 + i) = RGB(0, 255, clr)
309 Next
310 For i = 0 To 297
311 clr = CInt(i * 255 / 297)
312 palette(261 + i) = RGB(0, 255 - clr, 255)
313 Next
314 For i = 0 To 464
315 clr = CInt(i * 255 / 464)
316 palette(559 + i) = RGB(clr, 0, 255)
317 Next
318*/
319 return palette;
320}
321
6e98af87
RK
322function drawPoint(context, img_x, img_y, C, iterMax, algorithm) {
323 var itVal;
324 switch (algorithm) {
325 case 'oo':
326 itVal = mandelbrotValueOO(C, iterMax);
327 break;
328 case 'numeric':
329 default:
330 itVal = mandelbrotValueNumeric(C, iterMax);
331 break;
332 }
2cb9a6b5 333 return getColor(itVal, iterMax);
37b05b56
RK
334}
335
6e98af87
RK
336/***** pure UI functions *****/
337
4d8e7dcb
RK
338var zoomstart;
339
340function mouseevent(etype, event) {
341 let canvas = document.getElementById("mbrotImage");
342 switch (etype) {
343 case 'down':
344 if (event.button == 0)
345 // left button - start dragzoom
346 zoomstart = {x: event.clientX - canvas.offsetLeft,
347 y: event.clientY - canvas.offsetTop};
348 break;
349 case 'up':
350 if (event.button == 0)
351 alert(zoomstart.x + ',' + zoomstart.y + '-' +
352 (event.clientX - canvas.offsetLeft) + ',' +
353 (event.clientY - canvas.offsetTop));
354 zoomstart = undefined;
355 break;
356 }
357}
358
37b05b56 359function saveImage() {
740b86d1
RK
360 const bundle = document.getElementById("mbrotBundle");
361 const nsIFilePicker = Components.interfaces.nsIFilePicker;
362 var fp = null;
363 try {
364 fp = Components.classes["@mozilla.org/filepicker;1"]
365 .createInstance(nsIFilePicker);
366 } catch (e) {}
367 if (!fp) return;
368 var promptString = bundle.getString("savePrompt");
369 fp.init(window, promptString, nsIFilePicker.modeSave);
370 fp.appendFilter(bundle.getString("pngFilterName"), "*.png");
371 fp.defaultString = "mandelbrot.png";
372
373 var fpResult = fp.show();
374 if (fpResult != nsIFilePicker.returnCancel) {
375 saveCanvas(document.getElementById("mbrotImage"), fp.file);
376 }
37b05b56
RK
377}
378
6e98af87
RK
379function updateIterMenu() {
380 try {
381 var currentIter = gPref.getIntPref("mandelbrot.iteration_max");
382 }
383 catch(e) {
384 var currentIter = 0;
385 }
386 if (currentIter < 10) {
387 currentIter = 500;
388 setIter(currentIter);
389 }
390
391 var popup = document.getElementById("menu_iterPopup");
392 var item = popup.firstChild;
393 while (item) {
394 if (item.getAttribute("name") == "iter") {
395 if (item.getAttribute("value") == currentIter)
396 item.setAttribute("checked","true");
397 else
398 item.removeAttribute("checked");
399 }
400 item = item.nextSibling;
401 }
402}
403
404function setIter(aIter) {
405 gPref.setIntPref("mandelbrot.iteration_max", aIter);
406}
407
408function updatePaletteMenu() {
409 try {
410 var currentPalette = gPref.getCharPref("mandelbrot.color_palette");
411 }
412 catch(e) {
413 var currentPalette = '';
414 }
415 if (!currentPalette.length) {
416 currentPalette = 'kairo';
417 setPalette(currentPalette);
418 }
419 if (!gColorPalette || !gColorPalette.length)
420 gColorPalette = getColorPalette(currentPalette);
421
422 var popup = document.getElementById("menu_palettePopup");
423 var item = popup.firstChild;
424 while (item) {
425 if (item.getAttribute("name") == "palette") {
426 if (item.getAttribute("value") == currentPalette)
427 item.setAttribute("checked", "true");
428 else
429 item.removeAttribute("checked");
430 }
431 item = item.nextSibling;
432 }
433}
434
435function setPalette(aPaletteID) {
436 gPref.setCharPref("mandelbrot.color_palette", aPaletteID);
437 gColorPalette = getColorPalette(aPaletteID);
438}
439
6403d662
RK
440function imgSettings() {
441 window.openDialog("chrome://mandelbrot/content/image-settings.xul");
442}
443
6e98af87
RK
444function updateDebugMenu() {
445 var jitMenuItem = document.getElementById("jitEnabled");
446 jitMenuItem.setAttribute("checked", gPref.getBoolPref("javascript.options.jit.chrome"));
447}
448
449function toggleJITState(jitMenuItem) {
450 var jitEnabled = !gPref.getBoolPref("javascript.options.jit.chrome");
451 gPref.setBoolPref("javascript.options.jit.chrome", jitEnabled)
452 jitMenuItem.setAttribute("checked", jitEnabled? "true" : "false");
453}
454
455function updateAlgoMenu() {
456 try {
457 var currentAlgo = gPref.getCharPref("mandelbrot.use_algorithm");
458 }
459 catch(e) {
460 var currentAlgo = '';
461 }
462 if (!currentAlgo.length) {
463 currentAlgo = 'numeric';
464 setAlgorithm(currentAlgo);
465 }
466
467 var popup = document.getElementById("menu_algoPopup");
468 var item = popup.firstChild;
469 while (item) {
470 if (item.getAttribute("name") == "algorithm") {
471 if (item.getAttribute("value") == currentAlgo)
472 item.setAttribute("checked", "true");
473 else
474 item.removeAttribute("checked");
475 }
476 item = item.nextSibling;
477 }
478}
479
480function setAlgorithm(algoID) {
481 gPref.setCharPref("mandelbrot.use_algorithm", algoID);
482}
483
af3c147c
RK
484function addonsManager(aPane) {
485 var theEM = Components.classes["@mozilla.org/appshell/window-mediator;1"]
486 .getService(Components.interfaces.nsIWindowMediator)
487 .getMostRecentWindow("Extension:Manager");
488 if (theEM) {
489 theEM.focus();
490 if (aPane)
491 theEM.showView(aPane);
492 return;
493 }
494
495 const EMURL = "chrome://mozapps/content/extensions/extensions.xul";
496 const EMFEATURES = "all,dialog=no";
497 if (aPane)
498 window.openDialog(EMURL, "", EMFEATURES, aPane);
499 else
500 window.openDialog(EMURL, "", EMFEATURES);
501}
502
503function errorConsole() {
504 toOpenWindowByType("global:console", "chrome://global/content/console.xul");
505}
506
6e98af87
RK
507/***** helper functions from external sources *****/
508
740b86d1
RK
509// function below is based on http://developer.mozilla.org/en/docs/Code_snippets:Canvas
510// custom modifications:
511// - use "a"-prefix on function arguments
512// - take an nsILocalFile as aDestFile argument
513// - always do silent download
514function saveCanvas(aCanvas, aDestFile) {
37b05b56
RK
515 // create a data url from the canvas and then create URIs of the source and targets
516 var io = Components.classes["@mozilla.org/network/io-service;1"]
517 .getService(Components.interfaces.nsIIOService);
740b86d1 518 var source = io.newURI(aCanvas.toDataURL("image/png", ""), "UTF8", null);
37b05b56
RK
519
520 // prepare to save the canvas data
521 var persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
522 .createInstance(Components.interfaces.nsIWebBrowserPersist);
523
524 persist.persistFlags = Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
525 persist.persistFlags |= Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION;
526
37b05b56 527 // save the canvas data to the file
740b86d1 528 persist.saveURI(source, null, null, null, null, aDestFile);
37b05b56
RK
529}
530
531// function below is from http://developer.mozilla.org/en/docs/How_to_Quit_a_XUL_Application
532function quitApp(aForceQuit) {
533 var appStartup = Components.classes['@mozilla.org/toolkit/app-startup;1']
534 .getService(Components.interfaces.nsIAppStartup);
535
536 // eAttemptQuit will try to close each XUL window, but the XUL window can cancel the quit
537 // process if there is unsaved data. eForceQuit will quit no matter what.
538 var quitSeverity = aForceQuit ? Components.interfaces.nsIAppStartup.eForceQuit :
539 Components.interfaces.nsIAppStartup.eAttemptQuit;
540 appStartup.quit(quitSeverity);
541}
af3c147c
RK
542
543// functions below are from comm-central/suite/common/tasksOverlay.js
544function toOpenWindow(aWindow) {
545 try {
546 // Try to focus the previously focused window e.g. message compose body
547 aWindow.document.commandDispatcher.focusedWindow.focus();
548 } catch (e) {
549 // e.g. full-page plugin or non-XUL document; just raise the top window
550 aWindow.focus();
551 }
552}
553
554function toOpenWindowByType(inType, uri, features) {
555 // don't do several loads in parallel
556 if (uri in window)
557 return;
558
559 var topWindow = Components.classes["@mozilla.org/appshell/window-mediator;1"]
560 .getService(Components.interfaces.nsIWindowMediator)
561 .getMostRecentWindow(inType);
562 if ( topWindow )
563 toOpenWindow( topWindow );
564 else {
565 // open the requested window, but block it until it's fully loaded
566 function newWindowLoaded(event) {
567 // make sure that this handler is called only once
568 window.removeEventListener("unload", newWindowLoaded, false);
569 window[uri].removeEventListener("load", newWindowLoaded, false);
570 delete window[uri];
571 }
572 // remember the newly loading window until it's fully loaded
573 // or until the current window passes away
574 window[uri] = window.openDialog(uri, "", features || "all,dialog=no");
575 window[uri].addEventListener("load", newWindowLoaded, false);
576 window.addEventListener("unload", newWindowLoaded, false);
577 }
578}