use center-aligned hboxes to makes labels and textboxes etc. line up nicely
[mandelbrot.git] / xulapp / chrome / mandelbrot / content / mandelbrot.js
... / ...
CommitLineData
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
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}
50
51function drawImage() {
52 let canvas = document.getElementById("mbrotImage");
53 let context = canvas.getContext("2d");
54
55 document.getElementById("drawButton").hidden = true;
56
57 document.getElementById("statusLabel").value =
58 document.getElementById("mbrotBundle").getString("statusDrawing");
59
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
88 let iterMax = gPref.getIntPref("mandelbrot.iteration_max");
89 let algorithm = gPref.getCharPref("mandelbrot.use_algorithm");
90
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)";
114 context.fillRect(0, 0, canvas.width, canvas.height);
115
116 gStartTime = new Date();
117
118 drawLine(0, [Cr_min, Cr_max, Ci_min, Ci_max],
119 canvas, context, iterMax, algorithm);
120}
121
122function drawLine(line, dimensions, canvas, context, iterMax, algorithm) {
123 let Cr_min = dimensions[0];
124 let Cr_max = dimensions[1];
125 let Cr_scale = Cr_max - Cr_min;
126
127 let Ci_min = dimensions[2];
128 let Ci_max = dimensions[3];
129 let Ci_scale = Ci_max - Ci_min;
130
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++) {
134 let C = new complex(Cr_min + (img_x / canvas.width) * Cr_scale,
135 Ci_min + (img_y / canvas.height) * Ci_scale);
136 pixels.push.apply(pixels, drawPoint(context, img_x, img_y, C, iterMax, algorithm));
137 }
138 context.putImageData({width: canvas.width, height: pixels.length/4/canvas.width, data: pixels}, 0, line);
139
140 if (img_y < canvas.height)
141 setTimeout(drawLine, 0, img_y, dimensions, canvas, context, iterMax, algorithm);
142 else if (gStartTime)
143 EndCalc();
144}
145
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
153function complex(aReal, aImag) {
154 this.r = aReal;
155 this.i = aImag;
156}
157complex.prototype = {
158 square: function() {
159 return new complex(this.r * this.r - this.i * this.i,
160 2 * this.r * this.i);
161 },
162 dist: function() {
163 return Math.sqrt(this.r * this.r + this.i * this.i);
164 },
165 add: function(aComplex) {
166 return new complex(this.r + aComplex.r, this.i + aComplex.i);
167 }
168}
169
170function mandelbrotValueOO (aC, aIterMax) {
171 // this would be nice code in general but it looks like JS objects are too heavy for normal use.
172 let Z = new complex(0.0, 0.0);
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 }
177 return iter;
178}
179
180function mandelbrotValueNumeric (aC, aIterMax) {
181 // optimized numeric code for fast calculation
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 }
192 return iter;
193}
194
195function getColor(aIterValue, aIterMax) {
196 let standardizedValue = Math.round(aIterValue * 1024 / aIterMax);
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)
202 return [0, 0, 0, 255];
203 else
204 return [255, 255, 255, 255];
205}
206
207function getColorPalette(palName) {
208 var palette = [];
209 switch (palName) {
210 case 'bw':
211 for (let i = 0; i < 1024; i++) {
212 palette[i] = [255, 255, 255, 255];
213 }
214 palette[1024] = [0, 0, 0, 255];
215 break;
216 case 'kairo':
217 // outer areas
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);
221 palette[i] = [cc1, cc2, cc1, 255];
222 }
223 // inner areas
224 for (let i = 0; i < 51; i++) {
225 let cc = Math.floor(i * 170 / 50);
226 palette[32 + i] = [cc, 0, (170-cc), 255];
227 }
228 // corona
229 for (let i = 0; i < 101; i++) {
230 let cc = Math.floor(i * 200 / 100);
231 palette[83 + i] = [255, cc, 0, 255];
232 }
233 // inner corona
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);
238 palette[184 + i] = [cc1, cc2, cc3, 255];
239 }
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);
243 palette[385 + i] = [cc1, cc1, cc2, 255];
244 }
245 for (let i = 0; i < 338; i++) {
246 let cc = 127 + Math.floor(i * 128 / 337);
247 palette[686 + i] = [cc, cc, 255, 255];
248 }
249 palette[1024] = [0, 0, 0, 255];
250 break;
251 case 'rainbow-linear1':
252 for (let i = 0; i < 256; i++) {
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];
257 }
258 palette[1024] = [0, 0, 0, 255];
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
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 }
333 return getColor(itVal, iterMax);
334}
335
336/***** pure UI functions *****/
337
338function saveImage() {
339 const bundle = document.getElementById("mbrotBundle");
340 const nsIFilePicker = Components.interfaces.nsIFilePicker;
341 var fp = null;
342 try {
343 fp = Components.classes["@mozilla.org/filepicker;1"]
344 .createInstance(nsIFilePicker);
345 } catch (e) {}
346 if (!fp) return;
347 var promptString = bundle.getString("savePrompt");
348 fp.init(window, promptString, nsIFilePicker.modeSave);
349 fp.appendFilter(bundle.getString("pngFilterName"), "*.png");
350 fp.defaultString = "mandelbrot.png";
351
352 var fpResult = fp.show();
353 if (fpResult != nsIFilePicker.returnCancel) {
354 saveCanvas(document.getElementById("mbrotImage"), fp.file);
355 }
356}
357
358function updateIterMenu() {
359 try {
360 var currentIter = gPref.getIntPref("mandelbrot.iteration_max");
361 }
362 catch(e) {
363 var currentIter = 0;
364 }
365 if (currentIter < 10) {
366 currentIter = 500;
367 setIter(currentIter);
368 }
369
370 var popup = document.getElementById("menu_iterPopup");
371 var item = popup.firstChild;
372 while (item) {
373 if (item.getAttribute("name") == "iter") {
374 if (item.getAttribute("value") == currentIter)
375 item.setAttribute("checked","true");
376 else
377 item.removeAttribute("checked");
378 }
379 item = item.nextSibling;
380 }
381}
382
383function setIter(aIter) {
384 gPref.setIntPref("mandelbrot.iteration_max", aIter);
385}
386
387function updatePaletteMenu() {
388 try {
389 var currentPalette = gPref.getCharPref("mandelbrot.color_palette");
390 }
391 catch(e) {
392 var currentPalette = '';
393 }
394 if (!currentPalette.length) {
395 currentPalette = 'kairo';
396 setPalette(currentPalette);
397 }
398 if (!gColorPalette || !gColorPalette.length)
399 gColorPalette = getColorPalette(currentPalette);
400
401 var popup = document.getElementById("menu_palettePopup");
402 var item = popup.firstChild;
403 while (item) {
404 if (item.getAttribute("name") == "palette") {
405 if (item.getAttribute("value") == currentPalette)
406 item.setAttribute("checked", "true");
407 else
408 item.removeAttribute("checked");
409 }
410 item = item.nextSibling;
411 }
412}
413
414function setPalette(aPaletteID) {
415 gPref.setCharPref("mandelbrot.color_palette", aPaletteID);
416 gColorPalette = getColorPalette(aPaletteID);
417}
418
419function imgSettings() {
420 window.openDialog("chrome://mandelbrot/content/image-settings.xul");
421}
422
423function updateDebugMenu() {
424 var jitMenuItem = document.getElementById("jitEnabled");
425 jitMenuItem.setAttribute("checked", gPref.getBoolPref("javascript.options.jit.chrome"));
426}
427
428function toggleJITState(jitMenuItem) {
429 var jitEnabled = !gPref.getBoolPref("javascript.options.jit.chrome");
430 gPref.setBoolPref("javascript.options.jit.chrome", jitEnabled)
431 jitMenuItem.setAttribute("checked", jitEnabled? "true" : "false");
432}
433
434function updateAlgoMenu() {
435 try {
436 var currentAlgo = gPref.getCharPref("mandelbrot.use_algorithm");
437 }
438 catch(e) {
439 var currentAlgo = '';
440 }
441 if (!currentAlgo.length) {
442 currentAlgo = 'numeric';
443 setAlgorithm(currentAlgo);
444 }
445
446 var popup = document.getElementById("menu_algoPopup");
447 var item = popup.firstChild;
448 while (item) {
449 if (item.getAttribute("name") == "algorithm") {
450 if (item.getAttribute("value") == currentAlgo)
451 item.setAttribute("checked", "true");
452 else
453 item.removeAttribute("checked");
454 }
455 item = item.nextSibling;
456 }
457}
458
459function setAlgorithm(algoID) {
460 gPref.setCharPref("mandelbrot.use_algorithm", algoID);
461}
462
463function addonsManager(aPane) {
464 var theEM = Components.classes["@mozilla.org/appshell/window-mediator;1"]
465 .getService(Components.interfaces.nsIWindowMediator)
466 .getMostRecentWindow("Extension:Manager");
467 if (theEM) {
468 theEM.focus();
469 if (aPane)
470 theEM.showView(aPane);
471 return;
472 }
473
474 const EMURL = "chrome://mozapps/content/extensions/extensions.xul";
475 const EMFEATURES = "all,dialog=no";
476 if (aPane)
477 window.openDialog(EMURL, "", EMFEATURES, aPane);
478 else
479 window.openDialog(EMURL, "", EMFEATURES);
480}
481
482function errorConsole() {
483 toOpenWindowByType("global:console", "chrome://global/content/console.xul");
484}
485
486/***** helper functions from external sources *****/
487
488// function below is based on http://developer.mozilla.org/en/docs/Code_snippets:Canvas
489// custom modifications:
490// - use "a"-prefix on function arguments
491// - take an nsILocalFile as aDestFile argument
492// - always do silent download
493function saveCanvas(aCanvas, aDestFile) {
494 // create a data url from the canvas and then create URIs of the source and targets
495 var io = Components.classes["@mozilla.org/network/io-service;1"]
496 .getService(Components.interfaces.nsIIOService);
497 var source = io.newURI(aCanvas.toDataURL("image/png", ""), "UTF8", null);
498
499 // prepare to save the canvas data
500 var persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
501 .createInstance(Components.interfaces.nsIWebBrowserPersist);
502
503 persist.persistFlags = Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
504 persist.persistFlags |= Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION;
505
506 // save the canvas data to the file
507 persist.saveURI(source, null, null, null, null, aDestFile);
508}
509
510// function below is from http://developer.mozilla.org/en/docs/How_to_Quit_a_XUL_Application
511function quitApp(aForceQuit) {
512 var appStartup = Components.classes['@mozilla.org/toolkit/app-startup;1']
513 .getService(Components.interfaces.nsIAppStartup);
514
515 // eAttemptQuit will try to close each XUL window, but the XUL window can cancel the quit
516 // process if there is unsaved data. eForceQuit will quit no matter what.
517 var quitSeverity = aForceQuit ? Components.interfaces.nsIAppStartup.eForceQuit :
518 Components.interfaces.nsIAppStartup.eAttemptQuit;
519 appStartup.quit(quitSeverity);
520}
521
522// functions below are from comm-central/suite/common/tasksOverlay.js
523function toOpenWindow(aWindow) {
524 try {
525 // Try to focus the previously focused window e.g. message compose body
526 aWindow.document.commandDispatcher.focusedWindow.focus();
527 } catch (e) {
528 // e.g. full-page plugin or non-XUL document; just raise the top window
529 aWindow.focus();
530 }
531}
532
533function toOpenWindowByType(inType, uri, features) {
534 // don't do several loads in parallel
535 if (uri in window)
536 return;
537
538 var topWindow = Components.classes["@mozilla.org/appshell/window-mediator;1"]
539 .getService(Components.interfaces.nsIWindowMediator)
540 .getMostRecentWindow(inType);
541 if ( topWindow )
542 toOpenWindow( topWindow );
543 else {
544 // open the requested window, but block it until it's fully loaded
545 function newWindowLoaded(event) {
546 // make sure that this handler is called only once
547 window.removeEventListener("unload", newWindowLoaded, false);
548 window[uri].removeEventListener("load", newWindowLoaded, false);
549 delete window[uri];
550 }
551 // remember the newly loading window until it's fully loaded
552 // or until the current window passes away
553 window[uri] = window.openDialog(uri, "", features || "all,dialog=no");
554 window[uri].addEventListener("load", newWindowLoaded, false);
555 window.addEventListener("unload", newWindowLoaded, false);
556 }
557}