Bug 1287091 - part 1 - ContextualIdentityService should use a storage for the containers, r=Gijs
☠☠ backed out by 8b0f3616c00a ☠ ☠
authorAndrea Marchesini <amarchesini@mozilla.com>
Sat, 23 Jul 2016 08:57:40 +0200
changeset 346469 bf7c4e797f762c0de3e92e8ec19eec47a95ce92d
parent 346468 d8af5416b0627e13948a3e400ba0e9f152a5ee48
child 346470 93fa501cfd3a0d8b8ed5960789a2197a0db59ba9
push id6389
push userraliiev@mozilla.com
push dateMon, 19 Sep 2016 13:38:22 +0000
treeherdermozilla-beta@01d67bfe6c81 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersGijs
bugs1287091
milestone50.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1287091 - part 1 - ContextualIdentityService should use a storage for the containers, r=Gijs
browser/base/content/browser.js
browser/base/content/nsContextMenu.js
browser/base/content/utilityOverlay.js
toolkit/components/contextualidentity/ContextualIdentityService.jsm
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -3,16 +3,17 @@
  * 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/. */
 
 var Ci = Components.interfaces;
 var Cu = Components.utils;
 var Cc = Components.classes;
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/ContextualIdentityService.jsm");
 Cu.import("resource://gre/modules/NotificationDB.jsm");
 Cu.import("resource:///modules/RecentWindow.jsm");
 
 
 XPCOMUtils.defineLazyModuleGetter(this, "Preferences",
                                   "resource://gre/modules/Preferences.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "Deprecated",
                                   "resource://gre/modules/Deprecated.jsm");
@@ -51,18 +52,16 @@ XPCOMUtils.defineLazyServiceGetter(this,
                                    "mozIAsyncFavicons");
 XPCOMUtils.defineLazyServiceGetter(this, "gDNSService",
                                    "@mozilla.org/network/dns-service;1",
                                    "nsIDNSService");
 XPCOMUtils.defineLazyServiceGetter(this, "WindowsUIUtils",
                                    "@mozilla.org/windows-ui-utils;1", "nsIWindowsUIUtils");
 XPCOMUtils.defineLazyModuleGetter(this, "LightweightThemeManager",
                                   "resource://gre/modules/LightweightThemeManager.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "ContextualIdentityService",
-                                  "resource://gre/modules/ContextualIdentityService.jsm");
 XPCOMUtils.defineLazyServiceGetter(this, "gAboutNewTabService",
                                    "@mozilla.org/browser/aboutnewtab-service;1",
                                    "nsIAboutNewTabService");
 XPCOMUtils.defineLazyGetter(this, "gBrowserBundle", function() {
   return Services.strings.createBundle('chrome://browser/locale/browser.properties');
 });
 XPCOMUtils.defineLazyModuleGetter(this, "AddonWatcher",
                                   "resource://gre/modules/AddonWatcher.jsm");
--- a/browser/base/content/nsContextMenu.js
+++ b/browser/base/content/nsContextMenu.js
@@ -1,23 +1,22 @@
 /* -*- tab-width: 2; indent-tabs-mode: nil; js-indent-level: 2 -*- */
 /* vim: set ts=2 sw=2 sts=2 et tw=80: */
 # 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/.
 
+Components.utils.import("resource://gre/modules/ContextualIdentityService.jsm");
 Components.utils.import("resource://gre/modules/PrivateBrowsingUtils.jsm");
 Components.utils.import("resource://gre/modules/InlineSpellChecker.jsm");
 Components.utils.import("resource://gre/modules/LoginManagerContextMenu.jsm");
 Components.utils.import("resource://gre/modules/BrowserUtils.jsm");
 Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
 Components.utils.import("resource://gre/modules/Services.jsm");
 
