webapprt/WebappRT.jsm
author Chris Jones <jones.chris.g@gmail.com>
Tue, 08 May 2012 14:36:07 -0700
changeset 97585 251188d5a55c0fe0cc323505678d041db855bc53
parent 95171 ef55c163a23a0fb7dc361791a53b6149d69f3ca2
child 102795 df17f2f4ab63777c252b88b9e68211422a9c4501
permissions -rw-r--r--
Bug 745145, part 1: Generalize ScreenOrientation into ScreenConfiguration, and add screen rect and color+pixel depth to it. r=mounir

/* 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/. */

const EXPORTED_SYMBOLS = ["WebappRT"];

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;

Cu.import("resource://gre/modules/XPCOMUtils.jsm");

XPCOMUtils.defineLazyGetter(this, "FileUtils", function() {
  Cu.import("resource://gre/modules/FileUtils.jsm");
  return FileUtils;
});

let WebappRT = {
  get config() {
    let webappFile = FileUtils.getFile("AppRegD", ["webapp.json"]);
    let inputStream = Cc["@mozilla.org/network/file-input-stream;1"].
                      createInstance(Ci.nsIFileInputStream);
    inputStream.init(webappFile, -1, 0, 0);
    let json = Cc["@mozilla.org/dom/json;1"].createInstance(Ci.nsIJSON);
    let config = json.decodeFromStream(inputStream, webappFile.fileSize);

    // Memoize the getter, freezing the `config` object in the meantime so
    // consumers don't inadvertently (or intentionally) change it, as the object
    // is meant to be a read-only representation of the webapp's configuration.
    config = deepFreeze(config);
    delete this.config;
    Object.defineProperty(this, "config", { get: function getConfig() config });
    return this.config;
  }
};

function deepFreeze(o) {
  // First, freeze the object.
  Object.freeze(o);

  // Then recursively call deepFreeze() to freeze its properties.
  for (let p in o) {
    // If the object is on the prototype, not an object, or is already frozen,
    // skip it.  Note that this might leave an unfrozen reference somewhere in
    // the object if there is an already frozen object containing an unfrozen
    // object.
    if (!o.hasOwnProperty(p) || !(typeof o[p] == "object") ||
        Object.isFrozen(o[p]))
      continue;

    deepFreeze(o[p]);
  }

  return o;
}