extend image settings with coordinates and preview
[mandelbrot.git] / xulapp / chrome / mandelbrot / content / mandelbrot.js
index 440911348f03d47ef5c8628c08776b28aeb5611e..02654971e238b88020bf35a64a7046f7c1132de7 100644 (file)
-var gColorPalette = getColorPalette('kairo');
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is KaiRo.at Mandelbrot, XULRunner version.
+ *
+ * The Initial Developer of the Original Code is
+ * Robert Kaiser <kairo@kairo.at>.
+ * Portions created by the Initial Developer are Copyright (C) 2008
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Robert Kaiser <kairo@kairo.at>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+var gColorPalette = [];
+var gPref = Components.classes["@mozilla.org/preferences-service;1"]
+                      .getService(Components.interfaces.nsIPrefService)
+                      .getBranch(null);
+var gStartTime = 0;
+
+function Startup() {
+  updateIterMenu();
+  updatePaletteMenu();
+  document.getElementById("statusLabel").value =
+      document.getElementById("mbrotBundle").getString("statusEmpty");
+}
 
 function drawImage() {
-  var canvas = document.getElementById("mbrotImage");
-  if (canvas.getContext) {
-    var context = canvas.getContext("2d");
-
-    // example:
-    // context.fillStyle = "rgb(200,0,0)";
-    // context.fillRect (10, 10, 55, 50); // x, y, width, height
-    //
-    // context.fillStyle = "rgba(0, 0, 200, 0.5)";
-    // context.fillRect (30, 30, 55, 50);
-
-    var Cr_min = -2.0;
-    var Cr_max = 1.0;
-    var Cr_scale = Cr_max - Cr_min;
-
-    var Ci_min = -1.5;
-    var Ci_max = 1.5;
-    var Ci_scale = Ci_max - Ci_min;
-
-    var iterMax = 500;
-
-    for (var img_x = 0; img_x < canvas.width; img_x++) {
-      for (var img_y = 0; img_y < canvas.height; img_y++) {
-        var C = new complex(Cr_min + (img_x / canvas.width) * Cr_scale,
+  let canvas = document.getElementById("mbrotImage");
+  let context = canvas.getContext("2d");
+
+  document.getElementById("statusLabel").value =
+      document.getElementById("mbrotBundle").getString("statusDrawing");
+
+  let Cr_min = -2.0;
+  let Cr_max = 1.0;
+  try {
+    Cr_min = parseFloat(gPref.getCharPref("mandelbrot.last_image.Cr_min"));
+    Cr_max = parseFloat(gPref.getCharPref("mandelbrot.last_image.Cr_max"));
+  }
+  catch (e) { }
+  if ((Cr_min < -2) || (Cr_min > 2) ||
+      (Cr_max < -2) || (Cr_max > 2) || (Cr_min >= Cr_max)) {
+    Cr_min = -2.0; Cr_max = 1.0;
+  }
+  gPref.setCharPref("mandelbrot.last_image.Cr_min", Cr_min);
+  gPref.setCharPref("mandelbrot.last_image.Cr_max", Cr_max);
+
+  let Ci_min = -1.5;
+  let Ci_max = 1.5;
+  try {
+    Ci_min = parseFloat(gPref.getCharPref("mandelbrot.last_image.Ci_min"));
+    Ci_max = parseFloat(gPref.getCharPref("mandelbrot.last_image.Ci_max"));
+  }
+  catch (e) { }
+  if ((Ci_min < -2) || (Ci_min > 2) ||
+      (Ci_max < -2) || (Ci_max > 2) || (Ci_min >= Ci_max)) {
+    Ci_min = -2.0; Ci_max = 1.0;
+  }
+  gPref.setCharPref("mandelbrot.last_image.Ci_min", Ci_min);
+  gPref.setCharPref("mandelbrot.last_image.Ci_max", Ci_max);
+
+  let iterMax = gPref.getIntPref("mandelbrot.iteration_max");
+  let algorithm = gPref.getCharPref("mandelbrot.use_algorithm");
+
+  let iWidth = 0;
+  try {
+    iWidth = gPref.getIntPref("mandelbrot.image.width");
+  }
+  catch (e) { }
+  if ((iWidth < 10) || (iWidth > 5000)) {
+    iWidth = 300;
+    gPref.setIntPref("mandelbrot.image.width", iWidth);
+  }
+  let iHeight = 0;
+  try {
+    iHeight = gPref.getIntPref("mandelbrot.image.height");
+  }
+  catch (e) { }
+  if ((iHeight < 10) || (iHeight > 5000)) {
+    iHeight = 300;
+    gPref.setIntPref("mandelbrot.image.height", iHeight);
+  }
+
+  canvas.width = iWidth;
+  canvas.height = iHeight;
+
+  context.fillStyle = "rgba(255, 255, 255, 127)";
+  context.fillRect(0, 0, canvas.width, canvas.height);
+
+  gStartTime = new Date();
+
+  drawLine(0, [Cr_min, Cr_max, Ci_min, Ci_max],
+              canvas, context, iterMax, algorithm);
+}
+
+function drawLine(line, dimensions, canvas, context, iterMax, algorithm) {
+    let Cr_min = dimensions[0];
+    let Cr_max = dimensions[1];
+    let Cr_scale = Cr_max - Cr_min;
+
+    let Ci_min = dimensions[2];
+    let Ci_max = dimensions[3];
+    let Ci_scale = Ci_max - Ci_min;
+
+    let pixels = [];
+    for (var img_y = line; img_y < canvas.height && img_y < line+8; img_y++)
+      for (let img_x = 0; img_x < canvas.width; img_x++) {
+        let C = new complex(Cr_min + (img_x / canvas.width) * Cr_scale,
                             Ci_min + (img_y / canvas.height) * Ci_scale);
-        window.setTimeout(drawPoint, 0, context, img_x, img_y, C, iterMax);
+        pixels.push.apply(pixels, drawPoint(context, img_x, img_y, C, iterMax, algorithm));
       }
-    }
-  }
+    context.putImageData({width: canvas.width, height: pixels.length/4/canvas.width, data: pixels}, 0, line);
+
+    if (img_y < canvas.height)
+      setTimeout(drawLine, 0, img_y, dimensions, canvas, context, iterMax, algorithm);
+    else
+      EndCalc();
+}
+
+function EndCalc() {
+  let endTime = new Date();
+  let timeUsed = (endTime.getTime() - gStartTime.getTime()) / 1000;
+  document.getElementById("statusLabel").value =
+      document.getElementById("mbrotBundle").getFormattedString("statusTime", [timeUsed.toFixed(3)]);
 }
 
 function complex(aReal, aImag) {
   this.r = aReal;
   this.i = aImag;
-  this.square = function() {
+}
+complex.prototype = {
+  square: function() {
     return new complex(this.r * this.r - this.i * this.i,
                        2 * this.r * this.i);
-  }
-  this.dist = function() {
+  },
+  dist: function() {
     return Math.sqrt(this.r * this.r + this.i * this.i);
-  }
-  this.add = function(aComplex) {
+  },
+  add: function(aComplex) {
     return new complex(this.r + aComplex.r, this.i + aComplex.i);
   }
 }
 
-function mandelbrotValue (aC, aIterMax) {
-  /* XXX: this would be nice code but it looks like JS objects are too heavy for this.
+function mandelbrotValueOO (aC, aIterMax) {
+  // this would be nice code in general but it looks like JS objects are too heavy for normal use.
   let Z = new complex(0.0, 0.0);
   for (var iter = 0; iter < aIterMax; iter++) {
     Z = Z.square().add(aC);
     if (Z.r * Z.r + Z.i * Z.i > 256) { break; }
   }
-  */
+  return iter;
+}
 
-  // highly optimized code for fast calculation
+function mandelbrotValueNumeric (aC, aIterMax) {
+  // optimized numeric code for fast calculation
   let Cr = aC.r, Ci = aC.i;
   let Zr = 0.0, Zi = 0.0;
   let Zr2 = Zr * Zr, Zi2 = Zi * Zi;
@@ -71,69 +191,69 @@ function mandelbrotValue (aC, aIterMax) {
 }
 
 function getColor(aIterValue, aIterMax) {
-  var standardizedValue = Math.round(aIterValue * 1024 / aIterMax);
-  return gColorPalette[standardizedValue];
-  if (aIterValue == aIterMax) {
-    return "rgb(0,0,0)";
-  }
-  else {
-    //return "rgb(" + img_x + "," + img_y + ",0)";
-    return "rgb(255,255,255)";
-  }
+  let standardizedValue = Math.round(aIterValue * 1024 / aIterMax);
+  if (gColorPalette && gColorPalette.length)
+    return gColorPalette[standardizedValue];
+
+  // fallback to simple b/w if for some reason we don't have a palette
+  if (aIterValue == aIterMax)
+    return [0, 0, 0, 255];
+  else
+    return [255, 255, 255, 255];
 }
 
 function getColorPalette(palName) {
   var palette = [];
   switch (palName) {
     case 'bw':
-      for (var i = 0; i < 1024; i++) {
-        palette[i] = 'rgb(255,255,255)';
+      for (let i = 0; i < 1024; i++) {
+        palette[i] = [255, 255, 255, 255];
       }
-      palette[1024] = 'rgb(0,0,0)';
+      palette[1024] = [0, 0, 0, 255];
       break;
     case 'kairo':
       // outer areas
-      for (var i = 0; i < 32; i++) {
-        var cc1 = Math.floor(i * 127 / 31);
-        var cc2 = 170 - Math.floor(i * 43 / 31);
-        palette[i] = 'rgb(' + cc1 + ',' + cc2 + ',' + cc1 + ')';
+      for (let i = 0; i < 32; i++) {
+        let cc1 = Math.floor(i * 127 / 31);
+        let cc2 = 170 - Math.floor(i * 43 / 31);
+        palette[i] = [cc1, cc2, cc1, 255];
       }
       // inner areas
-      for (var i = 0; i < 51; i++) {
-        var cc = Math.floor(i * 170 / 50);
-        palette[32 + i] = 'rgb(' + cc + ',0,' + (170 + cc) + ')';
+      for (let i = 0; i < 51; i++) {
+        let cc = Math.floor(i * 170 / 50);
+        palette[32 + i] = [cc, 0, (170-cc), 255];
       }
       // corona
-      for (var i = 0; i < 101; i++) {
-        var cc = Math.floor(i * 200 / 100);
-        palette[83 + i] = 'rgb(255,' + cc + ',0)';
+      for (let i = 0; i < 101; i++) {
+        let cc = Math.floor(i * 200 / 100);
+        palette[83 + i] = [255, cc, 0, 255];
       }
       // inner corona
-      for (var i = 0; i < 201; i++) {
-        var cc1 = 255 - Math.floor(i * 85 / 200);
-        var cc2 = 200 - Math.floor(i * 30 / 200);
-        var cc3 = Math.floor(i * 170 / 200);
-        palette[184 + i] = 'rgb(' + cc1 + ',' + cc2 + ',' + cc3 + ')';
+      for (let i = 0; i < 201; i++) {
+        let cc1 = 255 - Math.floor(i * 85 / 200);
+        let cc2 = 200 - Math.floor(i * 30 / 200);
+        let cc3 = Math.floor(i * 170 / 200);
+        palette[184 + i] = [cc1, cc2, cc3, 255];
       }
-      for (var i = 0; i < 301; i++) {
-        var cc1 = 170 - Math.floor(i * 43 / 300);
-        var cc2 = 170 + Math.floor(i * 85 / 300);
-        palette[385 + i] = 'rgb(' + cc1 + ',' + cc1 + ',' + cc2 + ')';
+      for (let i = 0; i < 301; i++) {
+        let cc1 = 170 - Math.floor(i * 43 / 300);
+        let cc2 = 170 + Math.floor(i * 85 / 300);
+        palette[385 + i] = [cc1, cc1, cc2, 255];
       }
-      for (var i = 0; i < 338; i++) {
-        var cc = 127 + Math.floor(i * 128 / 337);
-        palette[686 + i] = 'rgb(' + cc + ',' + cc + ',255)';
+      for (let i = 0; i < 338; i++) {
+        let cc = 127 + Math.floor(i * 128 / 337);
+        palette[686 + i] = [cc, cc, 255, 255];
       }
-      palette[1024] = 'rgb(0,0,0)';
+      palette[1024] = [0, 0, 0, 255];
       break;
     case 'rainbow-linear1':
-      for (var i = 0; i < 256; i++) {
-        palette[i] = 'rgb(' + i + ',0,0)';
-        palette[256 + i] = 'rgb(255,' + i + ',0)';
-        palette[512 + i] = 'rgb(' + (255 - i) + ',255,' + i + ')';
-        palette[768 + i] = 'rgb(' + i + ',' + (255 - i) + ',255)';
+      for (let i = 0; i < 256; i++) {
+        palette[i] = [i, 0, 0, 255];
+        palette[256 + i] = [255, i, 0, 255];
+        palette[512 + i] = [255 - i, 255, i, 255];
+        palette[768 + i] = [i, 255-i, 255, 255];
       }
-      palette[1024] = 'rgb(0,0,0)';
+      palette[1024] = [0, 0, 0, 255];
       break;
   }
 /*
@@ -197,29 +317,159 @@ Case 5  'Regenbogen-Palette 2 (qu.)
   return palette;
 }
 
-function drawPoint(context, img_x, img_y, C, iterMax) {
-  var itVal = mandelbrotValue(C, iterMax);
-  context.fillStyle = getColor(itVal, iterMax);
-  context.fillRect (img_x, img_y, 1, 1); // x, y, width, height
+function drawPoint(context, img_x, img_y, C, iterMax, algorithm) {
+  var itVal;
+  switch (algorithm) {
+    case 'oo':
+      itVal = mandelbrotValueOO(C, iterMax);
+      break;
+    case 'numeric':
+    default:
+      itVal = mandelbrotValueNumeric(C, iterMax);
+      break;
+  }
+  return getColor(itVal, iterMax);
 }
 
+/***** pure UI functions *****/
+
 function saveImage() {
-  // should call filepicker!
-  saveCanvas(document.getElementById("mbrotImage"), "/home/robert/temp/canvas-save.png")
+  const bundle = document.getElementById("mbrotBundle");
+  const nsIFilePicker = Components.interfaces.nsIFilePicker;
+  var fp = null;
+  try {
+    fp = Components.classes["@mozilla.org/filepicker;1"]
+                   .createInstance(nsIFilePicker);
+  } catch (e) {}
+  if (!fp) return;
+  var promptString = bundle.getString("savePrompt");
+  fp.init(window, promptString, nsIFilePicker.modeSave);
+  fp.appendFilter(bundle.getString("pngFilterName"), "*.png");
+  fp.defaultString = "mandelbrot.png";
+
+  var fpResult = fp.show();
+  if (fpResult != nsIFilePicker.returnCancel) {
+    saveCanvas(document.getElementById("mbrotImage"), fp.file);
+  }
+}
+
+function updateIterMenu() {
+  try {
+    var currentIter = gPref.getIntPref("mandelbrot.iteration_max");
+  }
+  catch(e) {
+    var currentIter = 0;
+  }
+  if (currentIter < 10) {
+    currentIter = 500;
+    setIter(currentIter);
+  }
+
+  var popup = document.getElementById("menu_iterPopup");
+  var item = popup.firstChild;
+  while (item) {
+    if (item.getAttribute("name") == "iter") {
+      if (item.getAttribute("value") == currentIter)
+        item.setAttribute("checked","true");
+      else
+        item.removeAttribute("checked");
+    }
+    item = item.nextSibling;
+  }
+}
+
+function setIter(aIter) {
+  gPref.setIntPref("mandelbrot.iteration_max", aIter);
+}
+
+function updatePaletteMenu() {
+  try {
+    var currentPalette = gPref.getCharPref("mandelbrot.color_palette");
+  }
+  catch(e) {
+    var currentPalette = '';
+  }
+  if (!currentPalette.length) {
+    currentPalette = 'kairo';
+    setPalette(currentPalette);
+  }
+  if (!gColorPalette || !gColorPalette.length)
+    gColorPalette = getColorPalette(currentPalette);
+
+  var popup = document.getElementById("menu_palettePopup");
+  var item = popup.firstChild;
+  while (item) {
+    if (item.getAttribute("name") == "palette") {
+      if (item.getAttribute("value") == currentPalette)
+        item.setAttribute("checked", "true");
+      else
+        item.removeAttribute("checked");
+    }
+    item = item.nextSibling;
+  }
+}
+
+function setPalette(aPaletteID) {
+  gPref.setCharPref("mandelbrot.color_palette", aPaletteID);
+  gColorPalette = getColorPalette(aPaletteID);
+}
+
+function imgSettings() {
+  window.openDialog("chrome://mandelbrot/content/image-settings.xul");
+}
+
+function updateDebugMenu() {
+  var jitMenuItem = document.getElementById("jitEnabled");
+  jitMenuItem.setAttribute("checked", gPref.getBoolPref("javascript.options.jit.chrome"));
+}
+
+function toggleJITState(jitMenuItem) {
+  var jitEnabled = !gPref.getBoolPref("javascript.options.jit.chrome");
+  gPref.setBoolPref("javascript.options.jit.chrome", jitEnabled)
+  jitMenuItem.setAttribute("checked", jitEnabled? "true" : "false");
+}
+
+function updateAlgoMenu() {
+  try {
+    var currentAlgo = gPref.getCharPref("mandelbrot.use_algorithm");
+  }
+  catch(e) {
+    var currentAlgo = '';
+  }
+  if (!currentAlgo.length) {
+    currentAlgo = 'numeric';
+    setAlgorithm(currentAlgo);
+  }
+
+  var popup = document.getElementById("menu_algoPopup");
+  var item = popup.firstChild;
+  while (item) {
+    if (item.getAttribute("name") == "algorithm") {
+      if (item.getAttribute("value") == currentAlgo)
+        item.setAttribute("checked", "true");
+      else
+        item.removeAttribute("checked");
+    }
+    item = item.nextSibling;
+  }
 }
 
-// function below is from from http://developer.mozilla.org/en/docs/Code_snippets:Canvas
-function saveCanvas(canvas, destFile) {
-  // convert string filepath to an nsIFile
-  var file = Components.classes["@mozilla.org/file/local;1"]
-                       .createInstance(Components.interfaces.nsILocalFile);
-  file.initWithPath(destFile);
+function setAlgorithm(algoID) {
+  gPref.setCharPref("mandelbrot.use_algorithm", algoID);
+}
 
+/***** helper functions from external sources *****/
+
+// function below is based on http://developer.mozilla.org/en/docs/Code_snippets:Canvas
+// custom modifications:
+//   - use "a"-prefix on function arguments
+//   - take an nsILocalFile as aDestFile argument
+//   - always do silent download
+function saveCanvas(aCanvas, aDestFile) {
   // create a data url from the canvas and then create URIs of the source and targets  
   var io = Components.classes["@mozilla.org/network/io-service;1"]
                      .getService(Components.interfaces.nsIIOService);
-  var source = io.newURI(canvas.toDataURL("image/png", ""), "UTF8", null);
-  var target = io.newFileURI(file);
+  var source = io.newURI(aCanvas.toDataURL("image/png", ""), "UTF8", null);
 
   // prepare to save the canvas data
   var persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
@@ -228,14 +478,8 @@ function saveCanvas(canvas, destFile) {
   persist.persistFlags = Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
   persist.persistFlags |= Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION;
 
-  // displays a download dialog (remove these 3 lines for silent download)
-  var xfer = Components.classes["@mozilla.org/transfer;1"]
-                       .createInstance(Components.interfaces.nsITransfer);
-  xfer.init(source, target, "", null, null, null, persist);
-  persist.progressListener = xfer;
-
   // save the canvas data to the file
-  persist.saveURI(source, null, null, null, null, file);
+  persist.saveURI(source, null, null, null, null, aDestFile);
 }
 
 // function below is from http://developer.mozilla.org/en/docs/How_to_Quit_a_XUL_Application