-XPCOMUtils.defineLazyModuleGetter(this, "ContextualIdentityService",
-                                  "resource://gre/modules/ContextualIdentityService.jsm");
 
 XPCOMUtils.defineLazyModuleGetter(this, "LoginHelper",
   "resource://gre/modules/LoginHelper.jsm");
 
 var gContextMenuContentData = null;
 
 function nsContextMenu(aXulMenu, aIsShift) {
   this.shouldDisplay = true;
--- a/browser/base/content/utilityOverlay.js
+++ b/browser/base/content/utilityOverlay.js
@@ -1,26 +1,24 @@
 /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
  * 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/. */
 
 // Services = object with smart getters for common XPCOM services
 Components.utils.import("resource://gre/modules/AppConstants.jsm");
+Components.utils.import("resource://gre/modules/ContextualIdentityService.jsm");
 Components.utils.import("resource://gre/modules/Services.jsm");
 Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
 Components.utils.import("resource://gre/modules/PrivateBrowsingUtils.jsm");
 Components.utils.import("resource:///modules/RecentWindow.jsm");
 
 XPCOMUtils.defineLazyModuleGetter(this, "ShellService",
                                   "resource:///modules/ShellService.jsm");
 
-XPCOMUtils.defineLazyModuleGetter(this, "ContextualIdentityService",
-                                  "resource://gre/modules/ContextualIdentityService.jsm");
-
 XPCOMUtils.defineLazyServiceGetter(this, "aboutNewTabService",
                                    "@mozilla.org/browser/aboutnewtab-service;1",
                                    "nsIAboutNewTabService");
 
 this.__defineGetter__("BROWSER_NEW_TAB_URL", () => {
   if (PrivateBrowsingUtils.isWindowPrivate(window) &&
       !PrivateBrowsingUtils.permanentPrivateBrowsing &&
       !aboutNewTabService.overridden) {
--- a/toolkit/components/contextualidentity/ContextualIdentityService.jsm
+++ b/toolkit/components/contextualidentity/ContextualIdentityService.jsm
@@ -2,26 +2,44 @@
  * 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/. */
 
 this.EXPORTED_SYMBOLS = ["ContextualIdentityService"];
 
 const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm")
+Cu.import("resource://gre/modules/Services.jsm");
 
-const DEFAULT_TAB_COLOR = "#909090"
+const DEFAULT_TAB_COLOR = "#909090";
+const SAVE_DELAY_MS = 1500;
 
 XPCOMUtils.defineLazyGetter(this, "gBrowserBundle", function() {
   return Services.strings.createBundle("chrome://browser/locale/browser.properties");
 });
 
+XPCOMUtils.defineLazyGetter(this, "gTextDecoder", function () {
+  return new TextDecoder();
+});
+
+XPCOMUtils.defineLazyGetter(this, "gTextEncoder", function () {
+  return new TextEncoder();
+});
+
+XPCOMUtils.defineLazyModuleGetter(this, "AsyncShutdown",
+                                  "resource://gre/modules/AsyncShutdown.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "OS",
+                                  "resource://gre/modules/osfile.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "DeferredTask",
+                                  "resource://gre/modules/DeferredTask.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
+                                  "resource://gre/modules/FileUtils.jsm");
+
 this.ContextualIdentityService = {
-  _identities: [
+  _defaultIdentities: [
     { userContextId: 1,
       public: true,
       icon: "chrome://browser/skin/usercontext/personal.svg",
       color: "#00a7e0",
       label: "userContextPersonal.label",
       accessKey: "userContextPersonal.accesskey",
       alreadyOpened: false,
       telemetryId: 1,
@@ -57,25 +75,117 @@ this.ContextualIdentityService = {
       public: false,
       icon: "",
       color: "",
       label: "userContextIdInternal.thumbnail",
       accessKey: "",
       alreadyOpened: false },
   ],
 
+  _identities: null,
+
+  _path: null,
+  _dataReady: false,
+
+  _saver: null,
+
+  init() {
+    this._path = OS.Path.join(OS.Constants.Path.profileDir, "containers.json");
+
+    this._saver = new DeferredTask(() => this.save(), SAVE_DELAY_MS);
+    AsyncShutdown.profileBeforeChange.addBlocker("ContextualIdentityService: writing data",
+                                                 () => this._saver.finalize());
+
+    this.load();
+  },
+
+  load() {
+    OS.File.read(this._path).then(bytes => {
+      // If synchronous loading happened in the meantime, exit now.
+      if (this._dataReady) {
+        return;
+      }
+
+      try {
+        this._identities = JSON.parse(gTextDecoder.decode(bytes));
+        this._dataReady = true;
+      } catch(error) {
+        this.loadError(error);
+      }
+    }, (error) => {
+      this.loadError(error);
+    });
+  },
+
+  loadError(error) {
+    if (!(error instanceof OS.File.Error && error.becauseNoSuchFile) &&
+        !(error instanceof Components.Exception &&
+          error.result == Cr.NS_ERROR_FILE_NOT_FOUND)) {
+      // Let's report the error.
+      Cu.reportError(error);
+    }
+
+    // If synchronous loading happened in the meantime, exit now.
+    if (this._dataReady) {
+      return;
+    }
+
+    this._identities = this._defaultIdentities;
+    this._dataReady = true;
+
+    this.saveSoon();
+  },
+
+  saveSoon() {
+    this._saver.arm();
+  },
+
+  save() {
+   let bytes = gTextEncoder.encode(JSON.stringify(this._identities));
+   return OS.File.writeAtomic(this._path, bytes,
+                              { tmpPath: this._path + ".tmp" });
+  },
+
+  ensureDataReady() {
+    if (this._dataReady) {
+      return;
+    }
+
+    try {
+      // This reads the file and automatically detects the UTF-8 encoding.
+      let inputStream = Cc["@mozilla.org/network/file-input-stream;1"]
+                          .createInstance(Ci.nsIFileInputStream);
+      inputStream.init(new FileUtils.File(this._path),
+                       FileUtils.MODE_RDONLY, FileUtils.PERMS_FILE, 0);
+      try {
+        let json = Cc["@mozilla.org/dom/json;1"].createInstance(Ci.nsIJSON);
+        this._identities = json.decodeFromStream(inputStream,
+                                                 inputStream.available());
+        this._dataReady = true;
+      } finally {
+        inputStream.close();
+      }
+    } catch (error) {
+      this.loadError(error);
+      return;
+    }
+  },
+
   getIdentities() {
+    this.ensureDataReady();
     return this._identities.filter(info => info.public);
   },
 
   getPrivateIdentity(label) {
+    this.ensureDataReady();
     return this._identities.find(info => !info.public && info.label == label);
   },
 
   getIdentityFromId(userContextId) {
+    this.ensureDataReady();
     return this._identities.find(info => info.userContextId == userContextId);
   },
 
   getUserContextLabel(userContextId) {
     let identity = this.getIdentityFromId(userContextId);
     if (!identity.public) {
       return "";
     }
@@ -117,8 +227,10 @@ this.ContextualIdentityService = {
     Services.telemetry.getHistogramById("TOTAL_CONTAINERS_OPENED").add(1);
 
     if (identity.telemetryId) {
       Services.telemetry.getHistogramById("CONTAINER_USED")
                         .add(identity.telemetryId);
     }
   },
 }
+
+ContextualIdentityService.init();