save and load prefs correctly by creating a sync variant to deal with them (via init...
[mandelbrot-web.git] / js / mandelbrot.js
index ace0deda24e25a97dc9fd6ca4d2d817e2c47f140..c5bb688b71ce8baf9919746811d34959adc2e31d 100644 (file)
-/* ***** 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-210
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *   Robert Kaiser <kairo@kairo.at>
- *   Boris Zbarsky <bzbarsky@mit.edu>
- *
- * 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 ***** */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// Get the best-available indexedDB object.
+window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
+var mainDB;
+
+var gDebug = false;
+var gAction, gActionLabel;
+var gMainCanvas, gMainContext;
 var gColorPalette = [];
 var gStartTime = 0;
 var gCurrentImageData;
 var gLastImageData;
 
 function Startup() {
-  var img = document.getElementById("mbrotImage");
-  img.addEventListener("mouseup", imgEvHandler, false);
-  img.addEventListener("mousedown", imgEvHandler, false);
-  img.addEventListener("mousemove", imgEvHandler, false);
-  img.addEventListener("touchstart", imgEvHandler, false);
-  img.addEventListener("touchend", imgEvHandler, false);
-  img.addEventListener("touchcancel", imgEvHandler, false);
-  img.addEventListener("touchleave", imgEvHandler, false);
-  img.addEventListener("touchmove", imgEvHandler, false);
+  gAction = document.getElementById("action");
+  gActionLabel = document.getElementById("actionlabel");
+  gAction.addEventListener("dbinit-done", initPrefs, false);
+  initDB();
+
+  gMainCanvas = document.getElementById("mbrotImage");
+  gMainContext = gMainCanvas.getContext("2d");
+
+  gMainCanvas.addEventListener("mouseup", imgEvHandler, false);
+  gMainCanvas.addEventListener("mousedown", imgEvHandler, false);
+  gMainCanvas.addEventListener("mousemove", imgEvHandler, false);
+  gMainCanvas.addEventListener("touchstart", imgEvHandler, false);
+  gMainCanvas.addEventListener("touchend", imgEvHandler, false);
+  gMainCanvas.addEventListener("touchcancel", imgEvHandler, false);
+  gMainCanvas.addEventListener("touchleave", imgEvHandler, false);
+  gMainCanvas.addEventListener("touchmove", imgEvHandler, false);
+
+  var initTile = new Image();
+  initTile.src = "style/initial-overview.png";
+  initTile.onload = function() { gMainContext.drawImage(initTile, 0, 0); };
+}
+
+function initDB() {
+  // Open DB.
+  var request = window.indexedDB.open("MainDB-mandelbrot", 1);
+  request.onerror = function(event) {
+    // Errors can be handled here. Error codes explain in:
+    // https://developer.mozilla.org/en/IndexedDB/IDBDatabaseException#Constants
+    if (gDebug)
+      console.log("error opening mainDB: " + event.target.errorCode);
+  };
+  request.onsuccess = function(event) {
+    //document.getElementById("debug").textContent = "mainDB opened.";
+    mainDB = request.result;
+    var throwEv = new CustomEvent("dbinit-done");
+    gAction.dispatchEvent(throwEv);
+  };
+  request.onupgradeneeded = function(event) {
+    mainDB = request.result;
+    var ver = mainDB.version || 0; // version is empty string for a new DB
+    if (gDebug)
+      console.log("mainDB has version " + ver + ", upgrade needed.");
+    if (!mainDB.objectStoreNames.contains("prefs")) {
+      // Create a "prefs" objectStore.
+      var prefsStore = mainDB.createObjectStore("prefs");
+    }
+    if (!mainDB.objectStoreNames.contains("bookmarks")) {
+      // Create a "bookmarks" objectStore.
+      var prefsStore = mainDB.createObjectStore("bookmarks");
+    }
+    mainDB.onversionchange = function(event) {
+      mainDB.close();
+      mainDB = undefined;
+      initDB();
+    };
+  };
+}
+
+function initPrefs() {
+  if (gDebug)
+    console.log("initializing prefs...");
+  gSyncPrefs.init(function () {
+    // Update the various settings fields to values from prefs.
+    if (gSyncPrefs.get("image.width"))
+      document.getElementById("image_width").value = gSyncPrefs.get("image.width");
+    if (gSyncPrefs.get("image.height"))
+      document.getElementById("image_height").value = gSyncPrefs.get("image.height");
+    if (gSyncPrefs.get("Cr_min"))
+      document.getElementById("Cr_min").value = gSyncPrefs.get("Cr_min");
+    if (gSyncPrefs.get("Cr_max"))
+      document.getElementById("Cr_max").value = gSyncPrefs.get("Cr_max");
+    if (gSyncPrefs.get("Ci_min"))
+      document.getElementById("Ci_min").value = gSyncPrefs.get("Ci_min");
+    if (gSyncPrefs.get("Ci_max"))
+      document.getElementById("Ci_max").value = gSyncPrefs.get("Ci_max");
+    if (gSyncPrefs.get("iteration_max"))
+      document.getElementById("iterMax").value = gSyncPrefs.get("iteration_max");
+    if (gSyncPrefs.get("color_palette"))
+      document.getElementById("palette").value = gSyncPrefs.get("color_palette");
+    if (gSyncPrefs.get("syncProportions") === true || gSyncPrefs.get("syncProportions") === false)
+      document.getElementById("proportional").checked = gSyncPrefs.get("syncProportions");
+    if (gSyncPrefs.get("use_algorithm"))
+     document.getElementById("algorithm").value = gSyncPrefs.get("use_algorithm");
+    if (gDebug)
+      console.log("prefs loaded.");
+  });
 }
 
 function getAdjustVal(aName) {
@@ -63,9 +113,10 @@ function getAdjustVal(aName) {
         value = document.getElementById(aName.replace(".", "_")).value;
       }
       catch (e) { }
-      if ((value < 10) || (value > 5000)) {
+      if (!value || (value < 10) || (value > 5000)) {
         value = 300;
-        //document.getElementById(aName.replace(".", "_")).value = value;
+        gSyncPrefs.set(aName, value);
+        document.getElementById(aName.replace(".", "_")).value = value;
       }
       return value;
     case "last_image.Cr_*":
@@ -80,8 +131,11 @@ function getAdjustVal(aName) {
           (Cr_max < -3) || (Cr_max > 2) || (Cr_min >= Cr_max)) {
         Cr_min = -2.0; Cr_max = 1.0;
       }
+      gSyncPrefs.set("Cr_min", Cr_min);
+      gSyncPrefs.set("Cr_max", Cr_max);
       document.getElementById("Cr_min").value = Cr_min;
       document.getElementById("Cr_max").value = Cr_max;
+      document.getElementById("Cr_scale").value = Cr_max - Cr_min;
       return {Cr_min: Cr_min, Cr_max: Cr_max};
     case "last_image.Ci_*":
       var Ci_min = -1.5;
@@ -95,8 +149,11 @@ function getAdjustVal(aName) {
           (Ci_max < -2.5) || (Ci_max > 2.5) || (Ci_min >= Ci_max)) {
         Ci_min = -1.5; Ci_max = 1.5;
       }
+      gSyncPrefs.set("Ci_min", Ci_min);
+      gSyncPrefs.set("Ci_max", Ci_max);
       document.getElementById("Ci_min").value = Ci_min;
       document.getElementById("Ci_max").value = Ci_max;
+      document.getElementById("Ci_scale").value = Ci_max - Ci_min;
       return {Ci_min: Ci_min, Ci_max: Ci_max};
     case "iteration_max":
       value = 500;
@@ -135,6 +192,7 @@ function getAdjustVal(aName) {
         value = document.getElementById("proportional").value;
       }
       catch(e) {
+        gSyncPrefs.set(prefname, value);
         document.getElementById("proportional").value = value;
       }
       return value;
@@ -147,13 +205,18 @@ function setVal(aName, aValue) {
   switch (aName) {
     case "image.width":
     case "image.height":
-      document.getElementById(aName.replace(".", "_")).value = value;
+      gSyncPrefs.set(aName, aValue);
+      document.getElementById(aName.replace(".", "_")).value = aValue;
       break;
     case "last_image.Cr_*":
+      gSyncPrefs.set("Cr_min", aValue.Cr_min);
+      gSyncPrefs.set("Cr_max", aValue.Cr_max);
       document.getElementById("Cr_min").value = aValue.Cr_min;
       document.getElementById("Cr_max").value = aValue.Cr_max;
       break;
     case "last_image.Ci_*":
+      gSyncPrefs.set("Ci_min", aValue.Ci_min);
+      gSyncPrefs.set("Ci_max", aValue.Ci_max);
       document.getElementById("Ci_min").value = aValue.Ci_min;
       document.getElementById("Ci_max").value = aValue.Ci_max;
       break;
@@ -164,14 +227,71 @@ function setVal(aName, aValue) {
       setAlgorithm(aValue);
       break;
    case "color_palette":
-      setPalette(valueaValue);
+      setPalette(aValue);
       break;
    case "syncProportions":
+      gSyncPrefs.set(aName, aValue);
       document.getElementById("proportional").value = aValue;
       break;
   }
 }
 
+function checkISValue(textbox, type) {
+  if (type == "coord") {
+    textbox.value = roundCoord(parseFloat(textbox.value));
+  }
+  else if (type == "dim") {
+    textbox.value = parseInt(textbox.value);
+    if (textbox.id == "image_width")
+      gSyncPrefs.set("image.width", textbox.value);
+    if (textbox.id == "image_height")
+      gSyncPrefs.set("image.height", textbox.value);
+  }
+}
+
+function recalcCoord(coord, target) {
+  var othercoord = (coord == "Ci") ? "Cr" : "Ci";
+  var owndim = (coord == "Ci") ? "height" : "width";
+  var otherdim = (coord == "Ci") ? "width" : "height";
+  var myscale;
+  if (target == "scale") {
+    myscale =
+      parseFloat(document.getElementById(coord + "_max").value) -
+      parseFloat(document.getElementById(coord + "_min").value);
+    document.getElementById(coord + "_scale").value = roundCoord(myscale);
+  }
+  else if (target == 'max') {
+    var mymax =
+      parseFloat(document.getElementById(coord + "_min").value) +
+      parseFloat(document.getElementById(coord + "_scale").value);
+    document.getElementById(coord + "_max").value = roundCoord(mymax);
+    myscale = document.getElementById(coord + "_scale").value;
+  }
+  if (document.getElementById("proportional").checked) {
+    var otherscale = myscale *
+      document.getElementById("image_" + otherdim).value /
+      document.getElementById("image_" + owndim).value;
+    document.getElementById(othercoord + "_scale").value = roundCoord(otherscale);
+    var othermax =
+      parseFloat(document.getElementById(othercoord + "_min").value) +
+      parseFloat(document.getElementById(othercoord + "_scale").value);
+    document.getElementById(othercoord + "_max").value = roundCoord(othermax);
+  }
+}
+
+function checkProportions() {
+  var prop = document.getElementById("proportional").checked;
+  if (!prop) {
+    recalcCoord("Cr", "scale");
+  }
+  gSyncPrefs.set("syncProportions", prop);
+}
+
+function roundCoord(floatval) {
+  // We should round to 10 decimals here or so
+  return parseFloat(floatval.toFixed(10));
+}
+
 function adjustCoordsAndDraw(aC_min, aC_max) {
   var iWidth = getAdjustVal("image.width");
   var iHeight = getAdjustVal("image.height");
@@ -207,13 +327,14 @@ function adjustCoordsAndDraw(aC_min, aC_max) {
 }
 
 function drawImage() {
-  var canvas = document.getElementById("mbrotImage");
-  var context = canvas.getContext("2d");
+  var canvas = gMainCanvas;
+  var context = gMainContext;
 
   document.getElementById("calcTime").textContent = "--";
 
   if (gCurrentImageData) {
     gLastImageData = gCurrentImageData;
+    document.getElementById("backButton").disabled = false;
   }
 
   gColorPalette = getColorPalette(document.getElementById("palette").value);
@@ -229,16 +350,8 @@ function drawImage() {
   var iterMax = getAdjustVal("iteration_max");
   var algorithm = getAdjustVal("use_algorithm");
 
-  var iWidth = canvas.width;
-  if ((iWidth < 10) || (iWidth > 5000)) {
-    iWidth = 300;
-    canvas.width = iWidth;
-  }
-  var iHeight = canvas.height;
-  if ((iHeight < 10) || (iHeight > 5000)) {
-    iHeight = 300;
-    canvas.height = iHeight;
-  }
+  var iWidth = getAdjustVal("image.width");
+  var iHeight = getAdjustVal("image.height");
 
   gCurrentImageData = {
     C_min: new complex(Cr_min, Ci_min),
@@ -248,6 +361,9 @@ function drawImage() {
     iterMax: iterMax
   };
 
+  canvas.width = iWidth;
+  canvas.height = iHeight;
+
   context.fillStyle = "rgba(255, 255, 255, 127)";
   context.fillRect(0, 0, canvas.width, canvas.height);
 
@@ -527,15 +643,21 @@ var imgEvHandler = {
           if (zoomend.y < zoomstart.y)
             [zoomend.y, zoomstart.y] = [zoomstart.y, zoomend.y];
 
-          // determine new "coordinates"
-          var CWidth = gCurrentImageData.C_max.r - gCurrentImageData.C_min.r;
-          var CHeight = gCurrentImageData.C_max.i - gCurrentImageData.C_min.i;
-          var newC_min = new complex(
-              gCurrentImageData.C_min.r + zoomstart.x / gCurrentImageData.iWidth * CWidth,
-              gCurrentImageData.C_min.i + zoomstart.y / gCurrentImageData.iHeight * CHeight);
-          var newC_max = new complex(
-              gCurrentImageData.C_min.r + zoomend.x / gCurrentImageData.iWidth * CWidth,
-              gCurrentImageData.C_min.i + zoomend.y / gCurrentImageData.iHeight * CHeight);
+          if (gCurrentImageData) {
+            // determine new "coordinates"
+            var CWidth = gCurrentImageData.C_max.r - gCurrentImageData.C_min.r;
+            var CHeight = gCurrentImageData.C_max.i - gCurrentImageData.C_min.i;
+            var newC_min = new complex(
+                gCurrentImageData.C_min.r + zoomstart.x / gCurrentImageData.iWidth * CWidth,
+                gCurrentImageData.C_min.i + zoomstart.y / gCurrentImageData.iHeight * CHeight);
+            var newC_max = new complex(
+                gCurrentImageData.C_min.r + zoomend.x / gCurrentImageData.iWidth * CWidth,
+                gCurrentImageData.C_min.i + zoomend.y / gCurrentImageData.iHeight * CHeight);
+          }
+          else {
+            var newC_min = new complex(-2, -1.5);
+            var newC_max = new complex(1, 1.5);
+          }
 
           adjustCoordsAndDraw(newC_min, newC_max);
         }
@@ -550,11 +672,17 @@ var imgEvHandler = {
                              coordObj.clientX - canvas.offsetLeft - zoomstart.x,
                              coordObj.clientY - canvas.offsetTop - zoomstart.y);
         }
-      break;
+        break;
     }
   }
 };
 
+function drawIfEmpty() {
+  if (!gCurrentImageData) {
+    drawImage();
+  }
+}
+
 function toggleSettings() {
   var fs = document.getElementById("settings");
   if (fs.style.display != "block") {
@@ -571,18 +699,231 @@ function goBack() {
     // use gLastImageData.iWidth, gLastImageData.iHeight ???
     adjustCoordsAndDraw(gLastImageData.C_min, gLastImageData.C_max);
     gLastImageData = undefined;
+    document.getElementById("backButton").disabled = true;
   }
 }
 
 function setIter(aIter) {
-  document.getElementById("iterMax").value = aIter;
+  if (aIter)
+    document.getElementById("iterMax").value = aIter;
+  else
+    aIter = document.getElementById("iterMax").value;
+  gSyncPrefs.set("iteration_max", aIter);
 }
 
 function setPalette(aPaletteID) {
-  document.getElementById("palette").value = aPaletteID;
+  if (aPaletteID)
+    document.getElementById("palette").value = aPaletteID;
+  else
+    aPaletteID = document.getElementById("palette").value;
+  gSyncPrefs.set("color_palette", aPaletteID);
   gColorPalette = getColorPalette(aPaletteID);
 }
 
-function setAlgorithm(algoID) {
-  //document.getElementById("algorithm").value = algoID;
+function setAlgorithm(aAlgoID) {
+  if (aAlgoID)
+    document.getElementById("algorithm").value = aAlgoID;
+  else
+    aAlgoID = document.getElementById("algorithm").value;
+  gSyncPrefs.set("use_algorithm", aAlgoID);
+}
+
+function callBookmark(evtarget) {
+  if (evtarget.id == "bookmarkSave" || evtarget.id == "bookmarkSeparator")
+    return;
+  if (evtarget.id == "bookmarkOverview") {
+    adjustCoordsAndDraw(new complex(0,0), new complex(0,0));
+    return;
+  }
+
+  if (evtarget.getAttribute('bmRowID')) {
+    var iterMax = 0;
+    var C_min = null;
+    var C_max = null;
+
+    // Get coordinates for this row ID.
+    /*
+    while (statement.executeStep()) {
+      iterMax = ;
+      C_min = new complex(, );
+      C_max = new complex(, );
+    }
+
+    if (iterMax && C_min && C_max) {
+      setIter(iterMax)
+      adjustCoordsAndDraw(C_min, C_max);
+    }
+    */
+  }
 }
+
+var gSyncPrefs = {
+  objStore: "prefs",
+  shadow: {},
+
+  init: function(aCallback) {
+    // Fill the shadow from the DB.
+    if (!mainDB)
+      return;
+    var transaction = mainDB.transaction([this.objStore]);
+    var objStore = transaction.objectStore(this.objStore);
+    if (objStore.getAll) { // currently Mozilla-specific
+      objStore.getAll().onsuccess = function(event) {
+        gSyncPrefs.shadow = event.target.result;
+        aCallback();
+      };
+    }
+    else { // Use cursor (standard method).
+      objStore.openCursor().onsuccess = function(event) {
+        var cursor = event.target.result;
+        if (cursor) {
+          gSyncPrefs.shadow[cursor.key] = cursor.value;
+          cursor.continue();
+        }
+        else {
+          aCallback();
+        }
+      };
+    }
+  },
+
+  get: function(aKey) {
+    // Only use the shadow.
+    return this.shadow[aKey];
+  },
+
+  set: function(aKey, aValue) {
+    // First update the shadow.
+    this.shadow[aKey] = aValue;
+    // Now sync the DB with this.
+    if (!mainDB)
+      return;
+    var success = false;
+    var transaction = mainDB.transaction([this.objStore], "readwrite");
+    var objStore = transaction.objectStore(this.objStore);
+    var request = objStore.put(aValue, aKey);
+    request.onsuccess = function(event) {
+      success = true;
+      // Nothing else to be done!
+    };
+    request.onerror = function(event) {
+      // Errors could be handled here (but are ignored).
+    };
+  },
+
+  unset: function(aKey) {
+    // First update the shadow.
+    delete this.shadow[aKey];
+    // Now sync the DB with this.
+    if (!mainDB)
+      return;
+    var success = false;
+    var transaction = mainDB.transaction([this.objStore], "readwrite");
+    var request = transaction.objectStore(this.objStore).delete(aKey);
+    request.onsuccess = function(event) {
+      success = true;
+      // Nothing else to be done!
+    };
+    request.onerror = function(event) {
+      // Errors could be handled here (but are ignored).
+    }
+  }
+};
+
+var gBMStore = {
+  objStore: "bookmarks",
+
+  getList: function(aCallback) {
+    if (!mainDB)
+      return;
+    var transaction = mainDB.transaction([this.objStore]);
+    var objStore = transaction.objectStore(this.objStore);
+    if (objStore.getAll) { // currently Mozilla-specific
+      objStore.getAll().onsuccess = function(event) {
+        aCallback(event.target.result);
+      };
+    }
+    else { // Use cursor (standard method).
+      var BMs = {};
+      objStore.openCursor().onsuccess = function(event) {
+        var cursor = event.target.result;
+        if (cursor) {
+          BMs[cursor.key] = cursor.value;
+          cursor.continue();
+        }
+        else {
+          aCallback(BMs);
+        }
+      };
+    }
+  },
+
+  get: function(aKey, aCallback) {
+    if (!mainDB)
+      return;
+    var transaction = mainDB.transaction([this.objStore]);
+    var request = transaction.objectStore(this.objStore).get(aKey);
+    request.onsuccess = function(event) {
+      aCallback(request.result, event);
+    };
+    request.onerror = function(event) {
+      // Errors can be handled here.
+      aCallback(undefined, event);
+    };
+  },
+
+  set: function(aKey, aValue, aCallback) {
+    if (!mainDB)
+      return;
+    var success = false;
+    var transaction = mainDB.transaction([this.objStore], "readwrite");
+    var objStore = transaction.objectStore(this.objStore);
+    var request = objStore.put(aValue, aKey);
+    request.onsuccess = function(event) {
+      success = true;
+      if (aCallback)
+        aCallback(success, event);
+    };
+    request.onerror = function(event) {
+      // Errors can be handled here.
+      if (aCallback)
+        aCallback(success, event);
+    };
+  },
+
+  unset: function(aKey, aCallback) {
+    if (!mainDB)
+      return;
+    var success = false;
+    var transaction = mainDB.transaction([this.objStore], "readwrite");
+    var request = transaction.objectStore(this.objStore).delete(aKey);
+    request.onsuccess = function(event) {
+      success = true;
+      if (aCallback)
+        aCallback(success, event);
+    };
+    request.onerror = function(event) {
+      // Errors can be handled here.
+      if (aCallback)
+        aCallback(success, event);
+    }
+  },
+
+  clear: function(aCallback) {
+    if (!mainDB)
+      return;
+    var success = false;
+    var transaction = mainDB.transaction([this.objStore], "readwrite");
+    var request = transaction.objectStore(this.objStore).clear();
+    request.onsuccess = function(event) {
+      success = true;
+      if (aCallback)
+        aCallback(success, event);
+    };
+    request.onerror = function(event) {
+      // Errors can be handled here.
+      if (aCallback)
+        aCallback(success, event);
+    }
+  }
+};